2 // expression.cs: Expression representation for the IL tree.
5 // Miguel de Icaza (miguel@ximian.com)
7 // (C) 2001 Ximian, Inc.
12 namespace Mono.CSharp {
14 using System.Collections;
15 using System.Reflection;
16 using System.Reflection.Emit;
20 /// This is just a helper class, it is generated by Unary, UnaryMutator
21 /// when an overloaded method has been found. It just emits the code for a
24 public class StaticCallExpr : ExpressionStatement {
28 public StaticCallExpr (MethodInfo m, ArrayList a, Location l)
34 eclass = ExprClass.Value;
38 public override Expression DoResolve (EmitContext ec)
41 // We are born fully resolved
46 public override void Emit (EmitContext ec)
49 Invocation.EmitArguments (ec, mi, args);
51 ec.ig.Emit (OpCodes.Call, mi);
55 static public Expression MakeSimpleCall (EmitContext ec, MethodGroupExpr mg,
56 Expression e, Location loc)
61 args = new ArrayList (1);
62 args.Add (new Argument (e, Argument.AType.Expression));
63 method = Invocation.OverloadResolve (ec, (MethodGroupExpr) mg, args, loc);
68 return new StaticCallExpr ((MethodInfo) method, args, loc);
71 public override void EmitStatement (EmitContext ec)
74 if (TypeManager.TypeToCoreType (type) != TypeManager.void_type)
75 ec.ig.Emit (OpCodes.Pop);
80 /// Unary expressions.
84 /// Unary implements unary expressions. It derives from
85 /// ExpressionStatement becuase the pre/post increment/decrement
86 /// operators can be used in a statement context.
88 public class Unary : Expression {
89 public enum Operator : byte {
90 UnaryPlus, UnaryNegation, LogicalNot, OnesComplement,
91 Indirection, AddressOf, TOP
95 public Expression Expr;
97 public Unary (Operator op, Expression expr, Location loc)
105 /// Returns a stringified representation of the Operator
107 static public string OperName (Operator oper)
110 case Operator.UnaryPlus:
112 case Operator.UnaryNegation:
114 case Operator.LogicalNot:
116 case Operator.OnesComplement:
118 case Operator.AddressOf:
120 case Operator.Indirection:
124 return oper.ToString ();
127 public static readonly string [] oper_names;
131 oper_names = new string [(int)Operator.TOP];
133 oper_names [(int) Operator.UnaryPlus] = "op_UnaryPlus";
134 oper_names [(int) Operator.UnaryNegation] = "op_UnaryNegation";
135 oper_names [(int) Operator.LogicalNot] = "op_LogicalNot";
136 oper_names [(int) Operator.OnesComplement] = "op_OnesComplement";
137 oper_names [(int) Operator.Indirection] = "op_Indirection";
138 oper_names [(int) Operator.AddressOf] = "op_AddressOf";
141 void Error23 (Type t)
144 23, "Operator " + OperName (Oper) +
145 " cannot be applied to operand of type `" +
146 TypeManager.CSharpName (t) + "'");
150 /// The result has been already resolved:
152 /// FIXME: a minus constant -128 sbyte cant be turned into a
155 static Expression TryReduceNegative (Constant expr)
159 if (expr is IntConstant)
160 e = new IntConstant (-((IntConstant) expr).Value);
161 else if (expr is UIntConstant){
162 uint value = ((UIntConstant) expr).Value;
164 if (value < 2147483649)
165 return new IntConstant (-(int)value);
167 e = new LongConstant (-value);
169 else if (expr is LongConstant)
170 e = new LongConstant (-((LongConstant) expr).Value);
171 else if (expr is ULongConstant){
172 ulong value = ((ULongConstant) expr).Value;
174 if (value < 9223372036854775809)
175 return new LongConstant(-(long)value);
177 else if (expr is FloatConstant)
178 e = new FloatConstant (-((FloatConstant) expr).Value);
179 else if (expr is DoubleConstant)
180 e = new DoubleConstant (-((DoubleConstant) expr).Value);
181 else if (expr is DecimalConstant)
182 e = new DecimalConstant (-((DecimalConstant) expr).Value);
183 else if (expr is ShortConstant)
184 e = new IntConstant (-((ShortConstant) expr).Value);
185 else if (expr is UShortConstant)
186 e = new IntConstant (-((UShortConstant) expr).Value);
191 // This routine will attempt to simplify the unary expression when the
192 // argument is a constant. The result is returned in `result' and the
193 // function returns true or false depending on whether a reduction
194 // was performed or not
196 bool Reduce (EmitContext ec, Constant e, out Expression result)
198 Type expr_type = e.Type;
201 case Operator.UnaryPlus:
205 case Operator.UnaryNegation:
206 result = TryReduceNegative (e);
209 case Operator.LogicalNot:
210 if (expr_type != TypeManager.bool_type) {
216 BoolConstant b = (BoolConstant) e;
217 result = new BoolConstant (!(b.Value));
220 case Operator.OnesComplement:
221 if (!((expr_type == TypeManager.int32_type) ||
222 (expr_type == TypeManager.uint32_type) ||
223 (expr_type == TypeManager.int64_type) ||
224 (expr_type == TypeManager.uint64_type) ||
225 (expr_type.IsSubclassOf (TypeManager.enum_type)))){
228 if (ImplicitConversionExists (ec, e, TypeManager.int32_type)){
229 result = new Cast (new TypeExpr (TypeManager.int32_type, loc), e, loc);
230 result = result.Resolve (ec);
231 } else if (ImplicitConversionExists (ec, e, TypeManager.uint32_type)){
232 result = new Cast (new TypeExpr (TypeManager.uint32_type, loc), e, loc);
233 result = result.Resolve (ec);
234 } else if (ImplicitConversionExists (ec, e, TypeManager.int64_type)){
235 result = new Cast (new TypeExpr (TypeManager.int64_type, loc), e, loc);
236 result = result.Resolve (ec);
237 } else if (ImplicitConversionExists (ec, e, TypeManager.uint64_type)){
238 result = new Cast (new TypeExpr (TypeManager.uint64_type, loc), e, loc);
239 result = result.Resolve (ec);
242 if (result == null || !(result is Constant)){
248 expr_type = result.Type;
249 e = (Constant) result;
252 if (e is EnumConstant){
253 EnumConstant enum_constant = (EnumConstant) e;
256 if (Reduce (ec, enum_constant.Child, out reduced)){
257 result = new EnumConstant ((Constant) reduced, enum_constant.Type);
265 if (expr_type == TypeManager.int32_type){
266 result = new IntConstant (~ ((IntConstant) e).Value);
267 } else if (expr_type == TypeManager.uint32_type){
268 result = new UIntConstant (~ ((UIntConstant) e).Value);
269 } else if (expr_type == TypeManager.int64_type){
270 result = new LongConstant (~ ((LongConstant) e).Value);
271 } else if (expr_type == TypeManager.uint64_type){
272 result = new ULongConstant (~ ((ULongConstant) e).Value);
280 case Operator.AddressOf:
284 case Operator.Indirection:
288 throw new Exception ("Can not constant fold: " + Oper.ToString());
291 Expression ResolveOperator (EmitContext ec)
293 Type expr_type = Expr.Type;
296 // Step 1: Perform Operator Overload location
301 op_name = oper_names [(int) Oper];
303 mg = MemberLookup (ec, expr_type, op_name, MemberTypes.Method, AllBindingFlags, loc);
306 Expression e = StaticCallExpr.MakeSimpleCall (
307 ec, (MethodGroupExpr) mg, Expr, loc);
317 // Only perform numeric promotions on:
320 if (expr_type == null)
324 // Step 2: Default operations on CLI native types.
327 // Attempt to use a constant folding operation.
328 if (Expr is Constant){
331 if (Reduce (ec, (Constant) Expr, out result))
336 case Operator.LogicalNot:
337 if (expr_type != TypeManager.bool_type) {
338 Expr = ResolveBoolean (ec, Expr, loc);
345 type = TypeManager.bool_type;
348 case Operator.OnesComplement:
349 if (!((expr_type == TypeManager.int32_type) ||
350 (expr_type == TypeManager.uint32_type) ||
351 (expr_type == TypeManager.int64_type) ||
352 (expr_type == TypeManager.uint64_type) ||
353 (expr_type.IsSubclassOf (TypeManager.enum_type)))){
356 e = ConvertImplicit (ec, Expr, TypeManager.int32_type, loc);
358 type = TypeManager.int32_type;
361 e = ConvertImplicit (ec, Expr, TypeManager.uint32_type, loc);
363 type = TypeManager.uint32_type;
366 e = ConvertImplicit (ec, Expr, TypeManager.int64_type, loc);
368 type = TypeManager.int64_type;
371 e = ConvertImplicit (ec, Expr, TypeManager.uint64_type, loc);
373 type = TypeManager.uint64_type;
382 case Operator.AddressOf:
383 if (Expr.eclass != ExprClass.Variable){
384 Error (211, "Cannot take the address of non-variables");
393 if (!TypeManager.VerifyUnManaged (Expr.Type, loc)){
397 type = TypeManager.GetPointerType (Expr.Type);
400 case Operator.Indirection:
406 if (!expr_type.IsPointer){
407 Error (193, "The * or -> operator can only be applied to pointers");
412 // We create an Indirection expression, because
413 // it can implement the IMemoryLocation.
415 return new Indirection (Expr, loc);
417 case Operator.UnaryPlus:
419 // A plus in front of something is just a no-op, so return the child.
423 case Operator.UnaryNegation:
425 // Deals with -literals
426 // int operator- (int x)
427 // long operator- (long x)
428 // float operator- (float f)
429 // double operator- (double d)
430 // decimal operator- (decimal d)
432 Expression expr = null;
435 // transform - - expr into expr
438 Unary unary = (Unary) Expr;
440 if (unary.Oper == Operator.UnaryNegation)
445 // perform numeric promotions to int,
449 // The following is inneficient, because we call
450 // ConvertImplicit too many times.
452 // It is also not clear if we should convert to Float
453 // or Double initially.
455 if (expr_type == TypeManager.uint32_type){
457 // FIXME: handle exception to this rule that
458 // permits the int value -2147483648 (-2^31) to
459 // bt wrote as a decimal interger literal
461 type = TypeManager.int64_type;
462 Expr = ConvertImplicit (ec, Expr, type, loc);
466 if (expr_type == TypeManager.uint64_type){
468 // FIXME: Handle exception of `long value'
469 // -92233720368547758087 (-2^63) to be wrote as
470 // decimal integer literal.
476 if (expr_type == TypeManager.float_type){
481 expr = ConvertImplicit (ec, Expr, TypeManager.int32_type, loc);
488 expr = ConvertImplicit (ec, Expr, TypeManager.int64_type, loc);
495 expr = ConvertImplicit (ec, Expr, TypeManager.double_type, loc);
506 Error (187, "No such operator '" + OperName (Oper) + "' defined for type '" +
507 TypeManager.CSharpName (expr_type) + "'");
511 public override Expression DoResolve (EmitContext ec)
513 if (Oper == Operator.AddressOf)
514 Expr = Expr.ResolveLValue (ec, new EmptyExpression ());
516 Expr = Expr.Resolve (ec);
521 eclass = ExprClass.Value;
522 return ResolveOperator (ec);
525 public override void Emit (EmitContext ec)
527 ILGenerator ig = ec.ig;
528 Type expr_type = Expr.Type;
531 case Operator.UnaryPlus:
532 throw new Exception ("This should be caught by Resolve");
534 case Operator.UnaryNegation:
536 ig.Emit (OpCodes.Neg);
539 case Operator.LogicalNot:
541 ig.Emit (OpCodes.Ldc_I4_0);
542 ig.Emit (OpCodes.Ceq);
545 case Operator.OnesComplement:
547 ig.Emit (OpCodes.Not);
550 case Operator.AddressOf:
551 ((IMemoryLocation)Expr).AddressOf (ec, AddressOp.LoadStore);
555 throw new Exception ("This should not happen: Operator = "
561 /// This will emit the child expression for `ec' avoiding the logical
562 /// not. The parent will take care of changing brfalse/brtrue
564 public void EmitLogicalNot (EmitContext ec)
566 if (Oper != Operator.LogicalNot)
567 throw new Exception ("EmitLogicalNot can only be called with !expr");
572 public override string ToString ()
574 return "Unary (" + Oper + ", " + Expr + ")";
580 // Unary operators are turned into Indirection expressions
581 // after semantic analysis (this is so we can take the address
582 // of an indirection).
584 public class Indirection : Expression, IMemoryLocation, IAssignMethod {
586 LocalTemporary temporary;
589 public Indirection (Expression expr, Location l)
592 this.type = TypeManager.TypeToCoreType (expr.Type.GetElementType ());
593 eclass = ExprClass.Variable;
597 void LoadExprValue (EmitContext ec)
601 public override void Emit (EmitContext ec)
603 ILGenerator ig = ec.ig;
605 if (temporary != null){
611 ec.ig.Emit (OpCodes.Dup);
612 temporary.Store (ec);
613 have_temporary = true;
617 LoadFromPtr (ig, Type);
620 public void EmitAssign (EmitContext ec, Expression source)
622 if (temporary != null){
627 ec.ig.Emit (OpCodes.Dup);
628 temporary.Store (ec);
629 have_temporary = true;
635 StoreFromPtr (ec.ig, type);
638 public void AddressOf (EmitContext ec, AddressOp Mode)
640 if (temporary != null){
646 ec.ig.Emit (OpCodes.Dup);
647 temporary.Store (ec);
648 have_temporary = true;
653 public override Expression DoResolve (EmitContext ec)
656 // Born fully resolved
661 public new void CacheTemporaries (EmitContext ec)
663 temporary = new LocalTemporary (ec, type);
666 public override string ToString ()
668 return "*(" + expr + ")";
673 /// Unary Mutator expressions (pre and post ++ and --)
677 /// UnaryMutator implements ++ and -- expressions. It derives from
678 /// ExpressionStatement becuase the pre/post increment/decrement
679 /// operators can be used in a statement context.
681 /// FIXME: Idea, we could split this up in two classes, one simpler
682 /// for the common case, and one with the extra fields for more complex
683 /// classes (indexers require temporary access; overloaded require method)
686 public class UnaryMutator : ExpressionStatement {
688 public enum Mode : byte {
695 PreDecrement = IsDecrement,
696 PostIncrement = IsPost,
697 PostDecrement = IsPost | IsDecrement
702 LocalTemporary temp_storage;
705 // This is expensive for the simplest case.
709 public UnaryMutator (Mode m, Expression e, Location l)
716 static string OperName (Mode mode)
718 return (mode == Mode.PreIncrement || mode == Mode.PostIncrement) ?
722 void Error23 (Type t)
725 23, "Operator " + OperName (mode) +
726 " cannot be applied to operand of type `" +
727 TypeManager.CSharpName (t) + "'");
731 /// Returns whether an object of type `t' can be incremented
732 /// or decremented with add/sub (ie, basically whether we can
733 /// use pre-post incr-decr operations on it, but it is not a
734 /// System.Decimal, which we require operator overloading to catch)
736 static bool IsIncrementableNumber (Type t)
738 return (t == TypeManager.sbyte_type) ||
739 (t == TypeManager.byte_type) ||
740 (t == TypeManager.short_type) ||
741 (t == TypeManager.ushort_type) ||
742 (t == TypeManager.int32_type) ||
743 (t == TypeManager.uint32_type) ||
744 (t == TypeManager.int64_type) ||
745 (t == TypeManager.uint64_type) ||
746 (t == TypeManager.char_type) ||
747 (t.IsSubclassOf (TypeManager.enum_type)) ||
748 (t == TypeManager.float_type) ||
749 (t == TypeManager.double_type) ||
750 (t.IsPointer && t != TypeManager.void_ptr_type);
753 Expression ResolveOperator (EmitContext ec)
755 Type expr_type = expr.Type;
758 // Step 1: Perform Operator Overload location
763 if (mode == Mode.PreIncrement || mode == Mode.PostIncrement)
764 op_name = "op_Increment";
766 op_name = "op_Decrement";
768 mg = MemberLookup (ec, expr_type, op_name, MemberTypes.Method, AllBindingFlags, loc);
770 if (mg == null && expr_type.BaseType != null)
771 mg = MemberLookup (ec, expr_type.BaseType, op_name,
772 MemberTypes.Method, AllBindingFlags, loc);
775 method = StaticCallExpr.MakeSimpleCall (
776 ec, (MethodGroupExpr) mg, expr, loc);
783 // The operand of the prefix/postfix increment decrement operators
784 // should be an expression that is classified as a variable,
785 // a property access or an indexer access
788 if (expr.eclass == ExprClass.Variable){
789 if (IsIncrementableNumber (expr_type) ||
790 expr_type == TypeManager.decimal_type){
793 } else if (expr.eclass == ExprClass.IndexerAccess){
794 IndexerAccess ia = (IndexerAccess) expr;
796 temp_storage = new LocalTemporary (ec, expr.Type);
798 expr = ia.ResolveLValue (ec, temp_storage);
803 } else if (expr.eclass == ExprClass.PropertyAccess){
804 PropertyExpr pe = (PropertyExpr) expr;
806 if (pe.VerifyAssignable ())
811 expr.Error_UnexpectedKind ("variable, indexer or property access");
815 Error (187, "No such operator '" + OperName (mode) + "' defined for type '" +
816 TypeManager.CSharpName (expr_type) + "'");
820 public override Expression DoResolve (EmitContext ec)
822 expr = expr.Resolve (ec);
827 eclass = ExprClass.Value;
828 return ResolveOperator (ec);
831 static int PtrTypeSize (Type t)
833 return GetTypeSize (t.GetElementType ());
837 // Loads the proper "1" into the stack based on the type, then it emits the
838 // opcode for the operation requested
840 void LoadOneAndEmitOp (EmitContext ec, Type t)
843 // Measure if getting the typecode and using that is more/less efficient
844 // that comparing types. t.GetTypeCode() is an internal call.
846 ILGenerator ig = ec.ig;
848 if (t == TypeManager.uint64_type || t == TypeManager.int64_type)
849 LongConstant.EmitLong (ig, 1);
850 else if (t == TypeManager.double_type)
851 ig.Emit (OpCodes.Ldc_R8, 1.0);
852 else if (t == TypeManager.float_type)
853 ig.Emit (OpCodes.Ldc_R4, 1.0F);
854 else if (t.IsPointer){
855 int n = PtrTypeSize (t);
858 ig.Emit (OpCodes.Sizeof, t);
860 IntConstant.EmitInt (ig, n);
862 ig.Emit (OpCodes.Ldc_I4_1);
865 // Now emit the operation
868 if (t == TypeManager.int32_type ||
869 t == TypeManager.int64_type){
870 if ((mode & Mode.IsDecrement) != 0)
871 ig.Emit (OpCodes.Sub_Ovf);
873 ig.Emit (OpCodes.Add_Ovf);
874 } else if (t == TypeManager.uint32_type ||
875 t == TypeManager.uint64_type){
876 if ((mode & Mode.IsDecrement) != 0)
877 ig.Emit (OpCodes.Sub_Ovf_Un);
879 ig.Emit (OpCodes.Add_Ovf_Un);
881 if ((mode & Mode.IsDecrement) != 0)
882 ig.Emit (OpCodes.Sub_Ovf);
884 ig.Emit (OpCodes.Add_Ovf);
887 if ((mode & Mode.IsDecrement) != 0)
888 ig.Emit (OpCodes.Sub);
890 ig.Emit (OpCodes.Add);
893 if (t == TypeManager.sbyte_type){
895 ig.Emit (OpCodes.Conv_Ovf_I1);
897 ig.Emit (OpCodes.Conv_I1);
898 } else if (t == TypeManager.byte_type){
900 ig.Emit (OpCodes.Conv_Ovf_U1);
902 ig.Emit (OpCodes.Conv_U1);
903 } else if (t == TypeManager.short_type){
905 ig.Emit (OpCodes.Conv_Ovf_I2);
907 ig.Emit (OpCodes.Conv_I2);
908 } else if (t == TypeManager.ushort_type || t == TypeManager.char_type){
910 ig.Emit (OpCodes.Conv_Ovf_U2);
912 ig.Emit (OpCodes.Conv_U2);
917 void EmitCode (EmitContext ec, bool is_expr)
919 ILGenerator ig = ec.ig;
920 IAssignMethod ia = (IAssignMethod) expr;
921 Type expr_type = expr.Type;
923 ia.CacheTemporaries (ec);
925 if (temp_storage == null)
926 temp_storage = new LocalTemporary (ec, expr_type);
929 case Mode.PreIncrement:
930 case Mode.PreDecrement:
934 LoadOneAndEmitOp (ec, expr_type);
938 temp_storage.Store (ec);
939 ia.EmitAssign (ec, temp_storage);
941 temp_storage.Emit (ec);
944 case Mode.PostIncrement:
945 case Mode.PostDecrement:
953 ig.Emit (OpCodes.Dup);
955 LoadOneAndEmitOp (ec, expr_type);
960 temp_storage.Store (ec);
961 ia.EmitAssign (ec, temp_storage);
966 public override void Emit (EmitContext ec)
972 public override void EmitStatement (EmitContext ec)
974 EmitCode (ec, false);
980 /// Base class for the `Is' and `As' classes.
984 /// FIXME: Split this in two, and we get to save the `Operator' Oper
987 public abstract class Probe : Expression {
988 public readonly Expression ProbeType;
989 protected Expression expr;
990 protected Type probe_type;
992 public Probe (Expression expr, Expression probe_type, Location l)
994 ProbeType = probe_type;
999 public Expression Expr {
1005 public override Expression DoResolve (EmitContext ec)
1007 probe_type = ec.DeclSpace.ResolveType (ProbeType, false, loc);
1009 if (probe_type == null)
1012 expr = expr.Resolve (ec);
1019 /// Implementation of the `is' operator.
1021 public class Is : Probe {
1022 public Is (Expression expr, Expression probe_type, Location l)
1023 : base (expr, probe_type, l)
1028 AlwaysTrue, AlwaysNull, AlwaysFalse, LeaveOnStack, Probe
1033 public override void Emit (EmitContext ec)
1035 ILGenerator ig = ec.ig;
1040 case Action.AlwaysFalse:
1041 ig.Emit (OpCodes.Pop);
1042 IntConstant.EmitInt (ig, 0);
1044 case Action.AlwaysTrue:
1045 ig.Emit (OpCodes.Pop);
1046 IntConstant.EmitInt (ig, 1);
1048 case Action.LeaveOnStack:
1049 // the `e != null' rule.
1050 ig.Emit (OpCodes.Ldnull);
1051 ig.Emit (OpCodes.Ceq);
1052 ig.Emit (OpCodes.Ldc_I4_0);
1053 ig.Emit (OpCodes.Ceq);
1056 ig.Emit (OpCodes.Isinst, probe_type);
1057 ig.Emit (OpCodes.Ldnull);
1058 ig.Emit (OpCodes.Cgt_Un);
1061 throw new Exception ("never reached");
1064 public override Expression DoResolve (EmitContext ec)
1066 Expression e = base.DoResolve (ec);
1068 if ((e == null) || (expr == null))
1071 Type etype = expr.Type;
1072 bool warning_always_matches = false;
1073 bool warning_never_matches = false;
1075 type = TypeManager.bool_type;
1076 eclass = ExprClass.Value;
1079 // First case, if at compile time, there is an implicit conversion
1080 // then e != null (objects) or true (value types)
1082 e = ConvertImplicitStandard (ec, expr, probe_type, loc);
1085 if (etype.IsValueType)
1086 action = Action.AlwaysTrue;
1088 action = Action.LeaveOnStack;
1090 warning_always_matches = true;
1091 } else if (ExplicitReferenceConversionExists (etype, probe_type)){
1093 // Second case: explicit reference convresion
1095 if (expr is NullLiteral)
1096 action = Action.AlwaysFalse;
1098 action = Action.Probe;
1100 action = Action.AlwaysFalse;
1101 warning_never_matches = true;
1104 if (RootContext.WarningLevel >= 1){
1105 if (warning_always_matches)
1106 Warning (183, "The expression is always of type `" +
1107 TypeManager.CSharpName (probe_type) + "'");
1108 else if (warning_never_matches){
1109 if (!(probe_type.IsInterface || expr.Type.IsInterface))
1111 "The expression is never of type `" +
1112 TypeManager.CSharpName (probe_type) + "'");
1121 /// Implementation of the `as' operator.
1123 public class As : Probe {
1124 public As (Expression expr, Expression probe_type, Location l)
1125 : base (expr, probe_type, l)
1129 bool do_isinst = false;
1131 public override void Emit (EmitContext ec)
1133 ILGenerator ig = ec.ig;
1138 ig.Emit (OpCodes.Isinst, probe_type);
1141 static void Error_CannotConvertType (Type source, Type target, Location loc)
1144 39, loc, "as operator can not convert from `" +
1145 TypeManager.CSharpName (source) + "' to `" +
1146 TypeManager.CSharpName (target) + "'");
1149 public override Expression DoResolve (EmitContext ec)
1151 Expression e = base.DoResolve (ec);
1157 eclass = ExprClass.Value;
1158 Type etype = expr.Type;
1160 if (TypeManager.IsValueType (probe_type)){
1161 Report.Error (77, loc, "The as operator should be used with a reference type only (" +
1162 TypeManager.CSharpName (probe_type) + " is a value type");
1167 e = ConvertImplicit (ec, expr, probe_type, loc);
1174 if (ExplicitReferenceConversionExists (etype, probe_type)){
1179 Error_CannotConvertType (etype, probe_type, loc);
1185 /// This represents a typecast in the source language.
1187 /// FIXME: Cast expressions have an unusual set of parsing
1188 /// rules, we need to figure those out.
1190 public class Cast : Expression {
1191 Expression target_type;
1194 public Cast (Expression cast_type, Expression expr, Location loc)
1196 this.target_type = cast_type;
1201 public Expression TargetType {
1207 public Expression Expr {
1216 bool CheckRange (EmitContext ec, long value, Type type, long min, long max)
1218 if (!ec.ConstantCheckState)
1221 if ((value < min) || (value > max)) {
1222 Error (221, "Constant value `" + value + "' cannot be converted " +
1223 "to a `" + TypeManager.CSharpName (type) + "' (use `unchecked' " +
1224 "syntax to override)");
1231 bool CheckRange (EmitContext ec, ulong value, Type type, ulong max)
1233 if (!ec.ConstantCheckState)
1237 Error (221, "Constant value `" + value + "' cannot be converted " +
1238 "to a `" + TypeManager.CSharpName (type) + "' (use `unchecked' " +
1239 "syntax to override)");
1246 bool CheckUnsigned (EmitContext ec, long value, Type type)
1248 if (!ec.ConstantCheckState)
1252 Error (221, "Constant value `" + value + "' cannot be converted " +
1253 "to a `" + TypeManager.CSharpName (type) + "' (use `unchecked' " +
1254 "syntax to override)");
1262 /// Attempts to do a compile-time folding of a constant cast.
1264 Expression TryReduce (EmitContext ec, Type target_type)
1266 Expression real_expr = expr;
1267 if (real_expr is EnumConstant)
1268 real_expr = ((EnumConstant) real_expr).Child;
1270 if (real_expr is ByteConstant){
1271 byte v = ((ByteConstant) real_expr).Value;
1273 if (target_type == TypeManager.sbyte_type) {
1274 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1276 return new SByteConstant ((sbyte) v);
1278 if (target_type == TypeManager.short_type)
1279 return new ShortConstant ((short) v);
1280 if (target_type == TypeManager.ushort_type)
1281 return new UShortConstant ((ushort) v);
1282 if (target_type == TypeManager.int32_type)
1283 return new IntConstant ((int) v);
1284 if (target_type == TypeManager.uint32_type)
1285 return new UIntConstant ((uint) v);
1286 if (target_type == TypeManager.int64_type)
1287 return new LongConstant ((long) v);
1288 if (target_type == TypeManager.uint64_type)
1289 return new ULongConstant ((ulong) v);
1290 if (target_type == TypeManager.float_type)
1291 return new FloatConstant ((float) v);
1292 if (target_type == TypeManager.double_type)
1293 return new DoubleConstant ((double) v);
1294 if (target_type == TypeManager.char_type)
1295 return new CharConstant ((char) v);
1296 if (target_type == TypeManager.decimal_type)
1297 return new DecimalConstant ((decimal) v);
1299 if (real_expr is SByteConstant){
1300 sbyte v = ((SByteConstant) real_expr).Value;
1302 if (target_type == TypeManager.byte_type) {
1303 if (!CheckUnsigned (ec, v, target_type))
1305 return new ByteConstant ((byte) v);
1307 if (target_type == TypeManager.short_type)
1308 return new ShortConstant ((short) v);
1309 if (target_type == TypeManager.ushort_type) {
1310 if (!CheckUnsigned (ec, v, target_type))
1312 return new UShortConstant ((ushort) v);
1313 } if (target_type == TypeManager.int32_type)
1314 return new IntConstant ((int) v);
1315 if (target_type == TypeManager.uint32_type) {
1316 if (!CheckUnsigned (ec, v, target_type))
1318 return new UIntConstant ((uint) v);
1319 } if (target_type == TypeManager.int64_type)
1320 return new LongConstant ((long) v);
1321 if (target_type == TypeManager.uint64_type) {
1322 if (!CheckUnsigned (ec, v, target_type))
1324 return new ULongConstant ((ulong) v);
1326 if (target_type == TypeManager.float_type)
1327 return new FloatConstant ((float) v);
1328 if (target_type == TypeManager.double_type)
1329 return new DoubleConstant ((double) v);
1330 if (target_type == TypeManager.char_type) {
1331 if (!CheckUnsigned (ec, v, target_type))
1333 return new CharConstant ((char) v);
1335 if (target_type == TypeManager.decimal_type)
1336 return new DecimalConstant ((decimal) v);
1338 if (real_expr is ShortConstant){
1339 short v = ((ShortConstant) real_expr).Value;
1341 if (target_type == TypeManager.byte_type) {
1342 if (!CheckRange (ec, v, target_type, Byte.MinValue, Byte.MaxValue))
1344 return new ByteConstant ((byte) v);
1346 if (target_type == TypeManager.sbyte_type) {
1347 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1349 return new SByteConstant ((sbyte) v);
1351 if (target_type == TypeManager.ushort_type) {
1352 if (!CheckUnsigned (ec, v, target_type))
1354 return new UShortConstant ((ushort) v);
1356 if (target_type == TypeManager.int32_type)
1357 return new IntConstant ((int) v);
1358 if (target_type == TypeManager.uint32_type) {
1359 if (!CheckUnsigned (ec, v, target_type))
1361 return new UIntConstant ((uint) v);
1363 if (target_type == TypeManager.int64_type)
1364 return new LongConstant ((long) v);
1365 if (target_type == TypeManager.uint64_type) {
1366 if (!CheckUnsigned (ec, v, target_type))
1368 return new ULongConstant ((ulong) v);
1370 if (target_type == TypeManager.float_type)
1371 return new FloatConstant ((float) v);
1372 if (target_type == TypeManager.double_type)
1373 return new DoubleConstant ((double) v);
1374 if (target_type == TypeManager.char_type) {
1375 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1377 return new CharConstant ((char) v);
1379 if (target_type == TypeManager.decimal_type)
1380 return new DecimalConstant ((decimal) v);
1382 if (real_expr is UShortConstant){
1383 ushort v = ((UShortConstant) real_expr).Value;
1385 if (target_type == TypeManager.byte_type) {
1386 if (!CheckRange (ec, v, target_type, Byte.MinValue, Byte.MaxValue))
1388 return new ByteConstant ((byte) v);
1390 if (target_type == TypeManager.sbyte_type) {
1391 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1393 return new SByteConstant ((sbyte) v);
1395 if (target_type == TypeManager.short_type) {
1396 if (!CheckRange (ec, v, target_type, Int16.MinValue, Int16.MaxValue))
1398 return new ShortConstant ((short) v);
1400 if (target_type == TypeManager.int32_type)
1401 return new IntConstant ((int) v);
1402 if (target_type == TypeManager.uint32_type)
1403 return new UIntConstant ((uint) v);
1404 if (target_type == TypeManager.int64_type)
1405 return new LongConstant ((long) v);
1406 if (target_type == TypeManager.uint64_type)
1407 return new ULongConstant ((ulong) v);
1408 if (target_type == TypeManager.float_type)
1409 return new FloatConstant ((float) v);
1410 if (target_type == TypeManager.double_type)
1411 return new DoubleConstant ((double) v);
1412 if (target_type == TypeManager.char_type) {
1413 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1415 return new CharConstant ((char) v);
1417 if (target_type == TypeManager.decimal_type)
1418 return new DecimalConstant ((decimal) v);
1420 if (real_expr is IntConstant){
1421 int v = ((IntConstant) real_expr).Value;
1423 if (target_type == TypeManager.byte_type) {
1424 if (!CheckRange (ec, v, target_type, Byte.MinValue, Byte.MaxValue))
1426 return new ByteConstant ((byte) v);
1428 if (target_type == TypeManager.sbyte_type) {
1429 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1431 return new SByteConstant ((sbyte) v);
1433 if (target_type == TypeManager.short_type) {
1434 if (!CheckRange (ec, v, target_type, Int16.MinValue, Int16.MaxValue))
1436 return new ShortConstant ((short) v);
1438 if (target_type == TypeManager.ushort_type) {
1439 if (!CheckRange (ec, v, target_type, UInt16.MinValue, UInt16.MaxValue))
1441 return new UShortConstant ((ushort) v);
1443 if (target_type == TypeManager.uint32_type) {
1444 if (!CheckRange (ec, v, target_type, Int32.MinValue, Int32.MaxValue))
1446 return new UIntConstant ((uint) v);
1448 if (target_type == TypeManager.int64_type)
1449 return new LongConstant ((long) v);
1450 if (target_type == TypeManager.uint64_type) {
1451 if (!CheckUnsigned (ec, v, target_type))
1453 return new ULongConstant ((ulong) v);
1455 if (target_type == TypeManager.float_type)
1456 return new FloatConstant ((float) v);
1457 if (target_type == TypeManager.double_type)
1458 return new DoubleConstant ((double) v);
1459 if (target_type == TypeManager.char_type) {
1460 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1462 return new CharConstant ((char) v);
1464 if (target_type == TypeManager.decimal_type)
1465 return new DecimalConstant ((decimal) v);
1467 if (real_expr is UIntConstant){
1468 uint v = ((UIntConstant) real_expr).Value;
1470 if (target_type == TypeManager.byte_type) {
1471 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1473 return new ByteConstant ((byte) v);
1475 if (target_type == TypeManager.sbyte_type) {
1476 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1478 return new SByteConstant ((sbyte) v);
1480 if (target_type == TypeManager.short_type) {
1481 if (!CheckRange (ec, v, target_type, Int16.MinValue, Int16.MaxValue))
1483 return new ShortConstant ((short) v);
1485 if (target_type == TypeManager.ushort_type) {
1486 if (!CheckRange (ec, v, target_type, UInt16.MinValue, UInt16.MaxValue))
1488 return new UShortConstant ((ushort) v);
1490 if (target_type == TypeManager.int32_type) {
1491 if (!CheckRange (ec, v, target_type, Int32.MinValue, Int32.MaxValue))
1493 return new IntConstant ((int) v);
1495 if (target_type == TypeManager.int64_type)
1496 return new LongConstant ((long) v);
1497 if (target_type == TypeManager.uint64_type)
1498 return new ULongConstant ((ulong) v);
1499 if (target_type == TypeManager.float_type)
1500 return new FloatConstant ((float) v);
1501 if (target_type == TypeManager.double_type)
1502 return new DoubleConstant ((double) v);
1503 if (target_type == TypeManager.char_type) {
1504 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1506 return new CharConstant ((char) v);
1508 if (target_type == TypeManager.decimal_type)
1509 return new DecimalConstant ((decimal) v);
1511 if (real_expr is LongConstant){
1512 long v = ((LongConstant) real_expr).Value;
1514 if (target_type == TypeManager.byte_type) {
1515 if (!CheckRange (ec, v, target_type, Byte.MinValue, Byte.MaxValue))
1517 return new ByteConstant ((byte) v);
1519 if (target_type == TypeManager.sbyte_type) {
1520 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1522 return new SByteConstant ((sbyte) v);
1524 if (target_type == TypeManager.short_type) {
1525 if (!CheckRange (ec, v, target_type, Int16.MinValue, Int16.MaxValue))
1527 return new ShortConstant ((short) v);
1529 if (target_type == TypeManager.ushort_type) {
1530 if (!CheckRange (ec, v, target_type, UInt16.MinValue, UInt16.MaxValue))
1532 return new UShortConstant ((ushort) v);
1534 if (target_type == TypeManager.int32_type) {
1535 if (!CheckRange (ec, v, target_type, Int32.MinValue, Int32.MaxValue))
1537 return new IntConstant ((int) v);
1539 if (target_type == TypeManager.uint32_type) {
1540 if (!CheckRange (ec, v, target_type, UInt32.MinValue, UInt32.MaxValue))
1542 return new UIntConstant ((uint) v);
1544 if (target_type == TypeManager.uint64_type) {
1545 if (!CheckUnsigned (ec, v, target_type))
1547 return new ULongConstant ((ulong) v);
1549 if (target_type == TypeManager.float_type)
1550 return new FloatConstant ((float) v);
1551 if (target_type == TypeManager.double_type)
1552 return new DoubleConstant ((double) v);
1553 if (target_type == TypeManager.char_type) {
1554 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1556 return new CharConstant ((char) v);
1558 if (target_type == TypeManager.decimal_type)
1559 return new DecimalConstant ((decimal) v);
1561 if (real_expr is ULongConstant){
1562 ulong v = ((ULongConstant) real_expr).Value;
1564 if (target_type == TypeManager.byte_type) {
1565 if (!CheckRange (ec, v, target_type, Byte.MaxValue))
1567 return new ByteConstant ((byte) v);
1569 if (target_type == TypeManager.sbyte_type) {
1570 if (!CheckRange (ec, v, target_type, (ulong) SByte.MaxValue))
1572 return new SByteConstant ((sbyte) v);
1574 if (target_type == TypeManager.short_type) {
1575 if (!CheckRange (ec, v, target_type, (ulong) Int16.MaxValue))
1577 return new ShortConstant ((short) v);
1579 if (target_type == TypeManager.ushort_type) {
1580 if (!CheckRange (ec, v, target_type, UInt16.MaxValue))
1582 return new UShortConstant ((ushort) v);
1584 if (target_type == TypeManager.int32_type) {
1585 if (!CheckRange (ec, v, target_type, Int32.MaxValue))
1587 return new IntConstant ((int) v);
1589 if (target_type == TypeManager.uint32_type) {
1590 if (!CheckRange (ec, v, target_type, UInt32.MaxValue))
1592 return new UIntConstant ((uint) v);
1594 if (target_type == TypeManager.int64_type) {
1595 if (!CheckRange (ec, v, target_type, (ulong) Int64.MaxValue))
1597 return new LongConstant ((long) v);
1599 if (target_type == TypeManager.float_type)
1600 return new FloatConstant ((float) v);
1601 if (target_type == TypeManager.double_type)
1602 return new DoubleConstant ((double) v);
1603 if (target_type == TypeManager.char_type) {
1604 if (!CheckRange (ec, v, target_type, Char.MaxValue))
1606 return new CharConstant ((char) v);
1608 if (target_type == TypeManager.decimal_type)
1609 return new DecimalConstant ((decimal) v);
1611 if (real_expr is FloatConstant){
1612 float v = ((FloatConstant) real_expr).Value;
1614 if (target_type == TypeManager.byte_type)
1615 return new ByteConstant ((byte) v);
1616 if (target_type == TypeManager.sbyte_type)
1617 return new SByteConstant ((sbyte) v);
1618 if (target_type == TypeManager.short_type)
1619 return new ShortConstant ((short) v);
1620 if (target_type == TypeManager.ushort_type)
1621 return new UShortConstant ((ushort) v);
1622 if (target_type == TypeManager.int32_type)
1623 return new IntConstant ((int) v);
1624 if (target_type == TypeManager.uint32_type)
1625 return new UIntConstant ((uint) v);
1626 if (target_type == TypeManager.int64_type)
1627 return new LongConstant ((long) v);
1628 if (target_type == TypeManager.uint64_type)
1629 return new ULongConstant ((ulong) v);
1630 if (target_type == TypeManager.double_type)
1631 return new DoubleConstant ((double) v);
1632 if (target_type == TypeManager.char_type)
1633 return new CharConstant ((char) v);
1634 if (target_type == TypeManager.decimal_type)
1635 return new DecimalConstant ((decimal) v);
1637 if (real_expr is DoubleConstant){
1638 double v = ((DoubleConstant) real_expr).Value;
1640 if (target_type == TypeManager.byte_type)
1641 return new ByteConstant ((byte) v);
1642 if (target_type == TypeManager.sbyte_type)
1643 return new SByteConstant ((sbyte) v);
1644 if (target_type == TypeManager.short_type)
1645 return new ShortConstant ((short) v);
1646 if (target_type == TypeManager.ushort_type)
1647 return new UShortConstant ((ushort) v);
1648 if (target_type == TypeManager.int32_type)
1649 return new IntConstant ((int) v);
1650 if (target_type == TypeManager.uint32_type)
1651 return new UIntConstant ((uint) v);
1652 if (target_type == TypeManager.int64_type)
1653 return new LongConstant ((long) v);
1654 if (target_type == TypeManager.uint64_type)
1655 return new ULongConstant ((ulong) v);
1656 if (target_type == TypeManager.float_type)
1657 return new FloatConstant ((float) v);
1658 if (target_type == TypeManager.char_type)
1659 return new CharConstant ((char) v);
1660 if (target_type == TypeManager.decimal_type)
1661 return new DecimalConstant ((decimal) v);
1664 if (real_expr is CharConstant){
1665 char v = ((CharConstant) real_expr).Value;
1667 if (target_type == TypeManager.byte_type) {
1668 if (!CheckRange (ec, v, target_type, Byte.MinValue, Byte.MaxValue))
1670 return new ByteConstant ((byte) v);
1672 if (target_type == TypeManager.sbyte_type) {
1673 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1675 return new SByteConstant ((sbyte) v);
1677 if (target_type == TypeManager.short_type) {
1678 if (!CheckRange (ec, v, target_type, Int16.MinValue, Int16.MaxValue))
1680 return new ShortConstant ((short) v);
1682 if (target_type == TypeManager.int32_type)
1683 return new IntConstant ((int) v);
1684 if (target_type == TypeManager.uint32_type)
1685 return new UIntConstant ((uint) v);
1686 if (target_type == TypeManager.int64_type)
1687 return new LongConstant ((long) v);
1688 if (target_type == TypeManager.uint64_type)
1689 return new ULongConstant ((ulong) v);
1690 if (target_type == TypeManager.float_type)
1691 return new FloatConstant ((float) v);
1692 if (target_type == TypeManager.double_type)
1693 return new DoubleConstant ((double) v);
1694 if (target_type == TypeManager.char_type) {
1695 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1697 return new CharConstant ((char) v);
1699 if (target_type == TypeManager.decimal_type)
1700 return new DecimalConstant ((decimal) v);
1706 public override Expression DoResolve (EmitContext ec)
1708 expr = expr.Resolve (ec);
1712 int errors = Report.Errors;
1714 type = ec.DeclSpace.ResolveType (target_type, false, Location);
1719 eclass = ExprClass.Value;
1721 if (expr is Constant){
1722 Expression e = TryReduce (ec, type);
1728 expr = ConvertExplicit (ec, expr, type, loc);
1732 public override void Emit (EmitContext ec)
1735 // This one will never happen
1737 throw new Exception ("Should not happen");
1742 /// Binary operators
1744 public class Binary : Expression {
1745 public enum Operator : byte {
1746 Multiply, Division, Modulus,
1747 Addition, Subtraction,
1748 LeftShift, RightShift,
1749 LessThan, GreaterThan, LessThanOrEqual, GreaterThanOrEqual,
1750 Equality, Inequality,
1760 Expression left, right;
1763 // After resolution, method might contain the operator overload
1766 protected MethodBase method;
1767 ArrayList Arguments;
1769 bool DelegateOperation;
1771 // This must be kept in sync with Operator!!!
1772 public static readonly string [] oper_names;
1776 oper_names = new string [(int) Operator.TOP];
1778 oper_names [(int) Operator.Multiply] = "op_Multiply";
1779 oper_names [(int) Operator.Division] = "op_Division";
1780 oper_names [(int) Operator.Modulus] = "op_Modulus";
1781 oper_names [(int) Operator.Addition] = "op_Addition";
1782 oper_names [(int) Operator.Subtraction] = "op_Subtraction";
1783 oper_names [(int) Operator.LeftShift] = "op_LeftShift";
1784 oper_names [(int) Operator.RightShift] = "op_RightShift";
1785 oper_names [(int) Operator.LessThan] = "op_LessThan";
1786 oper_names [(int) Operator.GreaterThan] = "op_GreaterThan";
1787 oper_names [(int) Operator.LessThanOrEqual] = "op_LessThanOrEqual";
1788 oper_names [(int) Operator.GreaterThanOrEqual] = "op_GreaterThanOrEqual";
1789 oper_names [(int) Operator.Equality] = "op_Equality";
1790 oper_names [(int) Operator.Inequality] = "op_Inequality";
1791 oper_names [(int) Operator.BitwiseAnd] = "op_BitwiseAnd";
1792 oper_names [(int) Operator.BitwiseOr] = "op_BitwiseOr";
1793 oper_names [(int) Operator.ExclusiveOr] = "op_ExclusiveOr";
1794 oper_names [(int) Operator.LogicalOr] = "op_LogicalOr";
1795 oper_names [(int) Operator.LogicalAnd] = "op_LogicalAnd";
1798 public Binary (Operator oper, Expression left, Expression right, Location loc)
1806 public Operator Oper {
1815 public Expression Left {
1824 public Expression Right {
1835 /// Returns a stringified representation of the Operator
1837 static string OperName (Operator oper)
1840 case Operator.Multiply:
1842 case Operator.Division:
1844 case Operator.Modulus:
1846 case Operator.Addition:
1848 case Operator.Subtraction:
1850 case Operator.LeftShift:
1852 case Operator.RightShift:
1854 case Operator.LessThan:
1856 case Operator.GreaterThan:
1858 case Operator.LessThanOrEqual:
1860 case Operator.GreaterThanOrEqual:
1862 case Operator.Equality:
1864 case Operator.Inequality:
1866 case Operator.BitwiseAnd:
1868 case Operator.BitwiseOr:
1870 case Operator.ExclusiveOr:
1872 case Operator.LogicalOr:
1874 case Operator.LogicalAnd:
1878 return oper.ToString ();
1881 public override string ToString ()
1883 return "operator " + OperName (oper) + "(" + left.ToString () + ", " +
1884 right.ToString () + ")";
1887 Expression ForceConversion (EmitContext ec, Expression expr, Type target_type)
1889 if (expr.Type == target_type)
1892 return ConvertImplicit (ec, expr, target_type, loc);
1895 public static void Error_OperatorAmbiguous (Location loc, Operator oper, Type l, Type r)
1898 34, loc, "Operator `" + OperName (oper)
1899 + "' is ambiguous on operands of type `"
1900 + TypeManager.CSharpName (l) + "' "
1901 + "and `" + TypeManager.CSharpName (r)
1905 bool IsOfType (EmitContext ec, Type l, Type r, Type t, bool check_user_conversions)
1907 if ((l == t) || (r == t))
1910 if (!check_user_conversions)
1913 if (ImplicitUserConversionExists (ec, l, t))
1915 else if (ImplicitUserConversionExists (ec, r, t))
1922 // Note that handling the case l == Decimal || r == Decimal
1923 // is taken care of by the Step 1 Operator Overload resolution.
1925 // If `check_user_conv' is true, we also check whether a user-defined conversion
1926 // exists. Note that we only need to do this if both arguments are of a user-defined
1927 // type, otherwise ConvertImplict() already finds the user-defined conversion for us,
1928 // so we don't explicitly check for performance reasons.
1930 bool DoNumericPromotions (EmitContext ec, Type l, Type r, bool check_user_conv)
1932 if (IsOfType (ec, l, r, TypeManager.double_type, check_user_conv)){
1934 // If either operand is of type double, the other operand is
1935 // conveted to type double.
1937 if (r != TypeManager.double_type)
1938 right = ConvertImplicit (ec, right, TypeManager.double_type, loc);
1939 if (l != TypeManager.double_type)
1940 left = ConvertImplicit (ec, left, TypeManager.double_type, loc);
1942 type = TypeManager.double_type;
1943 } else if (IsOfType (ec, l, r, TypeManager.float_type, check_user_conv)){
1945 // if either operand is of type float, the other operand is
1946 // converted to type float.
1948 if (r != TypeManager.double_type)
1949 right = ConvertImplicit (ec, right, TypeManager.float_type, loc);
1950 if (l != TypeManager.double_type)
1951 left = ConvertImplicit (ec, left, TypeManager.float_type, loc);
1952 type = TypeManager.float_type;
1953 } else if (IsOfType (ec, l, r, TypeManager.uint64_type, check_user_conv)){
1957 // If either operand is of type ulong, the other operand is
1958 // converted to type ulong. or an error ocurrs if the other
1959 // operand is of type sbyte, short, int or long
1961 if (l == TypeManager.uint64_type){
1962 if (r != TypeManager.uint64_type){
1963 if (right is IntConstant){
1964 IntConstant ic = (IntConstant) right;
1966 e = TryImplicitIntConversion (l, ic);
1969 } else if (right is LongConstant){
1970 long ll = ((LongConstant) right).Value;
1973 right = new ULongConstant ((ulong) ll);
1975 e = ImplicitNumericConversion (ec, right, l, loc);
1982 if (left is IntConstant){
1983 e = TryImplicitIntConversion (r, (IntConstant) left);
1986 } else if (left is LongConstant){
1987 long ll = ((LongConstant) left).Value;
1990 left = new ULongConstant ((ulong) ll);
1992 e = ImplicitNumericConversion (ec, left, r, loc);
1999 if ((other == TypeManager.sbyte_type) ||
2000 (other == TypeManager.short_type) ||
2001 (other == TypeManager.int32_type) ||
2002 (other == TypeManager.int64_type))
2003 Error_OperatorAmbiguous (loc, oper, l, r);
2004 type = TypeManager.uint64_type;
2005 } else if (IsOfType (ec, l, r, TypeManager.int64_type, check_user_conv)){
2007 // If either operand is of type long, the other operand is converted
2010 if (l != TypeManager.int64_type)
2011 left = ConvertImplicit (ec, left, TypeManager.int64_type, loc);
2012 if (r != TypeManager.int64_type)
2013 right = ConvertImplicit (ec, right, TypeManager.int64_type, loc);
2015 type = TypeManager.int64_type;
2016 } else if (IsOfType (ec, l, r, TypeManager.uint32_type, check_user_conv)){
2018 // If either operand is of type uint, and the other
2019 // operand is of type sbyte, short or int, othe operands are
2020 // converted to type long.
2024 if (l == TypeManager.uint32_type){
2025 if (right is IntConstant){
2026 IntConstant ic = (IntConstant) right;
2030 right = new UIntConstant ((uint) val);
2037 else if (r == TypeManager.uint32_type){
2038 if (left is IntConstant){
2039 IntConstant ic = (IntConstant) left;
2043 left = new UIntConstant ((uint) val);
2052 if ((other == TypeManager.sbyte_type) ||
2053 (other == TypeManager.short_type) ||
2054 (other == TypeManager.int32_type)){
2055 left = ForceConversion (ec, left, TypeManager.int64_type);
2056 right = ForceConversion (ec, right, TypeManager.int64_type);
2057 type = TypeManager.int64_type;
2060 // if either operand is of type uint, the other
2061 // operand is converd to type uint
2063 left = ForceConversion (ec, left, TypeManager.uint32_type);
2064 right = ForceConversion (ec, right, TypeManager.uint32_type);
2065 type = TypeManager.uint32_type;
2067 } else if (l == TypeManager.decimal_type || r == TypeManager.decimal_type){
2068 if (l != TypeManager.decimal_type)
2069 left = ConvertImplicit (ec, left, TypeManager.decimal_type, loc);
2071 if (r != TypeManager.decimal_type)
2072 right = ConvertImplicit (ec, right, TypeManager.decimal_type, loc);
2073 type = TypeManager.decimal_type;
2075 left = ForceConversion (ec, left, TypeManager.int32_type);
2076 right = ForceConversion (ec, right, TypeManager.int32_type);
2078 type = TypeManager.int32_type;
2081 return (left != null) && (right != null);
2084 static public void Error_OperatorCannotBeApplied (Location loc, string name, Type l, Type r)
2086 Report.Error (19, loc,
2087 "Operator " + name + " cannot be applied to operands of type `" +
2088 TypeManager.CSharpName (l) + "' and `" +
2089 TypeManager.CSharpName (r) + "'");
2092 void Error_OperatorCannotBeApplied ()
2094 Error_OperatorCannotBeApplied (loc, OperName (oper), left.Type, right.Type);
2097 static bool is_32_or_64 (Type t)
2099 return (t == TypeManager.int32_type || t == TypeManager.uint32_type ||
2100 t == TypeManager.int64_type || t == TypeManager.uint64_type);
2103 static bool is_unsigned (Type t)
2105 return (t == TypeManager.uint32_type || t == TypeManager.uint64_type ||
2106 t == TypeManager.short_type || t == TypeManager.byte_type);
2109 static bool is_user_defined (Type t)
2111 if (t.IsSubclassOf (TypeManager.value_type) &&
2112 (!TypeManager.IsBuiltinType (t) || t == TypeManager.decimal_type))
2118 Expression CheckShiftArguments (EmitContext ec)
2122 Type r = right.Type;
2124 e = ForceConversion (ec, right, TypeManager.int32_type);
2126 Error_OperatorCannotBeApplied ();
2131 if (((e = ConvertImplicit (ec, left, TypeManager.int32_type, loc)) != null) ||
2132 ((e = ConvertImplicit (ec, left, TypeManager.uint32_type, loc)) != null) ||
2133 ((e = ConvertImplicit (ec, left, TypeManager.int64_type, loc)) != null) ||
2134 ((e = ConvertImplicit (ec, left, TypeManager.uint64_type, loc)) != null)){
2140 Error_OperatorCannotBeApplied ();
2144 Expression ResolveOperator (EmitContext ec)
2147 Type r = right.Type;
2149 bool overload_failed = false;
2152 // Special cases: string comapred to null
2154 if (oper == Operator.Equality || oper == Operator.Inequality){
2155 if ((l == TypeManager.string_type && (right is NullLiteral)) ||
2156 (r == TypeManager.string_type && (left is NullLiteral))){
2157 Type = TypeManager.bool_type;
2164 // Do not perform operator overload resolution when both sides are
2167 if (!(TypeManager.IsCLRType (l) && TypeManager.IsCLRType (r))){
2169 // Step 1: Perform Operator Overload location
2171 Expression left_expr, right_expr;
2173 string op = oper_names [(int) oper];
2175 MethodGroupExpr union;
2176 left_expr = MemberLookup (ec, l, op, MemberTypes.Method, AllBindingFlags, loc);
2178 right_expr = MemberLookup (
2179 ec, r, op, MemberTypes.Method, AllBindingFlags, loc);
2180 union = Invocation.MakeUnionSet (left_expr, right_expr, loc);
2182 union = (MethodGroupExpr) left_expr;
2184 if (union != null) {
2185 Arguments = new ArrayList ();
2186 Arguments.Add (new Argument (left, Argument.AType.Expression));
2187 Arguments.Add (new Argument (right, Argument.AType.Expression));
2189 method = Invocation.OverloadResolve (ec, union, Arguments, Location.Null);
2190 if (method != null) {
2191 MethodInfo mi = (MethodInfo) method;
2193 type = mi.ReturnType;
2196 overload_failed = true;
2202 // Step 2: Default operations on CLI native types.
2206 // Step 0: String concatenation (because overloading will get this wrong)
2208 if (oper == Operator.Addition){
2210 // If any of the arguments is a string, cast to string
2213 if (l == TypeManager.string_type){
2215 if (r == TypeManager.void_type) {
2216 Error_OperatorCannotBeApplied ();
2220 if (r == TypeManager.string_type){
2221 if (left is Constant && right is Constant){
2222 StringConstant ls = (StringConstant) left;
2223 StringConstant rs = (StringConstant) right;
2225 return new StringConstant (
2226 ls.Value + rs.Value);
2229 if (left is Binary){
2230 Binary b = (Binary) left;
2233 // Call String.Concat (string, string, string) or
2234 // String.Concat (string, string, string, string)
2237 if (b.oper == Operator.Addition &&
2238 (b.method == TypeManager.string_concat_string_string_string ||
2239 b.method == TypeManager.string_concat_string_string_string_string)){
2240 ArrayList bargs = b.Arguments;
2241 int count = bargs.Count;
2245 Arguments.Add (new Argument (right, Argument.AType.Expression));
2246 type = TypeManager.string_type;
2247 method = TypeManager.string_concat_string_string_string;
2250 } else if (count == 3){
2252 Arguments.Add (new Argument (right, Argument.AType.Expression));
2253 type = TypeManager.string_type;
2254 method = TypeManager.string_concat_string_string_string_string;
2261 method = TypeManager.string_concat_string_string;
2264 method = TypeManager.string_concat_object_object;
2265 right = ConvertImplicit (ec, right,
2266 TypeManager.object_type, loc);
2268 Error_OperatorCannotBeApplied (loc, OperName (oper), l, r);
2272 type = TypeManager.string_type;
2274 Arguments = new ArrayList ();
2275 Arguments.Add (new Argument (left, Argument.AType.Expression));
2276 Arguments.Add (new Argument (right, Argument.AType.Expression));
2280 } else if (r == TypeManager.string_type){
2283 if (l == TypeManager.void_type) {
2284 Error_OperatorCannotBeApplied ();
2288 method = TypeManager.string_concat_object_object;
2289 left = ConvertImplicit (ec, left, TypeManager.object_type, loc);
2291 Error_OperatorCannotBeApplied (loc, OperName (oper), l, r);
2294 Arguments = new ArrayList ();
2295 Arguments.Add (new Argument (left, Argument.AType.Expression));
2296 Arguments.Add (new Argument (right, Argument.AType.Expression));
2298 type = TypeManager.string_type;
2304 // Transform a + ( - b) into a - b
2306 if (right is Unary){
2307 Unary right_unary = (Unary) right;
2309 if (right_unary.Oper == Unary.Operator.UnaryNegation){
2310 oper = Operator.Subtraction;
2311 right = right_unary.Expr;
2317 if (oper == Operator.Equality || oper == Operator.Inequality){
2318 if (l == TypeManager.bool_type || r == TypeManager.bool_type){
2319 if (r != TypeManager.bool_type || l != TypeManager.bool_type){
2320 Error_OperatorCannotBeApplied ();
2324 type = TypeManager.bool_type;
2329 // operator != (object a, object b)
2330 // operator == (object a, object b)
2332 // For this to be used, both arguments have to be reference-types.
2333 // Read the rationale on the spec (14.9.6)
2335 // Also, if at compile time we know that the classes do not inherit
2336 // one from the other, then we catch the error there.
2338 if (!(l.IsValueType || r.IsValueType)){
2339 type = TypeManager.bool_type;
2344 if (l.IsSubclassOf (r) || r.IsSubclassOf (l))
2348 // Also, a standard conversion must exist from either one
2350 if (!(StandardConversionExists (left, r) ||
2351 StandardConversionExists (right, l))){
2352 Error_OperatorCannotBeApplied ();
2356 // We are going to have to convert to an object to compare
2358 if (l != TypeManager.object_type)
2359 left = new EmptyCast (left, TypeManager.object_type);
2360 if (r != TypeManager.object_type)
2361 right = new EmptyCast (right, TypeManager.object_type);
2364 // FIXME: CSC here catches errors cs254 and cs252
2370 // One of them is a valuetype, but the other one is not.
2372 if (!l.IsValueType || !r.IsValueType) {
2373 Error_OperatorCannotBeApplied ();
2378 // Only perform numeric promotions on:
2379 // +, -, *, /, %, &, |, ^, ==, !=, <, >, <=, >=
2381 if (oper == Operator.Addition || oper == Operator.Subtraction) {
2382 if (l.IsSubclassOf (TypeManager.delegate_type) &&
2383 r.IsSubclassOf (TypeManager.delegate_type)) {
2385 Arguments = new ArrayList ();
2386 Arguments.Add (new Argument (left, Argument.AType.Expression));
2387 Arguments.Add (new Argument (right, Argument.AType.Expression));
2389 if (oper == Operator.Addition)
2390 method = TypeManager.delegate_combine_delegate_delegate;
2392 method = TypeManager.delegate_remove_delegate_delegate;
2395 Error_OperatorCannotBeApplied ();
2399 DelegateOperation = true;
2405 // Pointer arithmetic:
2407 // T* operator + (T* x, int y);
2408 // T* operator + (T* x, uint y);
2409 // T* operator + (T* x, long y);
2410 // T* operator + (T* x, ulong y);
2412 // T* operator + (int y, T* x);
2413 // T* operator + (uint y, T *x);
2414 // T* operator + (long y, T *x);
2415 // T* operator + (ulong y, T *x);
2417 // T* operator - (T* x, int y);
2418 // T* operator - (T* x, uint y);
2419 // T* operator - (T* x, long y);
2420 // T* operator - (T* x, ulong y);
2422 // long operator - (T* x, T *y)
2425 if (r.IsPointer && oper == Operator.Subtraction){
2427 return new PointerArithmetic (
2428 false, left, right, TypeManager.int64_type,
2430 } else if (is_32_or_64 (r))
2431 return new PointerArithmetic (
2432 oper == Operator.Addition, left, right, l, loc);
2433 } else if (r.IsPointer && is_32_or_64 (l) && oper == Operator.Addition)
2434 return new PointerArithmetic (
2435 true, right, left, r, loc);
2439 // Enumeration operators
2441 bool lie = TypeManager.IsEnumType (l);
2442 bool rie = TypeManager.IsEnumType (r);
2446 // U operator - (E e, E f)
2447 if (lie && rie && oper == Operator.Subtraction){
2449 type = TypeManager.EnumToUnderlying (l);
2452 Error_OperatorCannotBeApplied ();
2457 // operator + (E e, U x)
2458 // operator - (E e, U x)
2460 if (oper == Operator.Addition || oper == Operator.Subtraction){
2461 Type enum_type = lie ? l : r;
2462 Type other_type = lie ? r : l;
2463 Type underlying_type = TypeManager.EnumToUnderlying (enum_type);
2466 if (underlying_type != other_type){
2467 Error_OperatorCannotBeApplied ();
2476 temp = ConvertImplicit (ec, right, l, loc);
2480 Error_OperatorCannotBeApplied ();
2484 temp = ConvertImplicit (ec, left, r, loc);
2489 Error_OperatorCannotBeApplied ();
2494 if (oper == Operator.Equality || oper == Operator.Inequality ||
2495 oper == Operator.LessThanOrEqual || oper == Operator.LessThan ||
2496 oper == Operator.GreaterThanOrEqual || oper == Operator.GreaterThan){
2497 if (left.Type != right.Type){
2498 Error_OperatorCannotBeApplied ();
2501 type = TypeManager.bool_type;
2505 if (oper == Operator.BitwiseAnd ||
2506 oper == Operator.BitwiseOr ||
2507 oper == Operator.ExclusiveOr){
2511 Error_OperatorCannotBeApplied ();
2515 if (oper == Operator.LeftShift || oper == Operator.RightShift)
2516 return CheckShiftArguments (ec);
2518 if (oper == Operator.LogicalOr || oper == Operator.LogicalAnd){
2519 if (l != TypeManager.bool_type || r != TypeManager.bool_type){
2520 Error_OperatorCannotBeApplied ();
2524 type = TypeManager.bool_type;
2529 // operator & (bool x, bool y)
2530 // operator | (bool x, bool y)
2531 // operator ^ (bool x, bool y)
2533 if (l == TypeManager.bool_type && r == TypeManager.bool_type){
2534 if (oper == Operator.BitwiseAnd ||
2535 oper == Operator.BitwiseOr ||
2536 oper == Operator.ExclusiveOr){
2543 // Pointer comparison
2545 if (l.IsPointer && r.IsPointer){
2546 if (oper == Operator.Equality || oper == Operator.Inequality ||
2547 oper == Operator.LessThan || oper == Operator.LessThanOrEqual ||
2548 oper == Operator.GreaterThan || oper == Operator.GreaterThanOrEqual){
2549 type = TypeManager.bool_type;
2555 // We are dealing with numbers
2557 if (overload_failed){
2558 Error_OperatorCannotBeApplied ();
2563 // This will leave left or right set to null if there is an error
2565 bool check_user_conv = is_user_defined (l) && is_user_defined (r);
2566 DoNumericPromotions (ec, l, r, check_user_conv);
2567 if (left == null || right == null){
2568 Error_OperatorCannotBeApplied (loc, OperName (oper), l, r);
2573 // reload our cached types if required
2578 if (oper == Operator.BitwiseAnd ||
2579 oper == Operator.BitwiseOr ||
2580 oper == Operator.ExclusiveOr){
2582 if (!((l == TypeManager.int32_type) ||
2583 (l == TypeManager.uint32_type) ||
2584 (l == TypeManager.int64_type) ||
2585 (l == TypeManager.uint64_type)))
2588 Error_OperatorCannotBeApplied ();
2593 if (oper == Operator.Equality ||
2594 oper == Operator.Inequality ||
2595 oper == Operator.LessThanOrEqual ||
2596 oper == Operator.LessThan ||
2597 oper == Operator.GreaterThanOrEqual ||
2598 oper == Operator.GreaterThan){
2599 type = TypeManager.bool_type;
2605 public override Expression DoResolve (EmitContext ec)
2607 left = left.Resolve (ec);
2608 right = right.Resolve (ec);
2610 if (left == null || right == null)
2613 eclass = ExprClass.Value;
2615 Constant rc = right as Constant;
2616 Constant lc = left as Constant;
2618 if (rc != null & lc != null){
2619 Expression e = ConstantFold.BinaryFold (
2620 ec, oper, lc, rc, loc);
2625 return ResolveOperator (ec);
2629 /// EmitBranchable is called from Statement.EmitBoolExpression in the
2630 /// context of a conditional bool expression. This function will return
2631 /// false if it is was possible to use EmitBranchable, or true if it was.
2633 /// The expression's code is generated, and we will generate a branch to `target'
2634 /// if the resulting expression value is equal to isTrue
2636 public bool EmitBranchable (EmitContext ec, Label target, bool onTrue)
2641 ILGenerator ig = ec.ig;
2644 // This is more complicated than it looks, but its just to avoid
2645 // duplicated tests: basically, we allow ==, !=, >, <, >= and <=
2646 // but on top of that we want for == and != to use a special path
2647 // if we are comparing against null
2649 if (oper == Operator.Equality || oper == Operator.Inequality){
2650 bool my_on_true = oper == Operator.Inequality ? onTrue : !onTrue;
2652 if (left is NullLiteral){
2655 ig.Emit (OpCodes.Brtrue, target);
2657 ig.Emit (OpCodes.Brfalse, target);
2659 } else if (right is NullLiteral){
2662 ig.Emit (OpCodes.Brtrue, target);
2664 ig.Emit (OpCodes.Brfalse, target);
2666 } else if (left is BoolConstant){
2668 if (my_on_true != ((BoolConstant) left).Value)
2669 ig.Emit (OpCodes.Brtrue, target);
2671 ig.Emit (OpCodes.Brfalse, target);
2673 } else if (right is BoolConstant){
2675 if (my_on_true != ((BoolConstant) right).Value)
2676 ig.Emit (OpCodes.Brtrue, target);
2678 ig.Emit (OpCodes.Brfalse, target);
2682 } else if (oper == Operator.LogicalAnd){
2683 if (left is Binary){
2684 Binary left_binary = (Binary) left;
2687 Label tests_end = ig.DefineLabel ();
2689 if (left_binary.EmitBranchable (ec, tests_end, false)){
2690 if (right is Binary){
2691 Binary right_binary = (Binary) right;
2693 if (right_binary.EmitBranchable (ec, target, true)){
2694 ig.MarkLabel (tests_end);
2699 ig.Emit (OpCodes.Brtrue, target);
2700 ig.MarkLabel (tests_end);
2704 if (left_binary.EmitBranchable (ec, target, false)){
2705 if (right is Binary){
2706 Binary right_binary = (Binary) right;
2708 if (right_binary.EmitBranchable (ec, target, false))
2713 ig.Emit (OpCodes.Brtrue, target);
2715 ig.Emit (OpCodes.Brfalse, target);
2720 // Give up, and let the regular Emit work, but we could
2721 // also optimize the left-non-Branchable, but-right-Branchable
2725 } else if (oper == Operator.LogicalOr){
2726 if (left is Binary){
2727 Binary left_binary = (Binary) left;
2730 if (left_binary.EmitBranchable (ec, target, true)){
2731 if (right is Binary){
2732 Binary right_binary = (Binary) right;
2734 if (right_binary.EmitBranchable (ec, target, true))
2738 ig.Emit (OpCodes.Brtrue, target);
2743 // Give up, and let the regular Emit work, but we could
2744 // also optimize the left-non-Branchable, but-right-Branchable
2747 Label tests_end = ig.DefineLabel ();
2749 if (left_binary.EmitBranchable (ec, tests_end, true)){
2750 if (right is Binary){
2751 Binary right_binary = (Binary) right;
2753 if (right_binary.EmitBranchable (ec, target, false)){
2754 ig.MarkLabel (tests_end);
2759 ig.Emit (OpCodes.Brfalse, target);
2760 ig.MarkLabel (tests_end);
2767 } else if (!(oper == Operator.LessThan ||
2768 oper == Operator.GreaterThan ||
2769 oper == Operator.LessThanOrEqual ||
2770 oper == Operator.GreaterThanOrEqual))
2777 bool isUnsigned = is_unsigned (t);
2780 case Operator.Equality:
2782 ig.Emit (OpCodes.Beq, target);
2784 ig.Emit (OpCodes.Bne_Un, target);
2787 case Operator.Inequality:
2789 ig.Emit (OpCodes.Bne_Un, target);
2791 ig.Emit (OpCodes.Beq, target);
2794 case Operator.LessThan:
2797 ig.Emit (OpCodes.Blt_Un, target);
2799 ig.Emit (OpCodes.Blt, target);
2802 ig.Emit (OpCodes.Bge_Un, target);
2804 ig.Emit (OpCodes.Bge, target);
2807 case Operator.GreaterThan:
2810 ig.Emit (OpCodes.Bgt_Un, target);
2812 ig.Emit (OpCodes.Bgt, target);
2815 ig.Emit (OpCodes.Ble_Un, target);
2817 ig.Emit (OpCodes.Ble, target);
2820 case Operator.LessThanOrEqual:
2821 if (t == TypeManager.double_type || t == TypeManager.float_type)
2826 ig.Emit (OpCodes.Ble_Un, target);
2828 ig.Emit (OpCodes.Ble, target);
2831 ig.Emit (OpCodes.Bgt_Un, target);
2833 ig.Emit (OpCodes.Bgt, target);
2837 case Operator.GreaterThanOrEqual:
2838 if (t == TypeManager.double_type || t == TypeManager.float_type)
2842 ig.Emit (OpCodes.Bge_Un, target);
2844 ig.Emit (OpCodes.Bge, target);
2847 ig.Emit (OpCodes.Blt_Un, target);
2849 ig.Emit (OpCodes.Blt, target);
2859 public override void Emit (EmitContext ec)
2861 ILGenerator ig = ec.ig;
2863 Type r = right.Type;
2866 if (method != null) {
2868 // Note that operators are static anyway
2870 if (Arguments != null)
2871 Invocation.EmitArguments (ec, method, Arguments);
2873 if (method is MethodInfo)
2874 ig.Emit (OpCodes.Call, (MethodInfo) method);
2876 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
2878 if (DelegateOperation)
2879 ig.Emit (OpCodes.Castclass, type);
2885 // Handle short-circuit operators differently
2888 if (oper == Operator.LogicalAnd){
2889 Label load_zero = ig.DefineLabel ();
2890 Label end = ig.DefineLabel ();
2891 bool process = true;
2893 if (left is Binary){
2894 Binary left_binary = (Binary) left;
2896 if (left_binary.EmitBranchable (ec, load_zero, false)){
2898 ig.Emit (OpCodes.Br, end);
2905 ig.Emit (OpCodes.Brfalse, load_zero);
2907 ig.Emit (OpCodes.Br, end);
2909 ig.MarkLabel (load_zero);
2910 ig.Emit (OpCodes.Ldc_I4_0);
2913 } else if (oper == Operator.LogicalOr){
2914 Label load_one = ig.DefineLabel ();
2915 Label end = ig.DefineLabel ();
2916 bool process = true;
2918 if (left is Binary){
2919 Binary left_binary = (Binary) left;
2921 if (left_binary.EmitBranchable (ec, load_one, true)){
2923 ig.Emit (OpCodes.Br, end);
2930 ig.Emit (OpCodes.Brtrue, load_one);
2932 ig.Emit (OpCodes.Br, end);
2934 ig.MarkLabel (load_one);
2935 ig.Emit (OpCodes.Ldc_I4_1);
2943 bool isUnsigned = is_unsigned (left.Type);
2946 case Operator.Multiply:
2948 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
2949 opcode = OpCodes.Mul_Ovf;
2950 else if (isUnsigned)
2951 opcode = OpCodes.Mul_Ovf_Un;
2953 opcode = OpCodes.Mul;
2955 opcode = OpCodes.Mul;
2959 case Operator.Division:
2961 opcode = OpCodes.Div_Un;
2963 opcode = OpCodes.Div;
2966 case Operator.Modulus:
2968 opcode = OpCodes.Rem_Un;
2970 opcode = OpCodes.Rem;
2973 case Operator.Addition:
2975 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
2976 opcode = OpCodes.Add_Ovf;
2977 else if (isUnsigned)
2978 opcode = OpCodes.Add_Ovf_Un;
2980 opcode = OpCodes.Add;
2982 opcode = OpCodes.Add;
2985 case Operator.Subtraction:
2987 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
2988 opcode = OpCodes.Sub_Ovf;
2989 else if (isUnsigned)
2990 opcode = OpCodes.Sub_Ovf_Un;
2992 opcode = OpCodes.Sub;
2994 opcode = OpCodes.Sub;
2997 case Operator.RightShift:
2999 opcode = OpCodes.Shr_Un;
3001 opcode = OpCodes.Shr;
3004 case Operator.LeftShift:
3005 opcode = OpCodes.Shl;
3008 case Operator.Equality:
3009 opcode = OpCodes.Ceq;
3012 case Operator.Inequality:
3013 ig.Emit (OpCodes.Ceq);
3014 ig.Emit (OpCodes.Ldc_I4_0);
3016 opcode = OpCodes.Ceq;
3019 case Operator.LessThan:
3021 opcode = OpCodes.Clt_Un;
3023 opcode = OpCodes.Clt;
3026 case Operator.GreaterThan:
3028 opcode = OpCodes.Cgt_Un;
3030 opcode = OpCodes.Cgt;
3033 case Operator.LessThanOrEqual:
3034 Type lt = left.Type;
3036 if (isUnsigned || (lt == TypeManager.double_type || lt == TypeManager.float_type))
3037 ig.Emit (OpCodes.Cgt_Un);
3039 ig.Emit (OpCodes.Cgt);
3040 ig.Emit (OpCodes.Ldc_I4_0);
3042 opcode = OpCodes.Ceq;
3045 case Operator.GreaterThanOrEqual:
3046 Type le = left.Type;
3048 if (isUnsigned || (le == TypeManager.double_type || le == TypeManager.float_type))
3049 ig.Emit (OpCodes.Clt_Un);
3051 ig.Emit (OpCodes.Clt);
3053 ig.Emit (OpCodes.Ldc_I4_1);
3055 opcode = OpCodes.Sub;
3058 case Operator.BitwiseOr:
3059 opcode = OpCodes.Or;
3062 case Operator.BitwiseAnd:
3063 opcode = OpCodes.And;
3066 case Operator.ExclusiveOr:
3067 opcode = OpCodes.Xor;
3071 throw new Exception ("This should not happen: Operator = "
3072 + oper.ToString ());
3078 public bool IsBuiltinOperator {
3080 return method == null;
3085 public class PointerArithmetic : Expression {
3086 Expression left, right;
3090 // We assume that `l' is always a pointer
3092 public PointerArithmetic (bool is_addition, Expression l, Expression r, Type t,
3096 eclass = ExprClass.Variable;
3100 is_add = is_addition;
3103 public override Expression DoResolve (EmitContext ec)
3106 // We are born fully resolved
3111 public override void Emit (EmitContext ec)
3113 Type op_type = left.Type;
3114 ILGenerator ig = ec.ig;
3115 int size = GetTypeSize (op_type.GetElementType ());
3117 if (right.Type.IsPointer){
3119 // handle (pointer - pointer)
3123 ig.Emit (OpCodes.Sub);
3127 ig.Emit (OpCodes.Sizeof, op_type);
3129 IntLiteral.EmitInt (ig, size);
3130 ig.Emit (OpCodes.Div);
3132 ig.Emit (OpCodes.Conv_I8);
3135 // handle + and - on (pointer op int)
3138 ig.Emit (OpCodes.Conv_I);
3142 ig.Emit (OpCodes.Sizeof, op_type);
3144 IntLiteral.EmitInt (ig, size);
3145 ig.Emit (OpCodes.Mul);
3148 ig.Emit (OpCodes.Add);
3150 ig.Emit (OpCodes.Sub);
3156 /// Implements the ternary conditional operator (?:)
3158 public class Conditional : Expression {
3159 Expression expr, trueExpr, falseExpr;
3161 public Conditional (Expression expr, Expression trueExpr, Expression falseExpr, Location l)
3164 this.trueExpr = trueExpr;
3165 this.falseExpr = falseExpr;
3169 public Expression Expr {
3175 public Expression TrueExpr {
3181 public Expression FalseExpr {
3187 public override Expression DoResolve (EmitContext ec)
3189 expr = expr.Resolve (ec);
3194 if (expr.Type != TypeManager.bool_type){
3195 expr = Expression.ResolveBoolean (
3202 trueExpr = trueExpr.Resolve (ec);
3203 falseExpr = falseExpr.Resolve (ec);
3205 if (trueExpr == null || falseExpr == null)
3208 eclass = ExprClass.Value;
3209 if (trueExpr.Type == falseExpr.Type)
3210 type = trueExpr.Type;
3213 Type true_type = trueExpr.Type;
3214 Type false_type = falseExpr.Type;
3216 if (trueExpr is NullLiteral){
3219 } else if (falseExpr is NullLiteral){
3225 // First, if an implicit conversion exists from trueExpr
3226 // to falseExpr, then the result type is of type falseExpr.Type
3228 conv = ConvertImplicit (ec, trueExpr, false_type, loc);
3231 // Check if both can convert implicitl to each other's type
3233 if (ConvertImplicit (ec, falseExpr, true_type, loc) != null){
3235 "Can not compute type of conditional expression " +
3236 "as `" + TypeManager.CSharpName (trueExpr.Type) +
3237 "' and `" + TypeManager.CSharpName (falseExpr.Type) +
3238 "' convert implicitly to each other");
3243 } else if ((conv = ConvertImplicit(ec, falseExpr, true_type,loc))!= null){
3247 Error (173, "The type of the conditional expression can " +
3248 "not be computed because there is no implicit conversion" +
3249 " from `" + TypeManager.CSharpName (trueExpr.Type) + "'" +
3250 " and `" + TypeManager.CSharpName (falseExpr.Type) + "'");
3255 if (expr is BoolConstant){
3256 BoolConstant bc = (BoolConstant) expr;
3267 public override void Emit (EmitContext ec)
3269 ILGenerator ig = ec.ig;
3270 Label false_target = ig.DefineLabel ();
3271 Label end_target = ig.DefineLabel ();
3273 Statement.EmitBoolExpression (ec, expr, false_target, false);
3275 ig.Emit (OpCodes.Br, end_target);
3276 ig.MarkLabel (false_target);
3277 falseExpr.Emit (ec);
3278 ig.MarkLabel (end_target);
3286 public class LocalVariableReference : Expression, IAssignMethod, IMemoryLocation, IVariable {
3287 public readonly string Name;
3288 public readonly Block Block;
3289 VariableInfo variable_info;
3292 public LocalVariableReference (Block block, string name, Location l)
3297 eclass = ExprClass.Variable;
3300 // Setting `is_readonly' to false will allow you to create a writable
3301 // reference to a read-only variable. This is used by foreach and using.
3302 public LocalVariableReference (Block block, string name, Location l,
3303 VariableInfo variable_info, bool is_readonly)
3304 : this (block, name, l)
3306 this.variable_info = variable_info;
3307 this.is_readonly = is_readonly;
3310 public VariableInfo VariableInfo {
3312 if (variable_info == null) {
3313 variable_info = Block.GetVariableInfo (Name);
3314 is_readonly = variable_info.ReadOnly;
3316 return variable_info;
3320 public bool IsAssigned (EmitContext ec, Location loc)
3322 return VariableInfo.IsAssigned (ec, loc);
3325 public bool IsFieldAssigned (EmitContext ec, string name, Location loc)
3327 return VariableInfo.IsFieldAssigned (ec, name, loc);
3330 public void SetAssigned (EmitContext ec)
3332 VariableInfo.SetAssigned (ec);
3335 public void SetFieldAssigned (EmitContext ec, string name)
3337 VariableInfo.SetFieldAssigned (ec, name);
3340 public bool IsReadOnly {
3342 if (variable_info == null) {
3343 variable_info = Block.GetVariableInfo (Name);
3344 is_readonly = variable_info.ReadOnly;
3350 public override Expression DoResolve (EmitContext ec)
3352 VariableInfo vi = VariableInfo;
3355 e = Block.GetConstantExpression (Name);
3358 type = vi.VariableType;
3359 eclass = ExprClass.Value;
3363 if (ec.DoFlowAnalysis && !IsAssigned (ec, loc))
3366 type = vi.VariableType;
3370 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
3372 VariableInfo vi = VariableInfo;
3374 if (ec.DoFlowAnalysis)
3375 ec.SetVariableAssigned (vi);
3377 Expression e = DoResolve (ec);
3383 Error (1604, "cannot assign to `" + Name + "' because it is readonly");
3390 public override void Emit (EmitContext ec)
3392 VariableInfo vi = VariableInfo;
3393 ILGenerator ig = ec.ig;
3395 if (vi.LocalBuilder == null){
3397 ig.Emit (OpCodes.Ldfld, vi.FieldBuilder);
3399 ig.Emit (OpCodes.Ldloc, vi.LocalBuilder);
3404 public void EmitAssign (EmitContext ec, Expression source)
3406 ILGenerator ig = ec.ig;
3407 VariableInfo vi = VariableInfo;
3411 if (vi.LocalBuilder == null){
3414 ig.Emit (OpCodes.Stfld, vi.FieldBuilder);
3417 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3421 public void AddressOf (EmitContext ec, AddressOp mode)
3423 VariableInfo vi = VariableInfo;
3425 if (vi.LocalBuilder == null){
3427 ec.ig.Emit (OpCodes.Ldflda, vi.FieldBuilder);
3429 ec.ig.Emit (OpCodes.Ldloca, vi.LocalBuilder);
3434 /// This represents a reference to a parameter in the intermediate
3437 public class ParameterReference : Expression, IAssignMethod, IMemoryLocation, IVariable {
3441 public Parameter.Modifier mod;
3442 public bool is_ref, is_out;
3444 public ParameterReference (Parameters pars, int idx, string name, Location loc)
3450 eclass = ExprClass.Variable;
3453 public bool IsAssigned (EmitContext ec, Location loc)
3455 if (!is_out || !ec.DoFlowAnalysis)
3458 if (!ec.CurrentBranching.IsParameterAssigned (idx)) {
3459 Report.Error (165, loc,
3460 "Use of unassigned local variable `" + name + "'");
3467 public bool IsFieldAssigned (EmitContext ec, string field_name, Location loc)
3469 if (!is_out || !ec.DoFlowAnalysis)
3472 if (ec.CurrentBranching.IsParameterAssigned (idx))
3475 if (!ec.CurrentBranching.IsParameterAssigned (idx, field_name)) {
3476 Report.Error (170, loc,
3477 "Use of possibly unassigned field `" + field_name + "'");
3484 public void SetAssigned (EmitContext ec)
3486 if (is_out && ec.DoFlowAnalysis)
3487 ec.CurrentBranching.SetParameterAssigned (idx);
3490 public void SetFieldAssigned (EmitContext ec, string field_name)
3492 if (is_out && ec.DoFlowAnalysis)
3493 ec.CurrentBranching.SetParameterAssigned (idx, field_name);
3497 // Notice that for ref/out parameters, the type exposed is not the
3498 // same type exposed externally.
3501 // externally we expose "int&"
3502 // here we expose "int".
3504 // We record this in "is_ref". This means that the type system can treat
3505 // the type as it is expected, but when we generate the code, we generate
3506 // the alternate kind of code.
3508 public override Expression DoResolve (EmitContext ec)
3510 type = pars.GetParameterInfo (ec.DeclSpace, idx, out mod);
3511 is_ref = (mod & Parameter.Modifier.ISBYREF) != 0;
3512 is_out = (mod & Parameter.Modifier.OUT) != 0;
3513 eclass = ExprClass.Variable;
3515 if (is_out && ec.DoFlowAnalysis && !IsAssigned (ec, loc))
3521 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
3523 type = pars.GetParameterInfo (ec.DeclSpace, idx, out mod);
3524 is_ref = (mod & Parameter.Modifier.ISBYREF) != 0;
3525 is_out = (mod & Parameter.Modifier.OUT) != 0;
3526 eclass = ExprClass.Variable;
3528 if (is_out && ec.DoFlowAnalysis)
3529 ec.SetParameterAssigned (idx);
3534 static public void EmitLdArg (ILGenerator ig, int x)
3538 case 0: ig.Emit (OpCodes.Ldarg_0); break;
3539 case 1: ig.Emit (OpCodes.Ldarg_1); break;
3540 case 2: ig.Emit (OpCodes.Ldarg_2); break;
3541 case 3: ig.Emit (OpCodes.Ldarg_3); break;
3542 default: ig.Emit (OpCodes.Ldarg_S, (byte) x); break;
3545 ig.Emit (OpCodes.Ldarg, x);
3549 // This method is used by parameters that are references, that are
3550 // being passed as references: we only want to pass the pointer (that
3551 // is already stored in the parameter, not the address of the pointer,
3552 // and not the value of the variable).
3554 public void EmitLoad (EmitContext ec)
3556 ILGenerator ig = ec.ig;
3562 EmitLdArg (ig, arg_idx);
3565 public override void Emit (EmitContext ec)
3567 ILGenerator ig = ec.ig;
3569 if (ec.RemapToProxy){
3570 ig.Emit (OpCodes.Ldarg_0);
3571 ec.EmitArgument (idx);
3580 EmitLdArg (ig, arg_idx);
3586 // If we are a reference, we loaded on the stack a pointer
3587 // Now lets load the real value
3589 LoadFromPtr (ig, type);
3592 public void EmitAssign (EmitContext ec, Expression source)
3594 ILGenerator ig = ec.ig;
3596 if (ec.RemapToProxy){
3597 ig.Emit (OpCodes.Ldarg_0);
3599 ec.EmitStoreArgument (idx);
3609 EmitLdArg (ig, arg_idx);
3614 StoreFromPtr (ig, type);
3617 ig.Emit (OpCodes.Starg_S, (byte) arg_idx);
3619 ig.Emit (OpCodes.Starg, arg_idx);
3623 public void AddressOf (EmitContext ec, AddressOp mode)
3625 if (ec.RemapToProxy){
3626 Report.Error (-1, "Report this: Taking the address of a remapped parameter not supported");
3637 ec.ig.Emit (OpCodes.Ldarg_S, (byte) arg_idx);
3639 ec.ig.Emit (OpCodes.Ldarg, arg_idx);
3642 ec.ig.Emit (OpCodes.Ldarga_S, (byte) arg_idx);
3644 ec.ig.Emit (OpCodes.Ldarga, arg_idx);
3651 /// Used for arguments to New(), Invocation()
3653 public class Argument {
3654 public enum AType : byte {
3660 public readonly AType ArgType;
3661 public Expression Expr;
3663 public Argument (Expression expr, AType type)
3666 this.ArgType = type;
3671 if (ArgType == AType.Ref || ArgType == AType.Out)
3672 return TypeManager.GetReferenceType (Expr.Type);
3678 public Parameter.Modifier GetParameterModifier ()
3682 return Parameter.Modifier.OUT | Parameter.Modifier.ISBYREF;
3685 return Parameter.Modifier.REF | Parameter.Modifier.ISBYREF;
3688 return Parameter.Modifier.NONE;
3692 public static string FullDesc (Argument a)
3694 return (a.ArgType == AType.Ref ? "ref " :
3695 (a.ArgType == AType.Out ? "out " : "")) +
3696 TypeManager.CSharpName (a.Expr.Type);
3699 public bool ResolveMethodGroup (EmitContext ec, Location loc)
3701 // FIXME: csc doesn't report any error if you try to use `ref' or
3702 // `out' in a delegate creation expression.
3703 Expr = Expr.Resolve (ec, ResolveFlags.VariableOrValue | ResolveFlags.MethodGroup);
3710 public bool Resolve (EmitContext ec, Location loc)
3712 if (ArgType == AType.Ref) {
3713 Expr = Expr.Resolve (ec);
3717 Expr = Expr.ResolveLValue (ec, Expr);
3718 } else if (ArgType == AType.Out)
3719 Expr = Expr.ResolveLValue (ec, new EmptyExpression ());
3721 Expr = Expr.Resolve (ec);
3726 if (ArgType == AType.Expression)
3729 if (Expr.eclass != ExprClass.Variable){
3731 // We just probe to match the CSC output
3733 if (Expr.eclass == ExprClass.PropertyAccess ||
3734 Expr.eclass == ExprClass.IndexerAccess){
3737 "A property or indexer can not be passed as an out or ref " +
3742 "An lvalue is required as an argument to out or ref");
3750 public void Emit (EmitContext ec)
3753 // Ref and Out parameters need to have their addresses taken.
3755 // ParameterReferences might already be references, so we want
3756 // to pass just the value
3758 if (ArgType == AType.Ref || ArgType == AType.Out){
3759 AddressOp mode = AddressOp.Store;
3761 if (ArgType == AType.Ref)
3762 mode |= AddressOp.Load;
3764 if (Expr is ParameterReference){
3765 ParameterReference pr = (ParameterReference) Expr;
3771 pr.AddressOf (ec, mode);
3774 ((IMemoryLocation)Expr).AddressOf (ec, mode);
3781 /// Invocation of methods or delegates.
3783 public class Invocation : ExpressionStatement {
3784 public readonly ArrayList Arguments;
3787 MethodBase method = null;
3790 static Hashtable method_parameter_cache;
3792 static Invocation ()
3794 method_parameter_cache = new PtrHashtable ();
3798 // arguments is an ArrayList, but we do not want to typecast,
3799 // as it might be null.
3801 // FIXME: only allow expr to be a method invocation or a
3802 // delegate invocation (7.5.5)
3804 public Invocation (Expression expr, ArrayList arguments, Location l)
3807 Arguments = arguments;
3811 public Expression Expr {
3818 /// Returns the Parameters (a ParameterData interface) for the
3821 public static ParameterData GetParameterData (MethodBase mb)
3823 object pd = method_parameter_cache [mb];
3827 return (ParameterData) pd;
3830 ip = TypeManager.LookupParametersByBuilder (mb);
3832 method_parameter_cache [mb] = ip;
3834 return (ParameterData) ip;
3836 ParameterInfo [] pi = mb.GetParameters ();
3837 ReflectionParameters rp = new ReflectionParameters (pi);
3838 method_parameter_cache [mb] = rp;
3840 return (ParameterData) rp;
3845 /// Determines "better conversion" as specified in 7.4.2.3
3846 /// Returns : 1 if a->p is better
3847 /// 0 if a->q or neither is better
3849 static int BetterConversion (EmitContext ec, Argument a, Type p, Type q, Location loc)
3851 Type argument_type = a.Type;
3852 Expression argument_expr = a.Expr;
3854 if (argument_type == null)
3855 throw new Exception ("Expression of type " + a.Expr + " does not resolve its type");
3858 // This is a special case since csc behaves this way. I can't find
3859 // it anywhere in the spec but oh well ...
3861 if (argument_expr is NullLiteral && p == TypeManager.string_type && q == TypeManager.object_type)
3863 else if (argument_expr is NullLiteral && p == TypeManager.object_type && q == TypeManager.string_type)
3869 if (argument_type == p)
3872 if (argument_type == q)
3876 // Now probe whether an implicit constant expression conversion
3879 // An implicit constant expression conversion permits the following
3882 // * A constant-expression of type `int' can be converted to type
3883 // sbyte, byute, short, ushort, uint, ulong provided the value of
3884 // of the expression is withing the range of the destination type.
3886 // * A constant-expression of type long can be converted to type
3887 // ulong, provided the value of the constant expression is not negative
3889 // FIXME: Note that this assumes that constant folding has
3890 // taken place. We dont do constant folding yet.
3893 if (argument_expr is IntConstant){
3894 IntConstant ei = (IntConstant) argument_expr;
3895 int value = ei.Value;
3897 if (p == TypeManager.sbyte_type){
3898 if (value >= SByte.MinValue && value <= SByte.MaxValue)
3900 } else if (p == TypeManager.byte_type){
3901 if (q == TypeManager.sbyte_type &&
3902 value >= SByte.MinValue && value <= SByte.MaxValue)
3904 else if (Byte.MinValue >= 0 && value <= Byte.MaxValue)
3906 } else if (p == TypeManager.short_type){
3907 if (value >= Int16.MinValue && value <= Int16.MaxValue)
3909 } else if (p == TypeManager.ushort_type){
3910 if (q == TypeManager.short_type &&
3911 value >= Int16.MinValue && value <= Int16.MaxValue)
3913 else if (value >= UInt16.MinValue && value <= UInt16.MaxValue)
3915 } else if (p == TypeManager.int32_type){
3916 if (value >= Int32.MinValue && value <= Int32.MaxValue)
3918 } else if (p == TypeManager.uint32_type){
3920 // we can optimize this case: a positive int32
3921 // always fits on a uint32
3925 } else if (p == TypeManager.uint64_type){
3927 // we can optimize this case: a positive int32
3928 // always fits on a uint64
3930 if (q == TypeManager.int64_type)
3932 else if (value >= 0)
3934 } else if (p == TypeManager.int64_type){
3937 } else if (argument_type == TypeManager.int64_type && argument_expr is LongConstant){
3938 LongConstant lc = (LongConstant) argument_expr;
3940 if (p == TypeManager.uint64_type){
3947 Expression tmp = ConvertImplicit (ec, argument_expr, p, loc);
3955 Expression p_tmp = new EmptyExpression (p);
3956 Expression q_tmp = new EmptyExpression (q);
3958 if (ImplicitConversionExists (ec, p_tmp, q) == true &&
3959 ImplicitConversionExists (ec, q_tmp, p) == false)
3962 if (p == TypeManager.sbyte_type)
3963 if (q == TypeManager.byte_type || q == TypeManager.ushort_type ||
3964 q == TypeManager.uint32_type || q == TypeManager.uint64_type)
3967 if (p == TypeManager.short_type)
3968 if (q == TypeManager.ushort_type || q == TypeManager.uint32_type ||
3969 q == TypeManager.uint64_type)
3972 if (p == TypeManager.int32_type)
3973 if (q == TypeManager.uint32_type || q == TypeManager.uint64_type)
3976 if (p == TypeManager.int64_type)
3977 if (q == TypeManager.uint64_type)
3984 /// Determines "Better function"
3987 /// and returns an integer indicating :
3988 /// 0 if candidate ain't better
3989 /// 1 if candidate is better than the current best match
3991 static int BetterFunction (EmitContext ec, ArrayList args,
3992 MethodBase candidate, MethodBase best,
3993 bool expanded_form, Location loc)
3995 ParameterData candidate_pd = GetParameterData (candidate);
3996 ParameterData best_pd;
4002 argument_count = args.Count;
4004 int cand_count = candidate_pd.Count;
4006 if (cand_count == 0 && argument_count == 0)
4009 if (candidate_pd.ParameterModifier (cand_count - 1) != Parameter.Modifier.PARAMS)
4010 if (cand_count != argument_count)
4016 if (argument_count == 0 && cand_count == 1 &&
4017 candidate_pd.ParameterModifier (cand_count - 1) == Parameter.Modifier.PARAMS)
4020 for (int j = argument_count; j > 0;) {
4023 Argument a = (Argument) args [j];
4024 Type t = candidate_pd.ParameterType (j);
4026 if (candidate_pd.ParameterModifier (j) == Parameter.Modifier.PARAMS)
4028 t = t.GetElementType ();
4030 x = BetterConversion (ec, a, t, null, loc);
4042 best_pd = GetParameterData (best);
4044 int rating1 = 0, rating2 = 0;
4046 for (int j = 0; j < argument_count; ++j) {
4049 Argument a = (Argument) args [j];
4051 Type ct = candidate_pd.ParameterType (j);
4052 Type bt = best_pd.ParameterType (j);
4054 if (candidate_pd.ParameterModifier (j) == Parameter.Modifier.PARAMS)
4056 ct = ct.GetElementType ();
4058 if (best_pd.ParameterModifier (j) == Parameter.Modifier.PARAMS)
4060 bt = bt.GetElementType ();
4062 x = BetterConversion (ec, a, ct, bt, loc);
4063 y = BetterConversion (ec, a, bt, ct, loc);
4072 if (rating1 > rating2)
4078 public static string FullMethodDesc (MethodBase mb)
4080 string ret_type = "";
4082 if (mb is MethodInfo)
4083 ret_type = TypeManager.CSharpName (((MethodInfo) mb).ReturnType);
4085 StringBuilder sb = new StringBuilder (ret_type);
4087 sb.Append (mb.ReflectedType.ToString ());
4089 sb.Append (mb.Name);
4091 ParameterData pd = GetParameterData (mb);
4093 int count = pd.Count;
4096 for (int i = count; i > 0; ) {
4099 sb.Append (pd.ParameterDesc (count - i - 1));
4105 return sb.ToString ();
4108 public static MethodGroupExpr MakeUnionSet (Expression mg1, Expression mg2, Location loc)
4110 MemberInfo [] miset;
4111 MethodGroupExpr union;
4116 return (MethodGroupExpr) mg2;
4119 return (MethodGroupExpr) mg1;
4122 MethodGroupExpr left_set = null, right_set = null;
4123 int length1 = 0, length2 = 0;
4125 left_set = (MethodGroupExpr) mg1;
4126 length1 = left_set.Methods.Length;
4128 right_set = (MethodGroupExpr) mg2;
4129 length2 = right_set.Methods.Length;
4131 ArrayList common = new ArrayList ();
4133 foreach (MethodBase l in left_set.Methods){
4134 foreach (MethodBase r in right_set.Methods){
4142 miset = new MemberInfo [length1 + length2 - common.Count];
4143 left_set.Methods.CopyTo (miset, 0);
4147 foreach (MemberInfo mi in right_set.Methods){
4148 if (!common.Contains (mi))
4152 union = new MethodGroupExpr (miset, loc);
4158 /// Determines is the candidate method, if a params method, is applicable
4159 /// in its expanded form to the given set of arguments
4161 static bool IsParamsMethodApplicable (EmitContext ec, ArrayList arguments, MethodBase candidate)
4165 if (arguments == null)
4168 arg_count = arguments.Count;
4170 ParameterData pd = GetParameterData (candidate);
4172 int pd_count = pd.Count;
4177 if (pd.ParameterModifier (pd_count - 1) != Parameter.Modifier.PARAMS)
4180 if (pd_count - 1 > arg_count)
4183 if (pd_count == 1 && arg_count == 0)
4187 // If we have come this far, the case which remains is when the number of parameters
4188 // is less than or equal to the argument count.
4190 for (int i = 0; i < pd_count - 1; ++i) {
4192 Argument a = (Argument) arguments [i];
4194 Parameter.Modifier a_mod = a.GetParameterModifier () &
4195 ~(Parameter.Modifier.OUT | Parameter.Modifier.REF);
4196 Parameter.Modifier p_mod = pd.ParameterModifier (i) &
4197 ~(Parameter.Modifier.OUT | Parameter.Modifier.REF);
4199 if (a_mod == p_mod) {
4201 if (a_mod == Parameter.Modifier.NONE)
4202 if (!ImplicitConversionExists (ec, a.Expr, pd.ParameterType (i)))
4205 if ((a_mod & Parameter.Modifier.ISBYREF) != 0) {
4206 Type pt = pd.ParameterType (i);
4209 pt = TypeManager.GetReferenceType (pt);
4219 Type element_type = pd.ParameterType (pd_count - 1).GetElementType ();
4221 for (int i = pd_count - 1; i < arg_count; i++) {
4222 Argument a = (Argument) arguments [i];
4224 if (!StandardConversionExists (a.Expr, element_type))
4232 /// Determines if the candidate method is applicable (section 14.4.2.1)
4233 /// to the given set of arguments
4235 static bool IsApplicable (EmitContext ec, ArrayList arguments, MethodBase candidate)
4239 if (arguments == null)
4242 arg_count = arguments.Count;
4244 ParameterData pd = GetParameterData (candidate);
4246 int pd_count = pd.Count;
4248 if (arg_count != pd.Count)
4251 for (int i = arg_count; i > 0; ) {
4254 Argument a = (Argument) arguments [i];
4256 Parameter.Modifier a_mod = a.GetParameterModifier () &
4257 ~(Parameter.Modifier.OUT | Parameter.Modifier.REF);
4258 Parameter.Modifier p_mod = pd.ParameterModifier (i) &
4259 ~(Parameter.Modifier.OUT | Parameter.Modifier.REF);
4261 if (a_mod == p_mod ||
4262 (a_mod == Parameter.Modifier.NONE && p_mod == Parameter.Modifier.PARAMS)) {
4263 if (a_mod == Parameter.Modifier.NONE)
4264 if (!ImplicitConversionExists (ec, a.Expr, pd.ParameterType (i)))
4267 if ((a_mod & Parameter.Modifier.ISBYREF) != 0) {
4268 Type pt = pd.ParameterType (i);
4271 pt = TypeManager.GetReferenceType (pt);
4286 /// Find the Applicable Function Members (7.4.2.1)
4288 /// me: Method Group expression with the members to select.
4289 /// it might contain constructors or methods (or anything
4290 /// that maps to a method).
4292 /// Arguments: ArrayList containing resolved Argument objects.
4294 /// loc: The location if we want an error to be reported, or a Null
4295 /// location for "probing" purposes.
4297 /// Returns: The MethodBase (either a ConstructorInfo or a MethodInfo)
4298 /// that is the best match of me on Arguments.
4301 public static MethodBase OverloadResolve (EmitContext ec, MethodGroupExpr me,
4302 ArrayList Arguments, Location loc)
4304 MethodBase method = null;
4305 Type current_type = null;
4307 ArrayList candidates = new ArrayList ();
4310 foreach (MethodBase candidate in me.Methods){
4313 // If we're going one level higher in the class hierarchy, abort if
4314 // we already found an applicable method.
4315 if (candidate.DeclaringType != current_type) {
4316 current_type = candidate.DeclaringType;
4321 // Check if candidate is applicable (section 14.4.2.1)
4322 if (!IsApplicable (ec, Arguments, candidate))
4325 candidates.Add (candidate);
4326 x = BetterFunction (ec, Arguments, candidate, method, false, loc);
4334 if (Arguments == null)
4337 argument_count = Arguments.Count;
4340 // Now we see if we can find params functions, applicable in their expanded form
4341 // since if they were applicable in their normal form, they would have been selected
4344 bool chose_params_expanded = false;
4346 if (method == null) {
4347 candidates = new ArrayList ();
4348 foreach (MethodBase candidate in me.Methods){
4349 if (!IsParamsMethodApplicable (ec, Arguments, candidate))
4352 candidates.Add (candidate);
4354 int x = BetterFunction (ec, Arguments, candidate, method, true, loc);
4359 chose_params_expanded = true;
4363 if (method == null) {
4365 // Okay so we have failed to find anything so we
4366 // return by providing info about the closest match
4368 for (int i = 0; i < me.Methods.Length; ++i) {
4370 MethodBase c = (MethodBase) me.Methods [i];
4371 ParameterData pd = GetParameterData (c);
4373 if (pd.Count != argument_count)
4376 VerifyArgumentsCompat (ec, Arguments, argument_count, c, false,
4384 // Now check that there are no ambiguities i.e the selected method
4385 // should be better than all the others
4388 foreach (MethodBase candidate in candidates){
4389 if (candidate == method)
4393 // If a normal method is applicable in the sense that it has the same
4394 // number of arguments, then the expanded params method is never applicable
4395 // so we debar the params method.
4397 if (IsParamsMethodApplicable (ec, Arguments, candidate) &&
4398 IsApplicable (ec, Arguments, method))
4401 int x = BetterFunction (ec, Arguments, method, candidate,
4402 chose_params_expanded, loc);
4407 "Ambiguous call when selecting function due to implicit casts");
4413 // And now check if the arguments are all compatible, perform conversions
4414 // if necessary etc. and return if everything is all right
4417 if (!VerifyArgumentsCompat (ec, Arguments, argument_count, method,
4418 chose_params_expanded, null, loc))
4424 static void Error_InvalidArguments (Location loc, int idx, MethodBase method, Type delegate_type, string arg_sig, string par_desc)
4426 if (delegate_type == null)
4427 Report.Error (1502, loc,
4428 "The best overloaded match for method '" +
4429 FullMethodDesc (method) +
4430 "' has some invalid arguments");
4432 Report.Error (1594, loc,
4433 "Delegate '" + delegate_type.ToString () +
4434 "' has some invalid arguments.");
4435 Report.Error (1503, loc,
4436 String.Format ("Argument {0}: Cannot convert from '{1}' to '{2}'",
4437 idx, arg_sig, par_desc));
4440 public static bool VerifyArgumentsCompat (EmitContext ec, ArrayList Arguments,
4443 bool chose_params_expanded,
4447 ParameterData pd = GetParameterData (method);
4448 int pd_count = pd.Count;
4450 for (int j = 0; j < argument_count; j++) {
4451 Argument a = (Argument) Arguments [j];
4452 Expression a_expr = a.Expr;
4453 Type parameter_type = pd.ParameterType (j);
4454 Parameter.Modifier pm = pd.ParameterModifier (j);
4456 if (pm == Parameter.Modifier.PARAMS){
4457 if (chose_params_expanded)
4458 parameter_type = TypeManager.TypeToCoreType (parameter_type.GetElementType ());
4463 if (pd.ParameterModifier (j) != a.GetParameterModifier ()){
4464 if (!Location.IsNull (loc))
4465 Error_InvalidArguments (
4466 loc, j, method, delegate_type,
4467 Argument.FullDesc (a), pd.ParameterDesc (j));
4475 if (a.Type != parameter_type){
4478 conv = ConvertImplicit (ec, a_expr, parameter_type, loc);
4481 if (!Location.IsNull (loc))
4482 Error_InvalidArguments (
4483 loc, j, method, delegate_type,
4484 Argument.FullDesc (a), pd.ParameterDesc (j));
4489 // Update the argument with the implicit conversion
4495 Parameter.Modifier a_mod = a.GetParameterModifier () &
4496 ~(Parameter.Modifier.OUT | Parameter.Modifier.REF);
4497 Parameter.Modifier p_mod = pd.ParameterModifier (j) &
4498 ~(Parameter.Modifier.OUT | Parameter.Modifier.REF);
4501 if (a_mod != p_mod &&
4502 pd.ParameterModifier (pd_count - 1) != Parameter.Modifier.PARAMS) {
4503 if (!Location.IsNull (loc)) {
4504 Console.WriteLine ("A:P: " + a.GetParameterModifier ());
4505 Console.WriteLine ("PP:: " + pd.ParameterModifier (j));
4506 Console.WriteLine ("PT: " + parameter_type.IsByRef);
4507 Report.Error (1502, loc,
4508 "The best overloaded match for method '" + FullMethodDesc (method)+
4509 "' has some invalid arguments");
4510 Report.Error (1503, loc,
4511 "Argument " + (j+1) +
4512 ": Cannot convert from '" + Argument.FullDesc (a)
4513 + "' to '" + pd.ParameterDesc (j) + "'");
4523 public override Expression DoResolve (EmitContext ec)
4526 // First, resolve the expression that is used to
4527 // trigger the invocation
4529 if (expr is BaseAccess)
4532 Expression old = expr;
4534 expr = expr.Resolve (ec, ResolveFlags.VariableOrValue | ResolveFlags.MethodGroup);
4538 if (!(expr is MethodGroupExpr)) {
4539 Type expr_type = expr.Type;
4541 if (expr_type != null){
4542 bool IsDelegate = TypeManager.IsDelegateType (expr_type);
4544 return (new DelegateInvocation (
4545 this.expr, Arguments, loc)).Resolve (ec);
4549 if (!(expr is MethodGroupExpr)){
4550 expr.Error_UnexpectedKind (ResolveFlags.MethodGroup);
4555 // Next, evaluate all the expressions in the argument list
4557 if (Arguments != null){
4558 foreach (Argument a in Arguments){
4559 if (!a.Resolve (ec, loc))
4564 MethodGroupExpr mg = (MethodGroupExpr) expr;
4565 method = OverloadResolve (ec, mg, Arguments, loc);
4567 if (method == null){
4569 "Could not find any applicable function for this argument list");
4573 MethodInfo mi = method as MethodInfo;
4575 type = TypeManager.TypeToCoreType (mi.ReturnType);
4576 if (!mi.IsStatic && !mg.IsExplicitImpl && (mg.InstanceExpression == null))
4577 SimpleName.Error_ObjectRefRequired (ec, loc, mi.Name);
4580 if (type.IsPointer){
4588 // Only base will allow this invocation to happen.
4590 if (is_base && method.IsAbstract){
4591 Report.Error (205, loc, "Cannot call an abstract base member: " +
4592 FullMethodDesc (method));
4596 if ((method.Attributes & MethodAttributes.SpecialName) != 0){
4597 if (TypeManager.IsSpecialMethod (method))
4598 Report.Error (571, loc, method.Name + ": can not call operator or accessor");
4601 eclass = ExprClass.Value;
4606 // Emits the list of arguments as an array
4608 static void EmitParams (EmitContext ec, int idx, ArrayList arguments)
4610 ILGenerator ig = ec.ig;
4611 int count = arguments.Count - idx;
4612 Argument a = (Argument) arguments [idx];
4613 Type t = a.Expr.Type;
4614 string array_type = t.FullName + "[]";
4617 array = ig.DeclareLocal (TypeManager.LookupType (array_type));
4618 IntConstant.EmitInt (ig, count);
4619 ig.Emit (OpCodes.Newarr, TypeManager.TypeToCoreType (t));
4620 ig.Emit (OpCodes.Stloc, array);
4622 int top = arguments.Count;
4623 for (int j = idx; j < top; j++){
4624 a = (Argument) arguments [j];
4626 ig.Emit (OpCodes.Ldloc, array);
4627 IntConstant.EmitInt (ig, j - idx);
4630 OpCode op = ArrayAccess.GetStoreOpcode (t, out is_stobj);
4632 ig.Emit (OpCodes.Ldelema, t);
4637 ig.Emit (OpCodes.Stobj, t);
4641 ig.Emit (OpCodes.Ldloc, array);
4645 /// Emits a list of resolved Arguments that are in the arguments
4648 /// The MethodBase argument might be null if the
4649 /// emission of the arguments is known not to contain
4650 /// a `params' field (for example in constructors or other routines
4651 /// that keep their arguments in this structure)
4653 public static void EmitArguments (EmitContext ec, MethodBase mb, ArrayList arguments)
4657 pd = GetParameterData (mb);
4662 // If we are calling a params method with no arguments, special case it
4664 if (arguments == null){
4665 if (pd != null && pd.Count > 0 &&
4666 pd.ParameterModifier (0) == Parameter.Modifier.PARAMS){
4667 ILGenerator ig = ec.ig;
4669 IntConstant.EmitInt (ig, 0);
4670 ig.Emit (OpCodes.Newarr, pd.ParameterType (0).GetElementType ());
4676 int top = arguments.Count;
4678 for (int i = 0; i < top; i++){
4679 Argument a = (Argument) arguments [i];
4682 if (pd.ParameterModifier (i) == Parameter.Modifier.PARAMS){
4684 // Special case if we are passing the same data as the
4685 // params argument, do not put it in an array.
4687 if (pd.ParameterType (i) == a.Type)
4690 EmitParams (ec, i, arguments);
4698 if (pd != null && pd.Count > top &&
4699 pd.ParameterModifier (top) == Parameter.Modifier.PARAMS){
4700 ILGenerator ig = ec.ig;
4702 IntConstant.EmitInt (ig, 0);
4703 ig.Emit (OpCodes.Newarr, pd.ParameterType (top).GetElementType ());
4708 /// is_base tells whether we want to force the use of the `call'
4709 /// opcode instead of using callvirt. Call is required to call
4710 /// a specific method, while callvirt will always use the most
4711 /// recent method in the vtable.
4713 /// is_static tells whether this is an invocation on a static method
4715 /// instance_expr is an expression that represents the instance
4716 /// it must be non-null if is_static is false.
4718 /// method is the method to invoke.
4720 /// Arguments is the list of arguments to pass to the method or constructor.
4722 public static void EmitCall (EmitContext ec, bool is_base,
4723 bool is_static, Expression instance_expr,
4724 MethodBase method, ArrayList Arguments, Location loc)
4726 ILGenerator ig = ec.ig;
4727 bool struct_call = false;
4729 Type decl_type = method.DeclaringType;
4731 if (!RootContext.StdLib) {
4732 // Replace any calls to the system's System.Array type with calls to
4733 // the newly created one.
4734 if (method == TypeManager.system_int_array_get_length)
4735 method = TypeManager.int_array_get_length;
4736 else if (method == TypeManager.system_int_array_get_rank)
4737 method = TypeManager.int_array_get_rank;
4738 else if (method == TypeManager.system_object_array_clone)
4739 method = TypeManager.object_array_clone;
4740 else if (method == TypeManager.system_int_array_get_length_int)
4741 method = TypeManager.int_array_get_length_int;
4742 else if (method == TypeManager.system_int_array_get_lower_bound_int)
4743 method = TypeManager.int_array_get_lower_bound_int;
4744 else if (method == TypeManager.system_int_array_get_upper_bound_int)
4745 method = TypeManager.int_array_get_upper_bound_int;
4746 else if (method == TypeManager.system_void_array_copyto_array_int)
4747 method = TypeManager.void_array_copyto_array_int;
4751 // This checks the `ConditionalAttribute' on the method, and the
4752 // ObsoleteAttribute
4754 TypeManager.MethodFlags flags = TypeManager.GetMethodFlags (method, loc);
4755 if ((flags & TypeManager.MethodFlags.IsObsoleteError) != 0)
4757 if ((flags & TypeManager.MethodFlags.ShouldIgnore) != 0)
4761 if (decl_type.IsValueType)
4764 // If this is ourselves, push "this"
4766 if (instance_expr == null){
4767 ig.Emit (OpCodes.Ldarg_0);
4770 // Push the instance expression
4772 if (instance_expr.Type.IsValueType){
4774 // Special case: calls to a function declared in a
4775 // reference-type with a value-type argument need
4776 // to have their value boxed.
4779 if (decl_type.IsValueType){
4781 // If the expression implements IMemoryLocation, then
4782 // we can optimize and use AddressOf on the
4785 // If not we have to use some temporary storage for
4787 if (instance_expr is IMemoryLocation){
4788 ((IMemoryLocation)instance_expr).
4789 AddressOf (ec, AddressOp.LoadStore);
4792 Type t = instance_expr.Type;
4794 instance_expr.Emit (ec);
4795 LocalBuilder temp = ig.DeclareLocal (t);
4796 ig.Emit (OpCodes.Stloc, temp);
4797 ig.Emit (OpCodes.Ldloca, temp);
4800 instance_expr.Emit (ec);
4801 ig.Emit (OpCodes.Box, instance_expr.Type);
4804 instance_expr.Emit (ec);
4808 EmitArguments (ec, method, Arguments);
4810 if (is_static || struct_call || is_base){
4811 if (method is MethodInfo) {
4812 ig.Emit (OpCodes.Call, (MethodInfo) method);
4814 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
4816 if (method is MethodInfo)
4817 ig.Emit (OpCodes.Callvirt, (MethodInfo) method);
4819 ig.Emit (OpCodes.Callvirt, (ConstructorInfo) method);
4823 public override void Emit (EmitContext ec)
4825 MethodGroupExpr mg = (MethodGroupExpr) this.expr;
4827 EmitCall (ec, is_base, method.IsStatic, mg.InstanceExpression, method, Arguments, loc);
4830 public override void EmitStatement (EmitContext ec)
4835 // Pop the return value if there is one
4837 if (method is MethodInfo){
4838 Type ret = ((MethodInfo)method).ReturnType;
4839 if (TypeManager.TypeToCoreType (ret) != TypeManager.void_type)
4840 ec.ig.Emit (OpCodes.Pop);
4846 // This class is used to "disable" the code generation for the
4847 // temporary variable when initializing value types.
4849 class EmptyAddressOf : EmptyExpression, IMemoryLocation {
4850 public void AddressOf (EmitContext ec, AddressOp Mode)
4857 /// Implements the new expression
4859 public class New : ExpressionStatement, IMemoryLocation {
4860 public readonly ArrayList Arguments;
4861 public readonly Expression RequestedType;
4863 MethodBase method = null;
4866 // If set, the new expression is for a value_target, and
4867 // we will not leave anything on the stack.
4869 Expression value_target;
4870 bool value_target_set = false;
4872 public New (Expression requested_type, ArrayList arguments, Location l)
4874 RequestedType = requested_type;
4875 Arguments = arguments;
4879 public Expression ValueTypeVariable {
4881 return value_target;
4885 value_target = value;
4886 value_target_set = true;
4891 // This function is used to disable the following code sequence for
4892 // value type initialization:
4894 // AddressOf (temporary)
4898 // Instead the provide will have provided us with the address on the
4899 // stack to store the results.
4901 static Expression MyEmptyExpression;
4903 public void DisableTemporaryValueType ()
4905 if (MyEmptyExpression == null)
4906 MyEmptyExpression = new EmptyAddressOf ();
4909 // To enable this, look into:
4910 // test-34 and test-89 and self bootstrapping.
4912 // For instance, we can avoid a copy by using `newobj'
4913 // instead of Call + Push-temp on value types.
4914 // value_target = MyEmptyExpression;
4917 public override Expression DoResolve (EmitContext ec)
4920 // The New DoResolve might be called twice when initializing field
4921 // expressions (see EmitFieldInitializers, the call to
4922 // GetInitializerExpression will perform a resolve on the expression,
4923 // and later the assign will trigger another resolution
4925 // This leads to bugs (#37014)
4930 type = ec.DeclSpace.ResolveType (RequestedType, false, loc);
4935 bool IsDelegate = TypeManager.IsDelegateType (type);
4938 return (new NewDelegate (type, Arguments, loc)).Resolve (ec);
4940 if (type.IsInterface || type.IsAbstract){
4941 Error (144, "It is not possible to create instances of interfaces or abstract classes");
4945 bool is_struct = false;
4946 is_struct = type.IsValueType;
4947 eclass = ExprClass.Value;
4950 // SRE returns a match for .ctor () on structs (the object constructor),
4951 // so we have to manually ignore it.
4953 if (is_struct && Arguments == null)
4957 ml = MemberLookupFinal (ec, null, type, ".ctor",
4958 MemberTypes.Constructor,
4959 AllBindingFlags | BindingFlags.DeclaredOnly, loc);
4964 if (! (ml is MethodGroupExpr)){
4966 ml.Error_UnexpectedKind ("method group");
4972 if (Arguments != null){
4973 foreach (Argument a in Arguments){
4974 if (!a.Resolve (ec, loc))
4979 method = Invocation.OverloadResolve (ec, (MethodGroupExpr) ml,
4984 if (method == null) {
4985 if (!is_struct || Arguments.Count > 0) {
4986 Error (1501, String.Format (
4987 "New invocation: Can not find a constructor in `{0}' for this argument list",
4988 TypeManager.CSharpName (type)));
4996 // This DoEmit can be invoked in two contexts:
4997 // * As a mechanism that will leave a value on the stack (new object)
4998 // * As one that wont (init struct)
5000 // You can control whether a value is required on the stack by passing
5001 // need_value_on_stack. The code *might* leave a value on the stack
5002 // so it must be popped manually
5004 // If we are dealing with a ValueType, we have a few
5005 // situations to deal with:
5007 // * The target is a ValueType, and we have been provided
5008 // the instance (this is easy, we are being assigned).
5010 // * The target of New is being passed as an argument,
5011 // to a boxing operation or a function that takes a
5014 // In this case, we need to create a temporary variable
5015 // that is the argument of New.
5017 // Returns whether a value is left on the stack
5019 bool DoEmit (EmitContext ec, bool need_value_on_stack)
5021 bool is_value_type = type.IsValueType;
5022 ILGenerator ig = ec.ig;
5027 // Allow DoEmit() to be called multiple times.
5028 // We need to create a new LocalTemporary each time since
5029 // you can't share LocalBuilders among ILGeneators.
5030 if (!value_target_set)
5031 value_target = new LocalTemporary (ec, type);
5033 ml = (IMemoryLocation) value_target;
5034 ml.AddressOf (ec, AddressOp.Store);
5038 Invocation.EmitArguments (ec, method, Arguments);
5042 ig.Emit (OpCodes.Initobj, type);
5044 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
5045 if (need_value_on_stack){
5046 value_target.Emit (ec);
5051 ig.Emit (OpCodes.Newobj, (ConstructorInfo) method);
5056 public override void Emit (EmitContext ec)
5061 public override void EmitStatement (EmitContext ec)
5063 if (DoEmit (ec, false))
5064 ec.ig.Emit (OpCodes.Pop);
5067 public void AddressOf (EmitContext ec, AddressOp Mode)
5069 if (!type.IsValueType){
5071 // We throw an exception. So far, I believe we only need to support
5073 // foreach (int j in new StructType ())
5076 throw new Exception ("AddressOf should not be used for classes");
5079 if (!value_target_set)
5080 value_target = new LocalTemporary (ec, type);
5082 IMemoryLocation ml = (IMemoryLocation) value_target;
5083 ml.AddressOf (ec, AddressOp.Store);
5085 Invocation.EmitArguments (ec, method, Arguments);
5088 ec.ig.Emit (OpCodes.Initobj, type);
5090 ec.ig.Emit (OpCodes.Call, (ConstructorInfo) method);
5092 ((IMemoryLocation) value_target).AddressOf (ec, Mode);
5097 /// 14.5.10.2: Represents an array creation expression.
5101 /// There are two possible scenarios here: one is an array creation
5102 /// expression that specifies the dimensions and optionally the
5103 /// initialization data and the other which does not need dimensions
5104 /// specified but where initialization data is mandatory.
5106 public class ArrayCreation : ExpressionStatement {
5107 Expression requested_base_type;
5108 ArrayList initializers;
5111 // The list of Argument types.
5112 // This is used to construct the `newarray' or constructor signature
5114 ArrayList arguments;
5117 // Method used to create the array object.
5119 MethodBase new_method = null;
5121 Type array_element_type;
5122 Type underlying_type;
5123 bool is_one_dimensional = false;
5124 bool is_builtin_type = false;
5125 bool expect_initializers = false;
5126 int num_arguments = 0;
5130 ArrayList array_data;
5135 // The number of array initializers that we can handle
5136 // via the InitializeArray method - through EmitStaticInitializers
5138 int num_automatic_initializers;
5140 const int max_automatic_initializers = 6;
5142 public ArrayCreation (Expression requested_base_type, ArrayList exprs, string rank, ArrayList initializers, Location l)
5144 this.requested_base_type = requested_base_type;
5145 this.initializers = initializers;
5149 arguments = new ArrayList ();
5151 foreach (Expression e in exprs) {
5152 arguments.Add (new Argument (e, Argument.AType.Expression));
5157 public ArrayCreation (Expression requested_base_type, string rank, ArrayList initializers, Location l)
5159 this.requested_base_type = requested_base_type;
5160 this.initializers = initializers;
5164 //this.rank = rank.Substring (0, rank.LastIndexOf ("["));
5166 //string tmp = rank.Substring (rank.LastIndexOf ("["));
5168 //dimensions = tmp.Length - 1;
5169 expect_initializers = true;
5172 public Expression FormArrayType (Expression base_type, int idx_count, string rank)
5174 StringBuilder sb = new StringBuilder (rank);
5177 for (int i = 1; i < idx_count; i++)
5182 return new ComposedCast (base_type, sb.ToString (), loc);
5185 void Error_IncorrectArrayInitializer ()
5187 Error (178, "Incorrectly structured array initializer");
5190 public bool CheckIndices (EmitContext ec, ArrayList probe, int idx, bool specified_dims)
5192 if (specified_dims) {
5193 Argument a = (Argument) arguments [idx];
5195 if (!a.Resolve (ec, loc))
5198 if (!(a.Expr is Constant)) {
5199 Error (150, "A constant value is expected");
5203 int value = (int) ((Constant) a.Expr).GetValue ();
5205 if (value != probe.Count) {
5206 Error_IncorrectArrayInitializer ();
5210 bounds [idx] = value;
5213 int child_bounds = -1;
5214 foreach (object o in probe) {
5215 if (o is ArrayList) {
5216 int current_bounds = ((ArrayList) o).Count;
5218 if (child_bounds == -1)
5219 child_bounds = current_bounds;
5221 else if (child_bounds != current_bounds){
5222 Error_IncorrectArrayInitializer ();
5225 if (specified_dims && (idx + 1 >= arguments.Count)){
5226 Error (623, "Array initializers can only be used in a variable or field initializer, try using the new expression");
5230 bool ret = CheckIndices (ec, (ArrayList) o, idx + 1, specified_dims);
5234 if (child_bounds != -1){
5235 Error_IncorrectArrayInitializer ();
5239 Expression tmp = (Expression) o;
5240 tmp = tmp.Resolve (ec);
5244 // Console.WriteLine ("I got: " + tmp);
5245 // Handle initialization from vars, fields etc.
5247 Expression conv = ConvertImplicitRequired (
5248 ec, tmp, underlying_type, loc);
5253 if (conv is StringConstant)
5254 array_data.Add (conv);
5255 else if (conv is Constant) {
5256 array_data.Add (conv);
5257 num_automatic_initializers++;
5259 array_data.Add (conv);
5266 public void UpdateIndices (EmitContext ec)
5269 for (ArrayList probe = initializers; probe != null;) {
5270 if (probe.Count > 0 && probe [0] is ArrayList) {
5271 Expression e = new IntConstant (probe.Count);
5272 arguments.Add (new Argument (e, Argument.AType.Expression));
5274 bounds [i++] = probe.Count;
5276 probe = (ArrayList) probe [0];
5279 Expression e = new IntConstant (probe.Count);
5280 arguments.Add (new Argument (e, Argument.AType.Expression));
5282 bounds [i++] = probe.Count;
5289 public bool ValidateInitializers (EmitContext ec, Type array_type)
5291 if (initializers == null) {
5292 if (expect_initializers)
5298 if (underlying_type == null)
5302 // We use this to store all the date values in the order in which we
5303 // will need to store them in the byte blob later
5305 array_data = new ArrayList ();
5306 bounds = new Hashtable ();
5310 if (arguments != null) {
5311 ret = CheckIndices (ec, initializers, 0, true);
5314 arguments = new ArrayList ();
5316 ret = CheckIndices (ec, initializers, 0, false);
5323 if (arguments.Count != dimensions) {
5324 Error_IncorrectArrayInitializer ();
5332 void Error_NegativeArrayIndex ()
5334 Error (284, "Can not create array with a negative size");
5338 // Converts `source' to an int, uint, long or ulong.
5340 Expression ExpressionToArrayArgument (EmitContext ec, Expression source)
5344 bool old_checked = ec.CheckState;
5345 ec.CheckState = true;
5347 target = ConvertImplicit (ec, source, TypeManager.int32_type, loc);
5348 if (target == null){
5349 target = ConvertImplicit (ec, source, TypeManager.uint32_type, loc);
5350 if (target == null){
5351 target = ConvertImplicit (ec, source, TypeManager.int64_type, loc);
5352 if (target == null){
5353 target = ConvertImplicit (ec, source, TypeManager.uint64_type, loc);
5355 Expression.Error_CannotConvertImplicit (loc, source.Type, TypeManager.int32_type);
5359 ec.CheckState = old_checked;
5362 // Only positive constants are allowed at compile time
5364 if (target is Constant){
5365 if (target is IntConstant){
5366 if (((IntConstant) target).Value < 0){
5367 Error_NegativeArrayIndex ();
5372 if (target is LongConstant){
5373 if (((LongConstant) target).Value < 0){
5374 Error_NegativeArrayIndex ();
5385 // Creates the type of the array
5387 bool LookupType (EmitContext ec)
5389 StringBuilder array_qualifier = new StringBuilder (rank);
5392 // `In the first form allocates an array instace of the type that results
5393 // from deleting each of the individual expression from the expression list'
5395 if (num_arguments > 0) {
5396 array_qualifier.Append ("[");
5397 for (int i = num_arguments-1; i > 0; i--)
5398 array_qualifier.Append (",");
5399 array_qualifier.Append ("]");
5405 Expression array_type_expr;
5406 array_type_expr = new ComposedCast (requested_base_type, array_qualifier.ToString (), loc);
5407 type = ec.DeclSpace.ResolveType (array_type_expr, false, loc);
5412 underlying_type = type;
5413 if (underlying_type.IsArray)
5414 underlying_type = TypeManager.TypeToCoreType (underlying_type.GetElementType ());
5415 dimensions = type.GetArrayRank ();
5420 public override Expression DoResolve (EmitContext ec)
5424 if (!LookupType (ec))
5428 // First step is to validate the initializers and fill
5429 // in any missing bits
5431 if (!ValidateInitializers (ec, type))
5434 if (arguments == null)
5437 arg_count = arguments.Count;
5438 foreach (Argument a in arguments){
5439 if (!a.Resolve (ec, loc))
5442 Expression real_arg = ExpressionToArrayArgument (ec, a.Expr, loc);
5443 if (real_arg == null)
5450 array_element_type = TypeManager.TypeToCoreType (type.GetElementType ());
5452 if (arg_count == 1) {
5453 is_one_dimensional = true;
5454 eclass = ExprClass.Value;
5458 is_builtin_type = TypeManager.IsBuiltinType (type);
5460 if (is_builtin_type) {
5463 ml = MemberLookup (ec, type, ".ctor", MemberTypes.Constructor,
5464 AllBindingFlags, loc);
5466 if (!(ml is MethodGroupExpr)) {
5467 ml.Error_UnexpectedKind ("method group");
5472 Error (-6, "New invocation: Can not find a constructor for " +
5473 "this argument list");
5477 new_method = Invocation.OverloadResolve (ec, (MethodGroupExpr) ml, arguments, loc);
5479 if (new_method == null) {
5480 Error (-6, "New invocation: Can not find a constructor for " +
5481 "this argument list");
5485 eclass = ExprClass.Value;
5488 ModuleBuilder mb = CodeGen.ModuleBuilder;
5489 ArrayList args = new ArrayList ();
5491 if (arguments != null) {
5492 for (int i = 0; i < arg_count; i++)
5493 args.Add (TypeManager.int32_type);
5496 Type [] arg_types = null;
5499 arg_types = new Type [args.Count];
5501 args.CopyTo (arg_types, 0);
5503 new_method = mb.GetArrayMethod (type, ".ctor", CallingConventions.HasThis, null,
5506 if (new_method == null) {
5507 Error (-6, "New invocation: Can not find a constructor for " +
5508 "this argument list");
5512 eclass = ExprClass.Value;
5517 public static byte [] MakeByteBlob (ArrayList array_data, Type underlying_type, Location loc)
5522 int count = array_data.Count;
5524 if (underlying_type.IsEnum)
5525 underlying_type = TypeManager.EnumToUnderlying (underlying_type);
5527 factor = GetTypeSize (underlying_type);
5529 throw new Exception ("unrecognized type in MakeByteBlob: " + underlying_type);
5531 data = new byte [(count * factor + 4) & ~3];
5534 for (int i = 0; i < count; ++i) {
5535 object v = array_data [i];
5537 if (v is EnumConstant)
5538 v = ((EnumConstant) v).Child;
5540 if (v is Constant && !(v is StringConstant))
5541 v = ((Constant) v).GetValue ();
5547 if (underlying_type == TypeManager.int64_type){
5548 if (!(v is Expression)){
5549 long val = (long) v;
5551 for (int j = 0; j < factor; ++j) {
5552 data [idx + j] = (byte) (val & 0xFF);
5556 } else if (underlying_type == TypeManager.uint64_type){
5557 if (!(v is Expression)){
5558 ulong val = (ulong) v;
5560 for (int j = 0; j < factor; ++j) {
5561 data [idx + j] = (byte) (val & 0xFF);
5565 } else if (underlying_type == TypeManager.float_type) {
5566 if (!(v is Expression)){
5567 element = BitConverter.GetBytes ((float) v);
5569 for (int j = 0; j < factor; ++j)
5570 data [idx + j] = element [j];
5572 } else if (underlying_type == TypeManager.double_type) {
5573 if (!(v is Expression)){
5574 element = BitConverter.GetBytes ((double) v);
5576 for (int j = 0; j < factor; ++j)
5577 data [idx + j] = element [j];
5579 } else if (underlying_type == TypeManager.char_type){
5580 if (!(v is Expression)){
5581 int val = (int) ((char) v);
5583 data [idx] = (byte) (val & 0xff);
5584 data [idx+1] = (byte) (val >> 8);
5586 } else if (underlying_type == TypeManager.short_type){
5587 if (!(v is Expression)){
5588 int val = (int) ((short) v);
5590 data [idx] = (byte) (val & 0xff);
5591 data [idx+1] = (byte) (val >> 8);
5593 } else if (underlying_type == TypeManager.ushort_type){
5594 if (!(v is Expression)){
5595 int val = (int) ((ushort) v);
5597 data [idx] = (byte) (val & 0xff);
5598 data [idx+1] = (byte) (val >> 8);
5600 } else if (underlying_type == TypeManager.int32_type) {
5601 if (!(v is Expression)){
5604 data [idx] = (byte) (val & 0xff);
5605 data [idx+1] = (byte) ((val >> 8) & 0xff);
5606 data [idx+2] = (byte) ((val >> 16) & 0xff);
5607 data [idx+3] = (byte) (val >> 24);
5609 } else if (underlying_type == TypeManager.uint32_type) {
5610 if (!(v is Expression)){
5611 uint val = (uint) v;
5613 data [idx] = (byte) (val & 0xff);
5614 data [idx+1] = (byte) ((val >> 8) & 0xff);
5615 data [idx+2] = (byte) ((val >> 16) & 0xff);
5616 data [idx+3] = (byte) (val >> 24);
5618 } else if (underlying_type == TypeManager.sbyte_type) {
5619 if (!(v is Expression)){
5620 sbyte val = (sbyte) v;
5621 data [idx] = (byte) val;
5623 } else if (underlying_type == TypeManager.byte_type) {
5624 if (!(v is Expression)){
5625 byte val = (byte) v;
5626 data [idx] = (byte) val;
5628 } else if (underlying_type == TypeManager.bool_type) {
5629 if (!(v is Expression)){
5630 bool val = (bool) v;
5631 data [idx] = (byte) (val ? 1 : 0);
5633 } else if (underlying_type == TypeManager.decimal_type){
5634 if (!(v is Expression)){
5635 int [] bits = Decimal.GetBits ((decimal) v);
5638 for (int j = 0; j < 4; j++){
5639 data [p++] = (byte) (bits [j] & 0xff);
5640 data [p++] = (byte) ((bits [j] >> 8) & 0xff);
5641 data [p++] = (byte) ((bits [j] >> 16) & 0xff);
5642 data [p++] = (byte) (bits [j] >> 24);
5646 throw new Exception ("Unrecognized type in MakeByteBlob: " + underlying_type);
5655 // Emits the initializers for the array
5657 void EmitStaticInitializers (EmitContext ec, bool is_expression)
5660 // First, the static data
5663 ILGenerator ig = ec.ig;
5665 byte [] data = MakeByteBlob (array_data, underlying_type, loc);
5667 fb = RootContext.MakeStaticData (data);
5670 ig.Emit (OpCodes.Dup);
5671 ig.Emit (OpCodes.Ldtoken, fb);
5672 ig.Emit (OpCodes.Call,
5673 TypeManager.void_initializearray_array_fieldhandle);
5677 // Emits pieces of the array that can not be computed at compile
5678 // time (variables and string locations).
5680 // This always expect the top value on the stack to be the array
5682 void EmitDynamicInitializers (EmitContext ec, bool is_expression)
5684 ILGenerator ig = ec.ig;
5685 int dims = bounds.Count;
5686 int [] current_pos = new int [dims];
5687 int top = array_data.Count;
5688 LocalBuilder temp = ig.DeclareLocal (type);
5690 ig.Emit (OpCodes.Stloc, temp);
5692 MethodInfo set = null;
5696 ModuleBuilder mb = null;
5697 mb = CodeGen.ModuleBuilder;
5698 args = new Type [dims + 1];
5701 for (j = 0; j < dims; j++)
5702 args [j] = TypeManager.int32_type;
5704 args [j] = array_element_type;
5706 set = mb.GetArrayMethod (
5708 CallingConventions.HasThis | CallingConventions.Standard,
5709 TypeManager.void_type, args);
5712 for (int i = 0; i < top; i++){
5714 Expression e = null;
5716 if (array_data [i] is Expression)
5717 e = (Expression) array_data [i];
5721 // Basically we do this for string literals and
5722 // other non-literal expressions
5724 if (e is EnumConstant){
5725 e = ((EnumConstant) e).Child;
5728 if (e is StringConstant || !(e is Constant) ||
5729 num_automatic_initializers <= max_automatic_initializers) {
5730 Type etype = e.Type;
5732 ig.Emit (OpCodes.Ldloc, temp);
5734 for (int idx = 0; idx < dims; idx++)
5735 IntConstant.EmitInt (ig, current_pos [idx]);
5738 // If we are dealing with a struct, get the
5739 // address of it, so we can store it.
5742 etype.IsSubclassOf (TypeManager.value_type) &&
5743 (!TypeManager.IsBuiltinType (etype) ||
5744 etype == TypeManager.decimal_type)) {
5749 // Let new know that we are providing
5750 // the address where to store the results
5752 n.DisableTemporaryValueType ();
5755 ig.Emit (OpCodes.Ldelema, etype);
5761 ArrayAccess.EmitStoreOpcode (ig, array_element_type);
5763 ig.Emit (OpCodes.Call, set);
5770 for (int j = dims - 1; j >= 0; j--){
5772 if (current_pos [j] < (int) bounds [j])
5774 current_pos [j] = 0;
5779 ig.Emit (OpCodes.Ldloc, temp);
5782 void EmitArrayArguments (EmitContext ec)
5784 ILGenerator ig = ec.ig;
5786 foreach (Argument a in arguments) {
5787 Type atype = a.Type;
5790 if (atype == TypeManager.uint64_type)
5791 ig.Emit (OpCodes.Conv_Ovf_U4);
5792 else if (atype == TypeManager.int64_type)
5793 ig.Emit (OpCodes.Conv_Ovf_I4);
5797 void DoEmit (EmitContext ec, bool is_statement)
5799 ILGenerator ig = ec.ig;
5801 EmitArrayArguments (ec);
5802 if (is_one_dimensional)
5803 ig.Emit (OpCodes.Newarr, array_element_type);
5805 if (is_builtin_type)
5806 ig.Emit (OpCodes.Newobj, (ConstructorInfo) new_method);
5808 ig.Emit (OpCodes.Newobj, (MethodInfo) new_method);
5811 if (initializers != null){
5813 // FIXME: Set this variable correctly.
5815 bool dynamic_initializers = true;
5817 if (underlying_type != TypeManager.string_type &&
5818 underlying_type != TypeManager.object_type) {
5819 if (num_automatic_initializers > max_automatic_initializers)
5820 EmitStaticInitializers (ec, dynamic_initializers || !is_statement);
5823 if (dynamic_initializers)
5824 EmitDynamicInitializers (ec, !is_statement);
5828 public override void Emit (EmitContext ec)
5833 public override void EmitStatement (EmitContext ec)
5838 public object EncodeAsAttribute ()
5840 if (!is_one_dimensional){
5841 Report.Error (-211, Location, "attribute can not encode multi-dimensional arrays");
5845 if (array_data == null){
5846 Report.Error (-212, Location, "array should be initialized when passing it to an attribute");
5850 object [] ret = new object [array_data.Count];
5852 foreach (Expression e in array_data){
5855 if (e is NullLiteral)
5858 if (!Attribute.GetAttributeArgumentExpression (e, Location, out v))
5868 /// Represents the `this' construct
5870 public class This : Expression, IAssignMethod, IMemoryLocation, IVariable {
5875 public This (Block block, Location loc)
5881 public This (Location loc)
5886 public bool IsAssigned (EmitContext ec, Location loc)
5891 return vi.IsAssigned (ec, loc);
5894 public bool IsFieldAssigned (EmitContext ec, string field_name, Location loc)
5899 return vi.IsFieldAssigned (ec, field_name, loc);
5902 public void SetAssigned (EmitContext ec)
5905 vi.SetAssigned (ec);
5908 public void SetFieldAssigned (EmitContext ec, string field_name)
5911 vi.SetFieldAssigned (ec, field_name);
5914 public override Expression DoResolve (EmitContext ec)
5916 eclass = ExprClass.Variable;
5917 type = ec.ContainerType;
5920 Error (26, "Keyword this not valid in static code");
5925 vi = block.ThisVariable;
5930 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
5934 VariableInfo vi = ec.CurrentBlock.ThisVariable;
5936 vi.SetAssigned (ec);
5938 if (ec.TypeContainer is Class){
5939 Error (1604, "Cannot assign to `this'");
5946 public override void Emit (EmitContext ec)
5948 ILGenerator ig = ec.ig;
5950 ig.Emit (OpCodes.Ldarg_0);
5951 if (ec.TypeContainer is Struct)
5952 ig.Emit (OpCodes.Ldobj, type);
5955 public void EmitAssign (EmitContext ec, Expression source)
5957 ILGenerator ig = ec.ig;
5959 if (ec.TypeContainer is Struct){
5960 ig.Emit (OpCodes.Ldarg_0);
5962 ig.Emit (OpCodes.Stobj, type);
5965 ig.Emit (OpCodes.Starg, 0);
5969 public void AddressOf (EmitContext ec, AddressOp mode)
5971 ec.ig.Emit (OpCodes.Ldarg_0);
5974 // FIGURE OUT WHY LDARG_S does not work
5976 // consider: struct X { int val; int P { set { val = value; }}}
5978 // Yes, this looks very bad. Look at `NOTAS' for
5980 // ec.ig.Emit (OpCodes.Ldarga_S, (byte) 0);
5985 /// Implements the typeof operator
5987 public class TypeOf : Expression {
5988 public readonly Expression QueriedType;
5991 public TypeOf (Expression queried_type, Location l)
5993 QueriedType = queried_type;
5997 public override Expression DoResolve (EmitContext ec)
5999 typearg = ec.DeclSpace.ResolveType (QueriedType, false, loc);
6001 if (typearg == null)
6004 type = TypeManager.type_type;
6005 eclass = ExprClass.Type;
6009 public override void Emit (EmitContext ec)
6011 ec.ig.Emit (OpCodes.Ldtoken, typearg);
6012 ec.ig.Emit (OpCodes.Call, TypeManager.system_type_get_type_from_handle);
6015 public Type TypeArg {
6016 get { return typearg; }
6021 /// Implements the sizeof expression
6023 public class SizeOf : Expression {
6024 public readonly Expression QueriedType;
6027 public SizeOf (Expression queried_type, Location l)
6029 this.QueriedType = queried_type;
6033 public override Expression DoResolve (EmitContext ec)
6037 233, loc, "Sizeof may only be used in an unsafe context " +
6038 "(consider using System.Runtime.InteropServices.Marshal.Sizeof");
6042 type_queried = ec.DeclSpace.ResolveType (QueriedType, false, loc);
6043 if (type_queried == null)
6046 if (!TypeManager.IsUnmanagedType (type_queried)){
6047 Report.Error (208, loc, "Cannot take the size of an unmanaged type (" + TypeManager.CSharpName (type_queried) + ")");
6051 type = TypeManager.int32_type;
6052 eclass = ExprClass.Value;
6056 public override void Emit (EmitContext ec)
6058 int size = GetTypeSize (type_queried);
6061 ec.ig.Emit (OpCodes.Sizeof, type_queried);
6063 IntConstant.EmitInt (ec.ig, size);
6068 /// Implements the member access expression
6070 public class MemberAccess : Expression {
6071 public readonly string Identifier;
6074 public MemberAccess (Expression expr, string id, Location l)
6081 public Expression Expr {
6087 static void error176 (Location loc, string name)
6089 Report.Error (176, loc, "Static member `" +
6090 name + "' cannot be accessed " +
6091 "with an instance reference, qualify with a " +
6092 "type name instead");
6095 static bool IdenticalNameAndTypeName (EmitContext ec, Expression left_original, Location loc)
6097 if (left_original == null)
6100 if (!(left_original is SimpleName))
6103 SimpleName sn = (SimpleName) left_original;
6105 Type t = RootContext.LookupType (ec.DeclSpace, sn.Name, true, loc);
6112 public static Expression ResolveMemberAccess (EmitContext ec, Expression member_lookup,
6113 Expression left, Location loc,
6114 Expression left_original)
6116 bool left_is_type, left_is_explicit;
6118 // If `left' is null, then we're called from SimpleNameResolve and this is
6119 // a member in the currently defining class.
6121 left_is_type = ec.IsStatic || ec.IsFieldInitializer;
6122 left_is_explicit = false;
6124 // Implicitly default to `this' unless we're static.
6125 if (!ec.IsStatic && !ec.IsFieldInitializer && !ec.InEnumContext)
6128 left_is_type = left is TypeExpr;
6129 left_is_explicit = true;
6132 if (member_lookup is FieldExpr){
6133 FieldExpr fe = (FieldExpr) member_lookup;
6134 FieldInfo fi = fe.FieldInfo;
6135 Type decl_type = fi.DeclaringType;
6137 if (fi is FieldBuilder) {
6138 Const c = TypeManager.LookupConstant ((FieldBuilder) fi);
6141 object o = c.LookupConstantValue (ec);
6145 object real_value = ((Constant) c.Expr).GetValue ();
6147 return Constantify (real_value, fi.FieldType);
6152 Type t = fi.FieldType;
6156 if (fi is FieldBuilder)
6157 o = TypeManager.GetValue ((FieldBuilder) fi);
6159 o = fi.GetValue (fi);
6161 if (decl_type.IsSubclassOf (TypeManager.enum_type)) {
6162 if (left_is_explicit && !left_is_type &&
6163 !IdenticalNameAndTypeName (ec, left_original, loc)) {
6164 error176 (loc, fe.FieldInfo.Name);
6168 Expression enum_member = MemberLookup (
6169 ec, decl_type, "value__", MemberTypes.Field,
6170 AllBindingFlags, loc);
6172 Enum en = TypeManager.LookupEnum (decl_type);
6176 c = Constantify (o, en.UnderlyingType);
6178 c = Constantify (o, enum_member.Type);
6180 return new EnumConstant (c, decl_type);
6183 Expression exp = Constantify (o, t);
6185 if (left_is_explicit && !left_is_type) {
6186 error176 (loc, fe.FieldInfo.Name);
6193 if (fi.FieldType.IsPointer && !ec.InUnsafe){
6199 if (member_lookup is EventExpr) {
6201 EventExpr ee = (EventExpr) member_lookup;
6204 // If the event is local to this class, we transform ourselves into
6208 if (ee.EventInfo.DeclaringType == ec.ContainerType) {
6209 MemberInfo mi = GetFieldFromEvent (ee);
6213 // If this happens, then we have an event with its own
6214 // accessors and private field etc so there's no need
6215 // to transform ourselves : we should instead flag an error
6217 Assign.error70 (ee.EventInfo, loc);
6221 Expression ml = ExprClassFromMemberInfo (ec, mi, loc);
6224 Report.Error (-200, loc, "Internal error!!");
6228 return ResolveMemberAccess (ec, ml, left, loc, left_original);
6232 if (member_lookup is IMemberExpr) {
6233 IMemberExpr me = (IMemberExpr) member_lookup;
6236 MethodGroupExpr mg = me as MethodGroupExpr;
6237 if ((mg != null) && left_is_explicit && left.Type.IsInterface)
6238 mg.IsExplicitImpl = left_is_explicit;
6241 if (IdenticalNameAndTypeName (ec, left_original, loc))
6242 return member_lookup;
6244 SimpleName.Error_ObjectRefRequired (ec, loc, me.Name);
6249 if (!me.IsInstance){
6250 if (IdenticalNameAndTypeName (ec, left_original, loc))
6251 return member_lookup;
6253 if (left_is_explicit) {
6254 error176 (loc, me.Name);
6260 // Since we can not check for instance objects in SimpleName,
6261 // becaue of the rule that allows types and variables to share
6262 // the name (as long as they can be de-ambiguated later, see
6263 // IdenticalNameAndTypeName), we have to check whether left
6264 // is an instance variable in a static context
6266 // However, if the left-hand value is explicitly given, then
6267 // it is already our instance expression, so we aren't in
6271 if (ec.IsStatic && !left_is_explicit && left is IMemberExpr){
6272 IMemberExpr mexp = (IMemberExpr) left;
6274 if (!mexp.IsStatic){
6275 SimpleName.Error_ObjectRefRequired (ec, loc, mexp.Name);
6280 me.InstanceExpression = left;
6283 return member_lookup;
6286 Console.WriteLine ("Left is: " + left);
6287 Report.Error (-100, loc, "Support for [" + member_lookup + "] is not present yet");
6288 Environment.Exit (0);
6292 public Expression DoResolve (EmitContext ec, Expression right_side, ResolveFlags flags)
6295 throw new Exception ();
6298 // Resolve the expression with flow analysis turned off, we'll do the definite
6299 // assignment checks later. This is because we don't know yet what the expression
6300 // will resolve to - it may resolve to a FieldExpr and in this case we must do the
6301 // definite assignment check on the actual field and not on the whole struct.
6304 Expression original = expr;
6305 expr = expr.Resolve (ec, flags | ResolveFlags.DisableFlowAnalysis);
6309 if (expr is SimpleName){
6310 SimpleName child_expr = (SimpleName) expr;
6312 Expression new_expr = new SimpleName (child_expr.Name, Identifier, loc);
6314 return new_expr.Resolve (ec, flags);
6318 // TODO: I mailed Ravi about this, and apparently we can get rid
6319 // of this and put it in the right place.
6321 // Handle enums here when they are in transit.
6322 // Note that we cannot afford to hit MemberLookup in this case because
6323 // it will fail to find any members at all
6326 int errors = Report.Errors;
6328 Type expr_type = expr.Type;
6329 if (expr is TypeExpr){
6330 if (!ec.DeclSpace.CheckAccessLevel (expr_type)){
6331 Error (122, "`" + expr_type + "' " +
6332 "is inaccessible because of its protection level");
6336 if (expr_type == TypeManager.enum_type || expr_type.IsSubclassOf (TypeManager.enum_type)){
6337 Enum en = TypeManager.LookupEnum (expr_type);
6340 object value = en.LookupEnumValue (ec, Identifier, loc);
6343 Constant c = Constantify (value, en.UnderlyingType);
6344 return new EnumConstant (c, expr_type);
6350 if (expr_type.IsPointer){
6351 Error (23, "The `.' operator can not be applied to pointer operands (" +
6352 TypeManager.CSharpName (expr_type) + ")");
6356 Expression member_lookup;
6357 member_lookup = MemberLookupFinal (ec, expr_type, expr_type, Identifier, loc);
6358 if (member_lookup == null)
6361 if (member_lookup is TypeExpr)
6362 return member_lookup;
6364 member_lookup = ResolveMemberAccess (ec, member_lookup, expr, loc, original);
6365 if (member_lookup == null)
6368 // The following DoResolve/DoResolveLValue will do the definite assignment
6371 if (right_side != null)
6372 member_lookup = member_lookup.DoResolveLValue (ec, right_side);
6374 member_lookup = member_lookup.DoResolve (ec);
6376 return member_lookup;
6379 public override Expression DoResolve (EmitContext ec)
6381 return DoResolve (ec, null, ResolveFlags.VariableOrValue |
6382 ResolveFlags.SimpleName | ResolveFlags.Type);
6385 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
6387 return DoResolve (ec, right_side, ResolveFlags.VariableOrValue |
6388 ResolveFlags.SimpleName | ResolveFlags.Type);
6391 public override Expression ResolveAsTypeStep (EmitContext ec)
6393 Expression new_expr = expr.ResolveAsTypeStep (ec);
6395 if (new_expr == null)
6398 if (new_expr is SimpleName){
6399 SimpleName child_expr = (SimpleName) new_expr;
6401 new_expr = new SimpleName (child_expr.Name, Identifier, loc);
6403 return new_expr.ResolveAsTypeStep (ec);
6406 Type expr_type = new_expr.Type;
6408 if (expr_type.IsPointer){
6409 Error (23, "The `.' operator can not be applied to pointer operands (" +
6410 TypeManager.CSharpName (expr_type) + ")");
6414 Expression member_lookup;
6415 member_lookup = MemberLookupFinal (ec, expr_type, expr_type, Identifier, loc);
6416 if (member_lookup == null)
6419 if (member_lookup is TypeExpr){
6420 member_lookup.Resolve (ec, ResolveFlags.Type);
6421 return member_lookup;
6427 public override void Emit (EmitContext ec)
6429 throw new Exception ("Should not happen");
6432 public override string ToString ()
6434 return expr + "." + Identifier;
6439 /// Implements checked expressions
6441 public class CheckedExpr : Expression {
6443 public Expression Expr;
6445 public CheckedExpr (Expression e, Location l)
6451 public override Expression DoResolve (EmitContext ec)
6453 bool last_check = ec.CheckState;
6454 bool last_const_check = ec.ConstantCheckState;
6456 ec.CheckState = true;
6457 ec.ConstantCheckState = true;
6458 Expr = Expr.Resolve (ec);
6459 ec.CheckState = last_check;
6460 ec.ConstantCheckState = last_const_check;
6465 if (Expr is Constant)
6468 eclass = Expr.eclass;
6473 public override void Emit (EmitContext ec)
6475 bool last_check = ec.CheckState;
6476 bool last_const_check = ec.ConstantCheckState;
6478 ec.CheckState = true;
6479 ec.ConstantCheckState = true;
6481 ec.CheckState = last_check;
6482 ec.ConstantCheckState = last_const_check;
6488 /// Implements the unchecked expression
6490 public class UnCheckedExpr : Expression {
6492 public Expression Expr;
6494 public UnCheckedExpr (Expression e, Location l)
6500 public override Expression DoResolve (EmitContext ec)
6502 bool last_check = ec.CheckState;
6503 bool last_const_check = ec.ConstantCheckState;
6505 ec.CheckState = false;
6506 ec.ConstantCheckState = false;
6507 Expr = Expr.Resolve (ec);
6508 ec.CheckState = last_check;
6509 ec.ConstantCheckState = last_const_check;
6514 if (Expr is Constant)
6517 eclass = Expr.eclass;
6522 public override void Emit (EmitContext ec)
6524 bool last_check = ec.CheckState;
6525 bool last_const_check = ec.ConstantCheckState;
6527 ec.CheckState = false;
6528 ec.ConstantCheckState = false;
6530 ec.CheckState = last_check;
6531 ec.ConstantCheckState = last_const_check;
6537 /// An Element Access expression.
6539 /// During semantic analysis these are transformed into
6540 /// IndexerAccess or ArrayAccess
6542 public class ElementAccess : Expression {
6543 public ArrayList Arguments;
6544 public Expression Expr;
6546 public ElementAccess (Expression e, ArrayList e_list, Location l)
6555 Arguments = new ArrayList ();
6556 foreach (Expression tmp in e_list)
6557 Arguments.Add (new Argument (tmp, Argument.AType.Expression));
6561 bool CommonResolve (EmitContext ec)
6563 Expr = Expr.Resolve (ec);
6568 if (Arguments == null)
6571 foreach (Argument a in Arguments){
6572 if (!a.Resolve (ec, loc))
6579 Expression MakePointerAccess ()
6583 if (t == TypeManager.void_ptr_type){
6584 Error (242, "The array index operation is not valid for void pointers");
6587 if (Arguments.Count != 1){
6588 Error (196, "A pointer must be indexed by a single value");
6593 p = new PointerArithmetic (true, Expr, ((Argument)Arguments [0]).Expr, t, loc);
6594 return new Indirection (p, loc);
6597 public override Expression DoResolve (EmitContext ec)
6599 if (!CommonResolve (ec))
6603 // We perform some simple tests, and then to "split" the emit and store
6604 // code we create an instance of a different class, and return that.
6606 // I am experimenting with this pattern.
6611 return (new ArrayAccess (this, loc)).Resolve (ec);
6612 else if (t.IsPointer)
6613 return MakePointerAccess ();
6615 return (new IndexerAccess (this, loc)).Resolve (ec);
6618 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
6620 if (!CommonResolve (ec))
6625 return (new ArrayAccess (this, loc)).ResolveLValue (ec, right_side);
6626 else if (t.IsPointer)
6627 return MakePointerAccess ();
6629 return (new IndexerAccess (this, loc)).ResolveLValue (ec, right_side);
6632 public override void Emit (EmitContext ec)
6634 throw new Exception ("Should never be reached");
6639 /// Implements array access
6641 public class ArrayAccess : Expression, IAssignMethod, IMemoryLocation {
6643 // Points to our "data" repository
6647 LocalTemporary [] cached_locations;
6649 public ArrayAccess (ElementAccess ea_data, Location l)
6652 eclass = ExprClass.Variable;
6656 public override Expression DoResolve (EmitContext ec)
6658 ExprClass eclass = ea.Expr.eclass;
6661 // As long as the type is valid
6662 if (!(eclass == ExprClass.Variable || eclass == ExprClass.PropertyAccess ||
6663 eclass == ExprClass.Value)) {
6664 ea.Expr.Error_UnexpectedKind ("variable or value");
6669 Type t = ea.Expr.Type;
6670 if (t.GetArrayRank () != ea.Arguments.Count){
6672 "Incorrect number of indexes for array " +
6673 " expected: " + t.GetArrayRank () + " got: " +
6674 ea.Arguments.Count);
6677 type = TypeManager.TypeToCoreType (t.GetElementType ());
6678 if (type.IsPointer && !ec.InUnsafe){
6679 UnsafeError (ea.Location);
6683 foreach (Argument a in ea.Arguments){
6684 Type argtype = a.Type;
6686 if (argtype == TypeManager.int32_type ||
6687 argtype == TypeManager.uint32_type ||
6688 argtype == TypeManager.int64_type ||
6689 argtype == TypeManager.uint64_type)
6693 // Mhm. This is strage, because the Argument.Type is not the same as
6694 // Argument.Expr.Type: the value changes depending on the ref/out setting.
6696 // Wonder if I will run into trouble for this.
6698 a.Expr = ExpressionToArrayArgument (ec, a.Expr, ea.Location);
6703 eclass = ExprClass.Variable;
6709 /// Emits the right opcode to load an object of Type `t'
6710 /// from an array of T
6712 static public void EmitLoadOpcode (ILGenerator ig, Type type)
6714 if (type == TypeManager.byte_type || type == TypeManager.bool_type)
6715 ig.Emit (OpCodes.Ldelem_U1);
6716 else if (type == TypeManager.sbyte_type)
6717 ig.Emit (OpCodes.Ldelem_I1);
6718 else if (type == TypeManager.short_type)
6719 ig.Emit (OpCodes.Ldelem_I2);
6720 else if (type == TypeManager.ushort_type || type == TypeManager.char_type)
6721 ig.Emit (OpCodes.Ldelem_U2);
6722 else if (type == TypeManager.int32_type)
6723 ig.Emit (OpCodes.Ldelem_I4);
6724 else if (type == TypeManager.uint32_type)
6725 ig.Emit (OpCodes.Ldelem_U4);
6726 else if (type == TypeManager.uint64_type)
6727 ig.Emit (OpCodes.Ldelem_I8);
6728 else if (type == TypeManager.int64_type)
6729 ig.Emit (OpCodes.Ldelem_I8);
6730 else if (type == TypeManager.float_type)
6731 ig.Emit (OpCodes.Ldelem_R4);
6732 else if (type == TypeManager.double_type)
6733 ig.Emit (OpCodes.Ldelem_R8);
6734 else if (type == TypeManager.intptr_type)
6735 ig.Emit (OpCodes.Ldelem_I);
6736 else if (type.IsValueType){
6737 ig.Emit (OpCodes.Ldelema, type);
6738 ig.Emit (OpCodes.Ldobj, type);
6740 ig.Emit (OpCodes.Ldelem_Ref);
6744 /// Emits the right opcode to store an object of Type `t'
6745 /// from an array of T.
6747 static public void EmitStoreOpcode (ILGenerator ig, Type t)
6750 OpCode op = GetStoreOpcode (t, out is_stobj);
6752 ig.Emit (OpCodes.Stobj, t);
6758 /// Returns the right opcode to store an object of Type `t'
6759 /// from an array of T.
6761 static public OpCode GetStoreOpcode (Type t, out bool is_stobj)
6764 t = TypeManager.TypeToCoreType (t);
6765 if (TypeManager.IsEnumType (t) && t != TypeManager.enum_type)
6766 t = TypeManager.EnumToUnderlying (t);
6767 if (t == TypeManager.byte_type || t == TypeManager.sbyte_type ||
6768 t == TypeManager.bool_type)
6769 return OpCodes.Stelem_I1;
6770 else if (t == TypeManager.short_type || t == TypeManager.ushort_type ||
6771 t == TypeManager.char_type)
6772 return OpCodes.Stelem_I2;
6773 else if (t == TypeManager.int32_type || t == TypeManager.uint32_type)
6774 return OpCodes.Stelem_I4;
6775 else if (t == TypeManager.int64_type || t == TypeManager.uint64_type)
6776 return OpCodes.Stelem_I8;
6777 else if (t == TypeManager.float_type)
6778 return OpCodes.Stelem_R4;
6779 else if (t == TypeManager.double_type)
6780 return OpCodes.Stelem_R8;
6781 else if (t == TypeManager.intptr_type)
6782 return OpCodes.Stelem_I;
6783 else if (t.IsValueType) {
6785 return OpCodes.Stobj;
6787 return OpCodes.Stelem_Ref;
6790 MethodInfo FetchGetMethod ()
6792 ModuleBuilder mb = CodeGen.ModuleBuilder;
6793 int arg_count = ea.Arguments.Count;
6794 Type [] args = new Type [arg_count];
6797 for (int i = 0; i < arg_count; i++){
6798 //args [i++] = a.Type;
6799 args [i] = TypeManager.int32_type;
6802 get = mb.GetArrayMethod (
6803 ea.Expr.Type, "Get",
6804 CallingConventions.HasThis |
6805 CallingConventions.Standard,
6811 MethodInfo FetchAddressMethod ()
6813 ModuleBuilder mb = CodeGen.ModuleBuilder;
6814 int arg_count = ea.Arguments.Count;
6815 Type [] args = new Type [arg_count];
6819 ret_type = TypeManager.GetReferenceType (type);
6821 for (int i = 0; i < arg_count; i++){
6822 //args [i++] = a.Type;
6823 args [i] = TypeManager.int32_type;
6826 address = mb.GetArrayMethod (
6827 ea.Expr.Type, "Address",
6828 CallingConventions.HasThis |
6829 CallingConventions.Standard,
6836 // Load the array arguments into the stack.
6838 // If we have been requested to cache the values (cached_locations array
6839 // initialized), then load the arguments the first time and store them
6840 // in locals. otherwise load from local variables.
6842 void LoadArrayAndArguments (EmitContext ec)
6844 ILGenerator ig = ec.ig;
6846 if (cached_locations == null){
6848 foreach (Argument a in ea.Arguments){
6849 Type argtype = a.Expr.Type;
6853 if (argtype == TypeManager.int64_type)
6854 ig.Emit (OpCodes.Conv_Ovf_I);
6855 else if (argtype == TypeManager.uint64_type)
6856 ig.Emit (OpCodes.Conv_Ovf_I_Un);
6861 if (cached_locations [0] == null){
6862 cached_locations [0] = new LocalTemporary (ec, ea.Expr.Type);
6864 ig.Emit (OpCodes.Dup);
6865 cached_locations [0].Store (ec);
6869 foreach (Argument a in ea.Arguments){
6870 Type argtype = a.Expr.Type;
6872 cached_locations [j] = new LocalTemporary (ec, TypeManager.intptr_type /* a.Expr.Type */);
6874 if (argtype == TypeManager.int64_type)
6875 ig.Emit (OpCodes.Conv_Ovf_I);
6876 else if (argtype == TypeManager.uint64_type)
6877 ig.Emit (OpCodes.Conv_Ovf_I_Un);
6879 ig.Emit (OpCodes.Dup);
6880 cached_locations [j].Store (ec);
6886 foreach (LocalTemporary lt in cached_locations)
6890 public new void CacheTemporaries (EmitContext ec)
6892 cached_locations = new LocalTemporary [ea.Arguments.Count + 1];
6895 public override void Emit (EmitContext ec)
6897 int rank = ea.Expr.Type.GetArrayRank ();
6898 ILGenerator ig = ec.ig;
6900 LoadArrayAndArguments (ec);
6903 EmitLoadOpcode (ig, type);
6907 method = FetchGetMethod ();
6908 ig.Emit (OpCodes.Call, method);
6912 public void EmitAssign (EmitContext ec, Expression source)
6914 int rank = ea.Expr.Type.GetArrayRank ();
6915 ILGenerator ig = ec.ig;
6916 Type t = source.Type;
6918 LoadArrayAndArguments (ec);
6921 // The stobj opcode used by value types will need
6922 // an address on the stack, not really an array/array
6926 if (t == TypeManager.enum_type || t == TypeManager.decimal_type ||
6927 (t.IsSubclassOf (TypeManager.value_type) && !TypeManager.IsEnumType (t) && !TypeManager.IsBuiltinType (t)))
6928 ig.Emit (OpCodes.Ldelema, t);
6934 EmitStoreOpcode (ig, t);
6936 ModuleBuilder mb = CodeGen.ModuleBuilder;
6937 int arg_count = ea.Arguments.Count;
6938 Type [] args = new Type [arg_count + 1];
6941 for (int i = 0; i < arg_count; i++){
6942 //args [i++] = a.Type;
6943 args [i] = TypeManager.int32_type;
6946 args [arg_count] = type;
6948 set = mb.GetArrayMethod (
6949 ea.Expr.Type, "Set",
6950 CallingConventions.HasThis |
6951 CallingConventions.Standard,
6952 TypeManager.void_type, args);
6954 ig.Emit (OpCodes.Call, set);
6958 public void AddressOf (EmitContext ec, AddressOp mode)
6960 int rank = ea.Expr.Type.GetArrayRank ();
6961 ILGenerator ig = ec.ig;
6963 LoadArrayAndArguments (ec);
6966 ig.Emit (OpCodes.Ldelema, type);
6968 MethodInfo address = FetchAddressMethod ();
6969 ig.Emit (OpCodes.Call, address);
6976 public ArrayList properties;
6977 static Hashtable map;
6981 map = new Hashtable ();
6986 properties = new ArrayList ();
6989 void Append (MemberInfo [] mi)
6991 foreach (PropertyInfo property in mi){
6992 MethodInfo get, set;
6994 get = property.GetGetMethod (true);
6995 set = property.GetSetMethod (true);
6996 properties.Add (new Pair (get, set));
7000 static private MemberInfo [] GetIndexersForTypeOrInterface (Type caller_type, Type lookup_type)
7002 string p_name = TypeManager.IndexerPropertyName (lookup_type);
7004 MemberInfo [] mi = TypeManager.MemberLookup (
7005 caller_type, caller_type, lookup_type, MemberTypes.Property,
7006 BindingFlags.Public | BindingFlags.Instance |
7007 BindingFlags.DeclaredOnly, p_name);
7009 if (mi == null || mi.Length == 0)
7015 static public Indexers GetIndexersForType (Type caller_type, Type lookup_type, Location loc)
7017 Indexers ix = (Indexers) map [lookup_type];
7022 Type copy = lookup_type;
7023 while (copy != TypeManager.object_type && copy != null){
7024 MemberInfo [] mi = GetIndexersForTypeOrInterface (caller_type, copy);
7028 ix = new Indexers ();
7033 copy = copy.BaseType;
7036 Type [] ifaces = TypeManager.GetInterfaces (lookup_type);
7037 if (ifaces != null) {
7038 foreach (Type itype in ifaces) {
7039 MemberInfo [] mi = GetIndexersForTypeOrInterface (caller_type, itype);
7042 ix = new Indexers ();
7054 /// Expressions that represent an indexer call.
7056 public class IndexerAccess : Expression, IAssignMethod {
7058 // Points to our "data" repository
7060 MethodInfo get, set;
7061 ArrayList set_arguments;
7062 bool is_base_indexer;
7064 protected Type indexer_type;
7065 protected Type current_type;
7066 protected Expression instance_expr;
7067 protected ArrayList arguments;
7069 public IndexerAccess (ElementAccess ea, Location loc)
7070 : this (ea.Expr, false, loc)
7072 this.arguments = ea.Arguments;
7075 protected IndexerAccess (Expression instance_expr, bool is_base_indexer,
7078 this.instance_expr = instance_expr;
7079 this.is_base_indexer = is_base_indexer;
7080 this.eclass = ExprClass.Value;
7084 protected virtual bool CommonResolve (EmitContext ec)
7086 indexer_type = instance_expr.Type;
7087 current_type = ec.ContainerType;
7092 public override Expression DoResolve (EmitContext ec)
7094 ArrayList AllGetters = new ArrayList();
7095 if (!CommonResolve (ec))
7099 // Step 1: Query for all `Item' *properties*. Notice
7100 // that the actual methods are pointed from here.
7102 // This is a group of properties, piles of them.
7104 bool found_any = false, found_any_getters = false;
7105 Type lookup_type = indexer_type;
7108 ilist = Indexers.GetIndexersForType (current_type, lookup_type, loc);
7109 if (ilist != null) {
7111 if (ilist.properties != null) {
7112 foreach (Pair o in ilist.properties) {
7113 if (o.First != null)
7114 AllGetters.Add(o.First);
7119 if (AllGetters.Count > 0) {
7120 found_any_getters = true;
7121 get = (MethodInfo) Invocation.OverloadResolve (
7122 ec, new MethodGroupExpr (AllGetters, loc), arguments, loc);
7126 Report.Error (21, loc,
7127 "Type `" + TypeManager.CSharpName (indexer_type) +
7128 "' does not have any indexers defined");
7132 if (!found_any_getters) {
7133 Error (154, "indexer can not be used in this context, because " +
7134 "it lacks a `get' accessor");
7139 Error (1501, "No Overload for method `this' takes `" +
7140 arguments.Count + "' arguments");
7145 // Only base will allow this invocation to happen.
7147 if (get.IsAbstract && this is BaseIndexerAccess){
7148 Report.Error (205, loc, "Cannot call an abstract base indexer: " + Invocation.FullMethodDesc (get));
7152 type = get.ReturnType;
7153 if (type.IsPointer && !ec.InUnsafe){
7158 eclass = ExprClass.IndexerAccess;
7162 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
7164 ArrayList AllSetters = new ArrayList();
7165 if (!CommonResolve (ec))
7168 Type right_type = right_side.Type;
7170 bool found_any = false, found_any_setters = false;
7172 Indexers ilist = Indexers.GetIndexersForType (current_type, indexer_type, loc);
7173 if (ilist != null) {
7175 if (ilist.properties != null) {
7176 foreach (Pair o in ilist.properties) {
7177 if (o.Second != null)
7178 AllSetters.Add(o.Second);
7182 if (AllSetters.Count > 0) {
7183 found_any_setters = true;
7184 set_arguments = (ArrayList) arguments.Clone ();
7185 set_arguments.Add (new Argument (right_side, Argument.AType.Expression));
7186 set = (MethodInfo) Invocation.OverloadResolve (
7187 ec, new MethodGroupExpr (AllSetters, loc),
7188 set_arguments, loc);
7192 Report.Error (21, loc,
7193 "Type `" + TypeManager.CSharpName (indexer_type) +
7194 "' does not have any indexers defined");
7198 if (!found_any_setters) {
7199 Error (154, "indexer can not be used in this context, because " +
7200 "it lacks a `set' accessor");
7205 Error (1501, "No Overload for method `this' takes `" +
7206 arguments.Count + "' arguments");
7211 // Only base will allow this invocation to happen.
7213 if (set.IsAbstract && this is BaseIndexerAccess){
7214 Report.Error (205, loc, "Cannot call an abstract base indexer: " + Invocation.FullMethodDesc (set));
7219 // Now look for the actual match in the list of indexers to set our "return" type
7221 type = TypeManager.void_type; // default value
7222 foreach (Pair t in ilist.properties){
7223 if (t.Second == set){
7224 if (t.First != null)
7225 type = ((MethodInfo) t.First).ReturnType;
7230 eclass = ExprClass.IndexerAccess;
7234 public override void Emit (EmitContext ec)
7236 Invocation.EmitCall (ec, false, false, instance_expr, get, arguments, loc);
7240 // source is ignored, because we already have a copy of it from the
7241 // LValue resolution and we have already constructed a pre-cached
7242 // version of the arguments (ea.set_arguments);
7244 public void EmitAssign (EmitContext ec, Expression source)
7246 Invocation.EmitCall (ec, false, false, instance_expr, set, set_arguments, loc);
7251 /// The base operator for method names
7253 public class BaseAccess : Expression {
7256 public BaseAccess (string member, Location l)
7258 this.member = member;
7262 public override Expression DoResolve (EmitContext ec)
7264 Expression c = CommonResolve (ec);
7270 // MethodGroups use this opportunity to flag an error on lacking ()
7272 if (!(c is MethodGroupExpr))
7273 return c.Resolve (ec);
7277 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
7279 Expression c = CommonResolve (ec);
7285 // MethodGroups use this opportunity to flag an error on lacking ()
7287 if (! (c is MethodGroupExpr))
7288 return c.DoResolveLValue (ec, right_side);
7293 Expression CommonResolve (EmitContext ec)
7295 Expression member_lookup;
7296 Type current_type = ec.ContainerType;
7297 Type base_type = current_type.BaseType;
7301 Error (1511, "Keyword base is not allowed in static method");
7305 member_lookup = MemberLookup (ec, ec.ContainerType, null, base_type, member,
7306 AllMemberTypes, AllBindingFlags, loc);
7307 if (member_lookup == null) {
7308 MemberLookupFailed (ec, base_type, base_type, member, null, loc);
7315 left = new TypeExpr (base_type, loc);
7319 e = MemberAccess.ResolveMemberAccess (ec, member_lookup, left, loc, null);
7321 if (e is PropertyExpr){
7322 PropertyExpr pe = (PropertyExpr) e;
7330 public override void Emit (EmitContext ec)
7332 throw new Exception ("Should never be called");
7337 /// The base indexer operator
7339 public class BaseIndexerAccess : IndexerAccess {
7340 public BaseIndexerAccess (ArrayList args, Location loc)
7341 : base (null, true, loc)
7343 arguments = new ArrayList ();
7344 foreach (Expression tmp in args)
7345 arguments.Add (new Argument (tmp, Argument.AType.Expression));
7348 protected override bool CommonResolve (EmitContext ec)
7350 instance_expr = ec.This;
7352 current_type = ec.ContainerType.BaseType;
7353 indexer_type = current_type;
7355 foreach (Argument a in arguments){
7356 if (!a.Resolve (ec, loc))
7365 /// This class exists solely to pass the Type around and to be a dummy
7366 /// that can be passed to the conversion functions (this is used by
7367 /// foreach implementation to typecast the object return value from
7368 /// get_Current into the proper type. All code has been generated and
7369 /// we only care about the side effect conversions to be performed
7371 /// This is also now used as a placeholder where a no-action expression
7372 /// is needed (the `New' class).
7374 public class EmptyExpression : Expression {
7375 public EmptyExpression ()
7377 type = TypeManager.object_type;
7378 eclass = ExprClass.Value;
7379 loc = Location.Null;
7382 public EmptyExpression (Type t)
7385 eclass = ExprClass.Value;
7386 loc = Location.Null;
7389 public override Expression DoResolve (EmitContext ec)
7394 public override void Emit (EmitContext ec)
7396 // nothing, as we only exist to not do anything.
7400 // This is just because we might want to reuse this bad boy
7401 // instead of creating gazillions of EmptyExpressions.
7402 // (CanConvertImplicit uses it)
7404 public void SetType (Type t)
7410 public class UserCast : Expression {
7414 public UserCast (MethodInfo method, Expression source, Location l)
7416 this.method = method;
7417 this.source = source;
7418 type = method.ReturnType;
7419 eclass = ExprClass.Value;
7423 public override Expression DoResolve (EmitContext ec)
7426 // We are born fully resolved
7431 public override void Emit (EmitContext ec)
7433 ILGenerator ig = ec.ig;
7437 if (method is MethodInfo)
7438 ig.Emit (OpCodes.Call, (MethodInfo) method);
7440 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
7446 // This class is used to "construct" the type during a typecast
7447 // operation. Since the Type.GetType class in .NET can parse
7448 // the type specification, we just use this to construct the type
7449 // one bit at a time.
7451 public class ComposedCast : Expression {
7455 public ComposedCast (Expression left, string dim, Location l)
7462 public override Expression ResolveAsTypeStep (EmitContext ec)
7464 Type ltype = ec.DeclSpace.ResolveType (left, false, loc);
7469 // ltype.Fullname is already fully qualified, so we can skip
7470 // a lot of probes, and go directly to TypeManager.LookupType
7472 string cname = ltype.FullName + dim;
7473 type = TypeManager.LookupTypeDirect (cname);
7476 // For arrays of enumerations we are having a problem
7477 // with the direct lookup. Need to investigate.
7479 // For now, fall back to the full lookup in that case.
7481 type = RootContext.LookupType (
7482 ec.DeclSpace, cname, false, loc);
7488 if (!ec.ResolvingTypeTree){
7490 // If the above flag is set, this is being invoked from the ResolveType function.
7491 // Upper layers take care of the type validity in this context.
7493 if (!ec.InUnsafe && type.IsPointer){
7499 eclass = ExprClass.Type;
7503 public override Expression DoResolve (EmitContext ec)
7505 return ResolveAsTypeStep (ec);
7508 public override void Emit (EmitContext ec)
7510 throw new Exception ("This should never be called");
7513 public override string ToString ()
7520 // This class is used to represent the address of an array, used
7521 // only by the Fixed statement, this is like the C "&a [0]" construct.
7523 public class ArrayPtr : Expression {
7526 public ArrayPtr (Expression array, Location l)
7528 Type array_type = array.Type.GetElementType ();
7532 type = TypeManager.GetPointerType (array_type);
7533 eclass = ExprClass.Value;
7537 public override void Emit (EmitContext ec)
7539 ILGenerator ig = ec.ig;
7542 IntLiteral.EmitInt (ig, 0);
7543 ig.Emit (OpCodes.Ldelema, array.Type.GetElementType ());
7546 public override Expression DoResolve (EmitContext ec)
7549 // We are born fully resolved
7556 // Used by the fixed statement
7558 public class StringPtr : Expression {
7561 public StringPtr (LocalBuilder b, Location l)
7564 eclass = ExprClass.Value;
7565 type = TypeManager.char_ptr_type;
7569 public override Expression DoResolve (EmitContext ec)
7571 // This should never be invoked, we are born in fully
7572 // initialized state.
7577 public override void Emit (EmitContext ec)
7579 ILGenerator ig = ec.ig;
7581 ig.Emit (OpCodes.Ldloc, b);
7582 ig.Emit (OpCodes.Conv_I);
7583 ig.Emit (OpCodes.Call, TypeManager.int_get_offset_to_string_data);
7584 ig.Emit (OpCodes.Add);
7589 // Implements the `stackalloc' keyword
7591 public class StackAlloc : Expression {
7596 public StackAlloc (Expression type, Expression count, Location l)
7603 public override Expression DoResolve (EmitContext ec)
7605 count = count.Resolve (ec);
7609 if (count.Type != TypeManager.int32_type){
7610 count = ConvertImplicitRequired (ec, count, TypeManager.int32_type, loc);
7615 if (ec.InCatch || ec.InFinally){
7617 "stackalloc can not be used in a catch or finally block");
7621 otype = ec.DeclSpace.ResolveType (t, false, loc);
7626 if (!TypeManager.VerifyUnManaged (otype, loc))
7629 type = TypeManager.GetPointerType (otype);
7630 eclass = ExprClass.Value;
7635 public override void Emit (EmitContext ec)
7637 int size = GetTypeSize (otype);
7638 ILGenerator ig = ec.ig;
7641 ig.Emit (OpCodes.Sizeof, otype);
7643 IntConstant.EmitInt (ig, size);
7645 ig.Emit (OpCodes.Mul);
7646 ig.Emit (OpCodes.Localloc);