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 string ptr_type_name = Expr.Type.FullName + "*";
398 type = TypeManager.LookupType (ptr_type_name);
402 case Operator.Indirection:
408 if (!expr_type.IsPointer){
411 "The * or -> operator can only be applied to pointers");
416 // We create an Indirection expression, because
417 // it can implement the IMemoryLocation.
419 return new Indirection (Expr, loc);
421 case Operator.UnaryPlus:
423 // A plus in front of something is just a no-op, so return the child.
427 case Operator.UnaryNegation:
429 // Deals with -literals
430 // int operator- (int x)
431 // long operator- (long x)
432 // float operator- (float f)
433 // double operator- (double d)
434 // decimal operator- (decimal d)
436 Expression expr = null;
439 // transform - - expr into expr
442 Unary unary = (Unary) Expr;
444 if (unary.Oper == Operator.UnaryNegation)
449 // perform numeric promotions to int,
453 // The following is inneficient, because we call
454 // ConvertImplicit too many times.
456 // It is also not clear if we should convert to Float
457 // or Double initially.
459 if (expr_type == TypeManager.uint32_type){
461 // FIXME: handle exception to this rule that
462 // permits the int value -2147483648 (-2^31) to
463 // bt wrote as a decimal interger literal
465 type = TypeManager.int64_type;
466 Expr = ConvertImplicit (ec, Expr, type, loc);
470 if (expr_type == TypeManager.uint64_type){
472 // FIXME: Handle exception of `long value'
473 // -92233720368547758087 (-2^63) to be wrote as
474 // decimal integer literal.
480 if (expr_type == TypeManager.float_type){
485 expr = ConvertImplicit (ec, Expr, TypeManager.int32_type, loc);
492 expr = ConvertImplicit (ec, Expr, TypeManager.int64_type, loc);
499 expr = ConvertImplicit (ec, Expr, TypeManager.double_type, loc);
510 Error (187, "No such operator '" + OperName (Oper) + "' defined for type '" +
511 TypeManager.CSharpName (expr_type) + "'");
515 public override Expression DoResolve (EmitContext ec)
517 if (Oper == Operator.AddressOf)
518 Expr = Expr.ResolveLValue (ec, new EmptyExpression ());
520 Expr = Expr.Resolve (ec);
525 eclass = ExprClass.Value;
526 return ResolveOperator (ec);
529 public override void Emit (EmitContext ec)
531 ILGenerator ig = ec.ig;
532 Type expr_type = Expr.Type;
535 case Operator.UnaryPlus:
536 throw new Exception ("This should be caught by Resolve");
538 case Operator.UnaryNegation:
540 ig.Emit (OpCodes.Neg);
543 case Operator.LogicalNot:
545 ig.Emit (OpCodes.Ldc_I4_0);
546 ig.Emit (OpCodes.Ceq);
549 case Operator.OnesComplement:
551 ig.Emit (OpCodes.Not);
554 case Operator.AddressOf:
555 ((IMemoryLocation)Expr).AddressOf (ec, AddressOp.LoadStore);
559 throw new Exception ("This should not happen: Operator = "
565 /// This will emit the child expression for `ec' avoiding the logical
566 /// not. The parent will take care of changing brfalse/brtrue
568 public void EmitLogicalNot (EmitContext ec)
570 if (Oper != Operator.LogicalNot)
571 throw new Exception ("EmitLogicalNot can only be called with !expr");
576 public override string ToString ()
578 return "Unary (" + Oper + ", " + Expr + ")";
584 // Unary operators are turned into Indirection expressions
585 // after semantic analysis (this is so we can take the address
586 // of an indirection).
588 public class Indirection : Expression, IMemoryLocation, IAssignMethod {
590 LocalTemporary temporary;
593 public Indirection (Expression expr, Location l)
596 this.type = TypeManager.TypeToCoreType (expr.Type.GetElementType ());
597 eclass = ExprClass.Variable;
601 void LoadExprValue (EmitContext ec)
605 public override void Emit (EmitContext ec)
607 ILGenerator ig = ec.ig;
609 if (temporary != null){
615 ec.ig.Emit (OpCodes.Dup);
616 temporary.Store (ec);
617 have_temporary = true;
621 LoadFromPtr (ig, Type);
624 public void EmitAssign (EmitContext ec, Expression source)
626 if (temporary != null){
631 ec.ig.Emit (OpCodes.Dup);
632 temporary.Store (ec);
633 have_temporary = true;
639 StoreFromPtr (ec.ig, type);
642 public void AddressOf (EmitContext ec, AddressOp Mode)
644 if (temporary != null){
650 ec.ig.Emit (OpCodes.Dup);
651 temporary.Store (ec);
652 have_temporary = true;
657 public override Expression DoResolve (EmitContext ec)
660 // Born fully resolved
665 public new void CacheTemporaries (EmitContext ec)
667 temporary = new LocalTemporary (ec, type);
670 public override string ToString ()
672 return "*(" + expr + ")";
677 /// Unary Mutator expressions (pre and post ++ and --)
681 /// UnaryMutator implements ++ and -- expressions. It derives from
682 /// ExpressionStatement becuase the pre/post increment/decrement
683 /// operators can be used in a statement context.
685 /// FIXME: Idea, we could split this up in two classes, one simpler
686 /// for the common case, and one with the extra fields for more complex
687 /// classes (indexers require temporary access; overloaded require method)
690 public class UnaryMutator : ExpressionStatement {
692 public enum Mode : byte {
699 PreDecrement = IsDecrement,
700 PostIncrement = IsPost,
701 PostDecrement = IsPost | IsDecrement
706 LocalTemporary temp_storage;
709 // This is expensive for the simplest case.
713 public UnaryMutator (Mode m, Expression e, Location l)
720 static string OperName (Mode mode)
722 return (mode == Mode.PreIncrement || mode == Mode.PostIncrement) ?
726 void Error23 (Type t)
729 23, "Operator " + OperName (mode) +
730 " cannot be applied to operand of type `" +
731 TypeManager.CSharpName (t) + "'");
735 /// Returns whether an object of type `t' can be incremented
736 /// or decremented with add/sub (ie, basically whether we can
737 /// use pre-post incr-decr operations on it, but it is not a
738 /// System.Decimal, which we require operator overloading to catch)
740 static bool IsIncrementableNumber (Type t)
742 return (t == TypeManager.sbyte_type) ||
743 (t == TypeManager.byte_type) ||
744 (t == TypeManager.short_type) ||
745 (t == TypeManager.ushort_type) ||
746 (t == TypeManager.int32_type) ||
747 (t == TypeManager.uint32_type) ||
748 (t == TypeManager.int64_type) ||
749 (t == TypeManager.uint64_type) ||
750 (t == TypeManager.char_type) ||
751 (t.IsSubclassOf (TypeManager.enum_type)) ||
752 (t == TypeManager.float_type) ||
753 (t == TypeManager.double_type) ||
754 (t.IsPointer && t != TypeManager.void_ptr_type);
757 Expression ResolveOperator (EmitContext ec)
759 Type expr_type = expr.Type;
762 // Step 1: Perform Operator Overload location
767 if (mode == Mode.PreIncrement || mode == Mode.PostIncrement)
768 op_name = "op_Increment";
770 op_name = "op_Decrement";
772 mg = MemberLookup (ec, expr_type, op_name, MemberTypes.Method, AllBindingFlags, loc);
774 if (mg == null && expr_type.BaseType != null)
775 mg = MemberLookup (ec, expr_type.BaseType, op_name,
776 MemberTypes.Method, AllBindingFlags, loc);
779 method = StaticCallExpr.MakeSimpleCall (
780 ec, (MethodGroupExpr) mg, expr, loc);
787 // The operand of the prefix/postfix increment decrement operators
788 // should be an expression that is classified as a variable,
789 // a property access or an indexer access
792 if (expr.eclass == ExprClass.Variable){
793 if (IsIncrementableNumber (expr_type) ||
794 expr_type == TypeManager.decimal_type){
797 } else if (expr.eclass == ExprClass.IndexerAccess){
798 IndexerAccess ia = (IndexerAccess) expr;
800 temp_storage = new LocalTemporary (ec, expr.Type);
802 expr = ia.ResolveLValue (ec, temp_storage);
807 } else if (expr.eclass == ExprClass.PropertyAccess){
808 PropertyExpr pe = (PropertyExpr) expr;
810 if (pe.VerifyAssignable ())
815 expr.Error118 ("variable, indexer or property access");
819 Error (187, "No such operator '" + OperName (mode) + "' defined for type '" +
820 TypeManager.CSharpName (expr_type) + "'");
824 public override Expression DoResolve (EmitContext ec)
826 expr = expr.Resolve (ec);
831 eclass = ExprClass.Value;
832 return ResolveOperator (ec);
835 static int PtrTypeSize (Type t)
837 return GetTypeSize (t.GetElementType ());
841 // Loads the proper "1" into the stack based on the type, then it emits the
842 // opcode for the operation requested
844 void LoadOneAndEmitOp (EmitContext ec, Type t)
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);
894 void EmitCode (EmitContext ec, bool is_expr)
896 ILGenerator ig = ec.ig;
897 IAssignMethod ia = (IAssignMethod) expr;
898 Type expr_type = expr.Type;
900 ia.CacheTemporaries (ec);
902 if (temp_storage == null)
903 temp_storage = new LocalTemporary (ec, expr_type);
906 case Mode.PreIncrement:
907 case Mode.PreDecrement:
911 LoadOneAndEmitOp (ec, expr_type);
915 temp_storage.Store (ec);
916 ia.EmitAssign (ec, temp_storage);
918 temp_storage.Emit (ec);
921 case Mode.PostIncrement:
922 case Mode.PostDecrement:
930 ig.Emit (OpCodes.Dup);
932 LoadOneAndEmitOp (ec, expr_type);
937 temp_storage.Store (ec);
938 ia.EmitAssign (ec, temp_storage);
943 public override void Emit (EmitContext ec)
949 public override void EmitStatement (EmitContext ec)
951 EmitCode (ec, false);
957 /// Base class for the `Is' and `As' classes.
961 /// FIXME: Split this in two, and we get to save the `Operator' Oper
964 public abstract class Probe : Expression {
965 public readonly Expression ProbeType;
966 protected Expression expr;
967 protected Type probe_type;
969 public Probe (Expression expr, Expression probe_type, Location l)
971 ProbeType = probe_type;
976 public Expression Expr {
982 public override Expression DoResolve (EmitContext ec)
984 probe_type = ec.DeclSpace.ResolveType (ProbeType, false, loc);
986 if (probe_type == null)
989 expr = expr.Resolve (ec);
996 /// Implementation of the `is' operator.
998 public class Is : Probe {
999 public Is (Expression expr, Expression probe_type, Location l)
1000 : base (expr, probe_type, l)
1005 AlwaysTrue, AlwaysNull, AlwaysFalse, LeaveOnStack, Probe
1010 public override void Emit (EmitContext ec)
1012 ILGenerator ig = ec.ig;
1017 case Action.AlwaysFalse:
1018 ig.Emit (OpCodes.Pop);
1019 IntConstant.EmitInt (ig, 0);
1021 case Action.AlwaysTrue:
1022 ig.Emit (OpCodes.Pop);
1023 IntConstant.EmitInt (ig, 1);
1025 case Action.LeaveOnStack:
1026 // the `e != null' rule.
1027 ig.Emit (OpCodes.Ldnull);
1028 ig.Emit (OpCodes.Ceq);
1029 ig.Emit (OpCodes.Ldc_I4_0);
1030 ig.Emit (OpCodes.Ceq);
1033 ig.Emit (OpCodes.Isinst, probe_type);
1034 ig.Emit (OpCodes.Ldnull);
1035 ig.Emit (OpCodes.Cgt_Un);
1038 throw new Exception ("never reached");
1041 public override Expression DoResolve (EmitContext ec)
1043 Expression e = base.DoResolve (ec);
1045 if ((e == null) || (expr == null))
1048 Type etype = expr.Type;
1049 bool warning_always_matches = false;
1050 bool warning_never_matches = false;
1052 type = TypeManager.bool_type;
1053 eclass = ExprClass.Value;
1056 // First case, if at compile time, there is an implicit conversion
1057 // then e != null (objects) or true (value types)
1059 e = ConvertImplicitStandard (ec, expr, probe_type, loc);
1062 if (etype.IsValueType)
1063 action = Action.AlwaysTrue;
1065 action = Action.LeaveOnStack;
1067 warning_always_matches = true;
1068 } else if (ExplicitReferenceConversionExists (etype, probe_type)){
1070 // Second case: explicit reference convresion
1072 if (expr is NullLiteral)
1073 action = Action.AlwaysFalse;
1075 action = Action.Probe;
1077 action = Action.AlwaysFalse;
1078 warning_never_matches = true;
1081 if (RootContext.WarningLevel >= 1){
1082 if (warning_always_matches)
1085 "The expression is always of type `" +
1086 TypeManager.CSharpName (probe_type) + "'");
1087 else if (warning_never_matches){
1088 if (!(probe_type.IsInterface || expr.Type.IsInterface))
1091 "The expression is never of type `" +
1092 TypeManager.CSharpName (probe_type) + "'");
1101 /// Implementation of the `as' operator.
1103 public class As : Probe {
1104 public As (Expression expr, Expression probe_type, Location l)
1105 : base (expr, probe_type, l)
1109 bool do_isinst = false;
1111 public override void Emit (EmitContext ec)
1113 ILGenerator ig = ec.ig;
1118 ig.Emit (OpCodes.Isinst, probe_type);
1121 static void Error_CannotConvertType (Type source, Type target, Location loc)
1124 39, loc, "as operator can not convert from `" +
1125 TypeManager.CSharpName (source) + "' to `" +
1126 TypeManager.CSharpName (target) + "'");
1129 public override Expression DoResolve (EmitContext ec)
1131 Expression e = base.DoResolve (ec);
1137 eclass = ExprClass.Value;
1138 Type etype = expr.Type;
1140 if (TypeManager.IsValueType (probe_type)){
1141 Report.Error (77, loc, "The as operator should be used with a reference type only (" +
1142 TypeManager.CSharpName (probe_type) + " is a value type");
1147 e = ConvertImplicit (ec, expr, probe_type, loc);
1154 if (ExplicitReferenceConversionExists (etype, probe_type)){
1159 Error_CannotConvertType (etype, probe_type, loc);
1165 /// This represents a typecast in the source language.
1167 /// FIXME: Cast expressions have an unusual set of parsing
1168 /// rules, we need to figure those out.
1170 public class Cast : Expression {
1171 Expression target_type;
1174 public Cast (Expression cast_type, Expression expr, Location loc)
1176 this.target_type = cast_type;
1181 public Expression TargetType {
1187 public Expression Expr {
1196 bool CheckRange (EmitContext ec, long value, Type type, long min, long max)
1198 if (!ec.ConstantCheckState)
1201 if ((value < min) || (value > max)) {
1202 Error (221, "Constant value `" + value + "' cannot be converted " +
1203 "to a `" + TypeManager.CSharpName (type) + "' (use `unchecked' " +
1204 "syntax to override)");
1211 bool CheckRange (EmitContext ec, ulong value, Type type, ulong max)
1213 if (!ec.ConstantCheckState)
1217 Error (221, "Constant value `" + value + "' cannot be converted " +
1218 "to a `" + TypeManager.CSharpName (type) + "' (use `unchecked' " +
1219 "syntax to override)");
1226 bool CheckUnsigned (EmitContext ec, long value, Type type)
1228 if (!ec.ConstantCheckState)
1232 Error (221, "Constant value `" + value + "' cannot be converted " +
1233 "to a `" + TypeManager.CSharpName (type) + "' (use `unchecked' " +
1234 "syntax to override)");
1242 /// Attempts to do a compile-time folding of a constant cast.
1244 Expression TryReduce (EmitContext ec, Type target_type)
1246 Expression real_expr = expr;
1247 if (real_expr is EnumConstant)
1248 real_expr = ((EnumConstant) real_expr).Child;
1250 if (real_expr is ByteConstant){
1251 byte v = ((ByteConstant) real_expr).Value;
1253 if (target_type == TypeManager.sbyte_type) {
1254 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1256 return new SByteConstant ((sbyte) v);
1258 if (target_type == TypeManager.short_type)
1259 return new ShortConstant ((short) v);
1260 if (target_type == TypeManager.ushort_type)
1261 return new UShortConstant ((ushort) v);
1262 if (target_type == TypeManager.int32_type)
1263 return new IntConstant ((int) v);
1264 if (target_type == TypeManager.uint32_type)
1265 return new UIntConstant ((uint) v);
1266 if (target_type == TypeManager.int64_type)
1267 return new LongConstant ((long) v);
1268 if (target_type == TypeManager.uint64_type)
1269 return new ULongConstant ((ulong) v);
1270 if (target_type == TypeManager.float_type)
1271 return new FloatConstant ((float) v);
1272 if (target_type == TypeManager.double_type)
1273 return new DoubleConstant ((double) v);
1274 if (target_type == TypeManager.char_type)
1275 return new CharConstant ((char) v);
1276 if (target_type == TypeManager.decimal_type)
1277 return new DecimalConstant ((decimal) v);
1279 if (real_expr is SByteConstant){
1280 sbyte v = ((SByteConstant) real_expr).Value;
1282 if (target_type == TypeManager.byte_type) {
1283 if (!CheckUnsigned (ec, v, target_type))
1285 return new ByteConstant ((byte) v);
1287 if (target_type == TypeManager.short_type)
1288 return new ShortConstant ((short) v);
1289 if (target_type == TypeManager.ushort_type) {
1290 if (!CheckUnsigned (ec, v, target_type))
1292 return new UShortConstant ((ushort) v);
1293 } if (target_type == TypeManager.int32_type)
1294 return new IntConstant ((int) v);
1295 if (target_type == TypeManager.uint32_type) {
1296 if (!CheckUnsigned (ec, v, target_type))
1298 return new UIntConstant ((uint) v);
1299 } if (target_type == TypeManager.int64_type)
1300 return new LongConstant ((long) v);
1301 if (target_type == TypeManager.uint64_type) {
1302 if (!CheckUnsigned (ec, v, target_type))
1304 return new ULongConstant ((ulong) v);
1306 if (target_type == TypeManager.float_type)
1307 return new FloatConstant ((float) v);
1308 if (target_type == TypeManager.double_type)
1309 return new DoubleConstant ((double) v);
1310 if (target_type == TypeManager.char_type) {
1311 if (!CheckUnsigned (ec, v, target_type))
1313 return new CharConstant ((char) v);
1315 if (target_type == TypeManager.decimal_type)
1316 return new DecimalConstant ((decimal) v);
1318 if (real_expr is ShortConstant){
1319 short v = ((ShortConstant) real_expr).Value;
1321 if (target_type == TypeManager.byte_type) {
1322 if (!CheckRange (ec, v, target_type, Byte.MinValue, Byte.MaxValue))
1324 return new ByteConstant ((byte) v);
1326 if (target_type == TypeManager.sbyte_type) {
1327 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1329 return new SByteConstant ((sbyte) v);
1331 if (target_type == TypeManager.ushort_type) {
1332 if (!CheckUnsigned (ec, v, target_type))
1334 return new UShortConstant ((ushort) v);
1336 if (target_type == TypeManager.int32_type)
1337 return new IntConstant ((int) v);
1338 if (target_type == TypeManager.uint32_type) {
1339 if (!CheckUnsigned (ec, v, target_type))
1341 return new UIntConstant ((uint) v);
1343 if (target_type == TypeManager.int64_type)
1344 return new LongConstant ((long) v);
1345 if (target_type == TypeManager.uint64_type) {
1346 if (!CheckUnsigned (ec, v, target_type))
1348 return new ULongConstant ((ulong) v);
1350 if (target_type == TypeManager.float_type)
1351 return new FloatConstant ((float) v);
1352 if (target_type == TypeManager.double_type)
1353 return new DoubleConstant ((double) v);
1354 if (target_type == TypeManager.char_type) {
1355 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1357 return new CharConstant ((char) v);
1359 if (target_type == TypeManager.decimal_type)
1360 return new DecimalConstant ((decimal) v);
1362 if (real_expr is UShortConstant){
1363 ushort v = ((UShortConstant) real_expr).Value;
1365 if (target_type == TypeManager.byte_type) {
1366 if (!CheckRange (ec, v, target_type, Byte.MinValue, Byte.MaxValue))
1368 return new ByteConstant ((byte) v);
1370 if (target_type == TypeManager.sbyte_type) {
1371 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1373 return new SByteConstant ((sbyte) v);
1375 if (target_type == TypeManager.short_type) {
1376 if (!CheckRange (ec, v, target_type, Int16.MinValue, Int16.MaxValue))
1378 return new ShortConstant ((short) v);
1380 if (target_type == TypeManager.int32_type)
1381 return new IntConstant ((int) v);
1382 if (target_type == TypeManager.uint32_type)
1383 return new UIntConstant ((uint) v);
1384 if (target_type == TypeManager.int64_type)
1385 return new LongConstant ((long) v);
1386 if (target_type == TypeManager.uint64_type)
1387 return new ULongConstant ((ulong) v);
1388 if (target_type == TypeManager.float_type)
1389 return new FloatConstant ((float) v);
1390 if (target_type == TypeManager.double_type)
1391 return new DoubleConstant ((double) v);
1392 if (target_type == TypeManager.char_type) {
1393 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1395 return new CharConstant ((char) v);
1397 if (target_type == TypeManager.decimal_type)
1398 return new DecimalConstant ((decimal) v);
1400 if (real_expr is IntConstant){
1401 int v = ((IntConstant) real_expr).Value;
1403 if (target_type == TypeManager.byte_type) {
1404 if (!CheckRange (ec, v, target_type, Byte.MinValue, Byte.MaxValue))
1406 return new ByteConstant ((byte) v);
1408 if (target_type == TypeManager.sbyte_type) {
1409 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1411 return new SByteConstant ((sbyte) v);
1413 if (target_type == TypeManager.short_type) {
1414 if (!CheckRange (ec, v, target_type, Int16.MinValue, Int16.MaxValue))
1416 return new ShortConstant ((short) v);
1418 if (target_type == TypeManager.ushort_type) {
1419 if (!CheckRange (ec, v, target_type, UInt16.MinValue, UInt16.MaxValue))
1421 return new UShortConstant ((ushort) v);
1423 if (target_type == TypeManager.uint32_type) {
1424 if (!CheckRange (ec, v, target_type, Int32.MinValue, Int32.MaxValue))
1426 return new UIntConstant ((uint) v);
1428 if (target_type == TypeManager.int64_type)
1429 return new LongConstant ((long) v);
1430 if (target_type == TypeManager.uint64_type) {
1431 if (!CheckUnsigned (ec, v, target_type))
1433 return new ULongConstant ((ulong) v);
1435 if (target_type == TypeManager.float_type)
1436 return new FloatConstant ((float) v);
1437 if (target_type == TypeManager.double_type)
1438 return new DoubleConstant ((double) v);
1439 if (target_type == TypeManager.char_type) {
1440 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1442 return new CharConstant ((char) v);
1444 if (target_type == TypeManager.decimal_type)
1445 return new DecimalConstant ((decimal) v);
1447 if (real_expr is UIntConstant){
1448 uint v = ((UIntConstant) real_expr).Value;
1450 if (target_type == TypeManager.byte_type) {
1451 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1453 return new ByteConstant ((byte) v);
1455 if (target_type == TypeManager.sbyte_type) {
1456 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1458 return new SByteConstant ((sbyte) v);
1460 if (target_type == TypeManager.short_type) {
1461 if (!CheckRange (ec, v, target_type, Int16.MinValue, Int16.MaxValue))
1463 return new ShortConstant ((short) v);
1465 if (target_type == TypeManager.ushort_type) {
1466 if (!CheckRange (ec, v, target_type, UInt16.MinValue, UInt16.MaxValue))
1468 return new UShortConstant ((ushort) v);
1470 if (target_type == TypeManager.int32_type) {
1471 if (!CheckRange (ec, v, target_type, Int32.MinValue, Int32.MaxValue))
1473 return new IntConstant ((int) v);
1475 if (target_type == TypeManager.int64_type)
1476 return new LongConstant ((long) v);
1477 if (target_type == TypeManager.uint64_type)
1478 return new ULongConstant ((ulong) v);
1479 if (target_type == TypeManager.float_type)
1480 return new FloatConstant ((float) v);
1481 if (target_type == TypeManager.double_type)
1482 return new DoubleConstant ((double) v);
1483 if (target_type == TypeManager.char_type) {
1484 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1486 return new CharConstant ((char) v);
1488 if (target_type == TypeManager.decimal_type)
1489 return new DecimalConstant ((decimal) v);
1491 if (real_expr is LongConstant){
1492 long v = ((LongConstant) real_expr).Value;
1494 if (target_type == TypeManager.byte_type) {
1495 if (!CheckRange (ec, v, target_type, Byte.MinValue, Byte.MaxValue))
1497 return new ByteConstant ((byte) v);
1499 if (target_type == TypeManager.sbyte_type) {
1500 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1502 return new SByteConstant ((sbyte) v);
1504 if (target_type == TypeManager.short_type) {
1505 if (!CheckRange (ec, v, target_type, Int16.MinValue, Int16.MaxValue))
1507 return new ShortConstant ((short) v);
1509 if (target_type == TypeManager.ushort_type) {
1510 if (!CheckRange (ec, v, target_type, UInt16.MinValue, UInt16.MaxValue))
1512 return new UShortConstant ((ushort) v);
1514 if (target_type == TypeManager.int32_type) {
1515 if (!CheckRange (ec, v, target_type, Int32.MinValue, Int32.MaxValue))
1517 return new IntConstant ((int) v);
1519 if (target_type == TypeManager.uint32_type) {
1520 if (!CheckRange (ec, v, target_type, UInt32.MinValue, UInt32.MaxValue))
1522 return new UIntConstant ((uint) v);
1524 if (target_type == TypeManager.uint64_type) {
1525 if (!CheckUnsigned (ec, v, target_type))
1527 return new ULongConstant ((ulong) v);
1529 if (target_type == TypeManager.float_type)
1530 return new FloatConstant ((float) v);
1531 if (target_type == TypeManager.double_type)
1532 return new DoubleConstant ((double) v);
1533 if (target_type == TypeManager.char_type) {
1534 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1536 return new CharConstant ((char) v);
1538 if (target_type == TypeManager.decimal_type)
1539 return new DecimalConstant ((decimal) v);
1541 if (real_expr is ULongConstant){
1542 ulong v = ((ULongConstant) real_expr).Value;
1544 if (target_type == TypeManager.byte_type) {
1545 if (!CheckRange (ec, v, target_type, Byte.MaxValue))
1547 return new ByteConstant ((byte) v);
1549 if (target_type == TypeManager.sbyte_type) {
1550 if (!CheckRange (ec, v, target_type, (ulong) SByte.MaxValue))
1552 return new SByteConstant ((sbyte) v);
1554 if (target_type == TypeManager.short_type) {
1555 if (!CheckRange (ec, v, target_type, (ulong) Int16.MaxValue))
1557 return new ShortConstant ((short) v);
1559 if (target_type == TypeManager.ushort_type) {
1560 if (!CheckRange (ec, v, target_type, UInt16.MaxValue))
1562 return new UShortConstant ((ushort) v);
1564 if (target_type == TypeManager.int32_type) {
1565 if (!CheckRange (ec, v, target_type, Int32.MaxValue))
1567 return new IntConstant ((int) v);
1569 if (target_type == TypeManager.uint32_type) {
1570 if (!CheckRange (ec, v, target_type, UInt32.MaxValue))
1572 return new UIntConstant ((uint) v);
1574 if (target_type == TypeManager.int64_type) {
1575 if (!CheckRange (ec, v, target_type, (ulong) Int64.MaxValue))
1577 return new LongConstant ((long) v);
1579 if (target_type == TypeManager.float_type)
1580 return new FloatConstant ((float) v);
1581 if (target_type == TypeManager.double_type)
1582 return new DoubleConstant ((double) v);
1583 if (target_type == TypeManager.char_type) {
1584 if (!CheckRange (ec, v, target_type, Char.MaxValue))
1586 return new CharConstant ((char) v);
1588 if (target_type == TypeManager.decimal_type)
1589 return new DecimalConstant ((decimal) v);
1591 if (real_expr is FloatConstant){
1592 float v = ((FloatConstant) real_expr).Value;
1594 if (target_type == TypeManager.byte_type)
1595 return new ByteConstant ((byte) v);
1596 if (target_type == TypeManager.sbyte_type)
1597 return new SByteConstant ((sbyte) v);
1598 if (target_type == TypeManager.short_type)
1599 return new ShortConstant ((short) v);
1600 if (target_type == TypeManager.ushort_type)
1601 return new UShortConstant ((ushort) v);
1602 if (target_type == TypeManager.int32_type)
1603 return new IntConstant ((int) v);
1604 if (target_type == TypeManager.uint32_type)
1605 return new UIntConstant ((uint) v);
1606 if (target_type == TypeManager.int64_type)
1607 return new LongConstant ((long) v);
1608 if (target_type == TypeManager.uint64_type)
1609 return new ULongConstant ((ulong) v);
1610 if (target_type == TypeManager.double_type)
1611 return new DoubleConstant ((double) v);
1612 if (target_type == TypeManager.char_type)
1613 return new CharConstant ((char) v);
1614 if (target_type == TypeManager.decimal_type)
1615 return new DecimalConstant ((decimal) v);
1617 if (real_expr is DoubleConstant){
1618 double v = ((DoubleConstant) real_expr).Value;
1620 if (target_type == TypeManager.byte_type)
1621 return new ByteConstant ((byte) v);
1622 if (target_type == TypeManager.sbyte_type)
1623 return new SByteConstant ((sbyte) v);
1624 if (target_type == TypeManager.short_type)
1625 return new ShortConstant ((short) v);
1626 if (target_type == TypeManager.ushort_type)
1627 return new UShortConstant ((ushort) v);
1628 if (target_type == TypeManager.int32_type)
1629 return new IntConstant ((int) v);
1630 if (target_type == TypeManager.uint32_type)
1631 return new UIntConstant ((uint) v);
1632 if (target_type == TypeManager.int64_type)
1633 return new LongConstant ((long) v);
1634 if (target_type == TypeManager.uint64_type)
1635 return new ULongConstant ((ulong) v);
1636 if (target_type == TypeManager.float_type)
1637 return new FloatConstant ((float) v);
1638 if (target_type == TypeManager.char_type)
1639 return new CharConstant ((char) v);
1640 if (target_type == TypeManager.decimal_type)
1641 return new DecimalConstant ((decimal) v);
1644 if (real_expr is CharConstant){
1645 char v = ((CharConstant) real_expr).Value;
1647 if (target_type == TypeManager.byte_type) {
1648 if (!CheckRange (ec, v, target_type, Byte.MinValue, Byte.MaxValue))
1650 return new ByteConstant ((byte) v);
1652 if (target_type == TypeManager.sbyte_type) {
1653 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1655 return new SByteConstant ((sbyte) v);
1657 if (target_type == TypeManager.short_type) {
1658 if (!CheckRange (ec, v, target_type, Int16.MinValue, Int16.MaxValue))
1660 return new ShortConstant ((short) v);
1662 if (target_type == TypeManager.int32_type)
1663 return new IntConstant ((int) v);
1664 if (target_type == TypeManager.uint32_type)
1665 return new UIntConstant ((uint) v);
1666 if (target_type == TypeManager.int64_type)
1667 return new LongConstant ((long) v);
1668 if (target_type == TypeManager.uint64_type)
1669 return new ULongConstant ((ulong) v);
1670 if (target_type == TypeManager.float_type)
1671 return new FloatConstant ((float) v);
1672 if (target_type == TypeManager.double_type)
1673 return new DoubleConstant ((double) v);
1674 if (target_type == TypeManager.char_type) {
1675 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1677 return new CharConstant ((char) v);
1679 if (target_type == TypeManager.decimal_type)
1680 return new DecimalConstant ((decimal) v);
1686 public override Expression DoResolve (EmitContext ec)
1688 expr = expr.Resolve (ec);
1692 int errors = Report.Errors;
1694 type = ec.DeclSpace.ResolveType (target_type, false, Location);
1699 eclass = ExprClass.Value;
1701 if (expr is Constant){
1702 Expression e = TryReduce (ec, type);
1708 expr = ConvertExplicit (ec, expr, type, loc);
1712 public override void Emit (EmitContext ec)
1715 // This one will never happen
1717 throw new Exception ("Should not happen");
1722 /// Binary operators
1724 public class Binary : Expression {
1725 public enum Operator : byte {
1726 Multiply, Division, Modulus,
1727 Addition, Subtraction,
1728 LeftShift, RightShift,
1729 LessThan, GreaterThan, LessThanOrEqual, GreaterThanOrEqual,
1730 Equality, Inequality,
1740 Expression left, right;
1743 // After resolution, method might contain the operator overload
1746 protected MethodBase method;
1747 ArrayList Arguments;
1749 bool DelegateOperation;
1751 // This must be kept in sync with Operator!!!
1752 public static readonly string [] oper_names;
1756 oper_names = new string [(int) Operator.TOP];
1758 oper_names [(int) Operator.Multiply] = "op_Multiply";
1759 oper_names [(int) Operator.Division] = "op_Division";
1760 oper_names [(int) Operator.Modulus] = "op_Modulus";
1761 oper_names [(int) Operator.Addition] = "op_Addition";
1762 oper_names [(int) Operator.Subtraction] = "op_Subtraction";
1763 oper_names [(int) Operator.LeftShift] = "op_LeftShift";
1764 oper_names [(int) Operator.RightShift] = "op_RightShift";
1765 oper_names [(int) Operator.LessThan] = "op_LessThan";
1766 oper_names [(int) Operator.GreaterThan] = "op_GreaterThan";
1767 oper_names [(int) Operator.LessThanOrEqual] = "op_LessThanOrEqual";
1768 oper_names [(int) Operator.GreaterThanOrEqual] = "op_GreaterThanOrEqual";
1769 oper_names [(int) Operator.Equality] = "op_Equality";
1770 oper_names [(int) Operator.Inequality] = "op_Inequality";
1771 oper_names [(int) Operator.BitwiseAnd] = "op_BitwiseAnd";
1772 oper_names [(int) Operator.BitwiseOr] = "op_BitwiseOr";
1773 oper_names [(int) Operator.ExclusiveOr] = "op_ExclusiveOr";
1774 oper_names [(int) Operator.LogicalOr] = "op_LogicalOr";
1775 oper_names [(int) Operator.LogicalAnd] = "op_LogicalAnd";
1778 public Binary (Operator oper, Expression left, Expression right, Location loc)
1786 public Operator Oper {
1795 public Expression Left {
1804 public Expression Right {
1815 /// Returns a stringified representation of the Operator
1817 static string OperName (Operator oper)
1820 case Operator.Multiply:
1822 case Operator.Division:
1824 case Operator.Modulus:
1826 case Operator.Addition:
1828 case Operator.Subtraction:
1830 case Operator.LeftShift:
1832 case Operator.RightShift:
1834 case Operator.LessThan:
1836 case Operator.GreaterThan:
1838 case Operator.LessThanOrEqual:
1840 case Operator.GreaterThanOrEqual:
1842 case Operator.Equality:
1844 case Operator.Inequality:
1846 case Operator.BitwiseAnd:
1848 case Operator.BitwiseOr:
1850 case Operator.ExclusiveOr:
1852 case Operator.LogicalOr:
1854 case Operator.LogicalAnd:
1858 return oper.ToString ();
1861 public override string ToString ()
1863 return "operator " + OperName (oper) + "(" + left.ToString () + ", " +
1864 right.ToString () + ")";
1867 Expression ForceConversion (EmitContext ec, Expression expr, Type target_type)
1869 if (expr.Type == target_type)
1872 return ConvertImplicit (ec, expr, target_type, loc);
1875 public static void Error_OperatorAmbiguous (Location loc, Operator oper, Type l, Type r)
1878 34, loc, "Operator `" + OperName (oper)
1879 + "' is ambiguous on operands of type `"
1880 + TypeManager.CSharpName (l) + "' "
1881 + "and `" + TypeManager.CSharpName (r)
1885 bool IsOfType (EmitContext ec, Type l, Type r, Type t, bool check_user_conversions)
1887 if ((l == t) || (r == t))
1890 if (!check_user_conversions)
1893 if (ImplicitUserConversionExists (ec, l, t))
1895 else if (ImplicitUserConversionExists (ec, r, t))
1902 // Note that handling the case l == Decimal || r == Decimal
1903 // is taken care of by the Step 1 Operator Overload resolution.
1905 // If `check_user_conv' is true, we also check whether a user-defined conversion
1906 // exists. Note that we only need to do this if both arguments are of a user-defined
1907 // type, otherwise ConvertImplict() already finds the user-defined conversion for us,
1908 // so we don't explicitly check for performance reasons.
1910 bool DoNumericPromotions (EmitContext ec, Type l, Type r, bool check_user_conv)
1912 if (IsOfType (ec, l, r, TypeManager.double_type, check_user_conv)){
1914 // If either operand is of type double, the other operand is
1915 // conveted to type double.
1917 if (r != TypeManager.double_type)
1918 right = ConvertImplicit (ec, right, TypeManager.double_type, loc);
1919 if (l != TypeManager.double_type)
1920 left = ConvertImplicit (ec, left, TypeManager.double_type, loc);
1922 type = TypeManager.double_type;
1923 } else if (IsOfType (ec, l, r, TypeManager.float_type, check_user_conv)){
1925 // if either operand is of type float, the other operand is
1926 // converted to type float.
1928 if (r != TypeManager.double_type)
1929 right = ConvertImplicit (ec, right, TypeManager.float_type, loc);
1930 if (l != TypeManager.double_type)
1931 left = ConvertImplicit (ec, left, TypeManager.float_type, loc);
1932 type = TypeManager.float_type;
1933 } else if (IsOfType (ec, l, r, TypeManager.uint64_type, check_user_conv)){
1937 // If either operand is of type ulong, the other operand is
1938 // converted to type ulong. or an error ocurrs if the other
1939 // operand is of type sbyte, short, int or long
1941 if (l == TypeManager.uint64_type){
1942 if (r != TypeManager.uint64_type){
1943 if (right is IntConstant){
1944 IntConstant ic = (IntConstant) right;
1946 e = TryImplicitIntConversion (l, ic);
1949 } else if (right is LongConstant){
1950 long ll = ((LongConstant) right).Value;
1953 right = new ULongConstant ((ulong) ll);
1955 e = ImplicitNumericConversion (ec, right, l, loc);
1962 if (left is IntConstant){
1963 e = TryImplicitIntConversion (r, (IntConstant) left);
1966 } else if (left is LongConstant){
1967 long ll = ((LongConstant) left).Value;
1970 left = new ULongConstant ((ulong) ll);
1972 e = ImplicitNumericConversion (ec, left, r, loc);
1979 if ((other == TypeManager.sbyte_type) ||
1980 (other == TypeManager.short_type) ||
1981 (other == TypeManager.int32_type) ||
1982 (other == TypeManager.int64_type))
1983 Error_OperatorAmbiguous (loc, oper, l, r);
1984 type = TypeManager.uint64_type;
1985 } else if (IsOfType (ec, l, r, TypeManager.int64_type, check_user_conv)){
1987 // If either operand is of type long, the other operand is converted
1990 if (l != TypeManager.int64_type)
1991 left = ConvertImplicit (ec, left, TypeManager.int64_type, loc);
1992 if (r != TypeManager.int64_type)
1993 right = ConvertImplicit (ec, right, TypeManager.int64_type, loc);
1995 type = TypeManager.int64_type;
1996 } else if (IsOfType (ec, l, r, TypeManager.uint32_type, check_user_conv)){
1998 // If either operand is of type uint, and the other
1999 // operand is of type sbyte, short or int, othe operands are
2000 // converted to type long.
2004 if (l == TypeManager.uint32_type){
2005 if (right is IntConstant){
2006 IntConstant ic = (IntConstant) right;
2010 right = new UIntConstant ((uint) val);
2017 else if (r == TypeManager.uint32_type){
2018 if (left is IntConstant){
2019 IntConstant ic = (IntConstant) left;
2023 left = new UIntConstant ((uint) val);
2032 if ((other == TypeManager.sbyte_type) ||
2033 (other == TypeManager.short_type) ||
2034 (other == TypeManager.int32_type)){
2035 left = ForceConversion (ec, left, TypeManager.int64_type);
2036 right = ForceConversion (ec, right, TypeManager.int64_type);
2037 type = TypeManager.int64_type;
2040 // if either operand is of type uint, the other
2041 // operand is converd to type uint
2043 left = ForceConversion (ec, left, TypeManager.uint32_type);
2044 right = ForceConversion (ec, right, TypeManager.uint32_type);
2045 type = TypeManager.uint32_type;
2047 } else if (l == TypeManager.decimal_type || r == TypeManager.decimal_type){
2048 if (l != TypeManager.decimal_type)
2049 left = ConvertImplicit (ec, left, TypeManager.decimal_type, loc);
2051 if (r != TypeManager.decimal_type)
2052 right = ConvertImplicit (ec, right, TypeManager.decimal_type, loc);
2053 type = TypeManager.decimal_type;
2055 left = ForceConversion (ec, left, TypeManager.int32_type);
2056 right = ForceConversion (ec, right, TypeManager.int32_type);
2058 type = TypeManager.int32_type;
2061 return (left != null) && (right != null);
2064 static public void Error_OperatorCannotBeApplied (Location loc, string name, Type l, Type r)
2066 Report.Error (19, loc,
2067 "Operator " + name + " cannot be applied to operands of type `" +
2068 TypeManager.CSharpName (l) + "' and `" +
2069 TypeManager.CSharpName (r) + "'");
2072 void Error_OperatorCannotBeApplied ()
2074 Error_OperatorCannotBeApplied (loc, OperName (oper), left.Type, right.Type);
2077 static bool is_32_or_64 (Type t)
2079 return (t == TypeManager.int32_type || t == TypeManager.uint32_type ||
2080 t == TypeManager.int64_type || t == TypeManager.uint64_type);
2083 static bool is_unsigned (Type t)
2085 return (t == TypeManager.uint32_type || t == TypeManager.uint64_type ||
2086 t == TypeManager.short_type || t == TypeManager.byte_type);
2089 static bool is_user_defined (Type t)
2091 if (t.IsSubclassOf (TypeManager.value_type) &&
2092 (!TypeManager.IsBuiltinType (t) || t == TypeManager.decimal_type))
2098 Expression CheckShiftArguments (EmitContext ec)
2102 Type r = right.Type;
2104 e = ForceConversion (ec, right, TypeManager.int32_type);
2106 Error_OperatorCannotBeApplied ();
2111 if (((e = ConvertImplicit (ec, left, TypeManager.int32_type, loc)) != null) ||
2112 ((e = ConvertImplicit (ec, left, TypeManager.uint32_type, loc)) != null) ||
2113 ((e = ConvertImplicit (ec, left, TypeManager.int64_type, loc)) != null) ||
2114 ((e = ConvertImplicit (ec, left, TypeManager.uint64_type, loc)) != null)){
2120 Error_OperatorCannotBeApplied ();
2124 Expression ResolveOperator (EmitContext ec)
2127 Type r = right.Type;
2129 bool overload_failed = false;
2132 // Special cases: string comapred to null
2134 if (oper == Operator.Equality || oper == Operator.Inequality){
2135 if ((l == TypeManager.string_type && (right is NullLiteral)) ||
2136 (r == TypeManager.string_type && (left is NullLiteral))){
2137 Type = TypeManager.bool_type;
2144 // Do not perform operator overload resolution when both sides are
2147 if (!(TypeManager.IsCLRType (l) && TypeManager.IsCLRType (r))){
2149 // Step 1: Perform Operator Overload location
2151 Expression left_expr, right_expr;
2153 string op = oper_names [(int) oper];
2155 MethodGroupExpr union;
2156 left_expr = MemberLookup (ec, l, op, MemberTypes.Method, AllBindingFlags, loc);
2158 right_expr = MemberLookup (
2159 ec, r, op, MemberTypes.Method, AllBindingFlags, loc);
2160 union = Invocation.MakeUnionSet (left_expr, right_expr, loc);
2162 union = (MethodGroupExpr) left_expr;
2164 if (union != null) {
2165 Arguments = new ArrayList ();
2166 Arguments.Add (new Argument (left, Argument.AType.Expression));
2167 Arguments.Add (new Argument (right, Argument.AType.Expression));
2169 method = Invocation.OverloadResolve (ec, union, Arguments, Location.Null);
2170 if (method != null) {
2171 MethodInfo mi = (MethodInfo) method;
2173 type = mi.ReturnType;
2176 overload_failed = true;
2182 // Step 2: Default operations on CLI native types.
2186 // Step 0: String concatenation (because overloading will get this wrong)
2188 if (oper == Operator.Addition){
2190 // If any of the arguments is a string, cast to string
2193 if (l == TypeManager.string_type){
2195 if (r == TypeManager.void_type) {
2196 Error_OperatorCannotBeApplied ();
2200 if (r == TypeManager.string_type){
2201 if (left is Constant && right is Constant){
2202 StringConstant ls = (StringConstant) left;
2203 StringConstant rs = (StringConstant) right;
2205 return new StringConstant (
2206 ls.Value + rs.Value);
2209 if (left is Binary){
2210 Binary b = (Binary) left;
2213 // Call String.Concat (string, string, string) or
2214 // String.Concat (string, string, string, string)
2217 if (b.oper == Operator.Addition &&
2218 (b.method == TypeManager.string_concat_string_string_string ||
2219 b.method == TypeManager.string_concat_string_string_string_string)){
2220 ArrayList bargs = b.Arguments;
2221 int count = bargs.Count;
2225 Arguments.Add (new Argument (right, Argument.AType.Expression));
2226 type = TypeManager.string_type;
2227 method = TypeManager.string_concat_string_string_string;
2230 } else if (count == 3){
2232 Arguments.Add (new Argument (right, Argument.AType.Expression));
2233 type = TypeManager.string_type;
2234 method = TypeManager.string_concat_string_string_string_string;
2241 method = TypeManager.string_concat_string_string;
2244 method = TypeManager.string_concat_object_object;
2245 right = ConvertImplicit (ec, right,
2246 TypeManager.object_type, loc);
2248 Error_OperatorCannotBeApplied (loc, OperName (oper), l, r);
2252 type = TypeManager.string_type;
2254 Arguments = new ArrayList ();
2255 Arguments.Add (new Argument (left, Argument.AType.Expression));
2256 Arguments.Add (new Argument (right, Argument.AType.Expression));
2260 } else if (r == TypeManager.string_type){
2263 if (l == TypeManager.void_type) {
2264 Error_OperatorCannotBeApplied ();
2268 method = TypeManager.string_concat_object_object;
2269 left = ConvertImplicit (ec, left, TypeManager.object_type, loc);
2271 Error_OperatorCannotBeApplied (loc, OperName (oper), l, r);
2274 Arguments = new ArrayList ();
2275 Arguments.Add (new Argument (left, Argument.AType.Expression));
2276 Arguments.Add (new Argument (right, Argument.AType.Expression));
2278 type = TypeManager.string_type;
2284 // Transform a + ( - b) into a - b
2286 if (right is Unary){
2287 Unary right_unary = (Unary) right;
2289 if (right_unary.Oper == Unary.Operator.UnaryNegation){
2290 oper = Operator.Subtraction;
2291 right = right_unary.Expr;
2297 if (oper == Operator.Equality || oper == Operator.Inequality){
2298 if (l == TypeManager.bool_type || r == TypeManager.bool_type){
2299 if (r != TypeManager.bool_type || l != TypeManager.bool_type){
2300 Error_OperatorCannotBeApplied ();
2304 type = TypeManager.bool_type;
2309 // operator != (object a, object b)
2310 // operator == (object a, object b)
2312 // For this to be used, both arguments have to be reference-types.
2313 // Read the rationale on the spec (14.9.6)
2315 // Also, if at compile time we know that the classes do not inherit
2316 // one from the other, then we catch the error there.
2318 if (!(l.IsValueType || r.IsValueType)){
2319 type = TypeManager.bool_type;
2324 if (l.IsSubclassOf (r) || r.IsSubclassOf (l))
2328 // Also, a standard conversion must exist from either one
2330 if (!(StandardConversionExists (left, r) ||
2331 StandardConversionExists (right, l))){
2332 Error_OperatorCannotBeApplied ();
2336 // We are going to have to convert to an object to compare
2338 if (l != TypeManager.object_type)
2339 left = new EmptyCast (left, TypeManager.object_type);
2340 if (r != TypeManager.object_type)
2341 right = new EmptyCast (right, TypeManager.object_type);
2344 // FIXME: CSC here catches errors cs254 and cs252
2350 // One of them is a valuetype, but the other one is not.
2352 if (!l.IsValueType || !r.IsValueType) {
2353 Error_OperatorCannotBeApplied ();
2358 // Only perform numeric promotions on:
2359 // +, -, *, /, %, &, |, ^, ==, !=, <, >, <=, >=
2361 if (oper == Operator.Addition || oper == Operator.Subtraction) {
2362 if (l.IsSubclassOf (TypeManager.delegate_type) &&
2363 r.IsSubclassOf (TypeManager.delegate_type)) {
2365 Arguments = new ArrayList ();
2366 Arguments.Add (new Argument (left, Argument.AType.Expression));
2367 Arguments.Add (new Argument (right, Argument.AType.Expression));
2369 if (oper == Operator.Addition)
2370 method = TypeManager.delegate_combine_delegate_delegate;
2372 method = TypeManager.delegate_remove_delegate_delegate;
2375 Error_OperatorCannotBeApplied ();
2379 DelegateOperation = true;
2385 // Pointer arithmetic:
2387 // T* operator + (T* x, int y);
2388 // T* operator + (T* x, uint y);
2389 // T* operator + (T* x, long y);
2390 // T* operator + (T* x, ulong y);
2392 // T* operator + (int y, T* x);
2393 // T* operator + (uint y, T *x);
2394 // T* operator + (long y, T *x);
2395 // T* operator + (ulong y, T *x);
2397 // T* operator - (T* x, int y);
2398 // T* operator - (T* x, uint y);
2399 // T* operator - (T* x, long y);
2400 // T* operator - (T* x, ulong y);
2402 // long operator - (T* x, T *y)
2405 if (r.IsPointer && oper == Operator.Subtraction){
2407 return new PointerArithmetic (
2408 false, left, right, TypeManager.int64_type,
2410 } else if (is_32_or_64 (r))
2411 return new PointerArithmetic (
2412 oper == Operator.Addition, left, right, l, loc);
2413 } else if (r.IsPointer && is_32_or_64 (l) && oper == Operator.Addition)
2414 return new PointerArithmetic (
2415 true, right, left, r, loc);
2419 // Enumeration operators
2421 bool lie = TypeManager.IsEnumType (l);
2422 bool rie = TypeManager.IsEnumType (r);
2426 // U operator - (E e, E f)
2427 if (lie && rie && oper == Operator.Subtraction){
2429 type = TypeManager.EnumToUnderlying (l);
2432 Error_OperatorCannotBeApplied ();
2437 // operator + (E e, U x)
2438 // operator - (E e, U x)
2440 if (oper == Operator.Addition || oper == Operator.Subtraction){
2441 Type enum_type = lie ? l : r;
2442 Type other_type = lie ? r : l;
2443 Type underlying_type = TypeManager.EnumToUnderlying (enum_type);
2446 if (underlying_type != other_type){
2447 Error_OperatorCannotBeApplied ();
2456 temp = ConvertImplicit (ec, right, l, loc);
2460 Error_OperatorCannotBeApplied ();
2464 temp = ConvertImplicit (ec, left, r, loc);
2469 Error_OperatorCannotBeApplied ();
2474 if (oper == Operator.Equality || oper == Operator.Inequality ||
2475 oper == Operator.LessThanOrEqual || oper == Operator.LessThan ||
2476 oper == Operator.GreaterThanOrEqual || oper == Operator.GreaterThan){
2477 type = TypeManager.bool_type;
2481 if (oper == Operator.BitwiseAnd ||
2482 oper == Operator.BitwiseOr ||
2483 oper == Operator.ExclusiveOr){
2487 Error_OperatorCannotBeApplied ();
2491 if (oper == Operator.LeftShift || oper == Operator.RightShift)
2492 return CheckShiftArguments (ec);
2494 if (oper == Operator.LogicalOr || oper == Operator.LogicalAnd){
2495 if (l != TypeManager.bool_type || r != TypeManager.bool_type){
2496 Error_OperatorCannotBeApplied ();
2500 type = TypeManager.bool_type;
2505 // operator & (bool x, bool y)
2506 // operator | (bool x, bool y)
2507 // operator ^ (bool x, bool y)
2509 if (l == TypeManager.bool_type && r == TypeManager.bool_type){
2510 if (oper == Operator.BitwiseAnd ||
2511 oper == Operator.BitwiseOr ||
2512 oper == Operator.ExclusiveOr){
2519 // Pointer comparison
2521 if (l.IsPointer && r.IsPointer){
2522 if (oper == Operator.Equality || oper == Operator.Inequality ||
2523 oper == Operator.LessThan || oper == Operator.LessThanOrEqual ||
2524 oper == Operator.GreaterThan || oper == Operator.GreaterThanOrEqual){
2525 type = TypeManager.bool_type;
2531 // We are dealing with numbers
2533 if (overload_failed){
2534 Error_OperatorCannotBeApplied ();
2539 // This will leave left or right set to null if there is an error
2541 bool check_user_conv = is_user_defined (l) && is_user_defined (r);
2542 DoNumericPromotions (ec, l, r, check_user_conv);
2543 if (left == null || right == null){
2544 Error_OperatorCannotBeApplied (loc, OperName (oper), l, r);
2549 // reload our cached types if required
2554 if (oper == Operator.BitwiseAnd ||
2555 oper == Operator.BitwiseOr ||
2556 oper == Operator.ExclusiveOr){
2558 if (!((l == TypeManager.int32_type) ||
2559 (l == TypeManager.uint32_type) ||
2560 (l == TypeManager.int64_type) ||
2561 (l == TypeManager.uint64_type)))
2564 Error_OperatorCannotBeApplied ();
2569 if (oper == Operator.Equality ||
2570 oper == Operator.Inequality ||
2571 oper == Operator.LessThanOrEqual ||
2572 oper == Operator.LessThan ||
2573 oper == Operator.GreaterThanOrEqual ||
2574 oper == Operator.GreaterThan){
2575 type = TypeManager.bool_type;
2581 public override Expression DoResolve (EmitContext ec)
2583 left = left.Resolve (ec);
2584 right = right.Resolve (ec);
2586 if (left == null || right == null)
2589 eclass = ExprClass.Value;
2591 Constant rc = right as Constant;
2592 Constant lc = left as Constant;
2594 if (rc != null & lc != null){
2595 Expression e = ConstantFold.BinaryFold (
2596 ec, oper, lc, rc, loc);
2601 return ResolveOperator (ec);
2605 /// EmitBranchable is called from Statement.EmitBoolExpression in the
2606 /// context of a conditional bool expression. This function will return
2607 /// false if it is was possible to use EmitBranchable, or true if it was.
2609 /// The expression's code is generated, and we will generate a branch to `target'
2610 /// if the resulting expression value is equal to isTrue
2612 public bool EmitBranchable (EmitContext ec, Label target, bool onTrue)
2617 ILGenerator ig = ec.ig;
2620 // This is more complicated than it looks, but its just to avoid
2621 // duplicated tests: basically, we allow ==, !=, >, <, >= and <=
2622 // but on top of that we want for == and != to use a special path
2623 // if we are comparing against null
2625 if (oper == Operator.Equality || oper == Operator.Inequality){
2626 bool my_on_true = oper == Operator.Inequality ? onTrue : !onTrue;
2628 if (left is NullLiteral){
2631 ig.Emit (OpCodes.Brtrue, target);
2633 ig.Emit (OpCodes.Brfalse, target);
2635 } else if (right is NullLiteral){
2638 ig.Emit (OpCodes.Brtrue, target);
2640 ig.Emit (OpCodes.Brfalse, target);
2642 } else if (left is BoolConstant){
2644 if (my_on_true != ((BoolConstant) left).Value)
2645 ig.Emit (OpCodes.Brtrue, target);
2647 ig.Emit (OpCodes.Brfalse, target);
2649 } else if (right is BoolConstant){
2651 if (my_on_true != ((BoolConstant) right).Value)
2652 ig.Emit (OpCodes.Brtrue, target);
2654 ig.Emit (OpCodes.Brfalse, target);
2658 } else if (oper == Operator.LogicalAnd){
2659 if (left is Binary){
2660 Binary left_binary = (Binary) left;
2663 Label tests_end = ig.DefineLabel ();
2665 if (left_binary.EmitBranchable (ec, tests_end, false)){
2666 if (right is Binary){
2667 Binary right_binary = (Binary) right;
2669 if (right_binary.EmitBranchable (ec, target, true)){
2670 ig.MarkLabel (tests_end);
2675 ig.Emit (OpCodes.Brtrue, target);
2676 ig.MarkLabel (tests_end);
2680 if (left_binary.EmitBranchable (ec, target, false)){
2681 if (right is Binary){
2682 Binary right_binary = (Binary) right;
2684 if (right_binary.EmitBranchable (ec, target, false))
2689 ig.Emit (OpCodes.Brtrue, target);
2691 ig.Emit (OpCodes.Brfalse, target);
2696 // Give up, and let the regular Emit work, but we could
2697 // also optimize the left-non-Branchable, but-right-Branchable
2701 } else if (oper == Operator.LogicalOr){
2702 if (left is Binary){
2703 Binary left_binary = (Binary) left;
2706 if (left_binary.EmitBranchable (ec, target, true)){
2707 if (right is Binary){
2708 Binary right_binary = (Binary) right;
2710 if (right_binary.EmitBranchable (ec, target, true))
2714 ig.Emit (OpCodes.Brtrue, target);
2719 // Give up, and let the regular Emit work, but we could
2720 // also optimize the left-non-Branchable, but-right-Branchable
2723 Label tests_end = ig.DefineLabel ();
2725 if (left_binary.EmitBranchable (ec, tests_end, true)){
2726 if (right is Binary){
2727 Binary right_binary = (Binary) right;
2729 if (right_binary.EmitBranchable (ec, target, false)){
2730 ig.MarkLabel (tests_end);
2735 ig.Emit (OpCodes.Brfalse, target);
2736 ig.MarkLabel (tests_end);
2743 } else if (!(oper == Operator.LessThan ||
2744 oper == Operator.GreaterThan ||
2745 oper == Operator.LessThanOrEqual ||
2746 oper == Operator.GreaterThanOrEqual))
2753 bool isUnsigned = is_unsigned (t);
2756 case Operator.Equality:
2758 ig.Emit (OpCodes.Beq, target);
2760 ig.Emit (OpCodes.Bne_Un, target);
2763 case Operator.Inequality:
2765 ig.Emit (OpCodes.Bne_Un, target);
2767 ig.Emit (OpCodes.Beq, target);
2770 case Operator.LessThan:
2773 ig.Emit (OpCodes.Blt_Un, target);
2775 ig.Emit (OpCodes.Blt, target);
2778 ig.Emit (OpCodes.Bge_Un, target);
2780 ig.Emit (OpCodes.Bge, target);
2783 case Operator.GreaterThan:
2786 ig.Emit (OpCodes.Bgt_Un, target);
2788 ig.Emit (OpCodes.Bgt, target);
2791 ig.Emit (OpCodes.Ble_Un, target);
2793 ig.Emit (OpCodes.Ble, target);
2796 case Operator.LessThanOrEqual:
2797 if (t == TypeManager.double_type || t == TypeManager.float_type)
2802 ig.Emit (OpCodes.Ble_Un, target);
2804 ig.Emit (OpCodes.Ble, target);
2807 ig.Emit (OpCodes.Bgt_Un, target);
2809 ig.Emit (OpCodes.Bgt, target);
2813 case Operator.GreaterThanOrEqual:
2814 if (t == TypeManager.double_type || t == TypeManager.float_type)
2818 ig.Emit (OpCodes.Bge_Un, target);
2820 ig.Emit (OpCodes.Bge, target);
2823 ig.Emit (OpCodes.Blt_Un, target);
2825 ig.Emit (OpCodes.Blt, target);
2835 public override void Emit (EmitContext ec)
2837 ILGenerator ig = ec.ig;
2839 Type r = right.Type;
2842 if (method != null) {
2844 // Note that operators are static anyway
2846 if (Arguments != null)
2847 Invocation.EmitArguments (ec, method, Arguments);
2849 if (method is MethodInfo)
2850 ig.Emit (OpCodes.Call, (MethodInfo) method);
2852 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
2854 if (DelegateOperation)
2855 ig.Emit (OpCodes.Castclass, type);
2861 // Handle short-circuit operators differently
2864 if (oper == Operator.LogicalAnd){
2865 Label load_zero = ig.DefineLabel ();
2866 Label end = ig.DefineLabel ();
2867 bool process = true;
2869 if (left is Binary){
2870 Binary left_binary = (Binary) left;
2872 if (left_binary.EmitBranchable (ec, load_zero, false)){
2874 ig.Emit (OpCodes.Br, end);
2881 ig.Emit (OpCodes.Brfalse, load_zero);
2883 ig.Emit (OpCodes.Br, end);
2885 ig.MarkLabel (load_zero);
2886 ig.Emit (OpCodes.Ldc_I4_0);
2889 } else if (oper == Operator.LogicalOr){
2890 Label load_one = ig.DefineLabel ();
2891 Label end = ig.DefineLabel ();
2892 bool process = true;
2894 if (left is Binary){
2895 Binary left_binary = (Binary) left;
2897 if (left_binary.EmitBranchable (ec, load_one, true)){
2899 ig.Emit (OpCodes.Br, end);
2906 ig.Emit (OpCodes.Brtrue, load_one);
2908 ig.Emit (OpCodes.Br, end);
2910 ig.MarkLabel (load_one);
2911 ig.Emit (OpCodes.Ldc_I4_1);
2919 bool isUnsigned = is_unsigned (left.Type);
2922 case Operator.Multiply:
2924 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
2925 opcode = OpCodes.Mul_Ovf;
2926 else if (isUnsigned)
2927 opcode = OpCodes.Mul_Ovf_Un;
2929 opcode = OpCodes.Mul;
2931 opcode = OpCodes.Mul;
2935 case Operator.Division:
2937 opcode = OpCodes.Div_Un;
2939 opcode = OpCodes.Div;
2942 case Operator.Modulus:
2944 opcode = OpCodes.Rem_Un;
2946 opcode = OpCodes.Rem;
2949 case Operator.Addition:
2951 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
2952 opcode = OpCodes.Add_Ovf;
2953 else if (isUnsigned)
2954 opcode = OpCodes.Add_Ovf_Un;
2956 opcode = OpCodes.Add;
2958 opcode = OpCodes.Add;
2961 case Operator.Subtraction:
2963 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
2964 opcode = OpCodes.Sub_Ovf;
2965 else if (isUnsigned)
2966 opcode = OpCodes.Sub_Ovf_Un;
2968 opcode = OpCodes.Sub;
2970 opcode = OpCodes.Sub;
2973 case Operator.RightShift:
2975 opcode = OpCodes.Shr_Un;
2977 opcode = OpCodes.Shr;
2980 case Operator.LeftShift:
2981 opcode = OpCodes.Shl;
2984 case Operator.Equality:
2985 opcode = OpCodes.Ceq;
2988 case Operator.Inequality:
2989 ig.Emit (OpCodes.Ceq);
2990 ig.Emit (OpCodes.Ldc_I4_0);
2992 opcode = OpCodes.Ceq;
2995 case Operator.LessThan:
2997 opcode = OpCodes.Clt_Un;
2999 opcode = OpCodes.Clt;
3002 case Operator.GreaterThan:
3004 opcode = OpCodes.Cgt_Un;
3006 opcode = OpCodes.Cgt;
3009 case Operator.LessThanOrEqual:
3010 Type lt = left.Type;
3012 if (isUnsigned || (lt == TypeManager.double_type || lt == TypeManager.float_type))
3013 ig.Emit (OpCodes.Cgt_Un);
3015 ig.Emit (OpCodes.Cgt);
3016 ig.Emit (OpCodes.Ldc_I4_0);
3018 opcode = OpCodes.Ceq;
3021 case Operator.GreaterThanOrEqual:
3022 Type le = left.Type;
3024 if (isUnsigned || (le == TypeManager.double_type || le == TypeManager.float_type))
3025 ig.Emit (OpCodes.Clt_Un);
3027 ig.Emit (OpCodes.Clt);
3029 ig.Emit (OpCodes.Ldc_I4_1);
3031 opcode = OpCodes.Sub;
3034 case Operator.BitwiseOr:
3035 opcode = OpCodes.Or;
3038 case Operator.BitwiseAnd:
3039 opcode = OpCodes.And;
3042 case Operator.ExclusiveOr:
3043 opcode = OpCodes.Xor;
3047 throw new Exception ("This should not happen: Operator = "
3048 + oper.ToString ());
3054 public bool IsBuiltinOperator {
3056 return method == null;
3061 public class PointerArithmetic : Expression {
3062 Expression left, right;
3066 // We assume that `l' is always a pointer
3068 public PointerArithmetic (bool is_addition, Expression l, Expression r, Type t,
3072 eclass = ExprClass.Variable;
3076 is_add = is_addition;
3079 public override Expression DoResolve (EmitContext ec)
3082 // We are born fully resolved
3087 public override void Emit (EmitContext ec)
3089 Type op_type = left.Type;
3090 ILGenerator ig = ec.ig;
3091 int size = GetTypeSize (op_type.GetElementType ());
3093 if (right.Type.IsPointer){
3095 // handle (pointer - pointer)
3099 ig.Emit (OpCodes.Sub);
3103 ig.Emit (OpCodes.Sizeof, op_type);
3105 IntLiteral.EmitInt (ig, size);
3106 ig.Emit (OpCodes.Div);
3108 ig.Emit (OpCodes.Conv_I8);
3111 // handle + and - on (pointer op int)
3114 ig.Emit (OpCodes.Conv_I);
3118 ig.Emit (OpCodes.Sizeof, op_type);
3120 IntLiteral.EmitInt (ig, size);
3121 ig.Emit (OpCodes.Mul);
3124 ig.Emit (OpCodes.Add);
3126 ig.Emit (OpCodes.Sub);
3132 /// Implements the ternary conditional operator (?:)
3134 public class Conditional : Expression {
3135 Expression expr, trueExpr, falseExpr;
3137 public Conditional (Expression expr, Expression trueExpr, Expression falseExpr, Location l)
3140 this.trueExpr = trueExpr;
3141 this.falseExpr = falseExpr;
3145 public Expression Expr {
3151 public Expression TrueExpr {
3157 public Expression FalseExpr {
3163 public override Expression DoResolve (EmitContext ec)
3165 expr = expr.Resolve (ec);
3170 if (expr.Type != TypeManager.bool_type){
3171 expr = Expression.ResolveBoolean (
3178 trueExpr = trueExpr.Resolve (ec);
3179 falseExpr = falseExpr.Resolve (ec);
3181 if (trueExpr == null || falseExpr == null)
3184 eclass = ExprClass.Value;
3185 if (trueExpr.Type == falseExpr.Type)
3186 type = trueExpr.Type;
3189 Type true_type = trueExpr.Type;
3190 Type false_type = falseExpr.Type;
3192 if (trueExpr is NullLiteral){
3195 } else if (falseExpr is NullLiteral){
3201 // First, if an implicit conversion exists from trueExpr
3202 // to falseExpr, then the result type is of type falseExpr.Type
3204 conv = ConvertImplicit (ec, trueExpr, false_type, loc);
3207 // Check if both can convert implicitl to each other's type
3209 if (ConvertImplicit (ec, falseExpr, true_type, loc) != null){
3211 "Can not compute type of conditional expression " +
3212 "as `" + TypeManager.CSharpName (trueExpr.Type) +
3213 "' and `" + TypeManager.CSharpName (falseExpr.Type) +
3214 "' convert implicitly to each other");
3219 } else if ((conv = ConvertImplicit(ec, falseExpr, true_type,loc))!= null){
3223 Error (173, "The type of the conditional expression can " +
3224 "not be computed because there is no implicit conversion" +
3225 " from `" + TypeManager.CSharpName (trueExpr.Type) + "'" +
3226 " and `" + TypeManager.CSharpName (falseExpr.Type) + "'");
3231 if (expr is BoolConstant){
3232 BoolConstant bc = (BoolConstant) expr;
3243 public override void Emit (EmitContext ec)
3245 ILGenerator ig = ec.ig;
3246 Label false_target = ig.DefineLabel ();
3247 Label end_target = ig.DefineLabel ();
3249 Statement.EmitBoolExpression (ec, expr, false_target, false);
3251 ig.Emit (OpCodes.Br, end_target);
3252 ig.MarkLabel (false_target);
3253 falseExpr.Emit (ec);
3254 ig.MarkLabel (end_target);
3262 public class LocalVariableReference : Expression, IAssignMethod, IMemoryLocation, IVariable {
3263 public readonly string Name;
3264 public readonly Block Block;
3265 VariableInfo variable_info;
3268 public LocalVariableReference (Block block, string name, Location l)
3273 eclass = ExprClass.Variable;
3276 // Setting `is_readonly' to false will allow you to create a writable
3277 // reference to a read-only variable. This is used by foreach and using.
3278 public LocalVariableReference (Block block, string name, Location l,
3279 VariableInfo variable_info, bool is_readonly)
3280 : this (block, name, l)
3282 this.variable_info = variable_info;
3283 this.is_readonly = is_readonly;
3286 public VariableInfo VariableInfo {
3288 if (variable_info == null) {
3289 variable_info = Block.GetVariableInfo (Name);
3290 is_readonly = variable_info.ReadOnly;
3292 return variable_info;
3296 public bool IsAssigned (EmitContext ec, Location loc)
3298 return VariableInfo.IsAssigned (ec, loc);
3301 public bool IsFieldAssigned (EmitContext ec, string name, Location loc)
3303 return VariableInfo.IsFieldAssigned (ec, name, loc);
3306 public void SetAssigned (EmitContext ec)
3308 VariableInfo.SetAssigned (ec);
3311 public void SetFieldAssigned (EmitContext ec, string name)
3313 VariableInfo.SetFieldAssigned (ec, name);
3316 public bool IsReadOnly {
3318 if (variable_info == null) {
3319 variable_info = Block.GetVariableInfo (Name);
3320 is_readonly = variable_info.ReadOnly;
3326 public override Expression DoResolve (EmitContext ec)
3328 VariableInfo vi = VariableInfo;
3331 e = Block.GetConstantExpression (Name);
3334 type = vi.VariableType;
3335 eclass = ExprClass.Value;
3339 if (ec.DoFlowAnalysis && !IsAssigned (ec, loc))
3342 type = vi.VariableType;
3346 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
3348 VariableInfo vi = VariableInfo;
3350 if (ec.DoFlowAnalysis)
3351 ec.SetVariableAssigned (vi);
3353 Expression e = DoResolve (ec);
3359 Error (1604, "cannot assign to `" + Name + "' because it is readonly");
3366 public override void Emit (EmitContext ec)
3368 VariableInfo vi = VariableInfo;
3369 ILGenerator ig = ec.ig;
3371 ig.Emit (OpCodes.Ldloc, vi.LocalBuilder);
3375 public void EmitAssign (EmitContext ec, Expression source)
3377 ILGenerator ig = ec.ig;
3378 VariableInfo vi = VariableInfo;
3384 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3387 public void AddressOf (EmitContext ec, AddressOp mode)
3389 VariableInfo vi = VariableInfo;
3391 ec.ig.Emit (OpCodes.Ldloca, vi.LocalBuilder);
3396 /// This represents a reference to a parameter in the intermediate
3399 public class ParameterReference : Expression, IAssignMethod, IMemoryLocation, IVariable {
3403 public Parameter.Modifier mod;
3404 public bool is_ref, is_out;
3406 public ParameterReference (Parameters pars, int idx, string name, Location loc)
3412 eclass = ExprClass.Variable;
3415 public bool IsAssigned (EmitContext ec, Location loc)
3417 if (!is_out || !ec.DoFlowAnalysis)
3420 if (!ec.CurrentBranching.IsParameterAssigned (idx)) {
3421 Report.Error (165, loc,
3422 "Use of unassigned local variable `" + name + "'");
3429 public bool IsFieldAssigned (EmitContext ec, string field_name, Location loc)
3431 if (!is_out || !ec.DoFlowAnalysis)
3434 if (ec.CurrentBranching.IsParameterAssigned (idx))
3437 if (!ec.CurrentBranching.IsParameterAssigned (idx, field_name)) {
3438 Report.Error (170, loc,
3439 "Use of possibly unassigned field `" + field_name + "'");
3446 public void SetAssigned (EmitContext ec)
3448 if (is_out && ec.DoFlowAnalysis)
3449 ec.CurrentBranching.SetParameterAssigned (idx);
3452 public void SetFieldAssigned (EmitContext ec, string field_name)
3454 if (is_out && ec.DoFlowAnalysis)
3455 ec.CurrentBranching.SetParameterAssigned (idx, field_name);
3459 // Notice that for ref/out parameters, the type exposed is not the
3460 // same type exposed externally.
3463 // externally we expose "int&"
3464 // here we expose "int".
3466 // We record this in "is_ref". This means that the type system can treat
3467 // the type as it is expected, but when we generate the code, we generate
3468 // the alternate kind of code.
3470 public override Expression DoResolve (EmitContext ec)
3472 type = pars.GetParameterInfo (ec.DeclSpace, idx, out mod);
3473 is_ref = (mod & Parameter.Modifier.ISBYREF) != 0;
3474 is_out = (mod & Parameter.Modifier.OUT) != 0;
3475 eclass = ExprClass.Variable;
3477 if (is_out && ec.DoFlowAnalysis && !IsAssigned (ec, loc))
3483 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
3485 type = pars.GetParameterInfo (ec.DeclSpace, idx, out mod);
3486 is_ref = (mod & Parameter.Modifier.ISBYREF) != 0;
3487 is_out = (mod & Parameter.Modifier.OUT) != 0;
3488 eclass = ExprClass.Variable;
3490 if (is_out && ec.DoFlowAnalysis)
3491 ec.SetParameterAssigned (idx);
3496 static void EmitLdArg (ILGenerator ig, int x)
3500 case 0: ig.Emit (OpCodes.Ldarg_0); break;
3501 case 1: ig.Emit (OpCodes.Ldarg_1); break;
3502 case 2: ig.Emit (OpCodes.Ldarg_2); break;
3503 case 3: ig.Emit (OpCodes.Ldarg_3); break;
3504 default: ig.Emit (OpCodes.Ldarg_S, (byte) x); break;
3507 ig.Emit (OpCodes.Ldarg, x);
3511 // This method is used by parameters that are references, that are
3512 // being passed as references: we only want to pass the pointer (that
3513 // is already stored in the parameter, not the address of the pointer,
3514 // and not the value of the variable).
3516 public void EmitLoad (EmitContext ec)
3518 ILGenerator ig = ec.ig;
3524 EmitLdArg (ig, arg_idx);
3527 public override void Emit (EmitContext ec)
3529 ILGenerator ig = ec.ig;
3535 EmitLdArg (ig, arg_idx);
3541 // If we are a reference, we loaded on the stack a pointer
3542 // Now lets load the real value
3544 LoadFromPtr (ig, type);
3547 public void EmitAssign (EmitContext ec, Expression source)
3549 ILGenerator ig = ec.ig;
3556 EmitLdArg (ig, arg_idx);
3561 StoreFromPtr (ig, type);
3564 ig.Emit (OpCodes.Starg_S, (byte) arg_idx);
3566 ig.Emit (OpCodes.Starg, arg_idx);
3570 public void AddressOf (EmitContext ec, AddressOp mode)
3579 ec.ig.Emit (OpCodes.Ldarg_S, (byte) arg_idx);
3581 ec.ig.Emit (OpCodes.Ldarg, arg_idx);
3584 ec.ig.Emit (OpCodes.Ldarga_S, (byte) arg_idx);
3586 ec.ig.Emit (OpCodes.Ldarga, arg_idx);
3593 /// Used for arguments to New(), Invocation()
3595 public class Argument {
3596 public enum AType : byte {
3602 public readonly AType ArgType;
3603 public Expression Expr;
3605 public Argument (Expression expr, AType type)
3608 this.ArgType = type;
3613 if (ArgType == AType.Ref || ArgType == AType.Out)
3614 return TypeManager.LookupType (Expr.Type.ToString () + "&");
3620 public Parameter.Modifier GetParameterModifier ()
3624 return Parameter.Modifier.OUT | Parameter.Modifier.ISBYREF;
3627 return Parameter.Modifier.REF | Parameter.Modifier.ISBYREF;
3630 return Parameter.Modifier.NONE;
3634 public static string FullDesc (Argument a)
3636 return (a.ArgType == AType.Ref ? "ref " :
3637 (a.ArgType == AType.Out ? "out " : "")) +
3638 TypeManager.CSharpName (a.Expr.Type);
3641 public bool ResolveMethodGroup (EmitContext ec, Location loc)
3643 // FIXME: csc doesn't report any error if you try to use `ref' or
3644 // `out' in a delegate creation expression.
3645 Expr = Expr.Resolve (ec, ResolveFlags.VariableOrValue | ResolveFlags.MethodGroup);
3652 public bool Resolve (EmitContext ec, Location loc)
3654 if (ArgType == AType.Ref) {
3655 Expr = Expr.Resolve (ec);
3659 Expr = Expr.ResolveLValue (ec, Expr);
3660 } else if (ArgType == AType.Out)
3661 Expr = Expr.ResolveLValue (ec, new EmptyExpression ());
3663 Expr = Expr.Resolve (ec);
3668 if (ArgType == AType.Expression)
3671 if (Expr.eclass != ExprClass.Variable){
3673 // We just probe to match the CSC output
3675 if (Expr.eclass == ExprClass.PropertyAccess ||
3676 Expr.eclass == ExprClass.IndexerAccess){
3679 "A property or indexer can not be passed as an out or ref " +
3684 "An lvalue is required as an argument to out or ref");
3692 public void Emit (EmitContext ec)
3695 // Ref and Out parameters need to have their addresses taken.
3697 // ParameterReferences might already be references, so we want
3698 // to pass just the value
3700 if (ArgType == AType.Ref || ArgType == AType.Out){
3701 AddressOp mode = AddressOp.Store;
3703 if (ArgType == AType.Ref)
3704 mode |= AddressOp.Load;
3706 if (Expr is ParameterReference){
3707 ParameterReference pr = (ParameterReference) Expr;
3713 pr.AddressOf (ec, mode);
3716 ((IMemoryLocation)Expr).AddressOf (ec, mode);
3723 /// Invocation of methods or delegates.
3725 public class Invocation : ExpressionStatement {
3726 public readonly ArrayList Arguments;
3729 MethodBase method = null;
3732 static Hashtable method_parameter_cache;
3734 static Invocation ()
3736 method_parameter_cache = new PtrHashtable ();
3740 // arguments is an ArrayList, but we do not want to typecast,
3741 // as it might be null.
3743 // FIXME: only allow expr to be a method invocation or a
3744 // delegate invocation (7.5.5)
3746 public Invocation (Expression expr, ArrayList arguments, Location l)
3749 Arguments = arguments;
3753 public Expression Expr {
3760 /// Returns the Parameters (a ParameterData interface) for the
3763 public static ParameterData GetParameterData (MethodBase mb)
3765 object pd = method_parameter_cache [mb];
3769 return (ParameterData) pd;
3772 ip = TypeManager.LookupParametersByBuilder (mb);
3774 method_parameter_cache [mb] = ip;
3776 return (ParameterData) ip;
3778 ParameterInfo [] pi = mb.GetParameters ();
3779 ReflectionParameters rp = new ReflectionParameters (pi);
3780 method_parameter_cache [mb] = rp;
3782 return (ParameterData) rp;
3787 /// Determines "better conversion" as specified in 7.4.2.3
3788 /// Returns : 1 if a->p is better
3789 /// 0 if a->q or neither is better
3791 static int BetterConversion (EmitContext ec, Argument a, Type p, Type q, Location loc)
3793 Type argument_type = a.Type;
3794 Expression argument_expr = a.Expr;
3796 if (argument_type == null)
3797 throw new Exception ("Expression of type " + a.Expr + " does not resolve its type");
3800 // This is a special case since csc behaves this way. I can't find
3801 // it anywhere in the spec but oh well ...
3803 if (argument_expr is NullLiteral && p == TypeManager.string_type && q == TypeManager.object_type)
3805 else if (argument_expr is NullLiteral && p == TypeManager.object_type && q == TypeManager.string_type)
3811 if (argument_type == p)
3814 if (argument_type == q)
3818 // Now probe whether an implicit constant expression conversion
3821 // An implicit constant expression conversion permits the following
3824 // * A constant-expression of type `int' can be converted to type
3825 // sbyte, byute, short, ushort, uint, ulong provided the value of
3826 // of the expression is withing the range of the destination type.
3828 // * A constant-expression of type long can be converted to type
3829 // ulong, provided the value of the constant expression is not negative
3831 // FIXME: Note that this assumes that constant folding has
3832 // taken place. We dont do constant folding yet.
3835 if (argument_expr is IntConstant){
3836 IntConstant ei = (IntConstant) argument_expr;
3837 int value = ei.Value;
3839 if (p == TypeManager.sbyte_type){
3840 if (value >= SByte.MinValue && value <= SByte.MaxValue)
3842 } else if (p == TypeManager.byte_type){
3843 if (q == TypeManager.sbyte_type &&
3844 value >= SByte.MinValue && value <= SByte.MaxValue)
3846 else if (Byte.MinValue >= 0 && value <= Byte.MaxValue)
3848 } else if (p == TypeManager.short_type){
3849 if (value >= Int16.MinValue && value <= Int16.MaxValue)
3851 } else if (p == TypeManager.ushort_type){
3852 if (q == TypeManager.short_type &&
3853 value >= Int16.MinValue && value <= Int16.MaxValue)
3855 else if (value >= UInt16.MinValue && value <= UInt16.MaxValue)
3857 } else if (p == TypeManager.int32_type){
3858 if (value >= Int32.MinValue && value <= Int32.MaxValue)
3860 } else if (p == TypeManager.uint32_type){
3862 // we can optimize this case: a positive int32
3863 // always fits on a uint32
3867 } else if (p == TypeManager.uint64_type){
3869 // we can optimize this case: a positive int32
3870 // always fits on a uint64
3872 if (q == TypeManager.int64_type)
3874 else if (value >= 0)
3876 } else if (p == TypeManager.int64_type){
3879 } else if (argument_type == TypeManager.int64_type && argument_expr is LongConstant){
3880 LongConstant lc = (LongConstant) argument_expr;
3882 if (p == TypeManager.uint64_type){
3889 Expression tmp = ConvertImplicit (ec, argument_expr, p, loc);
3897 Expression p_tmp = new EmptyExpression (p);
3898 Expression q_tmp = new EmptyExpression (q);
3900 if (ImplicitConversionExists (ec, p_tmp, q) == true &&
3901 ImplicitConversionExists (ec, q_tmp, p) == false)
3904 if (p == TypeManager.sbyte_type)
3905 if (q == TypeManager.byte_type || q == TypeManager.ushort_type ||
3906 q == TypeManager.uint32_type || q == TypeManager.uint64_type)
3909 if (p == TypeManager.short_type)
3910 if (q == TypeManager.ushort_type || q == TypeManager.uint32_type ||
3911 q == TypeManager.uint64_type)
3914 if (p == TypeManager.int32_type)
3915 if (q == TypeManager.uint32_type || q == TypeManager.uint64_type)
3918 if (p == TypeManager.int64_type)
3919 if (q == TypeManager.uint64_type)
3926 /// Determines "Better function"
3929 /// and returns an integer indicating :
3930 /// 0 if candidate ain't better
3931 /// 1 if candidate is better than the current best match
3933 static int BetterFunction (EmitContext ec, ArrayList args,
3934 MethodBase candidate, MethodBase best,
3935 bool expanded_form, Location loc)
3937 ParameterData candidate_pd = GetParameterData (candidate);
3938 ParameterData best_pd;
3944 argument_count = args.Count;
3946 int cand_count = candidate_pd.Count;
3948 if (cand_count == 0 && argument_count == 0)
3951 if (candidate_pd.ParameterModifier (cand_count - 1) != Parameter.Modifier.PARAMS)
3952 if (cand_count != argument_count)
3958 if (argument_count == 0 && cand_count == 1 &&
3959 candidate_pd.ParameterModifier (cand_count - 1) == Parameter.Modifier.PARAMS)
3962 for (int j = argument_count; j > 0;) {
3965 Argument a = (Argument) args [j];
3966 Type t = candidate_pd.ParameterType (j);
3968 if (candidate_pd.ParameterModifier (j) == Parameter.Modifier.PARAMS)
3970 t = t.GetElementType ();
3972 x = BetterConversion (ec, a, t, null, loc);
3984 best_pd = GetParameterData (best);
3986 int rating1 = 0, rating2 = 0;
3988 for (int j = 0; j < argument_count; ++j) {
3991 Argument a = (Argument) args [j];
3993 Type ct = candidate_pd.ParameterType (j);
3994 Type bt = best_pd.ParameterType (j);
3996 if (candidate_pd.ParameterModifier (j) == Parameter.Modifier.PARAMS)
3998 ct = ct.GetElementType ();
4000 if (best_pd.ParameterModifier (j) == Parameter.Modifier.PARAMS)
4002 bt = bt.GetElementType ();
4004 x = BetterConversion (ec, a, ct, bt, loc);
4005 y = BetterConversion (ec, a, bt, ct, loc);
4014 if (rating1 > rating2)
4020 public static string FullMethodDesc (MethodBase mb)
4022 string ret_type = "";
4024 if (mb is MethodInfo)
4025 ret_type = TypeManager.CSharpName (((MethodInfo) mb).ReturnType);
4027 StringBuilder sb = new StringBuilder (ret_type);
4029 sb.Append (mb.ReflectedType.ToString ());
4031 sb.Append (mb.Name);
4033 ParameterData pd = GetParameterData (mb);
4035 int count = pd.Count;
4038 for (int i = count; i > 0; ) {
4041 sb.Append (pd.ParameterDesc (count - i - 1));
4047 return sb.ToString ();
4050 public static MethodGroupExpr MakeUnionSet (Expression mg1, Expression mg2, Location loc)
4052 MemberInfo [] miset;
4053 MethodGroupExpr union;
4058 return (MethodGroupExpr) mg2;
4061 return (MethodGroupExpr) mg1;
4064 MethodGroupExpr left_set = null, right_set = null;
4065 int length1 = 0, length2 = 0;
4067 left_set = (MethodGroupExpr) mg1;
4068 length1 = left_set.Methods.Length;
4070 right_set = (MethodGroupExpr) mg2;
4071 length2 = right_set.Methods.Length;
4073 ArrayList common = new ArrayList ();
4075 foreach (MethodBase l in left_set.Methods){
4076 foreach (MethodBase r in right_set.Methods){
4084 miset = new MemberInfo [length1 + length2 - common.Count];
4085 left_set.Methods.CopyTo (miset, 0);
4089 foreach (MemberInfo mi in right_set.Methods){
4090 if (!common.Contains (mi))
4094 union = new MethodGroupExpr (miset, loc);
4100 /// Determines is the candidate method, if a params method, is applicable
4101 /// in its expanded form to the given set of arguments
4103 static bool IsParamsMethodApplicable (EmitContext ec, ArrayList arguments, MethodBase candidate)
4107 if (arguments == null)
4110 arg_count = arguments.Count;
4112 ParameterData pd = GetParameterData (candidate);
4114 int pd_count = pd.Count;
4119 if (pd.ParameterModifier (pd_count - 1) != Parameter.Modifier.PARAMS)
4122 if (pd_count - 1 > arg_count)
4125 if (pd_count == 1 && arg_count == 0)
4129 // If we have come this far, the case which remains is when the number of parameters
4130 // is less than or equal to the argument count.
4132 for (int i = 0; i < pd_count - 1; ++i) {
4134 Argument a = (Argument) arguments [i];
4136 Parameter.Modifier a_mod = a.GetParameterModifier () &
4137 ~(Parameter.Modifier.OUT | Parameter.Modifier.REF);
4138 Parameter.Modifier p_mod = pd.ParameterModifier (i) &
4139 ~(Parameter.Modifier.OUT | Parameter.Modifier.REF);
4141 if (a_mod == p_mod) {
4143 if (a_mod == Parameter.Modifier.NONE)
4144 if (!ImplicitConversionExists (ec, a.Expr, pd.ParameterType (i)))
4147 if ((a_mod & Parameter.Modifier.ISBYREF) != 0) {
4148 Type pt = pd.ParameterType (i);
4151 pt = TypeManager.LookupType (pt.FullName + "&");
4161 Type element_type = pd.ParameterType (pd_count - 1).GetElementType ();
4163 for (int i = pd_count - 1; i < arg_count; i++) {
4164 Argument a = (Argument) arguments [i];
4166 if (!StandardConversionExists (a.Expr, element_type))
4174 /// Determines if the candidate method is applicable (section 14.4.2.1)
4175 /// to the given set of arguments
4177 static bool IsApplicable (EmitContext ec, ArrayList arguments, MethodBase candidate)
4181 if (arguments == null)
4184 arg_count = arguments.Count;
4186 ParameterData pd = GetParameterData (candidate);
4188 int pd_count = pd.Count;
4190 if (arg_count != pd.Count)
4193 for (int i = arg_count; i > 0; ) {
4196 Argument a = (Argument) arguments [i];
4198 Parameter.Modifier a_mod = a.GetParameterModifier () &
4199 ~(Parameter.Modifier.OUT | Parameter.Modifier.REF);
4200 Parameter.Modifier p_mod = pd.ParameterModifier (i) &
4201 ~(Parameter.Modifier.OUT | Parameter.Modifier.REF);
4203 if (a_mod == p_mod ||
4204 (a_mod == Parameter.Modifier.NONE && p_mod == Parameter.Modifier.PARAMS)) {
4205 if (a_mod == Parameter.Modifier.NONE)
4206 if (!ImplicitConversionExists (ec, a.Expr, pd.ParameterType (i)))
4209 if ((a_mod & Parameter.Modifier.ISBYREF) != 0) {
4210 Type pt = pd.ParameterType (i);
4213 pt = TypeManager.LookupType (pt.FullName + "&");
4228 /// Find the Applicable Function Members (7.4.2.1)
4230 /// me: Method Group expression with the members to select.
4231 /// it might contain constructors or methods (or anything
4232 /// that maps to a method).
4234 /// Arguments: ArrayList containing resolved Argument objects.
4236 /// loc: The location if we want an error to be reported, or a Null
4237 /// location for "probing" purposes.
4239 /// Returns: The MethodBase (either a ConstructorInfo or a MethodInfo)
4240 /// that is the best match of me on Arguments.
4243 public static MethodBase OverloadResolve (EmitContext ec, MethodGroupExpr me,
4244 ArrayList Arguments, Location loc)
4246 MethodBase method = null;
4247 Type current_type = null;
4249 ArrayList candidates = new ArrayList ();
4252 foreach (MethodBase candidate in me.Methods){
4255 // If we're going one level higher in the class hierarchy, abort if
4256 // we already found an applicable method.
4257 if (candidate.DeclaringType != current_type) {
4258 current_type = candidate.DeclaringType;
4263 // Check if candidate is applicable (section 14.4.2.1)
4264 if (!IsApplicable (ec, Arguments, candidate))
4267 candidates.Add (candidate);
4268 x = BetterFunction (ec, Arguments, candidate, method, false, loc);
4276 if (Arguments == null)
4279 argument_count = Arguments.Count;
4282 // Now we see if we can find params functions, applicable in their expanded form
4283 // since if they were applicable in their normal form, they would have been selected
4286 bool chose_params_expanded = false;
4288 if (method == null) {
4289 candidates = new ArrayList ();
4290 foreach (MethodBase candidate in me.Methods){
4291 if (!IsParamsMethodApplicable (ec, Arguments, candidate))
4294 candidates.Add (candidate);
4296 int x = BetterFunction (ec, Arguments, candidate, method, true, loc);
4301 chose_params_expanded = true;
4305 if (method == null) {
4307 // Okay so we have failed to find anything so we
4308 // return by providing info about the closest match
4310 for (int i = 0; i < me.Methods.Length; ++i) {
4312 MethodBase c = (MethodBase) me.Methods [i];
4313 ParameterData pd = GetParameterData (c);
4315 if (pd.Count != argument_count)
4318 VerifyArgumentsCompat (ec, Arguments, argument_count, c, false,
4326 // Now check that there are no ambiguities i.e the selected method
4327 // should be better than all the others
4330 foreach (MethodBase candidate in candidates){
4331 if (candidate == method)
4335 // If a normal method is applicable in the sense that it has the same
4336 // number of arguments, then the expanded params method is never applicable
4337 // so we debar the params method.
4339 if (IsParamsMethodApplicable (ec, Arguments, candidate) &&
4340 IsApplicable (ec, Arguments, method))
4343 int x = BetterFunction (ec, Arguments, method, candidate,
4344 chose_params_expanded, loc);
4349 "Ambiguous call when selecting function due to implicit casts");
4355 // And now check if the arguments are all compatible, perform conversions
4356 // if necessary etc. and return if everything is all right
4359 if (!VerifyArgumentsCompat (ec, Arguments, argument_count, method,
4360 chose_params_expanded, null, loc))
4366 static void Error_InvalidArguments (Location loc, int idx, MethodBase method, Type delegate_type, string arg_sig, string par_desc)
4368 if (delegate_type == null)
4369 Report.Error (1502, loc,
4370 "The best overloaded match for method '" +
4371 FullMethodDesc (method) +
4372 "' has some invalid arguments");
4374 Report.Error (1594, loc,
4375 "Delegate '" + delegate_type.ToString () +
4376 "' has some invalid arguments.");
4377 Report.Error (1503, loc,
4378 String.Format ("Argument {0}: Cannot convert from '{1}' to '{2}'",
4379 idx, arg_sig, par_desc));
4382 public static bool VerifyArgumentsCompat (EmitContext ec, ArrayList Arguments,
4385 bool chose_params_expanded,
4389 ParameterData pd = GetParameterData (method);
4390 int pd_count = pd.Count;
4392 for (int j = 0; j < argument_count; j++) {
4393 Argument a = (Argument) Arguments [j];
4394 Expression a_expr = a.Expr;
4395 Type parameter_type = pd.ParameterType (j);
4396 Parameter.Modifier pm = pd.ParameterModifier (j);
4398 if (pm == Parameter.Modifier.PARAMS){
4399 if (chose_params_expanded)
4400 parameter_type = TypeManager.TypeToCoreType (parameter_type.GetElementType ());
4405 if (pd.ParameterModifier (j) != a.GetParameterModifier ()){
4406 if (!Location.IsNull (loc))
4407 Error_InvalidArguments (
4408 loc, j, method, delegate_type,
4409 Argument.FullDesc (a), pd.ParameterDesc (j));
4417 if (a.Type != parameter_type){
4420 conv = ConvertImplicit (ec, a_expr, parameter_type, loc);
4423 if (!Location.IsNull (loc))
4424 Error_InvalidArguments (
4425 loc, j, method, delegate_type,
4426 Argument.FullDesc (a), pd.ParameterDesc (j));
4431 // Update the argument with the implicit conversion
4437 Parameter.Modifier a_mod = a.GetParameterModifier () &
4438 ~(Parameter.Modifier.OUT | Parameter.Modifier.REF);
4439 Parameter.Modifier p_mod = pd.ParameterModifier (j) &
4440 ~(Parameter.Modifier.OUT | Parameter.Modifier.REF);
4443 if (a_mod != p_mod &&
4444 pd.ParameterModifier (pd_count - 1) != Parameter.Modifier.PARAMS) {
4445 if (!Location.IsNull (loc)) {
4446 Console.WriteLine ("A:P: " + a.GetParameterModifier ());
4447 Console.WriteLine ("PP:: " + pd.ParameterModifier (j));
4448 Console.WriteLine ("PT: " + parameter_type.IsByRef);
4449 Report.Error (1502, loc,
4450 "The best overloaded match for method '" + FullMethodDesc (method)+
4451 "' has some invalid arguments");
4452 Report.Error (1503, loc,
4453 "Argument " + (j+1) +
4454 ": Cannot convert from '" + Argument.FullDesc (a)
4455 + "' to '" + pd.ParameterDesc (j) + "'");
4465 public override Expression DoResolve (EmitContext ec)
4468 // First, resolve the expression that is used to
4469 // trigger the invocation
4471 if (expr is BaseAccess)
4474 Expression old = expr;
4476 expr = expr.Resolve (ec, ResolveFlags.VariableOrValue | ResolveFlags.MethodGroup);
4480 if (!(expr is MethodGroupExpr)) {
4481 Type expr_type = expr.Type;
4483 if (expr_type != null){
4484 bool IsDelegate = TypeManager.IsDelegateType (expr_type);
4486 return (new DelegateInvocation (
4487 this.expr, Arguments, loc)).Resolve (ec);
4491 if (!(expr is MethodGroupExpr)){
4492 expr.Error118 (ResolveFlags.MethodGroup);
4497 // Next, evaluate all the expressions in the argument list
4499 if (Arguments != null){
4500 foreach (Argument a in Arguments){
4501 if (!a.Resolve (ec, loc))
4506 MethodGroupExpr mg = (MethodGroupExpr) expr;
4507 method = OverloadResolve (ec, mg, Arguments, loc);
4509 if (method == null){
4511 "Could not find any applicable function for this argument list");
4515 MethodInfo mi = method as MethodInfo;
4517 type = TypeManager.TypeToCoreType (mi.ReturnType);
4518 if (!mi.IsStatic && !mg.IsExplicitImpl && (mg.InstanceExpression == null))
4519 SimpleName.Error_ObjectRefRequired (ec, loc, mi.Name);
4522 if (type.IsPointer){
4530 // Only base will allow this invocation to happen.
4532 if (is_base && method.IsAbstract){
4533 Report.Error (205, loc, "Cannot call an abstract base member: " +
4534 FullMethodDesc (method));
4538 if ((method.Attributes & MethodAttributes.SpecialName) != 0){
4539 if (TypeManager.IsSpecialMethod (method))
4540 Report.Error (571, loc, method.Name + ": can not call operator or accessor");
4543 eclass = ExprClass.Value;
4548 // Emits the list of arguments as an array
4550 static void EmitParams (EmitContext ec, int idx, ArrayList arguments)
4552 ILGenerator ig = ec.ig;
4553 int count = arguments.Count - idx;
4554 Argument a = (Argument) arguments [idx];
4555 Type t = a.Expr.Type;
4556 string array_type = t.FullName + "[]";
4559 array = ig.DeclareLocal (TypeManager.LookupType (array_type));
4560 IntConstant.EmitInt (ig, count);
4561 ig.Emit (OpCodes.Newarr, TypeManager.TypeToCoreType (t));
4562 ig.Emit (OpCodes.Stloc, array);
4564 int top = arguments.Count;
4565 for (int j = idx; j < top; j++){
4566 a = (Argument) arguments [j];
4568 ig.Emit (OpCodes.Ldloc, array);
4569 IntConstant.EmitInt (ig, j - idx);
4572 OpCode op = ArrayAccess.GetStoreOpcode (t, out is_stobj);
4574 ig.Emit (OpCodes.Ldelema, t);
4579 ig.Emit (OpCodes.Stobj, t);
4583 ig.Emit (OpCodes.Ldloc, array);
4587 /// Emits a list of resolved Arguments that are in the arguments
4590 /// The MethodBase argument might be null if the
4591 /// emission of the arguments is known not to contain
4592 /// a `params' field (for example in constructors or other routines
4593 /// that keep their arguments in this structure)
4595 public static void EmitArguments (EmitContext ec, MethodBase mb, ArrayList arguments)
4599 pd = GetParameterData (mb);
4604 // If we are calling a params method with no arguments, special case it
4606 if (arguments == null){
4607 if (pd != null && pd.Count > 0 &&
4608 pd.ParameterModifier (0) == Parameter.Modifier.PARAMS){
4609 ILGenerator ig = ec.ig;
4611 IntConstant.EmitInt (ig, 0);
4612 ig.Emit (OpCodes.Newarr, pd.ParameterType (0).GetElementType ());
4618 int top = arguments.Count;
4620 for (int i = 0; i < top; i++){
4621 Argument a = (Argument) arguments [i];
4624 if (pd.ParameterModifier (i) == Parameter.Modifier.PARAMS){
4626 // Special case if we are passing the same data as the
4627 // params argument, do not put it in an array.
4629 if (pd.ParameterType (i) == a.Type)
4632 EmitParams (ec, i, arguments);
4640 if (pd != null && pd.Count > top &&
4641 pd.ParameterModifier (top) == Parameter.Modifier.PARAMS){
4642 ILGenerator ig = ec.ig;
4644 IntConstant.EmitInt (ig, 0);
4645 ig.Emit (OpCodes.Newarr, pd.ParameterType (top).GetElementType ());
4650 /// is_base tells whether we want to force the use of the `call'
4651 /// opcode instead of using callvirt. Call is required to call
4652 /// a specific method, while callvirt will always use the most
4653 /// recent method in the vtable.
4655 /// is_static tells whether this is an invocation on a static method
4657 /// instance_expr is an expression that represents the instance
4658 /// it must be non-null if is_static is false.
4660 /// method is the method to invoke.
4662 /// Arguments is the list of arguments to pass to the method or constructor.
4664 public static void EmitCall (EmitContext ec, bool is_base,
4665 bool is_static, Expression instance_expr,
4666 MethodBase method, ArrayList Arguments, Location loc)
4668 ILGenerator ig = ec.ig;
4669 bool struct_call = false;
4671 Type decl_type = method.DeclaringType;
4673 if (!RootContext.StdLib) {
4674 // Replace any calls to the system's System.Array type with calls to
4675 // the newly created one.
4676 if (method == TypeManager.system_int_array_get_length)
4677 method = TypeManager.int_array_get_length;
4678 else if (method == TypeManager.system_int_array_get_rank)
4679 method = TypeManager.int_array_get_rank;
4680 else if (method == TypeManager.system_object_array_clone)
4681 method = TypeManager.object_array_clone;
4682 else if (method == TypeManager.system_int_array_get_length_int)
4683 method = TypeManager.int_array_get_length_int;
4684 else if (method == TypeManager.system_int_array_get_lower_bound_int)
4685 method = TypeManager.int_array_get_lower_bound_int;
4686 else if (method == TypeManager.system_int_array_get_upper_bound_int)
4687 method = TypeManager.int_array_get_upper_bound_int;
4688 else if (method == TypeManager.system_void_array_copyto_array_int)
4689 method = TypeManager.void_array_copyto_array_int;
4693 // This checks the `ConditionalAttribute' on the method, and the
4694 // ObsoleteAttribute
4696 TypeManager.MethodFlags flags = TypeManager.GetMethodFlags (method, loc);
4697 if ((flags & TypeManager.MethodFlags.IsObsoleteError) != 0)
4699 if ((flags & TypeManager.MethodFlags.ShouldIgnore) != 0)
4703 if (decl_type.IsValueType)
4706 // If this is ourselves, push "this"
4708 if (instance_expr == null){
4709 ig.Emit (OpCodes.Ldarg_0);
4712 // Push the instance expression
4714 if (instance_expr.Type.IsValueType){
4716 // Special case: calls to a function declared in a
4717 // reference-type with a value-type argument need
4718 // to have their value boxed.
4721 if (decl_type.IsValueType){
4723 // If the expression implements IMemoryLocation, then
4724 // we can optimize and use AddressOf on the
4727 // If not we have to use some temporary storage for
4729 if (instance_expr is IMemoryLocation){
4730 ((IMemoryLocation)instance_expr).
4731 AddressOf (ec, AddressOp.LoadStore);
4734 Type t = instance_expr.Type;
4736 instance_expr.Emit (ec);
4737 LocalBuilder temp = ig.DeclareLocal (t);
4738 ig.Emit (OpCodes.Stloc, temp);
4739 ig.Emit (OpCodes.Ldloca, temp);
4742 instance_expr.Emit (ec);
4743 ig.Emit (OpCodes.Box, instance_expr.Type);
4746 instance_expr.Emit (ec);
4750 EmitArguments (ec, method, Arguments);
4752 if (is_static || struct_call || is_base){
4753 if (method is MethodInfo) {
4754 ig.Emit (OpCodes.Call, (MethodInfo) method);
4756 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
4758 if (method is MethodInfo)
4759 ig.Emit (OpCodes.Callvirt, (MethodInfo) method);
4761 ig.Emit (OpCodes.Callvirt, (ConstructorInfo) method);
4765 public override void Emit (EmitContext ec)
4767 MethodGroupExpr mg = (MethodGroupExpr) this.expr;
4770 ec, is_base, method.IsStatic, mg.InstanceExpression, method, Arguments, loc);
4773 public override void EmitStatement (EmitContext ec)
4778 // Pop the return value if there is one
4780 if (method is MethodInfo){
4781 Type ret = ((MethodInfo)method).ReturnType;
4782 if (TypeManager.TypeToCoreType (ret) != TypeManager.void_type)
4783 ec.ig.Emit (OpCodes.Pop);
4789 // This class is used to "disable" the code generation for the
4790 // temporary variable when initializing value types.
4792 class EmptyAddressOf : EmptyExpression, IMemoryLocation {
4793 public void AddressOf (EmitContext ec, AddressOp Mode)
4800 /// Implements the new expression
4802 public class New : ExpressionStatement {
4803 public readonly ArrayList Arguments;
4804 public readonly Expression RequestedType;
4806 MethodBase method = null;
4809 // If set, the new expression is for a value_target, and
4810 // we will not leave anything on the stack.
4812 Expression value_target;
4813 bool value_target_set = false;
4815 public New (Expression requested_type, ArrayList arguments, Location l)
4817 RequestedType = requested_type;
4818 Arguments = arguments;
4822 public Expression ValueTypeVariable {
4824 return value_target;
4828 value_target = value;
4829 value_target_set = true;
4834 // This function is used to disable the following code sequence for
4835 // value type initialization:
4837 // AddressOf (temporary)
4841 // Instead the provide will have provided us with the address on the
4842 // stack to store the results.
4844 static Expression MyEmptyExpression;
4846 public void DisableTemporaryValueType ()
4848 if (MyEmptyExpression == null)
4849 MyEmptyExpression = new EmptyAddressOf ();
4852 // To enable this, look into:
4853 // test-34 and test-89 and self bootstrapping.
4855 // For instance, we can avoid a copy by using `newobj'
4856 // instead of Call + Push-temp on value types.
4857 // value_target = MyEmptyExpression;
4860 public override Expression DoResolve (EmitContext ec)
4863 // The New DoResolve might be called twice when initializing field
4864 // expressions (see EmitFieldInitializers, the call to
4865 // GetInitializerExpression will perform a resolve on the expression,
4866 // and later the assign will trigger another resolution
4868 // This leads to bugs (#37014)
4873 type = ec.DeclSpace.ResolveType (RequestedType, false, loc);
4878 bool IsDelegate = TypeManager.IsDelegateType (type);
4881 return (new NewDelegate (type, Arguments, loc)).Resolve (ec);
4883 if (type.IsInterface || type.IsAbstract){
4885 144, "It is not possible to create instances of interfaces " +
4886 "or abstract classes");
4890 bool is_struct = false;
4891 is_struct = type.IsValueType;
4892 eclass = ExprClass.Value;
4895 // SRE returns a match for .ctor () on structs (the object constructor),
4896 // so we have to manually ignore it.
4898 if (is_struct && Arguments == null)
4902 ml = MemberLookupFinal (ec, null, type, ".ctor",
4903 MemberTypes.Constructor,
4904 AllBindingFlags | BindingFlags.DeclaredOnly, loc);
4909 if (! (ml is MethodGroupExpr)){
4911 ml.Error118 ("method group");
4917 if (Arguments != null){
4918 foreach (Argument a in Arguments){
4919 if (!a.Resolve (ec, loc))
4924 method = Invocation.OverloadResolve (ec, (MethodGroupExpr) ml,
4929 if (method == null) {
4930 if (!is_struct || Arguments.Count > 0) {
4932 "New invocation: Can not find a constructor for " +
4933 "this argument list");
4941 // This DoEmit can be invoked in two contexts:
4942 // * As a mechanism that will leave a value on the stack (new object)
4943 // * As one that wont (init struct)
4945 // You can control whether a value is required on the stack by passing
4946 // need_value_on_stack. The code *might* leave a value on the stack
4947 // so it must be popped manually
4949 // If we are dealing with a ValueType, we have a few
4950 // situations to deal with:
4952 // * The target is a ValueType, and we have been provided
4953 // the instance (this is easy, we are being assigned).
4955 // * The target of New is being passed as an argument,
4956 // to a boxing operation or a function that takes a
4959 // In this case, we need to create a temporary variable
4960 // that is the argument of New.
4962 // Returns whether a value is left on the stack
4964 bool DoEmit (EmitContext ec, bool need_value_on_stack)
4966 bool is_value_type = type.IsValueType;
4967 ILGenerator ig = ec.ig;
4972 // Allow DoEmit() to be called multiple times.
4973 // We need to create a new LocalTemporary each time since
4974 // you can't share LocalBuilders among ILGeneators.
4975 if (!value_target_set)
4976 value_target = new LocalTemporary (ec, type);
4978 ml = (IMemoryLocation) value_target;
4979 ml.AddressOf (ec, AddressOp.Store);
4983 Invocation.EmitArguments (ec, method, Arguments);
4987 ig.Emit (OpCodes.Initobj, type);
4989 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
4990 if (need_value_on_stack){
4991 value_target.Emit (ec);
4996 ig.Emit (OpCodes.Newobj, (ConstructorInfo) method);
5001 public override void Emit (EmitContext ec)
5006 public override void EmitStatement (EmitContext ec)
5008 if (DoEmit (ec, false))
5009 ec.ig.Emit (OpCodes.Pop);
5014 /// 14.5.10.2: Represents an array creation expression.
5018 /// There are two possible scenarios here: one is an array creation
5019 /// expression that specifies the dimensions and optionally the
5020 /// initialization data and the other which does not need dimensions
5021 /// specified but where initialization data is mandatory.
5023 public class ArrayCreation : ExpressionStatement {
5024 Expression requested_base_type;
5025 ArrayList initializers;
5028 // The list of Argument types.
5029 // This is used to construct the `newarray' or constructor signature
5031 ArrayList arguments;
5034 // Method used to create the array object.
5036 MethodBase new_method = null;
5038 Type array_element_type;
5039 Type underlying_type;
5040 bool is_one_dimensional = false;
5041 bool is_builtin_type = false;
5042 bool expect_initializers = false;
5043 int num_arguments = 0;
5047 ArrayList array_data;
5052 // The number of array initializers that we can handle
5053 // via the InitializeArray method - through EmitStaticInitializers
5055 int num_automatic_initializers;
5057 const int max_automatic_initializers = 6;
5059 public ArrayCreation (Expression requested_base_type, ArrayList exprs, string rank, ArrayList initializers, Location l)
5061 this.requested_base_type = requested_base_type;
5062 this.initializers = initializers;
5066 arguments = new ArrayList ();
5068 foreach (Expression e in exprs) {
5069 arguments.Add (new Argument (e, Argument.AType.Expression));
5074 public ArrayCreation (Expression requested_base_type, string rank, ArrayList initializers, Location l)
5076 this.requested_base_type = requested_base_type;
5077 this.initializers = initializers;
5081 //this.rank = rank.Substring (0, rank.LastIndexOf ("["));
5083 //string tmp = rank.Substring (rank.LastIndexOf ("["));
5085 //dimensions = tmp.Length - 1;
5086 expect_initializers = true;
5089 public Expression FormArrayType (Expression base_type, int idx_count, string rank)
5091 StringBuilder sb = new StringBuilder (rank);
5094 for (int i = 1; i < idx_count; i++)
5099 return new ComposedCast (base_type, sb.ToString (), loc);
5102 void Error_IncorrectArrayInitializer ()
5104 Error (178, "Incorrectly structured array initializer");
5107 public bool CheckIndices (EmitContext ec, ArrayList probe, int idx, bool specified_dims)
5109 if (specified_dims) {
5110 Argument a = (Argument) arguments [idx];
5112 if (!a.Resolve (ec, loc))
5115 if (!(a.Expr is Constant)) {
5116 Error (150, "A constant value is expected");
5120 int value = (int) ((Constant) a.Expr).GetValue ();
5122 if (value != probe.Count) {
5123 Error_IncorrectArrayInitializer ();
5127 bounds [idx] = value;
5130 int child_bounds = -1;
5131 foreach (object o in probe) {
5132 if (o is ArrayList) {
5133 int current_bounds = ((ArrayList) o).Count;
5135 if (child_bounds == -1)
5136 child_bounds = current_bounds;
5138 else if (child_bounds != current_bounds){
5139 Error_IncorrectArrayInitializer ();
5142 bool ret = CheckIndices (ec, (ArrayList) o, idx + 1, specified_dims);
5146 if (child_bounds != -1){
5147 Error_IncorrectArrayInitializer ();
5151 Expression tmp = (Expression) o;
5152 tmp = tmp.Resolve (ec);
5156 // Console.WriteLine ("I got: " + tmp);
5157 // Handle initialization from vars, fields etc.
5159 Expression conv = ConvertImplicitRequired (
5160 ec, tmp, underlying_type, loc);
5165 if (conv is StringConstant)
5166 array_data.Add (conv);
5167 else if (conv is Constant) {
5168 array_data.Add (conv);
5169 num_automatic_initializers++;
5171 array_data.Add (conv);
5178 public void UpdateIndices (EmitContext ec)
5181 for (ArrayList probe = initializers; probe != null;) {
5182 if (probe.Count > 0 && probe [0] is ArrayList) {
5183 Expression e = new IntConstant (probe.Count);
5184 arguments.Add (new Argument (e, Argument.AType.Expression));
5186 bounds [i++] = probe.Count;
5188 probe = (ArrayList) probe [0];
5191 Expression e = new IntConstant (probe.Count);
5192 arguments.Add (new Argument (e, Argument.AType.Expression));
5194 bounds [i++] = probe.Count;
5201 public bool ValidateInitializers (EmitContext ec, Type array_type)
5203 if (initializers == null) {
5204 if (expect_initializers)
5210 if (underlying_type == null)
5214 // We use this to store all the date values in the order in which we
5215 // will need to store them in the byte blob later
5217 array_data = new ArrayList ();
5218 bounds = new Hashtable ();
5222 if (arguments != null) {
5223 ret = CheckIndices (ec, initializers, 0, true);
5226 arguments = new ArrayList ();
5228 ret = CheckIndices (ec, initializers, 0, false);
5235 if (arguments.Count != dimensions) {
5236 Error_IncorrectArrayInitializer ();
5244 void Error_NegativeArrayIndex ()
5246 Error (284, "Can not create array with a negative size");
5250 // Converts `source' to an int, uint, long or ulong.
5252 Expression ExpressionToArrayArgument (EmitContext ec, Expression source)
5256 bool old_checked = ec.CheckState;
5257 ec.CheckState = true;
5259 target = ConvertImplicit (ec, source, TypeManager.int32_type, loc);
5260 if (target == null){
5261 target = ConvertImplicit (ec, source, TypeManager.uint32_type, loc);
5262 if (target == null){
5263 target = ConvertImplicit (ec, source, TypeManager.int64_type, loc);
5264 if (target == null){
5265 target = ConvertImplicit (ec, source, TypeManager.uint64_type, loc);
5267 Expression.Error_CannotConvertImplicit (loc, source.Type, TypeManager.int32_type);
5271 ec.CheckState = old_checked;
5274 // Only positive constants are allowed at compile time
5276 if (target is Constant){
5277 if (target is IntConstant){
5278 if (((IntConstant) target).Value < 0){
5279 Error_NegativeArrayIndex ();
5284 if (target is LongConstant){
5285 if (((LongConstant) target).Value < 0){
5286 Error_NegativeArrayIndex ();
5297 // Creates the type of the array
5299 bool LookupType (EmitContext ec)
5301 StringBuilder array_qualifier = new StringBuilder (rank);
5304 // `In the first form allocates an array instace of the type that results
5305 // from deleting each of the individual expression from the expression list'
5307 if (num_arguments > 0) {
5308 array_qualifier.Append ("[");
5309 for (int i = num_arguments-1; i > 0; i--)
5310 array_qualifier.Append (",");
5311 array_qualifier.Append ("]");
5317 Expression array_type_expr;
5318 array_type_expr = new ComposedCast (requested_base_type, array_qualifier.ToString (), loc);
5319 type = ec.DeclSpace.ResolveType (array_type_expr, false, loc);
5324 underlying_type = type;
5325 if (underlying_type.IsArray)
5326 underlying_type = TypeManager.TypeToCoreType (underlying_type.GetElementType ());
5327 dimensions = type.GetArrayRank ();
5332 public override Expression DoResolve (EmitContext ec)
5336 if (!LookupType (ec))
5340 // First step is to validate the initializers and fill
5341 // in any missing bits
5343 if (!ValidateInitializers (ec, type))
5346 if (arguments == null)
5349 arg_count = arguments.Count;
5350 foreach (Argument a in arguments){
5351 if (!a.Resolve (ec, loc))
5354 Expression real_arg = ExpressionToArrayArgument (ec, a.Expr, loc);
5355 if (real_arg == null)
5362 array_element_type = TypeManager.TypeToCoreType (type.GetElementType ());
5364 if (arg_count == 1) {
5365 is_one_dimensional = true;
5366 eclass = ExprClass.Value;
5370 is_builtin_type = TypeManager.IsBuiltinType (type);
5372 if (is_builtin_type) {
5375 ml = MemberLookup (ec, type, ".ctor", MemberTypes.Constructor,
5376 AllBindingFlags, loc);
5378 if (!(ml is MethodGroupExpr)) {
5379 ml.Error118 ("method group");
5384 Error (-6, "New invocation: Can not find a constructor for " +
5385 "this argument list");
5389 new_method = Invocation.OverloadResolve (ec, (MethodGroupExpr) ml, arguments, loc);
5391 if (new_method == null) {
5392 Error (-6, "New invocation: Can not find a constructor for " +
5393 "this argument list");
5397 eclass = ExprClass.Value;
5400 ModuleBuilder mb = CodeGen.ModuleBuilder;
5401 ArrayList args = new ArrayList ();
5403 if (arguments != null) {
5404 for (int i = 0; i < arg_count; i++)
5405 args.Add (TypeManager.int32_type);
5408 Type [] arg_types = null;
5411 arg_types = new Type [args.Count];
5413 args.CopyTo (arg_types, 0);
5415 new_method = mb.GetArrayMethod (type, ".ctor", CallingConventions.HasThis, null,
5418 if (new_method == null) {
5419 Error (-6, "New invocation: Can not find a constructor for " +
5420 "this argument list");
5424 eclass = ExprClass.Value;
5429 public static byte [] MakeByteBlob (ArrayList array_data, Type underlying_type, Location loc)
5434 int count = array_data.Count;
5436 if (underlying_type.IsEnum)
5437 underlying_type = TypeManager.EnumToUnderlying (underlying_type);
5439 factor = GetTypeSize (underlying_type);
5441 throw new Exception ("unrecognized type in MakeByteBlob: " + underlying_type);
5443 data = new byte [(count * factor + 4) & ~3];
5446 for (int i = 0; i < count; ++i) {
5447 object v = array_data [i];
5449 if (v is EnumConstant)
5450 v = ((EnumConstant) v).Child;
5452 if (v is Constant && !(v is StringConstant))
5453 v = ((Constant) v).GetValue ();
5459 if (underlying_type == TypeManager.int64_type){
5460 if (!(v is Expression)){
5461 long val = (long) v;
5463 for (int j = 0; j < factor; ++j) {
5464 data [idx + j] = (byte) (val & 0xFF);
5468 } else if (underlying_type == TypeManager.uint64_type){
5469 if (!(v is Expression)){
5470 ulong val = (ulong) v;
5472 for (int j = 0; j < factor; ++j) {
5473 data [idx + j] = (byte) (val & 0xFF);
5477 } else if (underlying_type == TypeManager.float_type) {
5478 if (!(v is Expression)){
5479 element = BitConverter.GetBytes ((float) v);
5481 for (int j = 0; j < factor; ++j)
5482 data [idx + j] = element [j];
5484 } else if (underlying_type == TypeManager.double_type) {
5485 if (!(v is Expression)){
5486 element = BitConverter.GetBytes ((double) v);
5488 for (int j = 0; j < factor; ++j)
5489 data [idx + j] = element [j];
5491 } else if (underlying_type == TypeManager.char_type){
5492 if (!(v is Expression)){
5493 int val = (int) ((char) v);
5495 data [idx] = (byte) (val & 0xff);
5496 data [idx+1] = (byte) (val >> 8);
5498 } else if (underlying_type == TypeManager.short_type){
5499 if (!(v is Expression)){
5500 int val = (int) ((short) v);
5502 data [idx] = (byte) (val & 0xff);
5503 data [idx+1] = (byte) (val >> 8);
5505 } else if (underlying_type == TypeManager.ushort_type){
5506 if (!(v is Expression)){
5507 int val = (int) ((ushort) v);
5509 data [idx] = (byte) (val & 0xff);
5510 data [idx+1] = (byte) (val >> 8);
5512 } else if (underlying_type == TypeManager.int32_type) {
5513 if (!(v is Expression)){
5516 data [idx] = (byte) (val & 0xff);
5517 data [idx+1] = (byte) ((val >> 8) & 0xff);
5518 data [idx+2] = (byte) ((val >> 16) & 0xff);
5519 data [idx+3] = (byte) (val >> 24);
5521 } else if (underlying_type == TypeManager.uint32_type) {
5522 if (!(v is Expression)){
5523 uint val = (uint) v;
5525 data [idx] = (byte) (val & 0xff);
5526 data [idx+1] = (byte) ((val >> 8) & 0xff);
5527 data [idx+2] = (byte) ((val >> 16) & 0xff);
5528 data [idx+3] = (byte) (val >> 24);
5530 } else if (underlying_type == TypeManager.sbyte_type) {
5531 if (!(v is Expression)){
5532 sbyte val = (sbyte) v;
5533 data [idx] = (byte) val;
5535 } else if (underlying_type == TypeManager.byte_type) {
5536 if (!(v is Expression)){
5537 byte val = (byte) v;
5538 data [idx] = (byte) val;
5540 } else if (underlying_type == TypeManager.bool_type) {
5541 if (!(v is Expression)){
5542 bool val = (bool) v;
5543 data [idx] = (byte) (val ? 1 : 0);
5545 } else if (underlying_type == TypeManager.decimal_type){
5546 if (!(v is Expression)){
5547 int [] bits = Decimal.GetBits ((decimal) v);
5550 for (int j = 0; j < 4; j++){
5551 data [p++] = (byte) (bits [j] & 0xff);
5552 data [p++] = (byte) ((bits [j] >> 8) & 0xff);
5553 data [p++] = (byte) ((bits [j] >> 16) & 0xff);
5554 data [p++] = (byte) (bits [j] >> 24);
5558 throw new Exception ("Unrecognized type in MakeByteBlob: " + underlying_type);
5567 // Emits the initializers for the array
5569 void EmitStaticInitializers (EmitContext ec, bool is_expression)
5572 // First, the static data
5575 ILGenerator ig = ec.ig;
5577 byte [] data = MakeByteBlob (array_data, underlying_type, loc);
5579 fb = RootContext.MakeStaticData (data);
5582 ig.Emit (OpCodes.Dup);
5583 ig.Emit (OpCodes.Ldtoken, fb);
5584 ig.Emit (OpCodes.Call,
5585 TypeManager.void_initializearray_array_fieldhandle);
5589 // Emits pieces of the array that can not be computed at compile
5590 // time (variables and string locations).
5592 // This always expect the top value on the stack to be the array
5594 void EmitDynamicInitializers (EmitContext ec, bool is_expression)
5596 ILGenerator ig = ec.ig;
5597 int dims = bounds.Count;
5598 int [] current_pos = new int [dims];
5599 int top = array_data.Count;
5600 LocalBuilder temp = ig.DeclareLocal (type);
5602 ig.Emit (OpCodes.Stloc, temp);
5604 MethodInfo set = null;
5608 ModuleBuilder mb = null;
5609 mb = CodeGen.ModuleBuilder;
5610 args = new Type [dims + 1];
5613 for (j = 0; j < dims; j++)
5614 args [j] = TypeManager.int32_type;
5616 args [j] = array_element_type;
5618 set = mb.GetArrayMethod (
5620 CallingConventions.HasThis | CallingConventions.Standard,
5621 TypeManager.void_type, args);
5624 for (int i = 0; i < top; i++){
5626 Expression e = null;
5628 if (array_data [i] is Expression)
5629 e = (Expression) array_data [i];
5633 // Basically we do this for string literals and
5634 // other non-literal expressions
5636 if (e is EnumConstant){
5637 e = ((EnumConstant) e).Child;
5640 if (e is StringConstant || !(e is Constant) ||
5641 num_automatic_initializers <= max_automatic_initializers) {
5642 Type etype = e.Type;
5644 ig.Emit (OpCodes.Ldloc, temp);
5646 for (int idx = 0; idx < dims; idx++)
5647 IntConstant.EmitInt (ig, current_pos [idx]);
5650 // If we are dealing with a struct, get the
5651 // address of it, so we can store it.
5654 etype.IsSubclassOf (TypeManager.value_type) &&
5655 (!TypeManager.IsBuiltinType (etype) ||
5656 etype == TypeManager.decimal_type)) {
5661 // Let new know that we are providing
5662 // the address where to store the results
5664 n.DisableTemporaryValueType ();
5667 ig.Emit (OpCodes.Ldelema, etype);
5673 ArrayAccess.EmitStoreOpcode (ig, array_element_type);
5675 ig.Emit (OpCodes.Call, set);
5682 for (int j = dims - 1; j >= 0; j--){
5684 if (current_pos [j] < (int) bounds [j])
5686 current_pos [j] = 0;
5691 ig.Emit (OpCodes.Ldloc, temp);
5694 void EmitArrayArguments (EmitContext ec)
5696 ILGenerator ig = ec.ig;
5698 foreach (Argument a in arguments) {
5699 Type atype = a.Type;
5702 if (atype == TypeManager.uint64_type)
5703 ig.Emit (OpCodes.Conv_Ovf_U4);
5704 else if (atype == TypeManager.int64_type)
5705 ig.Emit (OpCodes.Conv_Ovf_I4);
5709 void DoEmit (EmitContext ec, bool is_statement)
5711 ILGenerator ig = ec.ig;
5713 EmitArrayArguments (ec);
5714 if (is_one_dimensional)
5715 ig.Emit (OpCodes.Newarr, array_element_type);
5717 if (is_builtin_type)
5718 ig.Emit (OpCodes.Newobj, (ConstructorInfo) new_method);
5720 ig.Emit (OpCodes.Newobj, (MethodInfo) new_method);
5723 if (initializers != null){
5725 // FIXME: Set this variable correctly.
5727 bool dynamic_initializers = true;
5729 if (underlying_type != TypeManager.string_type &&
5730 underlying_type != TypeManager.object_type) {
5731 if (num_automatic_initializers > max_automatic_initializers)
5732 EmitStaticInitializers (ec, dynamic_initializers || !is_statement);
5735 if (dynamic_initializers)
5736 EmitDynamicInitializers (ec, !is_statement);
5740 public override void Emit (EmitContext ec)
5745 public override void EmitStatement (EmitContext ec)
5753 /// Represents the `this' construct
5755 public class This : Expression, IAssignMethod, IMemoryLocation, IVariable {
5760 public This (Block block, Location loc)
5766 public This (Location loc)
5771 public bool IsAssigned (EmitContext ec, Location loc)
5776 return vi.IsAssigned (ec, loc);
5779 public bool IsFieldAssigned (EmitContext ec, string field_name, Location loc)
5784 return vi.IsFieldAssigned (ec, field_name, loc);
5787 public void SetAssigned (EmitContext ec)
5790 vi.SetAssigned (ec);
5793 public void SetFieldAssigned (EmitContext ec, string field_name)
5796 vi.SetFieldAssigned (ec, field_name);
5799 public override Expression DoResolve (EmitContext ec)
5801 eclass = ExprClass.Variable;
5802 type = ec.ContainerType;
5805 Error (26, "Keyword this not valid in static code");
5810 vi = block.ThisVariable;
5815 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
5819 VariableInfo vi = ec.CurrentBlock.ThisVariable;
5821 vi.SetAssigned (ec);
5823 if (ec.TypeContainer is Class){
5824 Error (1604, "Cannot assign to `this'");
5831 public override void Emit (EmitContext ec)
5833 ILGenerator ig = ec.ig;
5835 ig.Emit (OpCodes.Ldarg_0);
5836 if (ec.TypeContainer is Struct)
5837 ig.Emit (OpCodes.Ldobj, type);
5840 public void EmitAssign (EmitContext ec, Expression source)
5842 ILGenerator ig = ec.ig;
5844 if (ec.TypeContainer is Struct){
5845 ig.Emit (OpCodes.Ldarg_0);
5847 ig.Emit (OpCodes.Stobj, type);
5850 ig.Emit (OpCodes.Starg, 0);
5854 public void AddressOf (EmitContext ec, AddressOp mode)
5856 ec.ig.Emit (OpCodes.Ldarg_0);
5859 // FIGURE OUT WHY LDARG_S does not work
5861 // consider: struct X { int val; int P { set { val = value; }}}
5863 // Yes, this looks very bad. Look at `NOTAS' for
5865 // ec.ig.Emit (OpCodes.Ldarga_S, (byte) 0);
5870 /// Implements the typeof operator
5872 public class TypeOf : Expression {
5873 public readonly Expression QueriedType;
5876 public TypeOf (Expression queried_type, Location l)
5878 QueriedType = queried_type;
5882 public override Expression DoResolve (EmitContext ec)
5884 typearg = ec.DeclSpace.ResolveType (QueriedType, false, loc);
5886 if (typearg == null)
5889 type = TypeManager.type_type;
5890 eclass = ExprClass.Type;
5894 public override void Emit (EmitContext ec)
5896 ec.ig.Emit (OpCodes.Ldtoken, typearg);
5897 ec.ig.Emit (OpCodes.Call, TypeManager.system_type_get_type_from_handle);
5900 public Type TypeArg {
5901 get { return typearg; }
5906 /// Implements the sizeof expression
5908 public class SizeOf : Expression {
5909 public readonly Expression QueriedType;
5912 public SizeOf (Expression queried_type, Location l)
5914 this.QueriedType = queried_type;
5918 public override Expression DoResolve (EmitContext ec)
5922 233, loc, "Sizeof may only be used in an unsafe context " +
5923 "(consider using System.Runtime.InteropServices.Marshal.Sizeof");
5927 type_queried = ec.DeclSpace.ResolveType (QueriedType, false, loc);
5928 if (type_queried == null)
5931 if (!TypeManager.IsUnmanagedType (type_queried)){
5932 Report.Error (208, loc, "Cannot take the size of an unmanaged type (" + TypeManager.CSharpName (type_queried) + ")");
5936 type = TypeManager.int32_type;
5937 eclass = ExprClass.Value;
5941 public override void Emit (EmitContext ec)
5943 int size = GetTypeSize (type_queried);
5946 ec.ig.Emit (OpCodes.Sizeof, type_queried);
5948 IntConstant.EmitInt (ec.ig, size);
5953 /// Implements the member access expression
5955 public class MemberAccess : Expression, ITypeExpression {
5956 public readonly string Identifier;
5958 Expression member_lookup;
5960 public MemberAccess (Expression expr, string id, Location l)
5967 public Expression Expr {
5973 static void error176 (Location loc, string name)
5975 Report.Error (176, loc, "Static member `" +
5976 name + "' cannot be accessed " +
5977 "with an instance reference, qualify with a " +
5978 "type name instead");
5981 static bool IdenticalNameAndTypeName (EmitContext ec, Expression left_original, Location loc)
5983 if (left_original == null)
5986 if (!(left_original is SimpleName))
5989 SimpleName sn = (SimpleName) left_original;
5991 Type t = RootContext.LookupType (ec.DeclSpace, sn.Name, true, loc);
5998 public static Expression ResolveMemberAccess (EmitContext ec, Expression member_lookup,
5999 Expression left, Location loc,
6000 Expression left_original)
6002 bool left_is_type, left_is_explicit;
6004 // If `left' is null, then we're called from SimpleNameResolve and this is
6005 // a member in the currently defining class.
6007 left_is_type = ec.IsStatic || ec.IsFieldInitializer;
6008 left_is_explicit = false;
6010 // Implicitly default to `this' unless we're static.
6011 if (!ec.IsStatic && !ec.IsFieldInitializer && !ec.InEnumContext)
6014 left_is_type = left is TypeExpr;
6015 left_is_explicit = true;
6018 if (member_lookup is FieldExpr){
6019 FieldExpr fe = (FieldExpr) member_lookup;
6020 FieldInfo fi = fe.FieldInfo;
6021 Type decl_type = fi.DeclaringType;
6023 if (fi is FieldBuilder) {
6024 Const c = TypeManager.LookupConstant ((FieldBuilder) fi);
6027 object o = c.LookupConstantValue (ec);
6031 object real_value = ((Constant) c.Expr).GetValue ();
6033 return Constantify (real_value, fi.FieldType);
6038 Type t = fi.FieldType;
6042 if (fi is FieldBuilder)
6043 o = TypeManager.GetValue ((FieldBuilder) fi);
6045 o = fi.GetValue (fi);
6047 if (decl_type.IsSubclassOf (TypeManager.enum_type)) {
6048 if (left_is_explicit && !left_is_type &&
6049 !IdenticalNameAndTypeName (ec, left_original, loc)) {
6050 error176 (loc, fe.FieldInfo.Name);
6054 Expression enum_member = MemberLookup (
6055 ec, decl_type, "value__", MemberTypes.Field,
6056 AllBindingFlags, loc);
6058 Enum en = TypeManager.LookupEnum (decl_type);
6062 c = Constantify (o, en.UnderlyingType);
6064 c = Constantify (o, enum_member.Type);
6066 return new EnumConstant (c, decl_type);
6069 Expression exp = Constantify (o, t);
6071 if (left_is_explicit && !left_is_type) {
6072 error176 (loc, fe.FieldInfo.Name);
6079 if (fi.FieldType.IsPointer && !ec.InUnsafe){
6085 if (member_lookup is EventExpr) {
6087 EventExpr ee = (EventExpr) member_lookup;
6090 // If the event is local to this class, we transform ourselves into
6094 if (ee.EventInfo.DeclaringType == ec.ContainerType) {
6095 MemberInfo mi = GetFieldFromEvent (ee);
6099 // If this happens, then we have an event with its own
6100 // accessors and private field etc so there's no need
6101 // to transform ourselves : we should instead flag an error
6103 Assign.error70 (ee.EventInfo, loc);
6107 Expression ml = ExprClassFromMemberInfo (ec, mi, loc);
6110 Report.Error (-200, loc, "Internal error!!");
6114 return ResolveMemberAccess (ec, ml, left, loc, left_original);
6118 if (member_lookup is IMemberExpr) {
6119 IMemberExpr me = (IMemberExpr) member_lookup;
6122 MethodGroupExpr mg = me as MethodGroupExpr;
6123 if ((mg != null) && left_is_explicit && left.Type.IsInterface)
6124 mg.IsExplicitImpl = left_is_explicit;
6127 if (IdenticalNameAndTypeName (ec, left_original, loc))
6128 return member_lookup;
6130 SimpleName.Error_ObjectRefRequired (ec, loc, me.Name);
6135 if (!me.IsInstance){
6136 if (IdenticalNameAndTypeName (ec, left_original, loc))
6137 return member_lookup;
6139 if (left_is_explicit) {
6140 error176 (loc, me.Name);
6146 // Since we can not check for instance objects in SimpleName,
6147 // becaue of the rule that allows types and variables to share
6148 // the name (as long as they can be de-ambiguated later, see
6149 // IdenticalNameAndTypeName), we have to check whether left
6150 // is an instance variable in a static context
6152 // However, if the left-hand value is explicitly given, then
6153 // it is already our instance expression, so we aren't in
6157 if (ec.IsStatic && !left_is_explicit && left is IMemberExpr){
6158 IMemberExpr mexp = (IMemberExpr) left;
6160 if (!mexp.IsStatic){
6161 SimpleName.Error_ObjectRefRequired (ec, loc, mexp.Name);
6166 me.InstanceExpression = left;
6169 return member_lookup;
6172 if (member_lookup is TypeExpr){
6173 member_lookup.Resolve (ec, ResolveFlags.Type);
6174 return member_lookup;
6177 Console.WriteLine ("Left is: " + left);
6178 Report.Error (-100, loc, "Support for [" + member_lookup + "] is not present yet");
6179 Environment.Exit (0);
6183 public Expression DoResolve (EmitContext ec, Expression right_side, ResolveFlags flags)
6186 throw new Exception ();
6188 // Resolve the expression with flow analysis turned off, we'll do the definite
6189 // assignment checks later. This is because we don't know yet what the expression
6190 // will resolve to - it may resolve to a FieldExpr and in this case we must do the
6191 // definite assignment check on the actual field and not on the whole struct.
6194 Expression original = expr;
6195 expr = expr.Resolve (ec, flags | ResolveFlags.DisableFlowAnalysis);
6200 if (expr is SimpleName){
6201 SimpleName child_expr = (SimpleName) expr;
6203 Expression new_expr = new SimpleName (child_expr.Name, Identifier, loc);
6205 return new_expr.Resolve (ec, flags);
6209 // TODO: I mailed Ravi about this, and apparently we can get rid
6210 // of this and put it in the right place.
6212 // Handle enums here when they are in transit.
6213 // Note that we cannot afford to hit MemberLookup in this case because
6214 // it will fail to find any members at all
6217 int errors = Report.Errors;
6219 Type expr_type = expr.Type;
6220 if ((expr is TypeExpr) &&
6221 (expr_type == TypeManager.enum_type ||
6222 expr_type.IsSubclassOf (TypeManager.enum_type))){
6224 Enum en = TypeManager.LookupEnum (expr_type);
6227 object value = en.LookupEnumValue (ec, Identifier, loc);
6230 Constant c = Constantify (value, en.UnderlyingType);
6231 return new EnumConstant (c, expr_type);
6236 if (expr_type.IsPointer){
6237 Error (23, "The `.' operator can not be applied to pointer operands (" +
6238 TypeManager.CSharpName (expr_type) + ")");
6242 member_lookup = MemberLookupFinal (ec, expr_type, expr_type, Identifier, loc);
6243 if (member_lookup == null)
6246 if (member_lookup is TypeExpr){
6247 member_lookup.Resolve (ec, ResolveFlags.Type);
6248 return member_lookup;
6249 } else if ((flags & ResolveFlags.MaskExprClass) == ResolveFlags.Type)
6252 member_lookup = ResolveMemberAccess (ec, member_lookup, expr, loc, original);
6253 if (member_lookup == null)
6256 // The following DoResolve/DoResolveLValue will do the definite assignment
6259 if (right_side != null)
6260 member_lookup = member_lookup.DoResolveLValue (ec, right_side);
6262 member_lookup = member_lookup.DoResolve (ec);
6264 return member_lookup;
6267 public override Expression DoResolve (EmitContext ec)
6269 return DoResolve (ec, null, ResolveFlags.VariableOrValue |
6270 ResolveFlags.SimpleName | ResolveFlags.Type);
6273 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
6275 return DoResolve (ec, right_side, ResolveFlags.VariableOrValue |
6276 ResolveFlags.SimpleName | ResolveFlags.Type);
6279 public Expression DoResolveType (EmitContext ec)
6281 return DoResolve (ec, null, ResolveFlags.Type);
6284 public override void Emit (EmitContext ec)
6286 throw new Exception ("Should not happen");
6289 public override string ToString ()
6291 return expr + "." + Identifier;
6296 /// Implements checked expressions
6298 public class CheckedExpr : Expression {
6300 public Expression Expr;
6302 public CheckedExpr (Expression e, Location l)
6308 public override Expression DoResolve (EmitContext ec)
6310 bool last_check = ec.CheckState;
6311 bool last_const_check = ec.ConstantCheckState;
6313 ec.CheckState = true;
6314 ec.ConstantCheckState = true;
6315 Expr = Expr.Resolve (ec);
6316 ec.CheckState = last_check;
6317 ec.ConstantCheckState = last_const_check;
6322 if (Expr is Constant)
6325 eclass = Expr.eclass;
6330 public override void Emit (EmitContext ec)
6332 bool last_check = ec.CheckState;
6333 bool last_const_check = ec.ConstantCheckState;
6335 ec.CheckState = true;
6336 ec.ConstantCheckState = true;
6338 ec.CheckState = last_check;
6339 ec.ConstantCheckState = last_const_check;
6345 /// Implements the unchecked expression
6347 public class UnCheckedExpr : Expression {
6349 public Expression Expr;
6351 public UnCheckedExpr (Expression e, Location l)
6357 public override Expression DoResolve (EmitContext ec)
6359 bool last_check = ec.CheckState;
6360 bool last_const_check = ec.ConstantCheckState;
6362 ec.CheckState = false;
6363 ec.ConstantCheckState = false;
6364 Expr = Expr.Resolve (ec);
6365 ec.CheckState = last_check;
6366 ec.ConstantCheckState = last_const_check;
6371 if (Expr is Constant)
6374 eclass = Expr.eclass;
6379 public override void Emit (EmitContext ec)
6381 bool last_check = ec.CheckState;
6382 bool last_const_check = ec.ConstantCheckState;
6384 ec.CheckState = false;
6385 ec.ConstantCheckState = false;
6387 ec.CheckState = last_check;
6388 ec.ConstantCheckState = last_const_check;
6394 /// An Element Access expression.
6396 /// During semantic analysis these are transformed into
6397 /// IndexerAccess or ArrayAccess
6399 public class ElementAccess : Expression {
6400 public ArrayList Arguments;
6401 public Expression Expr;
6403 public ElementAccess (Expression e, ArrayList e_list, Location l)
6412 Arguments = new ArrayList ();
6413 foreach (Expression tmp in e_list)
6414 Arguments.Add (new Argument (tmp, Argument.AType.Expression));
6418 bool CommonResolve (EmitContext ec)
6420 Expr = Expr.Resolve (ec);
6425 if (Arguments == null)
6428 foreach (Argument a in Arguments){
6429 if (!a.Resolve (ec, loc))
6436 Expression MakePointerAccess ()
6440 if (t == TypeManager.void_ptr_type){
6441 Error (242, "The array index operation is not valid for void pointers");
6444 if (Arguments.Count != 1){
6445 Error (196, "A pointer must be indexed by a single value");
6450 p = new PointerArithmetic (true, Expr, ((Argument)Arguments [0]).Expr, t, loc);
6451 return new Indirection (p, loc);
6454 public override Expression DoResolve (EmitContext ec)
6456 if (!CommonResolve (ec))
6460 // We perform some simple tests, and then to "split" the emit and store
6461 // code we create an instance of a different class, and return that.
6463 // I am experimenting with this pattern.
6468 return (new ArrayAccess (this, loc)).Resolve (ec);
6469 else if (t.IsPointer)
6470 return MakePointerAccess ();
6472 return (new IndexerAccess (this, loc)).Resolve (ec);
6475 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
6477 if (!CommonResolve (ec))
6482 return (new ArrayAccess (this, loc)).ResolveLValue (ec, right_side);
6483 else if (t.IsPointer)
6484 return MakePointerAccess ();
6486 return (new IndexerAccess (this, loc)).ResolveLValue (ec, right_side);
6489 public override void Emit (EmitContext ec)
6491 throw new Exception ("Should never be reached");
6496 /// Implements array access
6498 public class ArrayAccess : Expression, IAssignMethod, IMemoryLocation {
6500 // Points to our "data" repository
6504 LocalTemporary [] cached_locations;
6506 public ArrayAccess (ElementAccess ea_data, Location l)
6509 eclass = ExprClass.Variable;
6513 public override Expression DoResolve (EmitContext ec)
6515 ExprClass eclass = ea.Expr.eclass;
6518 // As long as the type is valid
6519 if (!(eclass == ExprClass.Variable || eclass == ExprClass.PropertyAccess ||
6520 eclass == ExprClass.Value)) {
6521 ea.Expr.Error118 ("variable or value");
6526 Type t = ea.Expr.Type;
6527 if (t.GetArrayRank () != ea.Arguments.Count){
6529 "Incorrect number of indexes for array " +
6530 " expected: " + t.GetArrayRank () + " got: " +
6531 ea.Arguments.Count);
6534 type = TypeManager.TypeToCoreType (t.GetElementType ());
6535 if (type.IsPointer && !ec.InUnsafe){
6536 UnsafeError (ea.Location);
6540 foreach (Argument a in ea.Arguments){
6541 Type argtype = a.Type;
6543 if (argtype == TypeManager.int32_type ||
6544 argtype == TypeManager.uint32_type ||
6545 argtype == TypeManager.int64_type ||
6546 argtype == TypeManager.uint64_type)
6550 // Mhm. This is strage, because the Argument.Type is not the same as
6551 // Argument.Expr.Type: the value changes depending on the ref/out setting.
6553 // Wonder if I will run into trouble for this.
6555 a.Expr = ExpressionToArrayArgument (ec, a.Expr, ea.Location);
6560 eclass = ExprClass.Variable;
6566 /// Emits the right opcode to load an object of Type `t'
6567 /// from an array of T
6569 static public void EmitLoadOpcode (ILGenerator ig, Type type)
6571 if (type == TypeManager.byte_type || type == TypeManager.bool_type)
6572 ig.Emit (OpCodes.Ldelem_U1);
6573 else if (type == TypeManager.sbyte_type)
6574 ig.Emit (OpCodes.Ldelem_I1);
6575 else if (type == TypeManager.short_type)
6576 ig.Emit (OpCodes.Ldelem_I2);
6577 else if (type == TypeManager.ushort_type || type == TypeManager.char_type)
6578 ig.Emit (OpCodes.Ldelem_U2);
6579 else if (type == TypeManager.int32_type)
6580 ig.Emit (OpCodes.Ldelem_I4);
6581 else if (type == TypeManager.uint32_type)
6582 ig.Emit (OpCodes.Ldelem_U4);
6583 else if (type == TypeManager.uint64_type)
6584 ig.Emit (OpCodes.Ldelem_I8);
6585 else if (type == TypeManager.int64_type)
6586 ig.Emit (OpCodes.Ldelem_I8);
6587 else if (type == TypeManager.float_type)
6588 ig.Emit (OpCodes.Ldelem_R4);
6589 else if (type == TypeManager.double_type)
6590 ig.Emit (OpCodes.Ldelem_R8);
6591 else if (type == TypeManager.intptr_type)
6592 ig.Emit (OpCodes.Ldelem_I);
6593 else if (type.IsValueType){
6594 ig.Emit (OpCodes.Ldelema, type);
6595 ig.Emit (OpCodes.Ldobj, type);
6597 ig.Emit (OpCodes.Ldelem_Ref);
6601 /// Emits the right opcode to store an object of Type `t'
6602 /// from an array of T.
6604 static public void EmitStoreOpcode (ILGenerator ig, Type t)
6607 OpCode op = GetStoreOpcode (t, out is_stobj);
6609 ig.Emit (OpCodes.Stobj, t);
6615 /// Returns the right opcode to store an object of Type `t'
6616 /// from an array of T.
6618 static public OpCode GetStoreOpcode (Type t, out bool is_stobj)
6621 t = TypeManager.TypeToCoreType (t);
6622 if (TypeManager.IsEnumType (t) && t != TypeManager.enum_type)
6623 t = TypeManager.EnumToUnderlying (t);
6624 if (t == TypeManager.byte_type || t == TypeManager.sbyte_type ||
6625 t == TypeManager.bool_type)
6626 return OpCodes.Stelem_I1;
6627 else if (t == TypeManager.short_type || t == TypeManager.ushort_type ||
6628 t == TypeManager.char_type)
6629 return OpCodes.Stelem_I2;
6630 else if (t == TypeManager.int32_type || t == TypeManager.uint32_type)
6631 return OpCodes.Stelem_I4;
6632 else if (t == TypeManager.int64_type || t == TypeManager.uint64_type)
6633 return OpCodes.Stelem_I8;
6634 else if (t == TypeManager.float_type)
6635 return OpCodes.Stelem_R4;
6636 else if (t == TypeManager.double_type)
6637 return OpCodes.Stelem_R8;
6638 else if (t == TypeManager.intptr_type)
6639 return OpCodes.Stelem_I;
6640 else if (t.IsValueType) {
6642 return OpCodes.Stobj;
6644 return OpCodes.Stelem_Ref;
6647 MethodInfo FetchGetMethod ()
6649 ModuleBuilder mb = CodeGen.ModuleBuilder;
6650 int arg_count = ea.Arguments.Count;
6651 Type [] args = new Type [arg_count];
6654 for (int i = 0; i < arg_count; i++){
6655 //args [i++] = a.Type;
6656 args [i] = TypeManager.int32_type;
6659 get = mb.GetArrayMethod (
6660 ea.Expr.Type, "Get",
6661 CallingConventions.HasThis |
6662 CallingConventions.Standard,
6668 MethodInfo FetchAddressMethod ()
6670 ModuleBuilder mb = CodeGen.ModuleBuilder;
6671 int arg_count = ea.Arguments.Count;
6672 Type [] args = new Type [arg_count];
6674 string ptr_type_name;
6677 ptr_type_name = type.FullName + "&";
6678 ret_type = Type.GetType (ptr_type_name);
6681 // It is a type defined by the source code we are compiling
6683 if (ret_type == null){
6684 ret_type = mb.GetType (ptr_type_name);
6687 for (int i = 0; i < arg_count; i++){
6688 //args [i++] = a.Type;
6689 args [i] = TypeManager.int32_type;
6692 address = mb.GetArrayMethod (
6693 ea.Expr.Type, "Address",
6694 CallingConventions.HasThis |
6695 CallingConventions.Standard,
6702 // Load the array arguments into the stack.
6704 // If we have been requested to cache the values (cached_locations array
6705 // initialized), then load the arguments the first time and store them
6706 // in locals. otherwise load from local variables.
6708 void LoadArrayAndArguments (EmitContext ec)
6710 ILGenerator ig = ec.ig;
6712 if (cached_locations == null){
6714 foreach (Argument a in ea.Arguments){
6715 Type argtype = a.Expr.Type;
6719 if (argtype == TypeManager.int64_type)
6720 ig.Emit (OpCodes.Conv_Ovf_I);
6721 else if (argtype == TypeManager.uint64_type)
6722 ig.Emit (OpCodes.Conv_Ovf_I_Un);
6727 if (cached_locations [0] == null){
6728 cached_locations [0] = new LocalTemporary (ec, ea.Expr.Type);
6730 ig.Emit (OpCodes.Dup);
6731 cached_locations [0].Store (ec);
6735 foreach (Argument a in ea.Arguments){
6736 Type argtype = a.Expr.Type;
6738 cached_locations [j] = new LocalTemporary (ec, TypeManager.intptr_type /* a.Expr.Type */);
6740 if (argtype == TypeManager.int64_type)
6741 ig.Emit (OpCodes.Conv_Ovf_I);
6742 else if (argtype == TypeManager.uint64_type)
6743 ig.Emit (OpCodes.Conv_Ovf_I_Un);
6745 ig.Emit (OpCodes.Dup);
6746 cached_locations [j].Store (ec);
6752 foreach (LocalTemporary lt in cached_locations)
6756 public new void CacheTemporaries (EmitContext ec)
6758 cached_locations = new LocalTemporary [ea.Arguments.Count + 1];
6761 public override void Emit (EmitContext ec)
6763 int rank = ea.Expr.Type.GetArrayRank ();
6764 ILGenerator ig = ec.ig;
6766 LoadArrayAndArguments (ec);
6769 EmitLoadOpcode (ig, type);
6773 method = FetchGetMethod ();
6774 ig.Emit (OpCodes.Call, method);
6778 public void EmitAssign (EmitContext ec, Expression source)
6780 int rank = ea.Expr.Type.GetArrayRank ();
6781 ILGenerator ig = ec.ig;
6782 Type t = source.Type;
6784 LoadArrayAndArguments (ec);
6787 // The stobj opcode used by value types will need
6788 // an address on the stack, not really an array/array
6792 if (t == TypeManager.enum_type || t == TypeManager.decimal_type ||
6793 (t.IsSubclassOf (TypeManager.value_type) && !TypeManager.IsEnumType (t) && !TypeManager.IsBuiltinType (t)))
6794 ig.Emit (OpCodes.Ldelema, t);
6800 EmitStoreOpcode (ig, t);
6802 ModuleBuilder mb = CodeGen.ModuleBuilder;
6803 int arg_count = ea.Arguments.Count;
6804 Type [] args = new Type [arg_count + 1];
6807 for (int i = 0; i < arg_count; i++){
6808 //args [i++] = a.Type;
6809 args [i] = TypeManager.int32_type;
6812 args [arg_count] = type;
6814 set = mb.GetArrayMethod (
6815 ea.Expr.Type, "Set",
6816 CallingConventions.HasThis |
6817 CallingConventions.Standard,
6818 TypeManager.void_type, args);
6820 ig.Emit (OpCodes.Call, set);
6824 public void AddressOf (EmitContext ec, AddressOp mode)
6826 int rank = ea.Expr.Type.GetArrayRank ();
6827 ILGenerator ig = ec.ig;
6829 LoadArrayAndArguments (ec);
6832 ig.Emit (OpCodes.Ldelema, type);
6834 MethodInfo address = FetchAddressMethod ();
6835 ig.Emit (OpCodes.Call, address);
6842 public ArrayList properties;
6843 static Hashtable map;
6847 map = new Hashtable ();
6852 properties = new ArrayList ();
6855 void Append (MemberInfo [] mi)
6857 foreach (PropertyInfo property in mi){
6858 MethodInfo get, set;
6860 get = property.GetGetMethod (true);
6861 set = property.GetSetMethod (true);
6862 properties.Add (new Pair (get, set));
6866 static private MemberInfo [] GetIndexersForTypeOrInterface (Type caller_type, Type lookup_type)
6868 string p_name = TypeManager.IndexerPropertyName (lookup_type);
6870 MemberInfo [] mi = TypeManager.MemberLookup (
6871 caller_type, caller_type, lookup_type, MemberTypes.Property,
6872 BindingFlags.Public | BindingFlags.Instance |
6873 BindingFlags.DeclaredOnly, p_name);
6875 if (mi == null || mi.Length == 0)
6881 static public Indexers GetIndexersForType (Type caller_type, Type lookup_type, Location loc)
6883 Indexers ix = (Indexers) map [lookup_type];
6888 Type copy = lookup_type;
6889 while (copy != TypeManager.object_type && copy != null){
6890 MemberInfo [] mi = GetIndexersForTypeOrInterface (caller_type, copy);
6894 ix = new Indexers ();
6899 copy = copy.BaseType;
6902 Type [] ifaces = TypeManager.GetInterfaces (lookup_type);
6903 if (ifaces != null) {
6904 foreach (Type itype in ifaces) {
6905 MemberInfo [] mi = GetIndexersForTypeOrInterface (caller_type, itype);
6908 ix = new Indexers ();
6920 /// Expressions that represent an indexer call.
6922 public class IndexerAccess : Expression, IAssignMethod {
6924 // Points to our "data" repository
6926 MethodInfo get, set;
6927 ArrayList set_arguments;
6928 bool is_base_indexer;
6930 protected Type indexer_type;
6931 protected Type current_type;
6932 protected Expression instance_expr;
6933 protected ArrayList arguments;
6935 public IndexerAccess (ElementAccess ea, Location loc)
6936 : this (ea.Expr, false, loc)
6938 this.arguments = ea.Arguments;
6941 protected IndexerAccess (Expression instance_expr, bool is_base_indexer,
6944 this.instance_expr = instance_expr;
6945 this.is_base_indexer = is_base_indexer;
6946 this.eclass = ExprClass.Value;
6950 protected virtual bool CommonResolve (EmitContext ec)
6952 indexer_type = instance_expr.Type;
6953 current_type = ec.ContainerType;
6958 public override Expression DoResolve (EmitContext ec)
6960 ArrayList AllGetters = new ArrayList();
6961 if (!CommonResolve (ec))
6965 // Step 1: Query for all `Item' *properties*. Notice
6966 // that the actual methods are pointed from here.
6968 // This is a group of properties, piles of them.
6970 bool found_any = false, found_any_getters = false;
6971 Type lookup_type = indexer_type;
6974 ilist = Indexers.GetIndexersForType (current_type, lookup_type, loc);
6975 if (ilist != null) {
6977 if (ilist.properties != null) {
6978 foreach (Pair o in ilist.properties) {
6979 if (o.First != null)
6980 AllGetters.Add(o.First);
6985 if (AllGetters.Count > 0) {
6986 found_any_getters = true;
6987 get = (MethodInfo) Invocation.OverloadResolve (
6988 ec, new MethodGroupExpr (AllGetters, loc), arguments, loc);
6992 Report.Error (21, loc,
6993 "Type `" + TypeManager.CSharpName (indexer_type) +
6994 "' does not have any indexers defined");
6998 if (!found_any_getters) {
6999 Error (154, "indexer can not be used in this context, because " +
7000 "it lacks a `get' accessor");
7005 Error (1501, "No Overload for method `this' takes `" +
7006 arguments.Count + "' arguments");
7011 // Only base will allow this invocation to happen.
7013 if (get.IsAbstract && this is BaseIndexerAccess){
7014 Report.Error (205, loc, "Cannot call an abstract base indexer: " + Invocation.FullMethodDesc (get));
7018 type = get.ReturnType;
7019 if (type.IsPointer && !ec.InUnsafe){
7024 eclass = ExprClass.IndexerAccess;
7028 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
7030 ArrayList AllSetters = new ArrayList();
7031 if (!CommonResolve (ec))
7034 Type right_type = right_side.Type;
7036 bool found_any = false, found_any_setters = false;
7038 Indexers ilist = Indexers.GetIndexersForType (current_type, indexer_type, loc);
7039 if (ilist != null) {
7041 if (ilist.properties != null) {
7042 foreach (Pair o in ilist.properties) {
7043 if (o.Second != null)
7044 AllSetters.Add(o.Second);
7048 if (AllSetters.Count > 0) {
7049 found_any_setters = true;
7050 set_arguments = (ArrayList) arguments.Clone ();
7051 set_arguments.Add (new Argument (right_side, Argument.AType.Expression));
7052 set = (MethodInfo) Invocation.OverloadResolve (
7053 ec, new MethodGroupExpr (AllSetters, loc),
7054 set_arguments, loc);
7058 Report.Error (21, loc,
7059 "Type `" + TypeManager.CSharpName (indexer_type) +
7060 "' does not have any indexers defined");
7064 if (!found_any_setters) {
7065 Error (154, "indexer can not be used in this context, because " +
7066 "it lacks a `set' accessor");
7071 Error (1501, "No Overload for method `this' takes `" +
7072 arguments.Count + "' arguments");
7077 // Only base will allow this invocation to happen.
7079 if (set.IsAbstract && this is BaseIndexerAccess){
7080 Report.Error (205, loc, "Cannot call an abstract base indexer: " + Invocation.FullMethodDesc (set));
7085 // Now look for the actual match in the list of indexers to set our "return" type
7087 type = TypeManager.void_type; // default value
7088 foreach (Pair t in ilist.properties){
7089 if (t.Second == set){
7090 if (t.First != null)
7091 type = ((MethodInfo) t.First).ReturnType;
7096 eclass = ExprClass.IndexerAccess;
7100 public override void Emit (EmitContext ec)
7102 Invocation.EmitCall (ec, false, false, instance_expr, get, arguments, loc);
7106 // source is ignored, because we already have a copy of it from the
7107 // LValue resolution and we have already constructed a pre-cached
7108 // version of the arguments (ea.set_arguments);
7110 public void EmitAssign (EmitContext ec, Expression source)
7112 Invocation.EmitCall (ec, false, false, instance_expr, set, set_arguments, loc);
7117 /// The base operator for method names
7119 public class BaseAccess : Expression {
7122 public BaseAccess (string member, Location l)
7124 this.member = member;
7128 public override Expression DoResolve (EmitContext ec)
7130 Expression c = CommonResolve (ec);
7136 // MethodGroups use this opportunity to flag an error on lacking ()
7138 if (!(c is MethodGroupExpr))
7139 return c.Resolve (ec);
7143 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
7145 Expression c = CommonResolve (ec);
7151 // MethodGroups use this opportunity to flag an error on lacking ()
7153 if (! (c is MethodGroupExpr))
7154 return c.DoResolveLValue (ec, right_side);
7159 Expression CommonResolve (EmitContext ec)
7161 Expression member_lookup;
7162 Type current_type = ec.ContainerType;
7163 Type base_type = current_type.BaseType;
7167 Error (1511, "Keyword base is not allowed in static method");
7171 member_lookup = MemberLookup (ec, ec.ContainerType, null, base_type, member,
7172 AllMemberTypes, AllBindingFlags, loc);
7173 if (member_lookup == null) {
7174 MemberLookupFailed (ec, base_type, base_type, member, null, loc);
7181 left = new TypeExpr (base_type, loc);
7185 e = MemberAccess.ResolveMemberAccess (ec, member_lookup, left, loc, null);
7187 if (e is PropertyExpr){
7188 PropertyExpr pe = (PropertyExpr) e;
7196 public override void Emit (EmitContext ec)
7198 throw new Exception ("Should never be called");
7203 /// The base indexer operator
7205 public class BaseIndexerAccess : IndexerAccess {
7206 public BaseIndexerAccess (ArrayList args, Location loc)
7207 : base (null, true, loc)
7209 arguments = new ArrayList ();
7210 foreach (Expression tmp in args)
7211 arguments.Add (new Argument (tmp, Argument.AType.Expression));
7214 protected override bool CommonResolve (EmitContext ec)
7216 instance_expr = ec.This;
7218 current_type = ec.ContainerType.BaseType;
7219 indexer_type = current_type;
7221 foreach (Argument a in arguments){
7222 if (!a.Resolve (ec, loc))
7231 /// This class exists solely to pass the Type around and to be a dummy
7232 /// that can be passed to the conversion functions (this is used by
7233 /// foreach implementation to typecast the object return value from
7234 /// get_Current into the proper type. All code has been generated and
7235 /// we only care about the side effect conversions to be performed
7237 /// This is also now used as a placeholder where a no-action expression
7238 /// is needed (the `New' class).
7240 public class EmptyExpression : Expression {
7241 public EmptyExpression ()
7243 type = TypeManager.object_type;
7244 eclass = ExprClass.Value;
7245 loc = Location.Null;
7248 public EmptyExpression (Type t)
7251 eclass = ExprClass.Value;
7252 loc = Location.Null;
7255 public override Expression DoResolve (EmitContext ec)
7260 public override void Emit (EmitContext ec)
7262 // nothing, as we only exist to not do anything.
7266 // This is just because we might want to reuse this bad boy
7267 // instead of creating gazillions of EmptyExpressions.
7268 // (CanConvertImplicit uses it)
7270 public void SetType (Type t)
7276 public class UserCast : Expression {
7280 public UserCast (MethodInfo method, Expression source, Location l)
7282 this.method = method;
7283 this.source = source;
7284 type = method.ReturnType;
7285 eclass = ExprClass.Value;
7289 public override Expression DoResolve (EmitContext ec)
7292 // We are born fully resolved
7297 public override void Emit (EmitContext ec)
7299 ILGenerator ig = ec.ig;
7303 if (method is MethodInfo)
7304 ig.Emit (OpCodes.Call, (MethodInfo) method);
7306 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
7312 // This class is used to "construct" the type during a typecast
7313 // operation. Since the Type.GetType class in .NET can parse
7314 // the type specification, we just use this to construct the type
7315 // one bit at a time.
7317 public class ComposedCast : Expression, ITypeExpression {
7321 public ComposedCast (Expression left, string dim, Location l)
7328 public Expression DoResolveType (EmitContext ec)
7330 Type ltype = ec.DeclSpace.ResolveType (left, false, loc);
7335 // ltype.Fullname is already fully qualified, so we can skip
7336 // a lot of probes, and go directly to TypeManager.LookupType
7338 string cname = ltype.FullName + dim;
7339 type = TypeManager.LookupTypeDirect (cname);
7342 // For arrays of enumerations we are having a problem
7343 // with the direct lookup. Need to investigate.
7345 // For now, fall back to the full lookup in that case.
7347 type = RootContext.LookupType (
7348 ec.DeclSpace, cname, false, loc);
7354 if (!ec.ResolvingTypeTree){
7356 // If the above flag is set, this is being invoked from the ResolveType function.
7357 // Upper layers take care of the type validity in this context.
7359 if (!ec.InUnsafe && type.IsPointer){
7365 eclass = ExprClass.Type;
7369 public override Expression DoResolve (EmitContext ec)
7371 return DoResolveType (ec);
7374 public override void Emit (EmitContext ec)
7376 throw new Exception ("This should never be called");
7379 public override string ToString ()
7386 // This class is used to represent the address of an array, used
7387 // only by the Fixed statement, this is like the C "&a [0]" construct.
7389 public class ArrayPtr : Expression {
7392 public ArrayPtr (Expression array, Location l)
7394 Type array_type = array.Type.GetElementType ();
7398 string array_ptr_type_name = array_type.FullName + "*";
7400 type = Type.GetType (array_ptr_type_name);
7402 ModuleBuilder mb = CodeGen.ModuleBuilder;
7404 type = mb.GetType (array_ptr_type_name);
7407 eclass = ExprClass.Value;
7411 public override void Emit (EmitContext ec)
7413 ILGenerator ig = ec.ig;
7416 IntLiteral.EmitInt (ig, 0);
7417 ig.Emit (OpCodes.Ldelema, array.Type.GetElementType ());
7420 public override Expression DoResolve (EmitContext ec)
7423 // We are born fully resolved
7430 // Used by the fixed statement
7432 public class StringPtr : Expression {
7435 public StringPtr (LocalBuilder b, Location l)
7438 eclass = ExprClass.Value;
7439 type = TypeManager.char_ptr_type;
7443 public override Expression DoResolve (EmitContext ec)
7445 // This should never be invoked, we are born in fully
7446 // initialized state.
7451 public override void Emit (EmitContext ec)
7453 ILGenerator ig = ec.ig;
7455 ig.Emit (OpCodes.Ldloc, b);
7456 ig.Emit (OpCodes.Conv_I);
7457 ig.Emit (OpCodes.Call, TypeManager.int_get_offset_to_string_data);
7458 ig.Emit (OpCodes.Add);
7463 // Implements the `stackalloc' keyword
7465 public class StackAlloc : Expression {
7470 public StackAlloc (Expression type, Expression count, Location l)
7477 public override Expression DoResolve (EmitContext ec)
7479 count = count.Resolve (ec);
7483 if (count.Type != TypeManager.int32_type){
7484 count = ConvertImplicitRequired (ec, count, TypeManager.int32_type, loc);
7489 if (ec.InCatch || ec.InFinally){
7491 "stackalloc can not be used in a catch or finally block");
7495 otype = ec.DeclSpace.ResolveType (t, false, loc);
7500 if (!TypeManager.VerifyUnManaged (otype, loc))
7503 string ptr_name = otype.FullName + "*";
7504 type = Type.GetType (ptr_name);
7506 ModuleBuilder mb = CodeGen.ModuleBuilder;
7508 type = mb.GetType (ptr_name);
7510 eclass = ExprClass.Value;
7515 public override void Emit (EmitContext ec)
7517 int size = GetTypeSize (otype);
7518 ILGenerator ig = ec.ig;
7521 ig.Emit (OpCodes.Sizeof, otype);
7523 IntConstant.EmitInt (ig, size);
7525 ig.Emit (OpCodes.Mul);
7526 ig.Emit (OpCodes.Localloc);