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 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 static 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)))){
231 if (e is EnumConstant){
232 EnumConstant enum_constant = (EnumConstant) e;
235 if (Reduce (ec, enum_constant.Child, out reduced)){
236 result = new EnumConstant ((Constant) reduced, enum_constant.Type);
244 if (expr_type == TypeManager.int32_type){
245 result = new IntConstant (~ ((IntConstant) e).Value);
246 } else if (expr_type == TypeManager.uint32_type){
247 result = new UIntConstant (~ ((UIntConstant) e).Value);
248 } else if (expr_type == TypeManager.int64_type){
249 result = new LongConstant (~ ((LongConstant) e).Value);
250 } else if (expr_type == TypeManager.uint64_type){
251 result = new ULongConstant (~ ((ULongConstant) e).Value);
259 case Operator.AddressOf:
263 case Operator.Indirection:
267 throw new Exception ("Can not constant fold: " + Oper.ToString());
270 Expression ResolveOperator (EmitContext ec)
272 Type expr_type = Expr.Type;
275 // Step 1: Perform Operator Overload location
280 op_name = oper_names [(int) Oper];
282 mg = MemberLookup (ec, expr_type, op_name, MemberTypes.Method, AllBindingFlags, loc);
285 Expression e = StaticCallExpr.MakeSimpleCall (
286 ec, (MethodGroupExpr) mg, Expr, loc);
296 // Only perform numeric promotions on:
299 if (expr_type == null)
303 // Step 2: Default operations on CLI native types.
306 // Attempt to use a constant folding operation.
307 if (Expr is Constant){
310 if (Reduce (ec, (Constant) Expr, out result))
315 case Operator.LogicalNot:
316 if (expr_type != TypeManager.bool_type) {
321 type = TypeManager.bool_type;
324 case Operator.OnesComplement:
325 if (!((expr_type == TypeManager.int32_type) ||
326 (expr_type == TypeManager.uint32_type) ||
327 (expr_type == TypeManager.int64_type) ||
328 (expr_type == TypeManager.uint64_type) ||
329 (expr_type.IsSubclassOf (TypeManager.enum_type)))){
332 e = ConvertImplicit (ec, Expr, TypeManager.int32_type, loc);
334 type = TypeManager.int32_type;
337 e = ConvertImplicit (ec, Expr, TypeManager.uint32_type, loc);
339 type = TypeManager.uint32_type;
342 e = ConvertImplicit (ec, Expr, TypeManager.int64_type, loc);
344 type = TypeManager.int64_type;
347 e = ConvertImplicit (ec, Expr, TypeManager.uint64_type, loc);
349 type = TypeManager.uint64_type;
358 case Operator.AddressOf:
359 if (Expr.eclass != ExprClass.Variable){
360 Error (211, "Cannot take the address of non-variables");
369 if (!TypeManager.VerifyUnManaged (Expr.Type, loc)){
373 string ptr_type_name = Expr.Type.FullName + "*";
374 type = TypeManager.LookupType (ptr_type_name);
378 case Operator.Indirection:
384 if (!expr_type.IsPointer){
387 "The * or -> operator can only be applied to pointers");
392 // We create an Indirection expression, because
393 // it can implement the IMemoryLocation.
395 return new Indirection (Expr, loc);
397 case Operator.UnaryPlus:
399 // A plus in front of something is just a no-op, so return the child.
403 case Operator.UnaryNegation:
405 // Deals with -literals
406 // int operator- (int x)
407 // long operator- (long x)
408 // float operator- (float f)
409 // double operator- (double d)
410 // decimal operator- (decimal d)
412 Expression expr = null;
415 // transform - - expr into expr
418 Unary unary = (Unary) Expr;
420 if (unary.Oper == Operator.UnaryNegation)
425 // perform numeric promotions to int,
429 // The following is inneficient, because we call
430 // ConvertImplicit too many times.
432 // It is also not clear if we should convert to Float
433 // or Double initially.
435 if (expr_type == TypeManager.uint32_type){
437 // FIXME: handle exception to this rule that
438 // permits the int value -2147483648 (-2^31) to
439 // bt wrote as a decimal interger literal
441 type = TypeManager.int64_type;
442 Expr = ConvertImplicit (ec, Expr, type, loc);
446 if (expr_type == TypeManager.uint64_type){
448 // FIXME: Handle exception of `long value'
449 // -92233720368547758087 (-2^63) to be wrote as
450 // decimal integer literal.
456 if (expr_type == TypeManager.float_type){
461 expr = ConvertImplicit (ec, Expr, TypeManager.int32_type, loc);
468 expr = ConvertImplicit (ec, Expr, TypeManager.int64_type, loc);
475 expr = ConvertImplicit (ec, Expr, TypeManager.double_type, loc);
486 Error (187, "No such operator '" + OperName (Oper) + "' defined for type '" +
487 TypeManager.CSharpName (expr_type) + "'");
491 public override Expression DoResolve (EmitContext ec)
493 if (Oper == Operator.AddressOf)
494 Expr = Expr.ResolveLValue (ec, new EmptyExpression ());
496 Expr = Expr.Resolve (ec);
501 eclass = ExprClass.Value;
502 return ResolveOperator (ec);
505 public override void Emit (EmitContext ec)
507 ILGenerator ig = ec.ig;
508 Type expr_type = Expr.Type;
511 case Operator.UnaryPlus:
512 throw new Exception ("This should be caught by Resolve");
514 case Operator.UnaryNegation:
516 ig.Emit (OpCodes.Neg);
519 case Operator.LogicalNot:
521 ig.Emit (OpCodes.Ldc_I4_0);
522 ig.Emit (OpCodes.Ceq);
525 case Operator.OnesComplement:
527 ig.Emit (OpCodes.Not);
530 case Operator.AddressOf:
531 ((IMemoryLocation)Expr).AddressOf (ec, AddressOp.LoadStore);
535 throw new Exception ("This should not happen: Operator = "
541 /// This will emit the child expression for `ec' avoiding the logical
542 /// not. The parent will take care of changing brfalse/brtrue
544 public void EmitLogicalNot (EmitContext ec)
546 if (Oper != Operator.LogicalNot)
547 throw new Exception ("EmitLogicalNot can only be called with !expr");
552 public override string ToString ()
554 return "Unary (" + Oper + ", " + Expr + ")";
560 // Unary operators are turned into Indirection expressions
561 // after semantic analysis (this is so we can take the address
562 // of an indirection).
564 public class Indirection : Expression, IMemoryLocation, IAssignMethod {
566 LocalTemporary temporary;
569 public Indirection (Expression expr, Location l)
572 this.type = TypeManager.TypeToCoreType (expr.Type.GetElementType ());
573 eclass = ExprClass.Variable;
577 void LoadExprValue (EmitContext ec)
581 public override void Emit (EmitContext ec)
583 ILGenerator ig = ec.ig;
585 if (temporary != null){
591 ec.ig.Emit (OpCodes.Dup);
592 temporary.Store (ec);
593 have_temporary = true;
597 LoadFromPtr (ig, Type);
600 public void EmitAssign (EmitContext ec, Expression source)
602 if (temporary != null){
608 ec.ig.Emit (OpCodes.Dup);
609 temporary.Store (ec);
610 have_temporary = true;
615 StoreFromPtr (ec.ig, type);
618 public void AddressOf (EmitContext ec, AddressOp Mode)
620 if (temporary != null){
626 ec.ig.Emit (OpCodes.Dup);
627 temporary.Store (ec);
628 have_temporary = true;
633 public override Expression DoResolve (EmitContext ec)
636 // Born fully resolved
641 public new void CacheTemporaries (EmitContext ec)
643 temporary = new LocalTemporary (ec, type);
648 /// Unary Mutator expressions (pre and post ++ and --)
652 /// UnaryMutator implements ++ and -- expressions. It derives from
653 /// ExpressionStatement becuase the pre/post increment/decrement
654 /// operators can be used in a statement context.
656 /// FIXME: Idea, we could split this up in two classes, one simpler
657 /// for the common case, and one with the extra fields for more complex
658 /// classes (indexers require temporary access; overloaded require method)
661 public class UnaryMutator : ExpressionStatement {
663 public enum Mode : byte {
670 PreDecrement = IsDecrement,
671 PostIncrement = IsPost,
672 PostDecrement = IsPost | IsDecrement
677 LocalTemporary temp_storage;
680 // This is expensive for the simplest case.
684 public UnaryMutator (Mode m, Expression e, Location l)
691 static string OperName (Mode mode)
693 return (mode == Mode.PreIncrement || mode == Mode.PostIncrement) ?
697 void Error23 (Type t)
700 23, "Operator " + OperName (mode) +
701 " cannot be applied to operand of type `" +
702 TypeManager.CSharpName (t) + "'");
706 /// Returns whether an object of type `t' can be incremented
707 /// or decremented with add/sub (ie, basically whether we can
708 /// use pre-post incr-decr operations on it, but it is not a
709 /// System.Decimal, which we require operator overloading to catch)
711 static bool IsIncrementableNumber (Type t)
713 return (t == TypeManager.sbyte_type) ||
714 (t == TypeManager.byte_type) ||
715 (t == TypeManager.short_type) ||
716 (t == TypeManager.ushort_type) ||
717 (t == TypeManager.int32_type) ||
718 (t == TypeManager.uint32_type) ||
719 (t == TypeManager.int64_type) ||
720 (t == TypeManager.uint64_type) ||
721 (t == TypeManager.char_type) ||
722 (t.IsSubclassOf (TypeManager.enum_type)) ||
723 (t == TypeManager.float_type) ||
724 (t == TypeManager.double_type) ||
725 (t.IsPointer && t != TypeManager.void_ptr_type);
728 Expression ResolveOperator (EmitContext ec)
730 Type expr_type = expr.Type;
733 // Step 1: Perform Operator Overload location
738 if (mode == Mode.PreIncrement || mode == Mode.PostIncrement)
739 op_name = "op_Increment";
741 op_name = "op_Decrement";
743 mg = MemberLookup (ec, expr_type, op_name, MemberTypes.Method, AllBindingFlags, loc);
745 if (mg == null && expr_type.BaseType != null)
746 mg = MemberLookup (ec, expr_type.BaseType, op_name,
747 MemberTypes.Method, AllBindingFlags, loc);
750 method = StaticCallExpr.MakeSimpleCall (
751 ec, (MethodGroupExpr) mg, expr, loc);
758 // The operand of the prefix/postfix increment decrement operators
759 // should be an expression that is classified as a variable,
760 // a property access or an indexer access
763 if (expr.eclass == ExprClass.Variable){
764 if (IsIncrementableNumber (expr_type) ||
765 expr_type == TypeManager.decimal_type){
768 } else if (expr.eclass == ExprClass.IndexerAccess){
769 IndexerAccess ia = (IndexerAccess) expr;
771 temp_storage = new LocalTemporary (ec, expr.Type);
773 expr = ia.ResolveLValue (ec, temp_storage);
778 } else if (expr.eclass == ExprClass.PropertyAccess){
779 PropertyExpr pe = (PropertyExpr) expr;
781 if (pe.VerifyAssignable ())
786 expr.Error118 ("variable, indexer or property access");
790 Error (187, "No such operator '" + OperName (mode) + "' defined for type '" +
791 TypeManager.CSharpName (expr_type) + "'");
795 public override Expression DoResolve (EmitContext ec)
797 expr = expr.Resolve (ec);
802 eclass = ExprClass.Value;
803 return ResolveOperator (ec);
806 static int PtrTypeSize (Type t)
808 return GetTypeSize (t.GetElementType ());
812 // Loads the proper "1" into the stack based on the type, then it emits the
813 // opcode for the operation requested
815 void LoadOneAndEmitOp (EmitContext ec, Type t)
817 ILGenerator ig = ec.ig;
819 if (t == TypeManager.uint64_type || t == TypeManager.int64_type)
820 LongConstant.EmitLong (ig, 1);
821 else if (t == TypeManager.double_type)
822 ig.Emit (OpCodes.Ldc_R8, 1.0);
823 else if (t == TypeManager.float_type)
824 ig.Emit (OpCodes.Ldc_R4, 1.0F);
825 else if (t.IsPointer){
826 int n = PtrTypeSize (t);
829 ig.Emit (OpCodes.Sizeof, t);
831 IntConstant.EmitInt (ig, n);
833 ig.Emit (OpCodes.Ldc_I4_1);
836 // Now emit the operation
839 if (t == TypeManager.int32_type ||
840 t == TypeManager.int64_type){
841 if ((mode & Mode.IsDecrement) != 0)
842 ig.Emit (OpCodes.Sub_Ovf);
844 ig.Emit (OpCodes.Add_Ovf);
845 } else if (t == TypeManager.uint32_type ||
846 t == TypeManager.uint64_type){
847 if ((mode & Mode.IsDecrement) != 0)
848 ig.Emit (OpCodes.Sub_Ovf_Un);
850 ig.Emit (OpCodes.Add_Ovf_Un);
852 if ((mode & Mode.IsDecrement) != 0)
853 ig.Emit (OpCodes.Sub_Ovf);
855 ig.Emit (OpCodes.Add_Ovf);
858 if ((mode & Mode.IsDecrement) != 0)
859 ig.Emit (OpCodes.Sub);
861 ig.Emit (OpCodes.Add);
865 void EmitCode (EmitContext ec, bool is_expr)
867 ILGenerator ig = ec.ig;
868 IAssignMethod ia = (IAssignMethod) expr;
869 Type expr_type = expr.Type;
871 ia.CacheTemporaries (ec);
873 if (temp_storage == null)
874 temp_storage = new LocalTemporary (ec, expr_type);
877 case Mode.PreIncrement:
878 case Mode.PreDecrement:
882 LoadOneAndEmitOp (ec, expr_type);
886 temp_storage.Store (ec);
887 ia.EmitAssign (ec, temp_storage);
889 temp_storage.Emit (ec);
892 case Mode.PostIncrement:
893 case Mode.PostDecrement:
901 ig.Emit (OpCodes.Dup);
903 LoadOneAndEmitOp (ec, expr_type);
908 temp_storage.Store (ec);
909 ia.EmitAssign (ec, temp_storage);
914 public override void Emit (EmitContext ec)
920 public override void EmitStatement (EmitContext ec)
922 EmitCode (ec, false);
928 /// Base class for the `Is' and `As' classes.
932 /// FIXME: Split this in two, and we get to save the `Operator' Oper
935 public abstract class Probe : Expression {
936 public readonly Expression ProbeType;
937 protected Expression expr;
938 protected Type probe_type;
940 public Probe (Expression expr, Expression probe_type, Location l)
942 ProbeType = probe_type;
947 public Expression Expr {
953 public override Expression DoResolve (EmitContext ec)
955 probe_type = ec.DeclSpace.ResolveType (ProbeType, false, loc);
957 if (probe_type == null)
960 expr = expr.Resolve (ec);
967 /// Implementation of the `is' operator.
969 public class Is : Probe {
970 public Is (Expression expr, Expression probe_type, Location l)
971 : base (expr, probe_type, l)
976 AlwaysTrue, AlwaysNull, AlwaysFalse, LeaveOnStack, Probe
981 public override void Emit (EmitContext ec)
983 ILGenerator ig = ec.ig;
988 case Action.AlwaysFalse:
989 ig.Emit (OpCodes.Pop);
990 IntConstant.EmitInt (ig, 0);
992 case Action.AlwaysTrue:
993 ig.Emit (OpCodes.Pop);
994 IntConstant.EmitInt (ig, 1);
996 case Action.LeaveOnStack:
997 // the `e != null' rule.
1000 ig.Emit (OpCodes.Isinst, probe_type);
1001 ig.Emit (OpCodes.Ldnull);
1002 ig.Emit (OpCodes.Cgt_Un);
1005 throw new Exception ("never reached");
1008 public override Expression DoResolve (EmitContext ec)
1010 Expression e = base.DoResolve (ec);
1012 if ((e == null) || (expr == null))
1015 Type etype = expr.Type;
1016 bool warning_always_matches = false;
1017 bool warning_never_matches = false;
1019 type = TypeManager.bool_type;
1020 eclass = ExprClass.Value;
1023 // First case, if at compile time, there is an implicit conversion
1024 // then e != null (objects) or true (value types)
1026 e = ConvertImplicitStandard (ec, expr, probe_type, loc);
1029 if (etype.IsValueType)
1030 action = Action.AlwaysTrue;
1032 action = Action.LeaveOnStack;
1034 warning_always_matches = true;
1035 } else if (ExplicitReferenceConversionExists (etype, probe_type)){
1037 // Second case: explicit reference convresion
1039 if (expr is NullLiteral)
1040 action = Action.AlwaysFalse;
1042 action = Action.Probe;
1044 action = Action.AlwaysFalse;
1045 warning_never_matches = true;
1048 if (RootContext.WarningLevel >= 1){
1049 if (warning_always_matches)
1052 "The expression is always of type `" +
1053 TypeManager.CSharpName (probe_type) + "'");
1054 else if (warning_never_matches){
1055 if (!(probe_type.IsInterface || expr.Type.IsInterface))
1058 "The expression is never of type `" +
1059 TypeManager.CSharpName (probe_type) + "'");
1068 /// Implementation of the `as' operator.
1070 public class As : Probe {
1071 public As (Expression expr, Expression probe_type, Location l)
1072 : base (expr, probe_type, l)
1076 bool do_isinst = false;
1078 public override void Emit (EmitContext ec)
1080 ILGenerator ig = ec.ig;
1085 ig.Emit (OpCodes.Isinst, probe_type);
1088 static void Error_CannotConvertType (Type source, Type target, Location loc)
1091 39, loc, "as operator can not convert from `" +
1092 TypeManager.CSharpName (source) + "' to `" +
1093 TypeManager.CSharpName (target) + "'");
1096 public override Expression DoResolve (EmitContext ec)
1098 Expression e = base.DoResolve (ec);
1104 eclass = ExprClass.Value;
1105 Type etype = expr.Type;
1107 if (TypeManager.IsValueType (probe_type)){
1108 Report.Error (77, loc, "The as operator should be used with a reference type only (" +
1109 TypeManager.CSharpName (probe_type) + " is a value type");
1114 e = ConvertImplicit (ec, expr, probe_type, loc);
1121 if (ExplicitReferenceConversionExists (etype, probe_type)){
1126 Error_CannotConvertType (etype, probe_type, loc);
1132 /// This represents a typecast in the source language.
1134 /// FIXME: Cast expressions have an unusual set of parsing
1135 /// rules, we need to figure those out.
1137 public class Cast : Expression {
1138 Expression target_type;
1141 public Cast (Expression cast_type, Expression expr, Location loc)
1143 this.target_type = cast_type;
1148 public Expression TargetType {
1154 public Expression Expr {
1164 /// Attempts to do a compile-time folding of a constant cast.
1166 Expression TryReduce (EmitContext ec, Type target_type)
1168 if (expr is ByteConstant){
1169 byte v = ((ByteConstant) expr).Value;
1171 if (target_type == TypeManager.sbyte_type)
1172 return new SByteConstant ((sbyte) v);
1173 if (target_type == TypeManager.short_type)
1174 return new ShortConstant ((short) v);
1175 if (target_type == TypeManager.ushort_type)
1176 return new UShortConstant ((ushort) v);
1177 if (target_type == TypeManager.int32_type)
1178 return new IntConstant ((int) v);
1179 if (target_type == TypeManager.uint32_type)
1180 return new UIntConstant ((uint) v);
1181 if (target_type == TypeManager.int64_type)
1182 return new LongConstant ((long) v);
1183 if (target_type == TypeManager.uint64_type)
1184 return new ULongConstant ((ulong) v);
1185 if (target_type == TypeManager.float_type)
1186 return new FloatConstant ((float) v);
1187 if (target_type == TypeManager.double_type)
1188 return new DoubleConstant ((double) v);
1189 if (target_type == TypeManager.char_type)
1190 return new CharConstant ((char) v);
1191 if (target_type == TypeManager.decimal_type)
1192 return new DecimalConstant ((decimal) v);
1194 if (expr is SByteConstant){
1195 sbyte v = ((SByteConstant) expr).Value;
1197 if (target_type == TypeManager.byte_type)
1198 return new ByteConstant ((byte) v);
1199 if (target_type == TypeManager.short_type)
1200 return new ShortConstant ((short) v);
1201 if (target_type == TypeManager.ushort_type)
1202 return new UShortConstant ((ushort) v);
1203 if (target_type == TypeManager.int32_type)
1204 return new IntConstant ((int) v);
1205 if (target_type == TypeManager.uint32_type)
1206 return new UIntConstant ((uint) v);
1207 if (target_type == TypeManager.int64_type)
1208 return new LongConstant ((long) v);
1209 if (target_type == TypeManager.uint64_type)
1210 return new ULongConstant ((ulong) v);
1211 if (target_type == TypeManager.float_type)
1212 return new FloatConstant ((float) v);
1213 if (target_type == TypeManager.double_type)
1214 return new DoubleConstant ((double) v);
1215 if (target_type == TypeManager.char_type)
1216 return new CharConstant ((char) v);
1217 if (target_type == TypeManager.decimal_type)
1218 return new DecimalConstant ((decimal) v);
1220 if (expr is ShortConstant){
1221 short v = ((ShortConstant) expr).Value;
1223 if (target_type == TypeManager.byte_type)
1224 return new ByteConstant ((byte) v);
1225 if (target_type == TypeManager.sbyte_type)
1226 return new SByteConstant ((sbyte) v);
1227 if (target_type == TypeManager.ushort_type)
1228 return new UShortConstant ((ushort) v);
1229 if (target_type == TypeManager.int32_type)
1230 return new IntConstant ((int) v);
1231 if (target_type == TypeManager.uint32_type)
1232 return new UIntConstant ((uint) v);
1233 if (target_type == TypeManager.int64_type)
1234 return new LongConstant ((long) v);
1235 if (target_type == TypeManager.uint64_type)
1236 return new ULongConstant ((ulong) v);
1237 if (target_type == TypeManager.float_type)
1238 return new FloatConstant ((float) v);
1239 if (target_type == TypeManager.double_type)
1240 return new DoubleConstant ((double) v);
1241 if (target_type == TypeManager.char_type)
1242 return new CharConstant ((char) v);
1243 if (target_type == TypeManager.decimal_type)
1244 return new DecimalConstant ((decimal) v);
1246 if (expr is UShortConstant){
1247 ushort v = ((UShortConstant) expr).Value;
1249 if (target_type == TypeManager.byte_type)
1250 return new ByteConstant ((byte) v);
1251 if (target_type == TypeManager.sbyte_type)
1252 return new SByteConstant ((sbyte) v);
1253 if (target_type == TypeManager.short_type)
1254 return new ShortConstant ((short) v);
1255 if (target_type == TypeManager.int32_type)
1256 return new IntConstant ((int) v);
1257 if (target_type == TypeManager.uint32_type)
1258 return new UIntConstant ((uint) v);
1259 if (target_type == TypeManager.int64_type)
1260 return new LongConstant ((long) v);
1261 if (target_type == TypeManager.uint64_type)
1262 return new ULongConstant ((ulong) v);
1263 if (target_type == TypeManager.float_type)
1264 return new FloatConstant ((float) v);
1265 if (target_type == TypeManager.double_type)
1266 return new DoubleConstant ((double) v);
1267 if (target_type == TypeManager.char_type)
1268 return new CharConstant ((char) v);
1269 if (target_type == TypeManager.decimal_type)
1270 return new DecimalConstant ((decimal) v);
1272 if (expr is IntConstant){
1273 int v = ((IntConstant) expr).Value;
1275 if (target_type == TypeManager.byte_type)
1276 return new ByteConstant ((byte) v);
1277 if (target_type == TypeManager.sbyte_type)
1278 return new SByteConstant ((sbyte) v);
1279 if (target_type == TypeManager.short_type)
1280 return new ShortConstant ((short) v);
1281 if (target_type == TypeManager.ushort_type)
1282 return new UShortConstant ((ushort) v);
1283 if (target_type == TypeManager.uint32_type)
1284 return new UIntConstant ((uint) v);
1285 if (target_type == TypeManager.int64_type)
1286 return new LongConstant ((long) v);
1287 if (target_type == TypeManager.uint64_type)
1288 return new ULongConstant ((ulong) v);
1289 if (target_type == TypeManager.float_type)
1290 return new FloatConstant ((float) v);
1291 if (target_type == TypeManager.double_type)
1292 return new DoubleConstant ((double) v);
1293 if (target_type == TypeManager.char_type)
1294 return new CharConstant ((char) v);
1295 if (target_type == TypeManager.decimal_type)
1296 return new DecimalConstant ((decimal) v);
1298 if (expr is UIntConstant){
1299 uint v = ((UIntConstant) expr).Value;
1301 if (target_type == TypeManager.byte_type)
1302 return new ByteConstant ((byte) v);
1303 if (target_type == TypeManager.sbyte_type)
1304 return new SByteConstant ((sbyte) v);
1305 if (target_type == TypeManager.short_type)
1306 return new ShortConstant ((short) v);
1307 if (target_type == TypeManager.ushort_type)
1308 return new UShortConstant ((ushort) v);
1309 if (target_type == TypeManager.int32_type)
1310 return new IntConstant ((int) v);
1311 if (target_type == TypeManager.int64_type)
1312 return new LongConstant ((long) v);
1313 if (target_type == TypeManager.uint64_type)
1314 return new ULongConstant ((ulong) v);
1315 if (target_type == TypeManager.float_type)
1316 return new FloatConstant ((float) v);
1317 if (target_type == TypeManager.double_type)
1318 return new DoubleConstant ((double) v);
1319 if (target_type == TypeManager.char_type)
1320 return new CharConstant ((char) v);
1321 if (target_type == TypeManager.decimal_type)
1322 return new DecimalConstant ((decimal) v);
1324 if (expr is LongConstant){
1325 long v = ((LongConstant) expr).Value;
1327 if (target_type == TypeManager.byte_type)
1328 return new ByteConstant ((byte) v);
1329 if (target_type == TypeManager.sbyte_type)
1330 return new SByteConstant ((sbyte) v);
1331 if (target_type == TypeManager.short_type)
1332 return new ShortConstant ((short) v);
1333 if (target_type == TypeManager.ushort_type)
1334 return new UShortConstant ((ushort) v);
1335 if (target_type == TypeManager.int32_type)
1336 return new IntConstant ((int) v);
1337 if (target_type == TypeManager.uint32_type)
1338 return new UIntConstant ((uint) v);
1339 if (target_type == TypeManager.uint64_type)
1340 return new ULongConstant ((ulong) v);
1341 if (target_type == TypeManager.float_type)
1342 return new FloatConstant ((float) v);
1343 if (target_type == TypeManager.double_type)
1344 return new DoubleConstant ((double) v);
1345 if (target_type == TypeManager.char_type)
1346 return new CharConstant ((char) v);
1347 if (target_type == TypeManager.decimal_type)
1348 return new DecimalConstant ((decimal) v);
1350 if (expr is ULongConstant){
1351 ulong v = ((ULongConstant) expr).Value;
1353 if (target_type == TypeManager.byte_type)
1354 return new ByteConstant ((byte) v);
1355 if (target_type == TypeManager.sbyte_type)
1356 return new SByteConstant ((sbyte) v);
1357 if (target_type == TypeManager.short_type)
1358 return new ShortConstant ((short) v);
1359 if (target_type == TypeManager.ushort_type)
1360 return new UShortConstant ((ushort) v);
1361 if (target_type == TypeManager.int32_type)
1362 return new IntConstant ((int) v);
1363 if (target_type == TypeManager.uint32_type)
1364 return new UIntConstant ((uint) v);
1365 if (target_type == TypeManager.int64_type)
1366 return new LongConstant ((long) v);
1367 if (target_type == TypeManager.float_type)
1368 return new FloatConstant ((float) v);
1369 if (target_type == TypeManager.double_type)
1370 return new DoubleConstant ((double) v);
1371 if (target_type == TypeManager.char_type)
1372 return new CharConstant ((char) v);
1373 if (target_type == TypeManager.decimal_type)
1374 return new DecimalConstant ((decimal) v);
1376 if (expr is FloatConstant){
1377 float v = ((FloatConstant) expr).Value;
1379 if (target_type == TypeManager.byte_type)
1380 return new ByteConstant ((byte) v);
1381 if (target_type == TypeManager.sbyte_type)
1382 return new SByteConstant ((sbyte) v);
1383 if (target_type == TypeManager.short_type)
1384 return new ShortConstant ((short) v);
1385 if (target_type == TypeManager.ushort_type)
1386 return new UShortConstant ((ushort) v);
1387 if (target_type == TypeManager.int32_type)
1388 return new IntConstant ((int) v);
1389 if (target_type == TypeManager.uint32_type)
1390 return new UIntConstant ((uint) v);
1391 if (target_type == TypeManager.int64_type)
1392 return new LongConstant ((long) v);
1393 if (target_type == TypeManager.uint64_type)
1394 return new ULongConstant ((ulong) v);
1395 if (target_type == TypeManager.double_type)
1396 return new DoubleConstant ((double) v);
1397 if (target_type == TypeManager.char_type)
1398 return new CharConstant ((char) v);
1399 if (target_type == TypeManager.decimal_type)
1400 return new DecimalConstant ((decimal) v);
1402 if (expr is DoubleConstant){
1403 double v = ((DoubleConstant) expr).Value;
1405 if (target_type == TypeManager.byte_type)
1406 return new ByteConstant ((byte) v);
1407 if (target_type == TypeManager.sbyte_type)
1408 return new SByteConstant ((sbyte) v);
1409 if (target_type == TypeManager.short_type)
1410 return new ShortConstant ((short) v);
1411 if (target_type == TypeManager.ushort_type)
1412 return new UShortConstant ((ushort) v);
1413 if (target_type == TypeManager.int32_type)
1414 return new IntConstant ((int) v);
1415 if (target_type == TypeManager.uint32_type)
1416 return new UIntConstant ((uint) v);
1417 if (target_type == TypeManager.int64_type)
1418 return new LongConstant ((long) v);
1419 if (target_type == TypeManager.uint64_type)
1420 return new ULongConstant ((ulong) v);
1421 if (target_type == TypeManager.float_type)
1422 return new FloatConstant ((float) v);
1423 if (target_type == TypeManager.char_type)
1424 return new CharConstant ((char) v);
1425 if (target_type == TypeManager.decimal_type)
1426 return new DecimalConstant ((decimal) v);
1432 public override Expression DoResolve (EmitContext ec)
1434 expr = expr.Resolve (ec);
1438 int errors = Report.Errors;
1440 type = ec.DeclSpace.ResolveType (target_type, false, Location);
1445 eclass = ExprClass.Value;
1447 if (expr is Constant){
1448 Expression e = TryReduce (ec, type);
1454 expr = ConvertExplicit (ec, expr, type, loc);
1458 public override void Emit (EmitContext ec)
1461 // This one will never happen
1463 throw new Exception ("Should not happen");
1468 /// Binary operators
1470 public class Binary : Expression {
1471 public enum Operator : byte {
1472 Multiply, Division, Modulus,
1473 Addition, Subtraction,
1474 LeftShift, RightShift,
1475 LessThan, GreaterThan, LessThanOrEqual, GreaterThanOrEqual,
1476 Equality, Inequality,
1486 Expression left, right;
1489 // After resolution, method might contain the operator overload
1492 protected MethodBase method;
1493 ArrayList Arguments;
1495 bool DelegateOperation;
1497 // This must be kept in sync with Operator!!!
1498 static string [] oper_names;
1502 oper_names = new string [(int) Operator.TOP];
1504 oper_names [(int) Operator.Multiply] = "op_Multiply";
1505 oper_names [(int) Operator.Division] = "op_Division";
1506 oper_names [(int) Operator.Modulus] = "op_Modulus";
1507 oper_names [(int) Operator.Addition] = "op_Addition";
1508 oper_names [(int) Operator.Subtraction] = "op_Subtraction";
1509 oper_names [(int) Operator.LeftShift] = "op_LeftShift";
1510 oper_names [(int) Operator.RightShift] = "op_RightShift";
1511 oper_names [(int) Operator.LessThan] = "op_LessThan";
1512 oper_names [(int) Operator.GreaterThan] = "op_GreaterThan";
1513 oper_names [(int) Operator.LessThanOrEqual] = "op_LessThanOrEqual";
1514 oper_names [(int) Operator.GreaterThanOrEqual] = "op_GreaterThanOrEqual";
1515 oper_names [(int) Operator.Equality] = "op_Equality";
1516 oper_names [(int) Operator.Inequality] = "op_Inequality";
1517 oper_names [(int) Operator.BitwiseAnd] = "op_BitwiseAnd";
1518 oper_names [(int) Operator.BitwiseOr] = "op_BitwiseOr";
1519 oper_names [(int) Operator.ExclusiveOr] = "op_ExclusiveOr";
1520 oper_names [(int) Operator.LogicalOr] = "op_LogicalOr";
1521 oper_names [(int) Operator.LogicalAnd] = "op_LogicalAnd";
1524 public Binary (Operator oper, Expression left, Expression right, Location loc)
1532 public Operator Oper {
1541 public Expression Left {
1550 public Expression Right {
1561 /// Returns a stringified representation of the Operator
1563 static string OperName (Operator oper)
1566 case Operator.Multiply:
1568 case Operator.Division:
1570 case Operator.Modulus:
1572 case Operator.Addition:
1574 case Operator.Subtraction:
1576 case Operator.LeftShift:
1578 case Operator.RightShift:
1580 case Operator.LessThan:
1582 case Operator.GreaterThan:
1584 case Operator.LessThanOrEqual:
1586 case Operator.GreaterThanOrEqual:
1588 case Operator.Equality:
1590 case Operator.Inequality:
1592 case Operator.BitwiseAnd:
1594 case Operator.BitwiseOr:
1596 case Operator.ExclusiveOr:
1598 case Operator.LogicalOr:
1600 case Operator.LogicalAnd:
1604 return oper.ToString ();
1607 public override string ToString ()
1609 return "operator " + OperName (oper) + "(" + left.ToString () + ", " +
1610 right.ToString () + ")";
1613 Expression ForceConversion (EmitContext ec, Expression expr, Type target_type)
1615 if (expr.Type == target_type)
1618 return ConvertImplicit (ec, expr, target_type, new Location (-1));
1621 public static void Error_OperatorAmbiguous (Location loc, Operator oper, Type l, Type r)
1624 34, loc, "Operator `" + OperName (oper)
1625 + "' is ambiguous on operands of type `"
1626 + TypeManager.CSharpName (l) + "' "
1627 + "and `" + TypeManager.CSharpName (r)
1632 // Note that handling the case l == Decimal || r == Decimal
1633 // is taken care of by the Step 1 Operator Overload resolution.
1635 bool DoNumericPromotions (EmitContext ec, Type l, Type r)
1637 if (l == TypeManager.double_type || r == TypeManager.double_type){
1639 // If either operand is of type double, the other operand is
1640 // conveted to type double.
1642 if (r != TypeManager.double_type)
1643 right = ConvertImplicit (ec, right, TypeManager.double_type, loc);
1644 if (l != TypeManager.double_type)
1645 left = ConvertImplicit (ec, left, TypeManager.double_type, loc);
1647 type = TypeManager.double_type;
1648 } else if (l == TypeManager.float_type || r == TypeManager.float_type){
1650 // if either operand is of type float, the other operand is
1651 // converted to type float.
1653 if (r != TypeManager.double_type)
1654 right = ConvertImplicit (ec, right, TypeManager.float_type, loc);
1655 if (l != TypeManager.double_type)
1656 left = ConvertImplicit (ec, left, TypeManager.float_type, loc);
1657 type = TypeManager.float_type;
1658 } else if (l == TypeManager.uint64_type || r == TypeManager.uint64_type){
1662 // If either operand is of type ulong, the other operand is
1663 // converted to type ulong. or an error ocurrs if the other
1664 // operand is of type sbyte, short, int or long
1666 if (l == TypeManager.uint64_type){
1667 if (r != TypeManager.uint64_type){
1668 if (right is IntConstant){
1669 IntConstant ic = (IntConstant) right;
1671 e = TryImplicitIntConversion (l, ic);
1674 } else if (right is LongConstant){
1675 long ll = ((LongConstant) right).Value;
1678 right = new ULongConstant ((ulong) ll);
1680 e = ImplicitNumericConversion (ec, right, l, loc);
1687 if (left is IntConstant){
1688 e = TryImplicitIntConversion (r, (IntConstant) left);
1691 } else if (left is LongConstant){
1692 long ll = ((LongConstant) left).Value;
1695 left = new ULongConstant ((ulong) ll);
1697 e = ImplicitNumericConversion (ec, left, r, loc);
1704 if ((other == TypeManager.sbyte_type) ||
1705 (other == TypeManager.short_type) ||
1706 (other == TypeManager.int32_type) ||
1707 (other == TypeManager.int64_type))
1708 Error_OperatorAmbiguous (loc, oper, l, r);
1709 type = TypeManager.uint64_type;
1710 } else if (l == TypeManager.int64_type || r == TypeManager.int64_type){
1712 // If either operand is of type long, the other operand is converted
1715 if (l != TypeManager.int64_type)
1716 left = ConvertImplicit (ec, left, TypeManager.int64_type, loc);
1717 if (r != TypeManager.int64_type)
1718 right = ConvertImplicit (ec, right, TypeManager.int64_type, loc);
1720 type = TypeManager.int64_type;
1721 } else if (l == TypeManager.uint32_type || r == TypeManager.uint32_type){
1723 // If either operand is of type uint, and the other
1724 // operand is of type sbyte, short or int, othe operands are
1725 // converted to type long.
1729 if (l == TypeManager.uint32_type){
1730 if (right is IntConstant){
1731 IntConstant ic = (IntConstant) right;
1735 right = new UIntConstant ((uint) val);
1742 else if (r == TypeManager.uint32_type){
1743 if (left is IntConstant){
1744 IntConstant ic = (IntConstant) left;
1748 left = new UIntConstant ((uint) val);
1757 if ((other == TypeManager.sbyte_type) ||
1758 (other == TypeManager.short_type) ||
1759 (other == TypeManager.int32_type)){
1760 left = ForceConversion (ec, left, TypeManager.int64_type);
1761 right = ForceConversion (ec, right, TypeManager.int64_type);
1762 type = TypeManager.int64_type;
1765 // if either operand is of type uint, the other
1766 // operand is converd to type uint
1768 left = ForceConversion (ec, left, TypeManager.uint32_type);
1769 right = ForceConversion (ec, right, TypeManager.uint32_type);
1770 type = TypeManager.uint32_type;
1772 } else if (l == TypeManager.decimal_type || r == TypeManager.decimal_type){
1773 if (l != TypeManager.decimal_type)
1774 left = ConvertImplicit (ec, left, TypeManager.decimal_type, loc);
1776 if (r != TypeManager.decimal_type)
1777 right = ConvertImplicit (ec, right, TypeManager.decimal_type, loc);
1778 type = TypeManager.decimal_type;
1780 left = ForceConversion (ec, left, TypeManager.int32_type);
1781 right = ForceConversion (ec, right, TypeManager.int32_type);
1783 type = TypeManager.int32_type;
1786 return (left != null) && (right != null);
1789 static public void Error_OperatorCannotBeApplied (Location loc, string name, Type l, Type r)
1791 Report.Error (19, loc,
1792 "Operator " + name + " cannot be applied to operands of type `" +
1793 TypeManager.CSharpName (l) + "' and `" +
1794 TypeManager.CSharpName (r) + "'");
1797 void Error_OperatorCannotBeApplied ()
1799 Error_OperatorCannotBeApplied (loc, OperName (oper), left.Type, right.Type);
1802 static bool is_32_or_64 (Type t)
1804 return (t == TypeManager.int32_type || t == TypeManager.uint32_type ||
1805 t == TypeManager.int64_type || t == TypeManager.uint64_type);
1808 static bool is_unsigned (Type t)
1810 return (t == TypeManager.uint32_type || t == TypeManager.uint64_type ||
1811 t == TypeManager.short_type || t == TypeManager.byte_type);
1814 Expression CheckShiftArguments (EmitContext ec)
1818 Type r = right.Type;
1820 e = ForceConversion (ec, right, TypeManager.int32_type);
1822 Error_OperatorCannotBeApplied ();
1827 if (((e = ConvertImplicit (ec, left, TypeManager.int32_type, loc)) != null) ||
1828 ((e = ConvertImplicit (ec, left, TypeManager.uint32_type, loc)) != null) ||
1829 ((e = ConvertImplicit (ec, left, TypeManager.int64_type, loc)) != null) ||
1830 ((e = ConvertImplicit (ec, left, TypeManager.uint64_type, loc)) != null)){
1836 Error_OperatorCannotBeApplied ();
1840 Expression ResolveOperator (EmitContext ec)
1843 Type r = right.Type;
1845 bool overload_failed = false;
1848 // Step 1: Perform Operator Overload location
1850 Expression left_expr, right_expr;
1852 string op = oper_names [(int) oper];
1854 MethodGroupExpr union;
1855 left_expr = MemberLookup (ec, l, op, MemberTypes.Method, AllBindingFlags, loc);
1857 right_expr = MemberLookup (
1858 ec, r, op, MemberTypes.Method, AllBindingFlags, loc);
1859 union = Invocation.MakeUnionSet (left_expr, right_expr, loc);
1861 union = (MethodGroupExpr) left_expr;
1863 if (union != null) {
1864 Arguments = new ArrayList ();
1865 Arguments.Add (new Argument (left, Argument.AType.Expression));
1866 Arguments.Add (new Argument (right, Argument.AType.Expression));
1868 method = Invocation.OverloadResolve (ec, union, Arguments, Location.Null);
1869 if (method != null) {
1870 MethodInfo mi = (MethodInfo) method;
1872 type = mi.ReturnType;
1875 overload_failed = true;
1880 // Step 2: Default operations on CLI native types.
1884 // Step 0: String concatenation (because overloading will get this wrong)
1886 if (oper == Operator.Addition){
1888 // If any of the arguments is a string, cast to string
1891 if (l == TypeManager.string_type){
1893 if (r == TypeManager.void_type) {
1894 Error_OperatorCannotBeApplied ();
1898 if (r == TypeManager.string_type){
1899 if (left is Constant && right is Constant){
1900 StringConstant ls = (StringConstant) left;
1901 StringConstant rs = (StringConstant) right;
1903 return new StringConstant (
1904 ls.Value + rs.Value);
1908 method = TypeManager.string_concat_string_string;
1911 method = TypeManager.string_concat_object_object;
1912 right = ConvertImplicit (ec, right,
1913 TypeManager.object_type, loc);
1915 Error_OperatorCannotBeApplied (loc, OperName (oper), l, r);
1919 type = TypeManager.string_type;
1921 Arguments = new ArrayList ();
1922 Arguments.Add (new Argument (left, Argument.AType.Expression));
1923 Arguments.Add (new Argument (right, Argument.AType.Expression));
1927 } else if (r == TypeManager.string_type){
1930 if (l == TypeManager.void_type) {
1931 Error_OperatorCannotBeApplied ();
1935 method = TypeManager.string_concat_object_object;
1936 left = ConvertImplicit (ec, left, TypeManager.object_type, loc);
1938 Error_OperatorCannotBeApplied (loc, OperName (oper), l, r);
1941 Arguments = new ArrayList ();
1942 Arguments.Add (new Argument (left, Argument.AType.Expression));
1943 Arguments.Add (new Argument (right, Argument.AType.Expression));
1945 type = TypeManager.string_type;
1951 // Transform a + ( - b) into a - b
1953 if (right is Unary){
1954 Unary right_unary = (Unary) right;
1956 if (right_unary.Oper == Unary.Operator.UnaryNegation){
1957 oper = Operator.Subtraction;
1958 right = right_unary.Expr;
1964 if (oper == Operator.Equality || oper == Operator.Inequality){
1965 if (l == TypeManager.bool_type || r == TypeManager.bool_type){
1966 if (r != TypeManager.bool_type || l != TypeManager.bool_type){
1967 Error_OperatorCannotBeApplied ();
1971 type = TypeManager.bool_type;
1976 // operator != (object a, object b)
1977 // operator == (object a, object b)
1979 // For this to be used, both arguments have to be reference-types.
1980 // Read the rationale on the spec (14.9.6)
1982 // Also, if at compile time we know that the classes do not inherit
1983 // one from the other, then we catch the error there.
1985 if (!(l.IsValueType || r.IsValueType)){
1986 type = TypeManager.bool_type;
1991 if (l.IsSubclassOf (r) || r.IsSubclassOf (l))
1995 // Also, a standard conversion must exist from either one
1997 if (!(StandardConversionExists (left, r) ||
1998 StandardConversionExists (right, l))){
1999 Error_OperatorCannotBeApplied ();
2003 // We are going to have to convert to an object to compare
2005 if (l != TypeManager.object_type)
2006 left = new EmptyCast (left, TypeManager.object_type);
2007 if (r != TypeManager.object_type)
2008 right = new EmptyCast (right, TypeManager.object_type);
2011 // FIXME: CSC here catches errors cs254 and cs252
2017 // One of them is a valuetype, but the other one is not.
2019 if (!l.IsValueType || !r.IsValueType) {
2020 Error_OperatorCannotBeApplied ();
2025 // Only perform numeric promotions on:
2026 // +, -, *, /, %, &, |, ^, ==, !=, <, >, <=, >=
2028 if (oper == Operator.Addition || oper == Operator.Subtraction) {
2029 if (l.IsSubclassOf (TypeManager.delegate_type) &&
2030 r.IsSubclassOf (TypeManager.delegate_type)) {
2032 Arguments = new ArrayList ();
2033 Arguments.Add (new Argument (left, Argument.AType.Expression));
2034 Arguments.Add (new Argument (right, Argument.AType.Expression));
2036 if (oper == Operator.Addition)
2037 method = TypeManager.delegate_combine_delegate_delegate;
2039 method = TypeManager.delegate_remove_delegate_delegate;
2042 Error_OperatorCannotBeApplied ();
2046 DelegateOperation = true;
2052 // Pointer arithmetic:
2054 // T* operator + (T* x, int y);
2055 // T* operator + (T* x, uint y);
2056 // T* operator + (T* x, long y);
2057 // T* operator + (T* x, ulong y);
2059 // T* operator + (int y, T* x);
2060 // T* operator + (uint y, T *x);
2061 // T* operator + (long y, T *x);
2062 // T* operator + (ulong y, T *x);
2064 // T* operator - (T* x, int y);
2065 // T* operator - (T* x, uint y);
2066 // T* operator - (T* x, long y);
2067 // T* operator - (T* x, ulong y);
2069 // long operator - (T* x, T *y)
2072 if (r.IsPointer && oper == Operator.Subtraction){
2074 return new PointerArithmetic (
2075 false, left, right, TypeManager.int64_type,
2077 } else if (is_32_or_64 (r))
2078 return new PointerArithmetic (
2079 oper == Operator.Addition, left, right, l, loc);
2080 } else if (r.IsPointer && is_32_or_64 (l) && oper == Operator.Addition)
2081 return new PointerArithmetic (
2082 true, right, left, r, loc);
2086 // Enumeration operators
2088 bool lie = TypeManager.IsEnumType (l);
2089 bool rie = TypeManager.IsEnumType (r);
2093 // U operator - (E e, E f)
2094 if (lie && rie && oper == Operator.Subtraction){
2096 type = TypeManager.EnumToUnderlying (l);
2099 Error_OperatorCannotBeApplied ();
2104 // operator + (E e, U x)
2105 // operator - (E e, U x)
2107 if (oper == Operator.Addition || oper == Operator.Subtraction){
2108 Type enum_type = lie ? l : r;
2109 Type other_type = lie ? r : l;
2110 Type underlying_type = TypeManager.EnumToUnderlying (enum_type);
2113 if (underlying_type != other_type){
2114 Error_OperatorCannotBeApplied ();
2123 temp = ConvertImplicit (ec, right, l, loc);
2127 Error_OperatorCannotBeApplied ();
2131 temp = ConvertImplicit (ec, left, r, loc);
2136 Error_OperatorCannotBeApplied ();
2141 if (oper == Operator.Equality || oper == Operator.Inequality ||
2142 oper == Operator.LessThanOrEqual || oper == Operator.LessThan ||
2143 oper == Operator.GreaterThanOrEqual || oper == Operator.GreaterThan){
2144 type = TypeManager.bool_type;
2148 if (oper == Operator.BitwiseAnd ||
2149 oper == Operator.BitwiseOr ||
2150 oper == Operator.ExclusiveOr){
2154 Error_OperatorCannotBeApplied ();
2158 if (oper == Operator.LeftShift || oper == Operator.RightShift)
2159 return CheckShiftArguments (ec);
2161 if (oper == Operator.LogicalOr || oper == Operator.LogicalAnd){
2162 if (l != TypeManager.bool_type || r != TypeManager.bool_type){
2163 Error_OperatorCannotBeApplied ();
2167 type = TypeManager.bool_type;
2172 // operator & (bool x, bool y)
2173 // operator | (bool x, bool y)
2174 // operator ^ (bool x, bool y)
2176 if (l == TypeManager.bool_type && r == TypeManager.bool_type){
2177 if (oper == Operator.BitwiseAnd ||
2178 oper == Operator.BitwiseOr ||
2179 oper == Operator.ExclusiveOr){
2186 // Pointer comparison
2188 if (l.IsPointer && r.IsPointer){
2189 if (oper == Operator.Equality || oper == Operator.Inequality ||
2190 oper == Operator.LessThan || oper == Operator.LessThanOrEqual ||
2191 oper == Operator.GreaterThan || oper == Operator.GreaterThanOrEqual){
2192 type = TypeManager.bool_type;
2198 // We are dealing with numbers
2200 if (overload_failed){
2201 Error_OperatorCannotBeApplied ();
2206 // This will leave left or right set to null if there is an error
2208 DoNumericPromotions (ec, l, r);
2209 if (left == null || right == null){
2210 Error_OperatorCannotBeApplied (loc, OperName (oper), l, r);
2215 // reload our cached types if required
2220 if (oper == Operator.BitwiseAnd ||
2221 oper == Operator.BitwiseOr ||
2222 oper == Operator.ExclusiveOr){
2224 if (!((l == TypeManager.int32_type) ||
2225 (l == TypeManager.uint32_type) ||
2226 (l == TypeManager.int64_type) ||
2227 (l == TypeManager.uint64_type)))
2230 Error_OperatorCannotBeApplied ();
2235 if (oper == Operator.Equality ||
2236 oper == Operator.Inequality ||
2237 oper == Operator.LessThanOrEqual ||
2238 oper == Operator.LessThan ||
2239 oper == Operator.GreaterThanOrEqual ||
2240 oper == Operator.GreaterThan){
2241 type = TypeManager.bool_type;
2247 public override Expression DoResolve (EmitContext ec)
2249 left = left.Resolve (ec);
2250 right = right.Resolve (ec);
2252 if (left == null || right == null)
2255 if (left.Type == null)
2256 throw new Exception (
2257 "Resolve returned non null, but did not set the type! (" +
2258 left + ") at Line: " + loc.Row);
2259 if (right.Type == null)
2260 throw new Exception (
2261 "Resolve returned non null, but did not set the type! (" +
2262 right + ") at Line: "+ loc.Row);
2264 eclass = ExprClass.Value;
2266 if (left is Constant && right is Constant){
2267 Expression e = ConstantFold.BinaryFold (
2268 ec, oper, (Constant) left, (Constant) right, loc);
2273 return ResolveOperator (ec);
2277 /// EmitBranchable is called from Statement.EmitBoolExpression in the
2278 /// context of a conditional bool expression. This function will return
2279 /// false if it is was possible to use EmitBranchable, or true if it was.
2281 /// The expression's code is generated, and we will generate a branch to `target'
2282 /// if the resulting expression value is equal to isTrue
2284 public bool EmitBranchable (EmitContext ec, Label target, bool onTrue)
2289 ILGenerator ig = ec.ig;
2292 // This is more complicated than it looks, but its just to avoid
2293 // duplicated tests: basically, we allow ==, !=, >, <, >= and <=
2294 // but on top of that we want for == and != to use a special path
2295 // if we are comparing against null
2297 if (oper == Operator.Equality || oper == Operator.Inequality){
2298 bool my_on_true = oper == Operator.Inequality ? onTrue : !onTrue;
2300 if (left is NullLiteral){
2303 ig.Emit (OpCodes.Brtrue, target);
2305 ig.Emit (OpCodes.Brfalse, target);
2307 } else if (right is NullLiteral){
2310 ig.Emit (OpCodes.Brtrue, target);
2312 ig.Emit (OpCodes.Brfalse, target);
2315 } else if (!(oper == Operator.LessThan ||
2316 oper == Operator.GreaterThan ||
2317 oper == Operator.LessThanOrEqual ||
2318 oper == Operator.GreaterThanOrEqual))
2326 bool isUnsigned = is_unsigned (left.Type);
2329 case Operator.Equality:
2331 ig.Emit (OpCodes.Beq, target);
2333 ig.Emit (OpCodes.Bne_Un, target);
2336 case Operator.Inequality:
2338 ig.Emit (OpCodes.Bne_Un, target);
2340 ig.Emit (OpCodes.Beq, target);
2343 case Operator.LessThan:
2346 ig.Emit (OpCodes.Blt_Un, target);
2348 ig.Emit (OpCodes.Blt, target);
2351 ig.Emit (OpCodes.Bge_Un, target);
2353 ig.Emit (OpCodes.Bge, target);
2356 case Operator.GreaterThan:
2359 ig.Emit (OpCodes.Bgt_Un, target);
2361 ig.Emit (OpCodes.Bgt, target);
2364 ig.Emit (OpCodes.Ble_Un, target);
2366 ig.Emit (OpCodes.Ble, target);
2369 case Operator.LessThanOrEqual:
2372 ig.Emit (OpCodes.Ble_Un, target);
2374 ig.Emit (OpCodes.Ble, target);
2377 ig.Emit (OpCodes.Bgt_Un, target);
2379 ig.Emit (OpCodes.Bgt, target);
2383 case Operator.GreaterThanOrEqual:
2386 ig.Emit (OpCodes.Bge_Un, target);
2388 ig.Emit (OpCodes.Bge, target);
2391 ig.Emit (OpCodes.Blt_Un, target);
2393 ig.Emit (OpCodes.Blt, target);
2403 public override void Emit (EmitContext ec)
2405 ILGenerator ig = ec.ig;
2407 Type r = right.Type;
2410 if (method != null) {
2412 // Note that operators are static anyway
2414 if (Arguments != null)
2415 Invocation.EmitArguments (ec, method, Arguments);
2417 if (method is MethodInfo)
2418 ig.Emit (OpCodes.Call, (MethodInfo) method);
2420 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
2422 if (DelegateOperation)
2423 ig.Emit (OpCodes.Castclass, type);
2429 // Handle short-circuit operators differently
2432 if (oper == Operator.LogicalAnd){
2433 Label load_zero = ig.DefineLabel ();
2434 Label end = ig.DefineLabel ();
2437 ig.Emit (OpCodes.Brfalse, load_zero);
2439 ig.Emit (OpCodes.Br, end);
2440 ig.MarkLabel (load_zero);
2441 ig.Emit (OpCodes.Ldc_I4_0);
2444 } else if (oper == Operator.LogicalOr){
2445 Label load_one = ig.DefineLabel ();
2446 Label end = ig.DefineLabel ();
2449 ig.Emit (OpCodes.Brtrue, load_one);
2451 ig.Emit (OpCodes.Br, end);
2452 ig.MarkLabel (load_one);
2453 ig.Emit (OpCodes.Ldc_I4_1);
2461 bool isUnsigned = is_unsigned (left.Type);
2463 case Operator.Multiply:
2465 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
2466 opcode = OpCodes.Mul_Ovf;
2467 else if (isUnsigned)
2468 opcode = OpCodes.Mul_Ovf_Un;
2470 opcode = OpCodes.Mul;
2472 opcode = OpCodes.Mul;
2476 case Operator.Division:
2478 opcode = OpCodes.Div_Un;
2480 opcode = OpCodes.Div;
2483 case Operator.Modulus:
2485 opcode = OpCodes.Rem_Un;
2487 opcode = OpCodes.Rem;
2490 case Operator.Addition:
2492 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
2493 opcode = OpCodes.Add_Ovf;
2494 else if (isUnsigned)
2495 opcode = OpCodes.Add_Ovf_Un;
2497 opcode = OpCodes.Add;
2499 opcode = OpCodes.Add;
2502 case Operator.Subtraction:
2504 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
2505 opcode = OpCodes.Sub_Ovf;
2506 else if (isUnsigned)
2507 opcode = OpCodes.Sub_Ovf_Un;
2509 opcode = OpCodes.Sub;
2511 opcode = OpCodes.Sub;
2514 case Operator.RightShift:
2516 opcode = OpCodes.Shr_Un;
2518 opcode = OpCodes.Shr;
2521 case Operator.LeftShift:
2522 opcode = OpCodes.Shl;
2525 case Operator.Equality:
2526 opcode = OpCodes.Ceq;
2529 case Operator.Inequality:
2530 ig.Emit (OpCodes.Ceq);
2531 ig.Emit (OpCodes.Ldc_I4_0);
2533 opcode = OpCodes.Ceq;
2536 case Operator.LessThan:
2538 opcode = OpCodes.Clt_Un;
2540 opcode = OpCodes.Clt;
2543 case Operator.GreaterThan:
2545 opcode = OpCodes.Cgt_Un;
2547 opcode = OpCodes.Cgt;
2550 case Operator.LessThanOrEqual:
2552 ig.Emit (OpCodes.Cgt_Un);
2554 ig.Emit (OpCodes.Cgt);
2555 ig.Emit (OpCodes.Ldc_I4_0);
2557 opcode = OpCodes.Ceq;
2560 case Operator.GreaterThanOrEqual:
2562 ig.Emit (OpCodes.Clt_Un);
2564 ig.Emit (OpCodes.Clt);
2566 ig.Emit (OpCodes.Ldc_I4_1);
2568 opcode = OpCodes.Sub;
2571 case Operator.BitwiseOr:
2572 opcode = OpCodes.Or;
2575 case Operator.BitwiseAnd:
2576 opcode = OpCodes.And;
2579 case Operator.ExclusiveOr:
2580 opcode = OpCodes.Xor;
2584 throw new Exception ("This should not happen: Operator = "
2585 + oper.ToString ());
2591 public bool IsBuiltinOperator {
2593 return method == null;
2598 public class PointerArithmetic : Expression {
2599 Expression left, right;
2603 // We assume that `l' is always a pointer
2605 public PointerArithmetic (bool is_addition, Expression l, Expression r, Type t,
2609 eclass = ExprClass.Variable;
2613 is_add = is_addition;
2616 public override Expression DoResolve (EmitContext ec)
2619 // We are born fully resolved
2624 public override void Emit (EmitContext ec)
2626 Type op_type = left.Type;
2627 ILGenerator ig = ec.ig;
2628 int size = GetTypeSize (op_type.GetElementType ());
2630 if (right.Type.IsPointer){
2632 // handle (pointer - pointer)
2636 ig.Emit (OpCodes.Sub);
2640 ig.Emit (OpCodes.Sizeof, op_type);
2642 IntLiteral.EmitInt (ig, size);
2643 ig.Emit (OpCodes.Div);
2645 ig.Emit (OpCodes.Conv_I8);
2648 // handle + and - on (pointer op int)
2651 ig.Emit (OpCodes.Conv_I);
2655 ig.Emit (OpCodes.Sizeof, op_type);
2657 IntLiteral.EmitInt (ig, size);
2658 ig.Emit (OpCodes.Mul);
2661 ig.Emit (OpCodes.Add);
2663 ig.Emit (OpCodes.Sub);
2669 /// Implements the ternary conditional operator (?:)
2671 public class Conditional : Expression {
2672 Expression expr, trueExpr, falseExpr;
2674 public Conditional (Expression expr, Expression trueExpr, Expression falseExpr, Location l)
2677 this.trueExpr = trueExpr;
2678 this.falseExpr = falseExpr;
2682 public Expression Expr {
2688 public Expression TrueExpr {
2694 public Expression FalseExpr {
2700 public override Expression DoResolve (EmitContext ec)
2702 expr = expr.Resolve (ec);
2707 if (expr.Type != TypeManager.bool_type)
2708 expr = Expression.ConvertImplicitRequired (
2709 ec, expr, TypeManager.bool_type, loc);
2711 trueExpr = trueExpr.Resolve (ec);
2712 falseExpr = falseExpr.Resolve (ec);
2714 if (trueExpr == null || falseExpr == null)
2717 eclass = ExprClass.Value;
2718 if (trueExpr.Type == falseExpr.Type)
2719 type = trueExpr.Type;
2722 Type true_type = trueExpr.Type;
2723 Type false_type = falseExpr.Type;
2725 if (trueExpr is NullLiteral){
2728 } else if (falseExpr is NullLiteral){
2734 // First, if an implicit conversion exists from trueExpr
2735 // to falseExpr, then the result type is of type falseExpr.Type
2737 conv = ConvertImplicit (ec, trueExpr, false_type, loc);
2740 // Check if both can convert implicitl to each other's type
2742 if (ConvertImplicit (ec, falseExpr, true_type, loc) != null){
2744 "Can not compute type of conditional expression " +
2745 "as `" + TypeManager.CSharpName (trueExpr.Type) +
2746 "' and `" + TypeManager.CSharpName (falseExpr.Type) +
2747 "' convert implicitly to each other");
2752 } else if ((conv = ConvertImplicit(ec, falseExpr, true_type,loc))!= null){
2756 Error (173, "The type of the conditional expression can " +
2757 "not be computed because there is no implicit conversion" +
2758 " from `" + TypeManager.CSharpName (trueExpr.Type) + "'" +
2759 " and `" + TypeManager.CSharpName (falseExpr.Type) + "'");
2764 if (expr is BoolConstant){
2765 BoolConstant bc = (BoolConstant) expr;
2776 public override void Emit (EmitContext ec)
2778 ILGenerator ig = ec.ig;
2779 Label false_target = ig.DefineLabel ();
2780 Label end_target = ig.DefineLabel ();
2782 Statement.EmitBoolExpression (ec, expr, false_target, false);
2784 ig.Emit (OpCodes.Br, end_target);
2785 ig.MarkLabel (false_target);
2786 falseExpr.Emit (ec);
2787 ig.MarkLabel (end_target);
2795 public class LocalVariableReference : Expression, IAssignMethod, IMemoryLocation, IVariable {
2796 public readonly string Name;
2797 public readonly Block Block;
2798 VariableInfo variable_info;
2801 public LocalVariableReference (Block block, string name, Location l)
2806 eclass = ExprClass.Variable;
2809 // Setting `is_readonly' to false will allow you to create a writable
2810 // reference to a read-only variable. This is used by foreach and using.
2811 public LocalVariableReference (Block block, string name, Location l,
2812 VariableInfo variable_info, bool is_readonly)
2813 : this (block, name, l)
2815 this.variable_info = variable_info;
2816 this.is_readonly = is_readonly;
2819 public VariableInfo VariableInfo {
2821 if (variable_info == null) {
2822 variable_info = Block.GetVariableInfo (Name);
2823 is_readonly = variable_info.ReadOnly;
2825 return variable_info;
2829 public bool IsAssigned (EmitContext ec, Location loc)
2831 return VariableInfo.IsAssigned (ec, loc);
2834 public bool IsFieldAssigned (EmitContext ec, string name, Location loc)
2836 return VariableInfo.IsFieldAssigned (ec, name, loc);
2839 public void SetAssigned (EmitContext ec)
2841 VariableInfo.SetAssigned (ec);
2844 public void SetFieldAssigned (EmitContext ec, string name)
2846 VariableInfo.SetFieldAssigned (ec, name);
2849 public bool IsReadOnly {
2851 if (variable_info == null) {
2852 variable_info = Block.GetVariableInfo (Name);
2853 is_readonly = variable_info.ReadOnly;
2859 public override Expression DoResolve (EmitContext ec)
2861 VariableInfo vi = VariableInfo;
2864 e = Block.GetConstantExpression (Name);
2870 if (ec.DoFlowAnalysis && !IsAssigned (ec, loc))
2873 type = vi.VariableType;
2877 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
2879 VariableInfo vi = VariableInfo;
2881 if (ec.DoFlowAnalysis)
2882 ec.SetVariableAssigned (vi);
2884 Expression e = DoResolve (ec);
2890 Error (1604, "cannot assign to `" + Name + "' because it is readonly");
2897 public override void Emit (EmitContext ec)
2899 VariableInfo vi = VariableInfo;
2900 ILGenerator ig = ec.ig;
2902 ig.Emit (OpCodes.Ldloc, vi.LocalBuilder);
2906 public void EmitAssign (EmitContext ec, Expression source)
2908 ILGenerator ig = ec.ig;
2909 VariableInfo vi = VariableInfo;
2915 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
2918 public void AddressOf (EmitContext ec, AddressOp mode)
2920 VariableInfo vi = VariableInfo;
2922 ec.ig.Emit (OpCodes.Ldloca, vi.LocalBuilder);
2927 /// This represents a reference to a parameter in the intermediate
2930 public class ParameterReference : Expression, IAssignMethod, IMemoryLocation, IVariable {
2934 public Parameter.Modifier mod;
2935 public bool is_ref, is_out;
2937 public ParameterReference (Parameters pars, int idx, string name, Location loc)
2943 eclass = ExprClass.Variable;
2946 public bool IsAssigned (EmitContext ec, Location loc)
2948 if (!is_out || !ec.DoFlowAnalysis)
2951 if (!ec.CurrentBranching.IsParameterAssigned (idx)) {
2952 Report.Error (165, loc,
2953 "Use of unassigned local variable `" + name + "'");
2960 public bool IsFieldAssigned (EmitContext ec, string field_name, Location loc)
2962 if (!is_out || !ec.DoFlowAnalysis)
2965 if (ec.CurrentBranching.IsParameterAssigned (idx))
2968 if (!ec.CurrentBranching.IsParameterAssigned (idx, field_name)) {
2969 Report.Error (170, loc,
2970 "Use of possibly unassigned field `" + field_name + "'");
2977 public void SetAssigned (EmitContext ec)
2979 if (is_out && ec.DoFlowAnalysis)
2980 ec.CurrentBranching.SetParameterAssigned (idx);
2983 public void SetFieldAssigned (EmitContext ec, string field_name)
2985 if (is_out && ec.DoFlowAnalysis)
2986 ec.CurrentBranching.SetParameterAssigned (idx, field_name);
2990 // Notice that for ref/out parameters, the type exposed is not the
2991 // same type exposed externally.
2994 // externally we expose "int&"
2995 // here we expose "int".
2997 // We record this in "is_ref". This means that the type system can treat
2998 // the type as it is expected, but when we generate the code, we generate
2999 // the alternate kind of code.
3001 public override Expression DoResolve (EmitContext ec)
3003 type = pars.GetParameterInfo (ec.DeclSpace, idx, out mod);
3004 is_ref = (mod & Parameter.Modifier.ISBYREF) != 0;
3005 is_out = (mod & Parameter.Modifier.OUT) != 0;
3006 eclass = ExprClass.Variable;
3008 if (is_out && ec.DoFlowAnalysis && !IsAssigned (ec, loc))
3014 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
3016 type = pars.GetParameterInfo (ec.DeclSpace, idx, out mod);
3017 is_ref = (mod & Parameter.Modifier.ISBYREF) != 0;
3018 is_out = (mod & Parameter.Modifier.OUT) != 0;
3019 eclass = ExprClass.Variable;
3021 if (is_out && ec.DoFlowAnalysis)
3022 ec.SetParameterAssigned (idx);
3027 static void EmitLdArg (ILGenerator ig, int x)
3031 case 0: ig.Emit (OpCodes.Ldarg_0); break;
3032 case 1: ig.Emit (OpCodes.Ldarg_1); break;
3033 case 2: ig.Emit (OpCodes.Ldarg_2); break;
3034 case 3: ig.Emit (OpCodes.Ldarg_3); break;
3035 default: ig.Emit (OpCodes.Ldarg_S, (byte) x); break;
3038 ig.Emit (OpCodes.Ldarg, x);
3042 // This method is used by parameters that are references, that are
3043 // being passed as references: we only want to pass the pointer (that
3044 // is already stored in the parameter, not the address of the pointer,
3045 // and not the value of the variable).
3047 public void EmitLoad (EmitContext ec)
3049 ILGenerator ig = ec.ig;
3055 EmitLdArg (ig, arg_idx);
3058 public override void Emit (EmitContext ec)
3060 ILGenerator ig = ec.ig;
3066 EmitLdArg (ig, arg_idx);
3072 // If we are a reference, we loaded on the stack a pointer
3073 // Now lets load the real value
3075 LoadFromPtr (ig, type);
3078 public void EmitAssign (EmitContext ec, Expression source)
3080 ILGenerator ig = ec.ig;
3087 EmitLdArg (ig, arg_idx);
3092 StoreFromPtr (ig, type);
3095 ig.Emit (OpCodes.Starg_S, (byte) arg_idx);
3097 ig.Emit (OpCodes.Starg, arg_idx);
3101 public void AddressOf (EmitContext ec, AddressOp mode)
3110 ec.ig.Emit (OpCodes.Ldarg_S, (byte) arg_idx);
3112 ec.ig.Emit (OpCodes.Ldarg, arg_idx);
3115 ec.ig.Emit (OpCodes.Ldarga_S, (byte) arg_idx);
3117 ec.ig.Emit (OpCodes.Ldarga, arg_idx);
3124 /// Used for arguments to New(), Invocation()
3126 public class Argument {
3127 public enum AType : byte {
3133 public readonly AType ArgType;
3134 public Expression Expr;
3136 public Argument (Expression expr, AType type)
3139 this.ArgType = type;
3144 if (ArgType == AType.Ref || ArgType == AType.Out)
3145 return TypeManager.LookupType (Expr.Type.ToString () + "&");
3151 public Parameter.Modifier GetParameterModifier ()
3155 return Parameter.Modifier.OUT | Parameter.Modifier.ISBYREF;
3158 return Parameter.Modifier.REF | Parameter.Modifier.ISBYREF;
3161 return Parameter.Modifier.NONE;
3165 public static string FullDesc (Argument a)
3167 return (a.ArgType == AType.Ref ? "ref " :
3168 (a.ArgType == AType.Out ? "out " : "")) +
3169 TypeManager.CSharpName (a.Expr.Type);
3172 public bool ResolveMethodGroup (EmitContext ec, Location loc)
3174 // FIXME: csc doesn't report any error if you try to use `ref' or
3175 // `out' in a delegate creation expression.
3176 Expr = Expr.Resolve (ec, ResolveFlags.VariableOrValue | ResolveFlags.MethodGroup);
3183 public bool Resolve (EmitContext ec, Location loc)
3185 if (ArgType == AType.Ref) {
3186 Expr = Expr.Resolve (ec);
3190 Expr = Expr.ResolveLValue (ec, Expr);
3191 } else if (ArgType == AType.Out)
3192 Expr = Expr.ResolveLValue (ec, new EmptyExpression ());
3194 Expr = Expr.Resolve (ec);
3199 if (ArgType == AType.Expression)
3202 if (Expr.eclass != ExprClass.Variable){
3204 // We just probe to match the CSC output
3206 if (Expr.eclass == ExprClass.PropertyAccess ||
3207 Expr.eclass == ExprClass.IndexerAccess){
3210 "A property or indexer can not be passed as an out or ref " +
3215 "An lvalue is required as an argument to out or ref");
3223 public void Emit (EmitContext ec)
3226 // Ref and Out parameters need to have their addresses taken.
3228 // ParameterReferences might already be references, so we want
3229 // to pass just the value
3231 if (ArgType == AType.Ref || ArgType == AType.Out){
3232 AddressOp mode = AddressOp.Store;
3234 if (ArgType == AType.Ref)
3235 mode |= AddressOp.Load;
3237 if (Expr is ParameterReference){
3238 ParameterReference pr = (ParameterReference) Expr;
3244 pr.AddressOf (ec, mode);
3247 ((IMemoryLocation)Expr).AddressOf (ec, mode);
3254 /// Invocation of methods or delegates.
3256 public class Invocation : ExpressionStatement {
3257 public readonly ArrayList Arguments;
3260 MethodBase method = null;
3263 static Hashtable method_parameter_cache;
3265 static Invocation ()
3267 method_parameter_cache = new PtrHashtable ();
3271 // arguments is an ArrayList, but we do not want to typecast,
3272 // as it might be null.
3274 // FIXME: only allow expr to be a method invocation or a
3275 // delegate invocation (7.5.5)
3277 public Invocation (Expression expr, ArrayList arguments, Location l)
3280 Arguments = arguments;
3284 public Expression Expr {
3291 /// Returns the Parameters (a ParameterData interface) for the
3294 public static ParameterData GetParameterData (MethodBase mb)
3296 object pd = method_parameter_cache [mb];
3300 return (ParameterData) pd;
3303 ip = TypeManager.LookupParametersByBuilder (mb);
3305 method_parameter_cache [mb] = ip;
3307 return (ParameterData) ip;
3309 ParameterInfo [] pi = mb.GetParameters ();
3310 ReflectionParameters rp = new ReflectionParameters (pi);
3311 method_parameter_cache [mb] = rp;
3313 return (ParameterData) rp;
3318 /// Determines "better conversion" as specified in 7.4.2.3
3319 /// Returns : 1 if a->p is better
3320 /// 0 if a->q or neither is better
3322 static int BetterConversion (EmitContext ec, Argument a, Type p, Type q, Location loc)
3324 Type argument_type = a.Type;
3325 Expression argument_expr = a.Expr;
3327 if (argument_type == null)
3328 throw new Exception ("Expression of type " + a.Expr + " does not resolve its type");
3331 // This is a special case since csc behaves this way. I can't find
3332 // it anywhere in the spec but oh well ...
3334 if (argument_expr is NullLiteral && p == TypeManager.string_type && q == TypeManager.object_type)
3336 else if (argument_expr is NullLiteral && p == TypeManager.object_type && q == TypeManager.string_type)
3342 if (argument_type == p)
3345 if (argument_type == q)
3349 // Now probe whether an implicit constant expression conversion
3352 // An implicit constant expression conversion permits the following
3355 // * A constant-expression of type `int' can be converted to type
3356 // sbyte, byute, short, ushort, uint, ulong provided the value of
3357 // of the expression is withing the range of the destination type.
3359 // * A constant-expression of type long can be converted to type
3360 // ulong, provided the value of the constant expression is not negative
3362 // FIXME: Note that this assumes that constant folding has
3363 // taken place. We dont do constant folding yet.
3366 if (argument_expr is IntConstant){
3367 IntConstant ei = (IntConstant) argument_expr;
3368 int value = ei.Value;
3370 if (p == TypeManager.sbyte_type){
3371 if (value >= SByte.MinValue && value <= SByte.MaxValue)
3373 } else if (p == TypeManager.byte_type){
3374 if (Byte.MinValue >= 0 && value <= Byte.MaxValue)
3376 } else if (p == TypeManager.short_type){
3377 if (value >= Int16.MinValue && value <= Int16.MaxValue)
3379 } else if (p == TypeManager.ushort_type){
3380 if (value >= UInt16.MinValue && value <= UInt16.MaxValue)
3382 } else if (p == TypeManager.uint32_type){
3384 // we can optimize this case: a positive int32
3385 // always fits on a uint32
3389 } else if (p == TypeManager.uint64_type){
3391 // we can optimize this case: a positive int32
3392 // always fits on a uint64
3397 } else if (argument_type == TypeManager.int64_type && argument_expr is LongConstant){
3398 LongConstant lc = (LongConstant) argument_expr;
3400 if (p == TypeManager.uint64_type){
3407 Expression tmp = ConvertImplicit (ec, argument_expr, p, loc);
3415 Expression p_tmp = new EmptyExpression (p);
3416 Expression q_tmp = new EmptyExpression (q);
3418 if (StandardConversionExists (p_tmp, q) == true &&
3419 StandardConversionExists (q_tmp, p) == false)
3422 if (p == TypeManager.sbyte_type)
3423 if (q == TypeManager.byte_type || q == TypeManager.ushort_type ||
3424 q == TypeManager.uint32_type || q == TypeManager.uint64_type)
3427 if (p == TypeManager.short_type)
3428 if (q == TypeManager.ushort_type || q == TypeManager.uint32_type ||
3429 q == TypeManager.uint64_type)
3432 if (p == TypeManager.int32_type)
3433 if (q == TypeManager.uint32_type || q == TypeManager.uint64_type)
3436 if (p == TypeManager.int64_type)
3437 if (q == TypeManager.uint64_type)
3444 /// Determines "Better function"
3447 /// and returns an integer indicating :
3448 /// 0 if candidate ain't better
3449 /// 1 if candidate is better than the current best match
3451 static int BetterFunction (EmitContext ec, ArrayList args,
3452 MethodBase candidate, MethodBase best,
3453 bool expanded_form, Location loc)
3455 ParameterData candidate_pd = GetParameterData (candidate);
3456 ParameterData best_pd;
3462 argument_count = args.Count;
3464 int cand_count = candidate_pd.Count;
3466 if (cand_count == 0 && argument_count == 0)
3469 if (candidate_pd.ParameterModifier (cand_count - 1) != Parameter.Modifier.PARAMS)
3470 if (cand_count != argument_count)
3476 if (argument_count == 0 && cand_count == 1 &&
3477 candidate_pd.ParameterModifier (cand_count - 1) == Parameter.Modifier.PARAMS)
3480 for (int j = argument_count; j > 0;) {
3483 Argument a = (Argument) args [j];
3484 Type t = candidate_pd.ParameterType (j);
3486 if (candidate_pd.ParameterModifier (j) == Parameter.Modifier.PARAMS)
3488 t = t.GetElementType ();
3490 x = BetterConversion (ec, a, t, null, loc);
3502 best_pd = GetParameterData (best);
3504 int rating1 = 0, rating2 = 0;
3506 for (int j = 0; j < argument_count; ++j) {
3509 Argument a = (Argument) args [j];
3511 Type ct = candidate_pd.ParameterType (j);
3512 Type bt = best_pd.ParameterType (j);
3514 if (candidate_pd.ParameterModifier (j) == Parameter.Modifier.PARAMS)
3516 ct = ct.GetElementType ();
3518 if (best_pd.ParameterModifier (j) == Parameter.Modifier.PARAMS)
3520 bt = bt.GetElementType ();
3522 x = BetterConversion (ec, a, ct, bt, loc);
3523 y = BetterConversion (ec, a, bt, ct, loc);
3532 if (rating1 > rating2)
3538 public static string FullMethodDesc (MethodBase mb)
3540 string ret_type = "";
3542 if (mb is MethodInfo)
3543 ret_type = TypeManager.CSharpName (((MethodInfo) mb).ReturnType);
3545 StringBuilder sb = new StringBuilder (ret_type);
3547 sb.Append (mb.ReflectedType.ToString ());
3549 sb.Append (mb.Name);
3551 ParameterData pd = GetParameterData (mb);
3553 int count = pd.Count;
3556 for (int i = count; i > 0; ) {
3559 sb.Append (pd.ParameterDesc (count - i - 1));
3565 return sb.ToString ();
3568 public static MethodGroupExpr MakeUnionSet (Expression mg1, Expression mg2, Location loc)
3570 MemberInfo [] miset;
3571 MethodGroupExpr union;
3576 return (MethodGroupExpr) mg2;
3579 return (MethodGroupExpr) mg1;
3582 MethodGroupExpr left_set = null, right_set = null;
3583 int length1 = 0, length2 = 0;
3585 left_set = (MethodGroupExpr) mg1;
3586 length1 = left_set.Methods.Length;
3588 right_set = (MethodGroupExpr) mg2;
3589 length2 = right_set.Methods.Length;
3591 ArrayList common = new ArrayList ();
3593 foreach (MethodBase l in left_set.Methods){
3594 foreach (MethodBase r in right_set.Methods){
3602 miset = new MemberInfo [length1 + length2 - common.Count];
3603 left_set.Methods.CopyTo (miset, 0);
3607 foreach (MemberInfo mi in right_set.Methods){
3608 if (!common.Contains (mi))
3612 union = new MethodGroupExpr (miset, loc);
3618 /// Determines is the candidate method, if a params method, is applicable
3619 /// in its expanded form to the given set of arguments
3621 static bool IsParamsMethodApplicable (EmitContext ec, ArrayList arguments, MethodBase candidate)
3625 if (arguments == null)
3628 arg_count = arguments.Count;
3630 ParameterData pd = GetParameterData (candidate);
3632 int pd_count = pd.Count;
3637 if (pd.ParameterModifier (pd_count - 1) != Parameter.Modifier.PARAMS)
3640 if (pd_count - 1 > arg_count)
3643 if (pd_count == 1 && arg_count == 0)
3647 // If we have come this far, the case which remains is when the number of parameters
3648 // is less than or equal to the argument count.
3650 for (int i = 0; i < pd_count - 1; ++i) {
3652 Argument a = (Argument) arguments [i];
3654 Parameter.Modifier a_mod = a.GetParameterModifier () &
3655 ~(Parameter.Modifier.OUT | Parameter.Modifier.REF);
3656 Parameter.Modifier p_mod = pd.ParameterModifier (i) &
3657 ~(Parameter.Modifier.OUT | Parameter.Modifier.REF);
3659 if (a_mod == p_mod) {
3661 if (a_mod == Parameter.Modifier.NONE)
3662 if (!ImplicitConversionExists (ec, a.Expr, pd.ParameterType (i)))
3665 if ((a_mod & Parameter.Modifier.ISBYREF) != 0) {
3666 Type pt = pd.ParameterType (i);
3669 pt = TypeManager.LookupType (pt.FullName + "&");
3679 Type element_type = pd.ParameterType (pd_count - 1).GetElementType ();
3681 for (int i = pd_count - 1; i < arg_count; i++) {
3682 Argument a = (Argument) arguments [i];
3684 if (!StandardConversionExists (a.Expr, element_type))
3692 /// Determines if the candidate method is applicable (section 14.4.2.1)
3693 /// to the given set of arguments
3695 static bool IsApplicable (EmitContext ec, ArrayList arguments, MethodBase candidate)
3699 if (arguments == null)
3702 arg_count = arguments.Count;
3704 ParameterData pd = GetParameterData (candidate);
3706 int pd_count = pd.Count;
3708 if (arg_count != pd.Count)
3711 for (int i = arg_count; i > 0; ) {
3714 Argument a = (Argument) arguments [i];
3716 Parameter.Modifier a_mod = a.GetParameterModifier () &
3717 ~(Parameter.Modifier.OUT | Parameter.Modifier.REF);
3718 Parameter.Modifier p_mod = pd.ParameterModifier (i) &
3719 ~(Parameter.Modifier.OUT | Parameter.Modifier.REF);
3721 if (a_mod == p_mod ||
3722 (a_mod == Parameter.Modifier.NONE && p_mod == Parameter.Modifier.PARAMS)) {
3723 if (a_mod == Parameter.Modifier.NONE)
3724 if (!ImplicitConversionExists (ec, a.Expr, pd.ParameterType (i)))
3727 if ((a_mod & Parameter.Modifier.ISBYREF) != 0) {
3728 Type pt = pd.ParameterType (i);
3731 pt = TypeManager.LookupType (pt.FullName + "&");
3746 /// Find the Applicable Function Members (7.4.2.1)
3748 /// me: Method Group expression with the members to select.
3749 /// it might contain constructors or methods (or anything
3750 /// that maps to a method).
3752 /// Arguments: ArrayList containing resolved Argument objects.
3754 /// loc: The location if we want an error to be reported, or a Null
3755 /// location for "probing" purposes.
3757 /// Returns: The MethodBase (either a ConstructorInfo or a MethodInfo)
3758 /// that is the best match of me on Arguments.
3761 public static MethodBase OverloadResolve (EmitContext ec, MethodGroupExpr me,
3762 ArrayList Arguments, Location loc)
3764 ArrayList afm = new ArrayList ();
3765 MethodBase method = null;
3766 Type current_type = null;
3768 ArrayList candidates = new ArrayList ();
3771 foreach (MethodBase candidate in me.Methods){
3774 // If we're going one level higher in the class hierarchy, abort if
3775 // we already found an applicable method.
3776 if (candidate.DeclaringType != current_type) {
3777 current_type = candidate.DeclaringType;
3782 // Check if candidate is applicable (section 14.4.2.1)
3783 if (!IsApplicable (ec, Arguments, candidate))
3786 candidates.Add (candidate);
3787 x = BetterFunction (ec, Arguments, candidate, method, false, loc);
3795 if (Arguments == null)
3798 argument_count = Arguments.Count;
3801 // Now we see if we can find params functions, applicable in their expanded form
3802 // since if they were applicable in their normal form, they would have been selected
3805 bool chose_params_expanded = false;
3807 if (method == null) {
3808 candidates = new ArrayList ();
3809 foreach (MethodBase candidate in me.Methods){
3810 if (!IsParamsMethodApplicable (ec, Arguments, candidate))
3813 candidates.Add (candidate);
3815 int x = BetterFunction (ec, Arguments, candidate, method, true, loc);
3820 chose_params_expanded = true;
3824 if (method == null) {
3826 // Okay so we have failed to find anything so we
3827 // return by providing info about the closest match
3829 for (int i = 0; i < me.Methods.Length; ++i) {
3831 MethodBase c = (MethodBase) me.Methods [i];
3832 ParameterData pd = GetParameterData (c);
3834 if (pd.Count != argument_count)
3837 VerifyArgumentsCompat (ec, Arguments, argument_count, c, false,
3845 // Now check that there are no ambiguities i.e the selected method
3846 // should be better than all the others
3849 foreach (MethodBase candidate in candidates){
3850 if (candidate == method)
3854 // If a normal method is applicable in the sense that it has the same
3855 // number of arguments, then the expanded params method is never applicable
3856 // so we debar the params method.
3858 if (IsParamsMethodApplicable (ec, Arguments, candidate) &&
3859 IsApplicable (ec, Arguments, method))
3862 int x = BetterFunction (ec, Arguments, method, candidate,
3863 chose_params_expanded, loc);
3868 "Ambiguous call when selecting function due to implicit casts");
3874 // And now check if the arguments are all compatible, perform conversions
3875 // if necessary etc. and return if everything is all right
3878 if (!VerifyArgumentsCompat (ec, Arguments, argument_count, method,
3879 chose_params_expanded, null, loc))
3885 public static bool VerifyArgumentsCompat (EmitContext ec, ArrayList Arguments,
3888 bool chose_params_expanded,
3892 ParameterData pd = GetParameterData (method);
3893 int pd_count = pd.Count;
3895 for (int j = 0; j < argument_count; j++) {
3896 Argument a = (Argument) Arguments [j];
3897 Expression a_expr = a.Expr;
3898 Type parameter_type = pd.ParameterType (j);
3900 if (pd.ParameterModifier (j) == Parameter.Modifier.PARAMS &&
3901 chose_params_expanded)
3902 parameter_type = TypeManager.TypeToCoreType (parameter_type.GetElementType ());
3904 if (a.Type != parameter_type){
3907 conv = ConvertImplicit (ec, a_expr, parameter_type, loc);
3910 if (!Location.IsNull (loc)) {
3911 if (delegate_type == null)
3912 Report.Error (1502, loc,
3913 "The best overloaded match for method '" +
3914 FullMethodDesc (method) +
3915 "' has some invalid arguments");
3917 Report.Error (1594, loc,
3918 "Delegate '" + delegate_type.ToString () +
3919 "' has some invalid arguments.");
3920 Report.Error (1503, loc,
3921 "Argument " + (j+1) +
3922 ": Cannot convert from '" + Argument.FullDesc (a)
3923 + "' to '" + pd.ParameterDesc (j) + "'");
3930 // Update the argument with the implicit conversion
3936 Parameter.Modifier a_mod = a.GetParameterModifier () &
3937 ~(Parameter.Modifier.OUT | Parameter.Modifier.REF);
3938 Parameter.Modifier p_mod = pd.ParameterModifier (j) &
3939 ~(Parameter.Modifier.OUT | Parameter.Modifier.REF);
3942 if (a_mod != p_mod &&
3943 pd.ParameterModifier (pd_count - 1) != Parameter.Modifier.PARAMS) {
3944 if (!Location.IsNull (loc)) {
3945 Console.WriteLine ("A:P: " + a.GetParameterModifier ());
3946 Console.WriteLine ("PP:: " + pd.ParameterModifier (j));
3947 Console.WriteLine ("PT: " + parameter_type.IsByRef);
3948 Report.Error (1502, loc,
3949 "The best overloaded match for method '" + FullMethodDesc (method)+
3950 "' has some invalid arguments");
3951 Report.Error (1503, loc,
3952 "Argument " + (j+1) +
3953 ": Cannot convert from '" + Argument.FullDesc (a)
3954 + "' to '" + pd.ParameterDesc (j) + "'");
3964 public override Expression DoResolve (EmitContext ec)
3967 // First, resolve the expression that is used to
3968 // trigger the invocation
3970 if (expr is BaseAccess)
3973 expr = expr.Resolve (ec, ResolveFlags.VariableOrValue | ResolveFlags.MethodGroup);
3977 if (!(expr is MethodGroupExpr)) {
3978 Type expr_type = expr.Type;
3980 if (expr_type != null){
3981 bool IsDelegate = TypeManager.IsDelegateType (expr_type);
3983 return (new DelegateInvocation (
3984 this.expr, Arguments, loc)).Resolve (ec);
3988 if (!(expr is MethodGroupExpr)){
3989 expr.Error118 (ResolveFlags.MethodGroup);
3994 // Next, evaluate all the expressions in the argument list
3996 if (Arguments != null){
3997 foreach (Argument a in Arguments){
3998 if (!a.Resolve (ec, loc))
4003 MethodGroupExpr mg = (MethodGroupExpr) expr;
4004 method = OverloadResolve (ec, mg, Arguments, loc);
4006 if (method == null){
4008 "Could not find any applicable function for this argument list");
4012 MethodInfo mi = method as MethodInfo;
4014 type = TypeManager.TypeToCoreType (mi.ReturnType);
4015 if (!mi.IsStatic && !mg.IsExplicitImpl && (mg.InstanceExpression == null))
4016 SimpleName.Error_ObjectRefRequired (ec, loc, mi.Name);
4019 if (type.IsPointer){
4027 // Only base will allow this invocation to happen.
4029 if (is_base && method.IsAbstract){
4030 Report.Error (205, loc, "Cannot call an abstract base member: " +
4031 FullMethodDesc (method));
4035 eclass = ExprClass.Value;
4040 // Emits the list of arguments as an array
4042 static void EmitParams (EmitContext ec, int idx, ArrayList arguments)
4044 ILGenerator ig = ec.ig;
4045 int count = arguments.Count - idx;
4046 Argument a = (Argument) arguments [idx];
4047 Type t = a.Expr.Type;
4048 string array_type = t.FullName + "[]";
4051 array = ig.DeclareLocal (TypeManager.LookupType (array_type));
4052 IntConstant.EmitInt (ig, count);
4053 ig.Emit (OpCodes.Newarr, TypeManager.TypeToCoreType (t));
4054 ig.Emit (OpCodes.Stloc, array);
4056 int top = arguments.Count;
4057 for (int j = idx; j < top; j++){
4058 a = (Argument) arguments [j];
4060 ig.Emit (OpCodes.Ldloc, array);
4061 IntConstant.EmitInt (ig, j - idx);
4064 ArrayAccess.EmitStoreOpcode (ig, t);
4066 ig.Emit (OpCodes.Ldloc, array);
4070 /// Emits a list of resolved Arguments that are in the arguments
4073 /// The MethodBase argument might be null if the
4074 /// emission of the arguments is known not to contain
4075 /// a `params' field (for example in constructors or other routines
4076 /// that keep their arguments in this structure)
4078 public static void EmitArguments (EmitContext ec, MethodBase mb, ArrayList arguments)
4082 pd = GetParameterData (mb);
4087 // If we are calling a params method with no arguments, special case it
4089 if (arguments == null){
4090 if (pd != null && pd.Count > 0 &&
4091 pd.ParameterModifier (0) == Parameter.Modifier.PARAMS){
4092 ILGenerator ig = ec.ig;
4094 IntConstant.EmitInt (ig, 0);
4095 ig.Emit (OpCodes.Newarr, pd.ParameterType (0).GetElementType ());
4101 int top = arguments.Count;
4103 for (int i = 0; i < top; i++){
4104 Argument a = (Argument) arguments [i];
4107 if (pd.ParameterModifier (i) == Parameter.Modifier.PARAMS){
4109 // Special case if we are passing the same data as the
4110 // params argument, do not put it in an array.
4112 if (pd.ParameterType (i) == a.Type)
4115 EmitParams (ec, i, arguments);
4123 if (pd != null && pd.Count > top &&
4124 pd.ParameterModifier (top) == Parameter.Modifier.PARAMS){
4125 ILGenerator ig = ec.ig;
4127 IntConstant.EmitInt (ig, 0);
4128 ig.Emit (OpCodes.Newarr, pd.ParameterType (top).GetElementType ());
4133 /// is_base tells whether we want to force the use of the `call'
4134 /// opcode instead of using callvirt. Call is required to call
4135 /// a specific method, while callvirt will always use the most
4136 /// recent method in the vtable.
4138 /// is_static tells whether this is an invocation on a static method
4140 /// instance_expr is an expression that represents the instance
4141 /// it must be non-null if is_static is false.
4143 /// method is the method to invoke.
4145 /// Arguments is the list of arguments to pass to the method or constructor.
4147 public static void EmitCall (EmitContext ec, bool is_base,
4148 bool is_static, Expression instance_expr,
4149 MethodBase method, ArrayList Arguments, Location loc)
4151 ILGenerator ig = ec.ig;
4152 bool struct_call = false;
4154 Type decl_type = method.DeclaringType;
4156 if (!RootContext.StdLib) {
4157 // Replace any calls to the system's System.Array type with calls to
4158 // the newly created one.
4159 if (method == TypeManager.system_int_array_get_length)
4160 method = TypeManager.int_array_get_length;
4161 else if (method == TypeManager.system_int_array_get_rank)
4162 method = TypeManager.int_array_get_rank;
4163 else if (method == TypeManager.system_object_array_clone)
4164 method = TypeManager.object_array_clone;
4165 else if (method == TypeManager.system_int_array_get_length_int)
4166 method = TypeManager.int_array_get_length_int;
4167 else if (method == TypeManager.system_int_array_get_lower_bound_int)
4168 method = TypeManager.int_array_get_lower_bound_int;
4169 else if (method == TypeManager.system_int_array_get_upper_bound_int)
4170 method = TypeManager.int_array_get_upper_bound_int;
4171 else if (method == TypeManager.system_void_array_copyto_array_int)
4172 method = TypeManager.void_array_copyto_array_int;
4176 // This checks the `ConditionalAttribute' on the method, and the
4177 // ObsoleteAttribute
4179 TypeManager.MethodFlags flags = TypeManager.GetMethodFlags (method, loc);
4180 if ((flags & TypeManager.MethodFlags.IsObsoleteError) != 0)
4182 if ((flags & TypeManager.MethodFlags.ShouldIgnore) != 0)
4186 if (decl_type.IsValueType)
4189 // If this is ourselves, push "this"
4191 if (instance_expr == null){
4192 ig.Emit (OpCodes.Ldarg_0);
4195 // Push the instance expression
4197 if (instance_expr.Type.IsValueType){
4199 // Special case: calls to a function declared in a
4200 // reference-type with a value-type argument need
4201 // to have their value boxed.
4204 if (decl_type.IsValueType){
4206 // If the expression implements IMemoryLocation, then
4207 // we can optimize and use AddressOf on the
4210 // If not we have to use some temporary storage for
4212 if (instance_expr is IMemoryLocation){
4213 ((IMemoryLocation)instance_expr).
4214 AddressOf (ec, AddressOp.LoadStore);
4217 Type t = instance_expr.Type;
4219 instance_expr.Emit (ec);
4220 LocalBuilder temp = ig.DeclareLocal (t);
4221 ig.Emit (OpCodes.Stloc, temp);
4222 ig.Emit (OpCodes.Ldloca, temp);
4225 instance_expr.Emit (ec);
4226 ig.Emit (OpCodes.Box, instance_expr.Type);
4229 instance_expr.Emit (ec);
4233 EmitArguments (ec, method, Arguments);
4235 if (is_static || struct_call || is_base){
4236 if (method is MethodInfo) {
4237 ig.Emit (OpCodes.Call, (MethodInfo) method);
4239 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
4241 if (method is MethodInfo)
4242 ig.Emit (OpCodes.Callvirt, (MethodInfo) method);
4244 ig.Emit (OpCodes.Callvirt, (ConstructorInfo) method);
4248 public override void Emit (EmitContext ec)
4250 MethodGroupExpr mg = (MethodGroupExpr) this.expr;
4253 ec, is_base, method.IsStatic, mg.InstanceExpression, method, Arguments, loc);
4256 public override void EmitStatement (EmitContext ec)
4261 // Pop the return value if there is one
4263 if (method is MethodInfo){
4264 Type ret = ((MethodInfo)method).ReturnType;
4265 if (TypeManager.TypeToCoreType (ret) != TypeManager.void_type)
4266 ec.ig.Emit (OpCodes.Pop);
4272 // This class is used to "disable" the code generation for the
4273 // temporary variable when initializing value types.
4275 class EmptyAddressOf : EmptyExpression, IMemoryLocation {
4276 public void AddressOf (EmitContext ec, AddressOp Mode)
4283 /// Implements the new expression
4285 public class New : ExpressionStatement {
4286 public readonly ArrayList Arguments;
4287 public readonly Expression RequestedType;
4289 MethodBase method = null;
4292 // If set, the new expression is for a value_target, and
4293 // we will not leave anything on the stack.
4295 Expression value_target;
4296 bool value_target_set = false;
4298 public New (Expression requested_type, ArrayList arguments, Location l)
4300 RequestedType = requested_type;
4301 Arguments = arguments;
4305 public Expression ValueTypeVariable {
4307 return value_target;
4311 value_target = value;
4312 value_target_set = true;
4317 // This function is used to disable the following code sequence for
4318 // value type initialization:
4320 // AddressOf (temporary)
4324 // Instead the provide will have provided us with the address on the
4325 // stack to store the results.
4327 static Expression MyEmptyExpression;
4329 public void DisableTemporaryValueType ()
4331 if (MyEmptyExpression == null)
4332 MyEmptyExpression = new EmptyAddressOf ();
4335 // To enable this, look into:
4336 // test-34 and test-89 and self bootstrapping.
4338 // For instance, we can avoid a copy by using `newobj'
4339 // instead of Call + Push-temp on value types.
4340 // value_target = MyEmptyExpression;
4343 public override Expression DoResolve (EmitContext ec)
4345 type = ec.DeclSpace.ResolveType (RequestedType, false, loc);
4350 bool IsDelegate = TypeManager.IsDelegateType (type);
4353 return (new NewDelegate (type, Arguments, loc)).Resolve (ec);
4355 if (type.IsInterface || type.IsAbstract){
4357 144, "It is not possible to create instances of interfaces " +
4358 "or abstract classes");
4362 bool is_struct = false;
4363 is_struct = type.IsValueType;
4364 eclass = ExprClass.Value;
4367 // SRE returns a match for .ctor () on structs (the object constructor),
4368 // so we have to manually ignore it.
4370 if (is_struct && Arguments == null)
4374 ml = MemberLookupFinal (ec, type, ".ctor",
4375 MemberTypes.Constructor,
4376 AllBindingFlags | BindingFlags.DeclaredOnly, loc);
4381 if (! (ml is MethodGroupExpr)){
4383 ml.Error118 ("method group");
4389 if (Arguments != null){
4390 foreach (Argument a in Arguments){
4391 if (!a.Resolve (ec, loc))
4396 method = Invocation.OverloadResolve (ec, (MethodGroupExpr) ml,
4401 if (method == null) {
4402 if (!is_struct || Arguments.Count > 0) {
4404 "New invocation: Can not find a constructor for " +
4405 "this argument list");
4413 // This DoEmit can be invoked in two contexts:
4414 // * As a mechanism that will leave a value on the stack (new object)
4415 // * As one that wont (init struct)
4417 // You can control whether a value is required on the stack by passing
4418 // need_value_on_stack. The code *might* leave a value on the stack
4419 // so it must be popped manually
4421 // If we are dealing with a ValueType, we have a few
4422 // situations to deal with:
4424 // * The target is a ValueType, and we have been provided
4425 // the instance (this is easy, we are being assigned).
4427 // * The target of New is being passed as an argument,
4428 // to a boxing operation or a function that takes a
4431 // In this case, we need to create a temporary variable
4432 // that is the argument of New.
4434 // Returns whether a value is left on the stack
4436 bool DoEmit (EmitContext ec, bool need_value_on_stack)
4438 bool is_value_type = type.IsValueType;
4439 ILGenerator ig = ec.ig;
4444 // Allow DoEmit() to be called multiple times.
4445 // We need to create a new LocalTemporary each time since
4446 // you can't share LocalBuilders among ILGeneators.
4447 if (!value_target_set)
4448 value_target = new LocalTemporary (ec, type);
4450 ml = (IMemoryLocation) value_target;
4451 ml.AddressOf (ec, AddressOp.Store);
4455 Invocation.EmitArguments (ec, method, Arguments);
4459 ig.Emit (OpCodes.Initobj, type);
4461 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
4462 if (need_value_on_stack){
4463 value_target.Emit (ec);
4468 ig.Emit (OpCodes.Newobj, (ConstructorInfo) method);
4473 public override void Emit (EmitContext ec)
4478 public override void EmitStatement (EmitContext ec)
4480 if (DoEmit (ec, false))
4481 ec.ig.Emit (OpCodes.Pop);
4486 /// 14.5.10.2: Represents an array creation expression.
4490 /// There are two possible scenarios here: one is an array creation
4491 /// expression that specifies the dimensions and optionally the
4492 /// initialization data and the other which does not need dimensions
4493 /// specified but where initialization data is mandatory.
4495 public class ArrayCreation : ExpressionStatement {
4496 Expression requested_base_type;
4497 ArrayList initializers;
4500 // The list of Argument types.
4501 // This is used to construct the `newarray' or constructor signature
4503 ArrayList arguments;
4506 // Method used to create the array object.
4508 MethodBase new_method = null;
4510 Type array_element_type;
4511 Type underlying_type;
4512 bool is_one_dimensional = false;
4513 bool is_builtin_type = false;
4514 bool expect_initializers = false;
4515 int num_arguments = 0;
4519 ArrayList array_data;
4524 // The number of array initializers that we can handle
4525 // via the InitializeArray method - through EmitStaticInitializers
4527 int num_automatic_initializers;
4529 public ArrayCreation (Expression requested_base_type, ArrayList exprs, string rank, ArrayList initializers, Location l)
4531 this.requested_base_type = requested_base_type;
4532 this.initializers = initializers;
4536 arguments = new ArrayList ();
4538 foreach (Expression e in exprs) {
4539 arguments.Add (new Argument (e, Argument.AType.Expression));
4544 public ArrayCreation (Expression requested_base_type, string rank, ArrayList initializers, Location l)
4546 this.requested_base_type = requested_base_type;
4547 this.initializers = initializers;
4551 //this.rank = rank.Substring (0, rank.LastIndexOf ("["));
4553 //string tmp = rank.Substring (rank.LastIndexOf ("["));
4555 //dimensions = tmp.Length - 1;
4556 expect_initializers = true;
4559 public Expression FormArrayType (Expression base_type, int idx_count, string rank)
4561 StringBuilder sb = new StringBuilder (rank);
4564 for (int i = 1; i < idx_count; i++)
4569 return new ComposedCast (base_type, sb.ToString (), loc);
4572 void Error_IncorrectArrayInitializer ()
4574 Error (178, "Incorrectly structured array initializer");
4577 public bool CheckIndices (EmitContext ec, ArrayList probe, int idx, bool specified_dims)
4579 if (specified_dims) {
4580 Argument a = (Argument) arguments [idx];
4582 if (!a.Resolve (ec, loc))
4585 if (!(a.Expr is Constant)) {
4586 Error (150, "A constant value is expected");
4590 int value = (int) ((Constant) a.Expr).GetValue ();
4592 if (value != probe.Count) {
4593 Error_IncorrectArrayInitializer ();
4597 bounds [idx] = value;
4600 int child_bounds = -1;
4601 foreach (object o in probe) {
4602 if (o is ArrayList) {
4603 int current_bounds = ((ArrayList) o).Count;
4605 if (child_bounds == -1)
4606 child_bounds = current_bounds;
4608 else if (child_bounds != current_bounds){
4609 Error_IncorrectArrayInitializer ();
4612 bool ret = CheckIndices (ec, (ArrayList) o, idx + 1, specified_dims);
4616 if (child_bounds != -1){
4617 Error_IncorrectArrayInitializer ();
4621 Expression tmp = (Expression) o;
4622 tmp = tmp.Resolve (ec);
4626 // Console.WriteLine ("I got: " + tmp);
4627 // Handle initialization from vars, fields etc.
4629 Expression conv = ConvertImplicitRequired (
4630 ec, tmp, underlying_type, loc);
4635 if (conv is StringConstant)
4636 array_data.Add (conv);
4637 else if (conv is Constant) {
4638 array_data.Add (conv);
4639 num_automatic_initializers++;
4641 array_data.Add (conv);
4648 public void UpdateIndices (EmitContext ec)
4651 for (ArrayList probe = initializers; probe != null;) {
4652 if (probe.Count > 0 && probe [0] is ArrayList) {
4653 Expression e = new IntConstant (probe.Count);
4654 arguments.Add (new Argument (e, Argument.AType.Expression));
4656 bounds [i++] = probe.Count;
4658 probe = (ArrayList) probe [0];
4661 Expression e = new IntConstant (probe.Count);
4662 arguments.Add (new Argument (e, Argument.AType.Expression));
4664 bounds [i++] = probe.Count;
4671 public bool ValidateInitializers (EmitContext ec, Type array_type)
4673 if (initializers == null) {
4674 if (expect_initializers)
4680 if (underlying_type == null)
4684 // We use this to store all the date values in the order in which we
4685 // will need to store them in the byte blob later
4687 array_data = new ArrayList ();
4688 bounds = new Hashtable ();
4692 if (arguments != null) {
4693 ret = CheckIndices (ec, initializers, 0, true);
4696 arguments = new ArrayList ();
4698 ret = CheckIndices (ec, initializers, 0, false);
4705 if (arguments.Count != dimensions) {
4706 Error_IncorrectArrayInitializer ();
4714 void Error_NegativeArrayIndex ()
4716 Error (284, "Can not create array with a negative size");
4720 // Converts `source' to an int, uint, long or ulong.
4722 Expression ExpressionToArrayArgument (EmitContext ec, Expression source)
4726 bool old_checked = ec.CheckState;
4727 ec.CheckState = true;
4729 target = ConvertImplicit (ec, source, TypeManager.int32_type, loc);
4730 if (target == null){
4731 target = ConvertImplicit (ec, source, TypeManager.uint32_type, loc);
4732 if (target == null){
4733 target = ConvertImplicit (ec, source, TypeManager.int64_type, loc);
4734 if (target == null){
4735 target = ConvertImplicit (ec, source, TypeManager.uint64_type, loc);
4737 Expression.Error_CannotConvertImplicit (loc, source.Type, TypeManager.int32_type);
4741 ec.CheckState = old_checked;
4744 // Only positive constants are allowed at compile time
4746 if (target is Constant){
4747 if (target is IntConstant){
4748 if (((IntConstant) target).Value < 0){
4749 Error_NegativeArrayIndex ();
4754 if (target is LongConstant){
4755 if (((LongConstant) target).Value < 0){
4756 Error_NegativeArrayIndex ();
4767 // Creates the type of the array
4769 bool LookupType (EmitContext ec)
4771 StringBuilder array_qualifier = new StringBuilder (rank);
4774 // `In the first form allocates an array instace of the type that results
4775 // from deleting each of the individual expression from the expression list'
4777 if (num_arguments > 0) {
4778 array_qualifier.Append ("[");
4779 for (int i = num_arguments-1; i > 0; i--)
4780 array_qualifier.Append (",");
4781 array_qualifier.Append ("]");
4787 Expression array_type_expr;
4788 array_type_expr = new ComposedCast (requested_base_type, array_qualifier.ToString (), loc);
4789 type = ec.DeclSpace.ResolveType (array_type_expr, false, loc);
4794 underlying_type = type;
4795 if (underlying_type.IsArray)
4796 underlying_type = TypeManager.TypeToCoreType (underlying_type.GetElementType ());
4797 dimensions = type.GetArrayRank ();
4802 public override Expression DoResolve (EmitContext ec)
4806 if (!LookupType (ec))
4810 // First step is to validate the initializers and fill
4811 // in any missing bits
4813 if (!ValidateInitializers (ec, type))
4816 if (arguments == null)
4819 arg_count = arguments.Count;
4820 foreach (Argument a in arguments){
4821 if (!a.Resolve (ec, loc))
4824 Expression real_arg = ExpressionToArrayArgument (ec, a.Expr, loc);
4825 if (real_arg == null)
4832 array_element_type = TypeManager.TypeToCoreType (type.GetElementType ());
4834 if (arg_count == 1) {
4835 is_one_dimensional = true;
4836 eclass = ExprClass.Value;
4840 is_builtin_type = TypeManager.IsBuiltinType (type);
4842 if (is_builtin_type) {
4845 ml = MemberLookup (ec, type, ".ctor", MemberTypes.Constructor,
4846 AllBindingFlags, loc);
4848 if (!(ml is MethodGroupExpr)) {
4849 ml.Error118 ("method group");
4854 Error (-6, "New invocation: Can not find a constructor for " +
4855 "this argument list");
4859 new_method = Invocation.OverloadResolve (ec, (MethodGroupExpr) ml, arguments, loc);
4861 if (new_method == null) {
4862 Error (-6, "New invocation: Can not find a constructor for " +
4863 "this argument list");
4867 eclass = ExprClass.Value;
4870 ModuleBuilder mb = CodeGen.ModuleBuilder;
4871 ArrayList args = new ArrayList ();
4873 if (arguments != null) {
4874 for (int i = 0; i < arg_count; i++)
4875 args.Add (TypeManager.int32_type);
4878 Type [] arg_types = null;
4881 arg_types = new Type [args.Count];
4883 args.CopyTo (arg_types, 0);
4885 new_method = mb.GetArrayMethod (type, ".ctor", CallingConventions.HasThis, null,
4888 if (new_method == null) {
4889 Error (-6, "New invocation: Can not find a constructor for " +
4890 "this argument list");
4894 eclass = ExprClass.Value;
4899 public static byte [] MakeByteBlob (ArrayList array_data, Type underlying_type, Location loc)
4904 int count = array_data.Count;
4906 if (underlying_type.IsEnum)
4907 underlying_type = TypeManager.EnumToUnderlying (underlying_type);
4909 factor = GetTypeSize (underlying_type);
4911 throw new Exception ("unrecognized type in MakeByteBlob: " + underlying_type);
4913 data = new byte [(count * factor + 4) & ~3];
4916 for (int i = 0; i < count; ++i) {
4917 object v = array_data [i];
4919 if (v is EnumConstant)
4920 v = ((EnumConstant) v).Child;
4922 if (v is Constant && !(v is StringConstant))
4923 v = ((Constant) v).GetValue ();
4929 if (underlying_type == TypeManager.int64_type){
4930 if (!(v is Expression)){
4931 long val = (long) v;
4933 for (int j = 0; j < factor; ++j) {
4934 data [idx + j] = (byte) (val & 0xFF);
4938 } else if (underlying_type == TypeManager.uint64_type){
4939 if (!(v is Expression)){
4940 ulong val = (ulong) v;
4942 for (int j = 0; j < factor; ++j) {
4943 data [idx + j] = (byte) (val & 0xFF);
4947 } else if (underlying_type == TypeManager.float_type) {
4948 if (!(v is Expression)){
4949 element = BitConverter.GetBytes ((float) v);
4951 for (int j = 0; j < factor; ++j)
4952 data [idx + j] = element [j];
4954 } else if (underlying_type == TypeManager.double_type) {
4955 if (!(v is Expression)){
4956 element = BitConverter.GetBytes ((double) v);
4958 for (int j = 0; j < factor; ++j)
4959 data [idx + j] = element [j];
4961 } else if (underlying_type == TypeManager.char_type){
4962 if (!(v is Expression)){
4963 int val = (int) ((char) v);
4965 data [idx] = (byte) (val & 0xff);
4966 data [idx+1] = (byte) (val >> 8);
4968 } else if (underlying_type == TypeManager.short_type){
4969 if (!(v is Expression)){
4970 int val = (int) ((short) v);
4972 data [idx] = (byte) (val & 0xff);
4973 data [idx+1] = (byte) (val >> 8);
4975 } else if (underlying_type == TypeManager.ushort_type){
4976 if (!(v is Expression)){
4977 int val = (int) ((ushort) v);
4979 data [idx] = (byte) (val & 0xff);
4980 data [idx+1] = (byte) (val >> 8);
4982 } else if (underlying_type == TypeManager.int32_type) {
4983 if (!(v is Expression)){
4986 data [idx] = (byte) (val & 0xff);
4987 data [idx+1] = (byte) ((val >> 8) & 0xff);
4988 data [idx+2] = (byte) ((val >> 16) & 0xff);
4989 data [idx+3] = (byte) (val >> 24);
4991 } else if (underlying_type == TypeManager.uint32_type) {
4992 if (!(v is Expression)){
4993 uint val = (uint) v;
4995 data [idx] = (byte) (val & 0xff);
4996 data [idx+1] = (byte) ((val >> 8) & 0xff);
4997 data [idx+2] = (byte) ((val >> 16) & 0xff);
4998 data [idx+3] = (byte) (val >> 24);
5000 } else if (underlying_type == TypeManager.sbyte_type) {
5001 if (!(v is Expression)){
5002 sbyte val = (sbyte) v;
5003 data [idx] = (byte) val;
5005 } else if (underlying_type == TypeManager.byte_type) {
5006 if (!(v is Expression)){
5007 byte val = (byte) v;
5008 data [idx] = (byte) val;
5010 } else if (underlying_type == TypeManager.bool_type) {
5011 if (!(v is Expression)){
5012 bool val = (bool) v;
5013 data [idx] = (byte) (val ? 1 : 0);
5015 } else if (underlying_type == TypeManager.decimal_type){
5016 if (!(v is Expression)){
5017 int [] bits = Decimal.GetBits ((decimal) v);
5020 for (int j = 0; j < 4; j++){
5021 data [p++] = (byte) (bits [j] & 0xff);
5022 data [p++] = (byte) ((bits [j] >> 8) & 0xff);
5023 data [p++] = (byte) ((bits [j] >> 16) & 0xff);
5024 data [p++] = (byte) (bits [j] >> 24);
5028 throw new Exception ("Unrecognized type in MakeByteBlob: " + underlying_type);
5037 // Emits the initializers for the array
5039 void EmitStaticInitializers (EmitContext ec, bool is_expression)
5042 // First, the static data
5045 ILGenerator ig = ec.ig;
5047 byte [] data = MakeByteBlob (array_data, underlying_type, loc);
5049 fb = RootContext.MakeStaticData (data);
5052 ig.Emit (OpCodes.Dup);
5053 ig.Emit (OpCodes.Ldtoken, fb);
5054 ig.Emit (OpCodes.Call,
5055 TypeManager.void_initializearray_array_fieldhandle);
5059 // Emits pieces of the array that can not be computed at compile
5060 // time (variables and string locations).
5062 // This always expect the top value on the stack to be the array
5064 void EmitDynamicInitializers (EmitContext ec, bool is_expression)
5066 ILGenerator ig = ec.ig;
5067 int dims = bounds.Count;
5068 int [] current_pos = new int [dims];
5069 int top = array_data.Count;
5070 LocalBuilder temp = ig.DeclareLocal (type);
5072 ig.Emit (OpCodes.Stloc, temp);
5074 MethodInfo set = null;
5078 ModuleBuilder mb = null;
5079 mb = CodeGen.ModuleBuilder;
5080 args = new Type [dims + 1];
5083 for (j = 0; j < dims; j++)
5084 args [j] = TypeManager.int32_type;
5086 args [j] = array_element_type;
5088 set = mb.GetArrayMethod (
5090 CallingConventions.HasThis | CallingConventions.Standard,
5091 TypeManager.void_type, args);
5094 for (int i = 0; i < top; i++){
5096 Expression e = null;
5098 if (array_data [i] is Expression)
5099 e = (Expression) array_data [i];
5103 // Basically we do this for string literals and
5104 // other non-literal expressions
5106 if (e is StringConstant || !(e is Constant) ||
5107 num_automatic_initializers <= 2) {
5108 Type etype = e.Type;
5110 ig.Emit (OpCodes.Ldloc, temp);
5112 for (int idx = 0; idx < dims; idx++)
5113 IntConstant.EmitInt (ig, current_pos [idx]);
5116 // If we are dealing with a struct, get the
5117 // address of it, so we can store it.
5120 etype.IsSubclassOf (TypeManager.value_type) &&
5121 (!TypeManager.IsBuiltinType (etype) ||
5122 etype == TypeManager.decimal_type)) {
5127 // Let new know that we are providing
5128 // the address where to store the results
5130 n.DisableTemporaryValueType ();
5133 ig.Emit (OpCodes.Ldelema, etype);
5139 ArrayAccess.EmitStoreOpcode (ig, array_element_type);
5141 ig.Emit (OpCodes.Call, set);
5148 for (int j = dims - 1; j >= 0; j--){
5150 if (current_pos [j] < (int) bounds [j])
5152 current_pos [j] = 0;
5157 ig.Emit (OpCodes.Ldloc, temp);
5160 void EmitArrayArguments (EmitContext ec)
5162 ILGenerator ig = ec.ig;
5164 foreach (Argument a in arguments) {
5165 Type atype = a.Type;
5168 if (atype == TypeManager.uint64_type)
5169 ig.Emit (OpCodes.Conv_Ovf_U4);
5170 else if (atype == TypeManager.int64_type)
5171 ig.Emit (OpCodes.Conv_Ovf_I4);
5175 void DoEmit (EmitContext ec, bool is_statement)
5177 ILGenerator ig = ec.ig;
5179 EmitArrayArguments (ec);
5180 if (is_one_dimensional)
5181 ig.Emit (OpCodes.Newarr, array_element_type);
5183 if (is_builtin_type)
5184 ig.Emit (OpCodes.Newobj, (ConstructorInfo) new_method);
5186 ig.Emit (OpCodes.Newobj, (MethodInfo) new_method);
5189 if (initializers != null){
5191 // FIXME: Set this variable correctly.
5193 bool dynamic_initializers = true;
5195 if (underlying_type != TypeManager.string_type &&
5196 underlying_type != TypeManager.object_type) {
5197 if (num_automatic_initializers > 2)
5198 EmitStaticInitializers (ec, dynamic_initializers || !is_statement);
5201 if (dynamic_initializers)
5202 EmitDynamicInitializers (ec, !is_statement);
5206 public override void Emit (EmitContext ec)
5211 public override void EmitStatement (EmitContext ec)
5219 /// Represents the `this' construct
5221 public class This : Expression, IAssignMethod, IMemoryLocation, IVariable {
5226 public This (Block block, Location loc)
5232 public This (Location loc)
5237 public bool IsAssigned (EmitContext ec, Location loc)
5242 return vi.IsAssigned (ec, loc);
5245 public bool IsFieldAssigned (EmitContext ec, string field_name, Location loc)
5250 return vi.IsFieldAssigned (ec, field_name, loc);
5253 public void SetAssigned (EmitContext ec)
5256 vi.SetAssigned (ec);
5259 public void SetFieldAssigned (EmitContext ec, string field_name)
5262 vi.SetFieldAssigned (ec, field_name);
5265 public override Expression DoResolve (EmitContext ec)
5267 eclass = ExprClass.Variable;
5268 type = ec.ContainerType;
5271 Error (26, "Keyword this not valid in static code");
5276 vi = block.ThisVariable;
5281 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
5285 VariableInfo vi = ec.CurrentBlock.ThisVariable;
5287 vi.SetAssigned (ec);
5289 if (ec.TypeContainer is Class){
5290 Error (1604, "Cannot assign to `this'");
5297 public override void Emit (EmitContext ec)
5299 ILGenerator ig = ec.ig;
5301 ig.Emit (OpCodes.Ldarg_0);
5302 if (ec.TypeContainer is Struct)
5303 ig.Emit (OpCodes.Ldobj, type);
5306 public void EmitAssign (EmitContext ec, Expression source)
5308 ILGenerator ig = ec.ig;
5310 if (ec.TypeContainer is Struct){
5311 ig.Emit (OpCodes.Ldarg_0);
5313 ig.Emit (OpCodes.Stobj, type);
5316 ig.Emit (OpCodes.Starg, 0);
5320 public void AddressOf (EmitContext ec, AddressOp mode)
5322 ec.ig.Emit (OpCodes.Ldarg_0);
5325 // FIGURE OUT WHY LDARG_S does not work
5327 // consider: struct X { int val; int P { set { val = value; }}}
5329 // Yes, this looks very bad. Look at `NOTAS' for
5331 // ec.ig.Emit (OpCodes.Ldarga_S, (byte) 0);
5336 /// Implements the typeof operator
5338 public class TypeOf : Expression {
5339 public readonly Expression QueriedType;
5342 public TypeOf (Expression queried_type, Location l)
5344 QueriedType = queried_type;
5348 public override Expression DoResolve (EmitContext ec)
5350 typearg = ec.DeclSpace.ResolveType (QueriedType, false, loc);
5352 if (typearg == null)
5355 type = TypeManager.type_type;
5356 eclass = ExprClass.Type;
5360 public override void Emit (EmitContext ec)
5362 ec.ig.Emit (OpCodes.Ldtoken, typearg);
5363 ec.ig.Emit (OpCodes.Call, TypeManager.system_type_get_type_from_handle);
5366 public Type TypeArg {
5367 get { return typearg; }
5372 /// Implements the sizeof expression
5374 public class SizeOf : Expression {
5375 public readonly Expression QueriedType;
5378 public SizeOf (Expression queried_type, Location l)
5380 this.QueriedType = queried_type;
5384 public override Expression DoResolve (EmitContext ec)
5387 Error (233, "Sizeof may only be used in an unsafe context " +
5388 "(consider using System.Runtime.InteropServices.Marshal.Sizeof");
5392 type_queried = ec.DeclSpace.ResolveType (QueriedType, false, loc);
5393 if (type_queried == null)
5396 if (!TypeManager.IsUnmanagedType (type_queried)){
5397 Report.Error (208, "Cannot take the size of an unmanaged type (" + TypeManager.CSharpName (type_queried) + ")");
5401 type = TypeManager.int32_type;
5402 eclass = ExprClass.Value;
5406 public override void Emit (EmitContext ec)
5408 int size = GetTypeSize (type_queried);
5411 ec.ig.Emit (OpCodes.Sizeof, type_queried);
5413 IntConstant.EmitInt (ec.ig, size);
5418 /// Implements the member access expression
5420 public class MemberAccess : Expression, ITypeExpression {
5421 public readonly string Identifier;
5423 Expression member_lookup;
5425 public MemberAccess (Expression expr, string id, Location l)
5432 public Expression Expr {
5438 static void error176 (Location loc, string name)
5440 Report.Error (176, loc, "Static member `" +
5441 name + "' cannot be accessed " +
5442 "with an instance reference, qualify with a " +
5443 "type name instead");
5446 static bool IdenticalNameAndTypeName (EmitContext ec, Expression left_original, Location loc)
5448 if (left_original == null)
5451 if (!(left_original is SimpleName))
5454 SimpleName sn = (SimpleName) left_original;
5456 Type t = RootContext.LookupType (ec.DeclSpace, sn.Name, true, loc);
5463 public static Expression ResolveMemberAccess (EmitContext ec, Expression member_lookup,
5464 Expression left, Location loc,
5465 Expression left_original)
5467 bool left_is_type, left_is_explicit;
5469 // If `left' is null, then we're called from SimpleNameResolve and this is
5470 // a member in the currently defining class.
5472 left_is_type = ec.IsStatic || ec.IsFieldInitializer;
5473 left_is_explicit = false;
5475 // Implicitly default to `this' unless we're static.
5476 if (!ec.IsStatic && !ec.IsFieldInitializer && !ec.InEnumContext)
5479 left_is_type = left is TypeExpr;
5480 left_is_explicit = true;
5483 if (member_lookup is FieldExpr){
5484 FieldExpr fe = (FieldExpr) member_lookup;
5485 FieldInfo fi = fe.FieldInfo;
5486 Type decl_type = fi.DeclaringType;
5488 if (fi is FieldBuilder) {
5489 Const c = TypeManager.LookupConstant ((FieldBuilder) fi);
5492 object o = c.LookupConstantValue (ec);
5493 object real_value = ((Constant) c.Expr).GetValue ();
5495 return Constantify (real_value, fi.FieldType);
5500 Type t = fi.FieldType;
5504 if (fi is FieldBuilder)
5505 o = TypeManager.GetValue ((FieldBuilder) fi);
5507 o = fi.GetValue (fi);
5509 if (decl_type.IsSubclassOf (TypeManager.enum_type)) {
5510 if (left_is_explicit && !left_is_type &&
5511 !IdenticalNameAndTypeName (ec, left_original, loc)) {
5512 error176 (loc, fe.FieldInfo.Name);
5516 Expression enum_member = MemberLookup (
5517 ec, decl_type, "value__", MemberTypes.Field,
5518 AllBindingFlags, loc);
5520 Enum en = TypeManager.LookupEnum (decl_type);
5524 c = Constantify (o, en.UnderlyingType);
5526 c = Constantify (o, enum_member.Type);
5528 return new EnumConstant (c, decl_type);
5531 Expression exp = Constantify (o, t);
5533 if (left_is_explicit && !left_is_type) {
5534 error176 (loc, fe.FieldInfo.Name);
5541 if (fi.FieldType.IsPointer && !ec.InUnsafe){
5547 if (member_lookup is EventExpr) {
5549 EventExpr ee = (EventExpr) member_lookup;
5552 // If the event is local to this class, we transform ourselves into
5556 if (ee.EventInfo.DeclaringType == ec.ContainerType) {
5557 MemberInfo mi = GetFieldFromEvent (ee);
5561 // If this happens, then we have an event with its own
5562 // accessors and private field etc so there's no need
5563 // to transform ourselves : we should instead flag an error
5565 Assign.error70 (ee.EventInfo, loc);
5569 Expression ml = ExprClassFromMemberInfo (ec, mi, loc);
5572 Report.Error (-200, loc, "Internal error!!");
5576 return ResolveMemberAccess (ec, ml, left, loc, left_original);
5580 if (member_lookup is IMemberExpr) {
5581 IMemberExpr me = (IMemberExpr) member_lookup;
5584 MethodGroupExpr mg = me as MethodGroupExpr;
5585 if ((mg != null) && left_is_explicit && left.Type.IsInterface)
5586 mg.IsExplicitImpl = left_is_explicit;
5589 if (IdenticalNameAndTypeName (ec, left_original, loc))
5590 return member_lookup;
5592 SimpleName.Error_ObjectRefRequired (ec, loc, me.Name);
5597 if (!me.IsInstance){
5598 if (IdenticalNameAndTypeName (ec, left_original, loc))
5599 return member_lookup;
5601 if (left_is_explicit) {
5602 error176 (loc, me.Name);
5608 // Since we can not check for instance objects in SimpleName,
5609 // becaue of the rule that allows types and variables to share
5610 // the name (as long as they can be de-ambiguated later, see
5611 // IdenticalNameAndTypeName), we have to check whether left
5612 // is an instance variable in a static context
5614 // However, if the left-hand value is explicitly given, then
5615 // it is already our instance expression, so we aren't in
5619 if (ec.IsStatic && !left_is_explicit && left is IMemberExpr){
5620 IMemberExpr mexp = (IMemberExpr) left;
5622 if (!mexp.IsStatic){
5623 SimpleName.Error_ObjectRefRequired (ec, loc, mexp.Name);
5628 me.InstanceExpression = left;
5631 return member_lookup;
5634 if (member_lookup is TypeExpr){
5635 member_lookup.Resolve (ec, ResolveFlags.Type);
5636 return member_lookup;
5639 Console.WriteLine ("Left is: " + left);
5640 Report.Error (-100, loc, "Support for [" + member_lookup + "] is not present yet");
5641 Environment.Exit (0);
5645 public Expression DoResolve (EmitContext ec, Expression right_side, ResolveFlags flags)
5648 throw new Exception ();
5650 // Resolve the expression with flow analysis turned off, we'll do the definite
5651 // assignment checks later. This is because we don't know yet what the expression
5652 // will resolve to - it may resolve to a FieldExpr and in this case we must do the
5653 // definite assignment check on the actual field and not on the whole struct.
5656 Expression original = expr;
5657 expr = expr.Resolve (ec, flags | ResolveFlags.DisableFlowAnalysis);
5662 if (expr is SimpleName){
5663 SimpleName child_expr = (SimpleName) expr;
5665 Expression new_expr = new SimpleName (child_expr.Name + "." + Identifier, loc);
5667 return new_expr.Resolve (ec, flags);
5671 // TODO: I mailed Ravi about this, and apparently we can get rid
5672 // of this and put it in the right place.
5674 // Handle enums here when they are in transit.
5675 // Note that we cannot afford to hit MemberLookup in this case because
5676 // it will fail to find any members at all
5679 int errors = Report.Errors;
5681 Type expr_type = expr.Type;
5682 if ((expr is TypeExpr) && (expr_type.IsSubclassOf (TypeManager.enum_type))){
5684 Enum en = TypeManager.LookupEnum (expr_type);
5687 object value = en.LookupEnumValue (ec, Identifier, loc);
5690 Constant c = Constantify (value, en.UnderlyingType);
5691 return new EnumConstant (c, expr_type);
5696 if (expr_type.IsPointer){
5697 Error (23, "The `.' operator can not be applied to pointer operands (" +
5698 TypeManager.CSharpName (expr_type) + ")");
5702 member_lookup = MemberLookup (ec, expr_type, Identifier, loc);
5704 if (member_lookup == null){
5705 // Error has already been reported.
5706 if (errors < Report.Errors)
5710 // Try looking the member up from the same type, if we find
5711 // it, we know that the error was due to limited visibility
5713 object lookup = TypeManager.MemberLookup (
5714 expr_type, expr_type, AllMemberTypes, AllBindingFlags |
5715 BindingFlags.NonPublic, Identifier);
5717 Error (117, "`" + expr_type + "' does not contain a " +
5718 "definition for `" + Identifier + "'");
5719 else if ((expr_type != ec.ContainerType) &&
5720 ec.ContainerType.IsSubclassOf (expr_type)){
5722 // Although a derived class can access protected members of
5723 // its base class it cannot do so through an instance of the
5724 // base class (CS1540). If the expr_type is a parent of the
5725 // ec.ContainerType and the lookup succeeds with the latter one,
5726 // then we are in this situation.
5728 lookup = TypeManager.MemberLookup (
5729 ec.ContainerType, ec.ContainerType, AllMemberTypes,
5730 AllBindingFlags, Identifier);
5733 Error (1540, "Cannot access protected member `" +
5734 expr_type + "." + Identifier + "' " +
5735 "via a qualifier of type `" +
5736 TypeManager.CSharpName (expr_type) + "'; the " +
5737 "qualifier must be of type `" +
5738 TypeManager.CSharpName (ec.ContainerType) + "' " +
5739 "(or derived from it)");
5741 Error (122, "`" + expr_type + "." + Identifier + "' " +
5742 "is inaccessible because of its protection level");
5744 Error (122, "`" + expr_type + "." + Identifier + "' " +
5745 "is inaccessible because of its protection level");
5750 if (member_lookup is TypeExpr){
5751 member_lookup.Resolve (ec, ResolveFlags.Type);
5752 return member_lookup;
5753 } else if ((flags & ResolveFlags.MaskExprClass) == ResolveFlags.Type)
5756 member_lookup = ResolveMemberAccess (ec, member_lookup, expr, loc, original);
5757 if (member_lookup == null)
5760 // The following DoResolve/DoResolveLValue will do the definite assignment
5763 if (right_side != null)
5764 member_lookup = member_lookup.DoResolveLValue (ec, right_side);
5766 member_lookup = member_lookup.DoResolve (ec);
5768 return member_lookup;
5771 public override Expression DoResolve (EmitContext ec)
5773 return DoResolve (ec, null, ResolveFlags.VariableOrValue |
5774 ResolveFlags.SimpleName | ResolveFlags.Type);
5777 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
5779 return DoResolve (ec, right_side, ResolveFlags.VariableOrValue |
5780 ResolveFlags.SimpleName | ResolveFlags.Type);
5783 public Expression DoResolveType (EmitContext ec)
5785 return DoResolve (ec, null, ResolveFlags.Type);
5788 public override void Emit (EmitContext ec)
5790 throw new Exception ("Should not happen");
5793 public override string ToString ()
5795 return expr + "." + Identifier;
5800 /// Implements checked expressions
5802 public class CheckedExpr : Expression {
5804 public Expression Expr;
5806 public CheckedExpr (Expression e, Location l)
5812 public override Expression DoResolve (EmitContext ec)
5814 bool last_const_check = ec.ConstantCheckState;
5816 ec.ConstantCheckState = true;
5817 Expr = Expr.Resolve (ec);
5818 ec.ConstantCheckState = last_const_check;
5823 if (Expr is Constant)
5826 eclass = Expr.eclass;
5831 public override void Emit (EmitContext ec)
5833 bool last_check = ec.CheckState;
5834 bool last_const_check = ec.ConstantCheckState;
5836 ec.CheckState = true;
5837 ec.ConstantCheckState = true;
5839 ec.CheckState = last_check;
5840 ec.ConstantCheckState = last_const_check;
5846 /// Implements the unchecked expression
5848 public class UnCheckedExpr : Expression {
5850 public Expression Expr;
5852 public UnCheckedExpr (Expression e, Location l)
5858 public override Expression DoResolve (EmitContext ec)
5860 bool last_const_check = ec.ConstantCheckState;
5862 ec.ConstantCheckState = false;
5863 Expr = Expr.Resolve (ec);
5864 ec.ConstantCheckState = last_const_check;
5869 if (Expr is Constant)
5872 eclass = Expr.eclass;
5877 public override void Emit (EmitContext ec)
5879 bool last_check = ec.CheckState;
5880 bool last_const_check = ec.ConstantCheckState;
5882 ec.CheckState = false;
5883 ec.ConstantCheckState = false;
5885 ec.CheckState = last_check;
5886 ec.ConstantCheckState = last_const_check;
5892 /// An Element Access expression.
5894 /// During semantic analysis these are transformed into
5895 /// IndexerAccess or ArrayAccess
5897 public class ElementAccess : Expression {
5898 public ArrayList Arguments;
5899 public Expression Expr;
5901 public ElementAccess (Expression e, ArrayList e_list, Location l)
5910 Arguments = new ArrayList ();
5911 foreach (Expression tmp in e_list)
5912 Arguments.Add (new Argument (tmp, Argument.AType.Expression));
5916 bool CommonResolve (EmitContext ec)
5918 Expr = Expr.Resolve (ec);
5923 if (Arguments == null)
5926 foreach (Argument a in Arguments){
5927 if (!a.Resolve (ec, loc))
5934 Expression MakePointerAccess ()
5938 if (t == TypeManager.void_ptr_type){
5941 "The array index operation is not valid for void pointers");
5944 if (Arguments.Count != 1){
5947 "A pointer must be indexed by a single value");
5950 Expression p = new PointerArithmetic (true, Expr, ((Argument)Arguments [0]).Expr,
5952 return new Indirection (p, loc);
5955 public override Expression DoResolve (EmitContext ec)
5957 if (!CommonResolve (ec))
5961 // We perform some simple tests, and then to "split" the emit and store
5962 // code we create an instance of a different class, and return that.
5964 // I am experimenting with this pattern.
5969 return (new ArrayAccess (this, loc)).Resolve (ec);
5970 else if (t.IsPointer)
5971 return MakePointerAccess ();
5973 return (new IndexerAccess (this, loc)).Resolve (ec);
5976 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
5978 if (!CommonResolve (ec))
5983 return (new ArrayAccess (this, loc)).ResolveLValue (ec, right_side);
5984 else if (t.IsPointer)
5985 return MakePointerAccess ();
5987 return (new IndexerAccess (this, loc)).ResolveLValue (ec, right_side);
5990 public override void Emit (EmitContext ec)
5992 throw new Exception ("Should never be reached");
5997 /// Implements array access
5999 public class ArrayAccess : Expression, IAssignMethod, IMemoryLocation {
6001 // Points to our "data" repository
6005 LocalTemporary [] cached_locations;
6007 public ArrayAccess (ElementAccess ea_data, Location l)
6010 eclass = ExprClass.Variable;
6014 public override Expression DoResolve (EmitContext ec)
6016 ExprClass eclass = ea.Expr.eclass;
6019 // As long as the type is valid
6020 if (!(eclass == ExprClass.Variable || eclass == ExprClass.PropertyAccess ||
6021 eclass == ExprClass.Value)) {
6022 ea.Expr.Error118 ("variable or value");
6027 Type t = ea.Expr.Type;
6028 if (t.GetArrayRank () != ea.Arguments.Count){
6030 "Incorrect number of indexes for array " +
6031 " expected: " + t.GetArrayRank () + " got: " +
6032 ea.Arguments.Count);
6035 type = TypeManager.TypeToCoreType (t.GetElementType ());
6036 if (type.IsPointer && !ec.InUnsafe){
6037 UnsafeError (ea.Location);
6041 foreach (Argument a in ea.Arguments){
6042 Type argtype = a.Type;
6044 if (argtype == TypeManager.int32_type ||
6045 argtype == TypeManager.uint32_type ||
6046 argtype == TypeManager.int64_type ||
6047 argtype == TypeManager.uint64_type)
6051 // Mhm. This is strage, because the Argument.Type is not the same as
6052 // Argument.Expr.Type: the value changes depending on the ref/out setting.
6054 // Wonder if I will run into trouble for this.
6056 a.Expr = ExpressionToArrayArgument (ec, a.Expr, ea.Location);
6061 eclass = ExprClass.Variable;
6067 /// Emits the right opcode to load an object of Type `t'
6068 /// from an array of T
6070 static public void EmitLoadOpcode (ILGenerator ig, Type type)
6072 if (type == TypeManager.byte_type || type == TypeManager.bool_type)
6073 ig.Emit (OpCodes.Ldelem_U1);
6074 else if (type == TypeManager.sbyte_type)
6075 ig.Emit (OpCodes.Ldelem_I1);
6076 else if (type == TypeManager.short_type)
6077 ig.Emit (OpCodes.Ldelem_I2);
6078 else if (type == TypeManager.ushort_type || type == TypeManager.char_type)
6079 ig.Emit (OpCodes.Ldelem_U2);
6080 else if (type == TypeManager.int32_type)
6081 ig.Emit (OpCodes.Ldelem_I4);
6082 else if (type == TypeManager.uint32_type)
6083 ig.Emit (OpCodes.Ldelem_U4);
6084 else if (type == TypeManager.uint64_type)
6085 ig.Emit (OpCodes.Ldelem_I8);
6086 else if (type == TypeManager.int64_type)
6087 ig.Emit (OpCodes.Ldelem_I8);
6088 else if (type == TypeManager.float_type)
6089 ig.Emit (OpCodes.Ldelem_R4);
6090 else if (type == TypeManager.double_type)
6091 ig.Emit (OpCodes.Ldelem_R8);
6092 else if (type == TypeManager.intptr_type)
6093 ig.Emit (OpCodes.Ldelem_I);
6094 else if (type.IsValueType){
6095 ig.Emit (OpCodes.Ldelema, type);
6096 ig.Emit (OpCodes.Ldobj, type);
6098 ig.Emit (OpCodes.Ldelem_Ref);
6102 /// Emits the right opcode to store an object of Type `t'
6103 /// from an array of T.
6105 static public void EmitStoreOpcode (ILGenerator ig, Type t)
6107 t = TypeManager.TypeToCoreType (t);
6108 if (TypeManager.IsEnumType (t) && t != TypeManager.enum_type)
6109 t = TypeManager.EnumToUnderlying (t);
6110 if (t == TypeManager.byte_type || t == TypeManager.sbyte_type ||
6111 t == TypeManager.bool_type)
6112 ig.Emit (OpCodes.Stelem_I1);
6113 else if (t == TypeManager.short_type || t == TypeManager.ushort_type || t == TypeManager.char_type)
6114 ig.Emit (OpCodes.Stelem_I2);
6115 else if (t == TypeManager.int32_type || t == TypeManager.uint32_type)
6116 ig.Emit (OpCodes.Stelem_I4);
6117 else if (t == TypeManager.int64_type || t == TypeManager.uint64_type)
6118 ig.Emit (OpCodes.Stelem_I8);
6119 else if (t == TypeManager.float_type)
6120 ig.Emit (OpCodes.Stelem_R4);
6121 else if (t == TypeManager.double_type)
6122 ig.Emit (OpCodes.Stelem_R8);
6123 else if (t == TypeManager.intptr_type)
6124 ig.Emit (OpCodes.Stelem_I);
6125 else if (t.IsValueType){
6126 ig.Emit (OpCodes.Stobj, t);
6128 ig.Emit (OpCodes.Stelem_Ref);
6131 MethodInfo FetchGetMethod ()
6133 ModuleBuilder mb = CodeGen.ModuleBuilder;
6134 int arg_count = ea.Arguments.Count;
6135 Type [] args = new Type [arg_count];
6138 for (int i = 0; i < arg_count; i++){
6139 //args [i++] = a.Type;
6140 args [i] = TypeManager.int32_type;
6143 get = mb.GetArrayMethod (
6144 ea.Expr.Type, "Get",
6145 CallingConventions.HasThis |
6146 CallingConventions.Standard,
6152 MethodInfo FetchAddressMethod ()
6154 ModuleBuilder mb = CodeGen.ModuleBuilder;
6155 int arg_count = ea.Arguments.Count;
6156 Type [] args = new Type [arg_count];
6158 string ptr_type_name;
6161 ptr_type_name = type.FullName + "&";
6162 ret_type = Type.GetType (ptr_type_name);
6165 // It is a type defined by the source code we are compiling
6167 if (ret_type == null){
6168 ret_type = mb.GetType (ptr_type_name);
6171 for (int i = 0; i < arg_count; i++){
6172 //args [i++] = a.Type;
6173 args [i] = TypeManager.int32_type;
6176 address = mb.GetArrayMethod (
6177 ea.Expr.Type, "Address",
6178 CallingConventions.HasThis |
6179 CallingConventions.Standard,
6186 // Load the array arguments into the stack.
6188 // If we have been requested to cache the values (cached_locations array
6189 // initialized), then load the arguments the first time and store them
6190 // in locals. otherwise load from local variables.
6192 void LoadArrayAndArguments (EmitContext ec)
6194 ILGenerator ig = ec.ig;
6196 if (cached_locations == null){
6198 foreach (Argument a in ea.Arguments){
6199 Type argtype = a.Expr.Type;
6203 if (argtype == TypeManager.int64_type)
6204 ig.Emit (OpCodes.Conv_Ovf_I);
6205 else if (argtype == TypeManager.uint64_type)
6206 ig.Emit (OpCodes.Conv_Ovf_I_Un);
6211 if (cached_locations [0] == null){
6212 cached_locations [0] = new LocalTemporary (ec, ea.Expr.Type);
6214 ig.Emit (OpCodes.Dup);
6215 cached_locations [0].Store (ec);
6219 foreach (Argument a in ea.Arguments){
6220 Type argtype = a.Expr.Type;
6222 cached_locations [j] = new LocalTemporary (ec, TypeManager.intptr_type /* a.Expr.Type */);
6224 if (argtype == TypeManager.int64_type)
6225 ig.Emit (OpCodes.Conv_Ovf_I);
6226 else if (argtype == TypeManager.uint64_type)
6227 ig.Emit (OpCodes.Conv_Ovf_I_Un);
6229 ig.Emit (OpCodes.Dup);
6230 cached_locations [j].Store (ec);
6236 foreach (LocalTemporary lt in cached_locations)
6240 public new void CacheTemporaries (EmitContext ec)
6242 cached_locations = new LocalTemporary [ea.Arguments.Count + 1];
6245 public override void Emit (EmitContext ec)
6247 int rank = ea.Expr.Type.GetArrayRank ();
6248 ILGenerator ig = ec.ig;
6250 LoadArrayAndArguments (ec);
6253 EmitLoadOpcode (ig, type);
6257 method = FetchGetMethod ();
6258 ig.Emit (OpCodes.Call, method);
6262 public void EmitAssign (EmitContext ec, Expression source)
6264 int rank = ea.Expr.Type.GetArrayRank ();
6265 ILGenerator ig = ec.ig;
6266 Type t = source.Type;
6268 LoadArrayAndArguments (ec);
6271 // The stobj opcode used by value types will need
6272 // an address on the stack, not really an array/array
6276 if (t == TypeManager.enum_type || t == TypeManager.decimal_type ||
6277 (t.IsSubclassOf (TypeManager.value_type) && !TypeManager.IsEnumType (t) && !TypeManager.IsBuiltinType (t)))
6278 ig.Emit (OpCodes.Ldelema, t);
6284 EmitStoreOpcode (ig, t);
6286 ModuleBuilder mb = CodeGen.ModuleBuilder;
6287 int arg_count = ea.Arguments.Count;
6288 Type [] args = new Type [arg_count + 1];
6291 for (int i = 0; i < arg_count; i++){
6292 //args [i++] = a.Type;
6293 args [i] = TypeManager.int32_type;
6296 args [arg_count] = type;
6298 set = mb.GetArrayMethod (
6299 ea.Expr.Type, "Set",
6300 CallingConventions.HasThis |
6301 CallingConventions.Standard,
6302 TypeManager.void_type, args);
6304 ig.Emit (OpCodes.Call, set);
6308 public void AddressOf (EmitContext ec, AddressOp mode)
6310 int rank = ea.Expr.Type.GetArrayRank ();
6311 ILGenerator ig = ec.ig;
6313 LoadArrayAndArguments (ec);
6316 ig.Emit (OpCodes.Ldelema, type);
6318 MethodInfo address = FetchAddressMethod ();
6319 ig.Emit (OpCodes.Call, address);
6326 public ArrayList getters, setters;
6327 static Hashtable map;
6331 map = new Hashtable ();
6334 Indexers (MemberInfo [] mi)
6336 foreach (PropertyInfo property in mi){
6337 MethodInfo get, set;
6339 get = property.GetGetMethod (true);
6341 if (getters == null)
6342 getters = new ArrayList ();
6347 set = property.GetSetMethod (true);
6349 if (setters == null)
6350 setters = new ArrayList ();
6356 static private Indexers GetIndexersForTypeOrInterface (Type caller_type, Type lookup_type)
6358 Indexers ix = (Indexers) map [lookup_type];
6363 string p_name = TypeManager.IndexerPropertyName (lookup_type);
6365 MemberInfo [] mi = TypeManager.MemberLookup (
6366 caller_type, lookup_type, MemberTypes.Property,
6367 BindingFlags.Public | BindingFlags.Instance, p_name);
6369 if (mi == null || mi.Length == 0)
6372 ix = new Indexers (mi);
6373 map [lookup_type] = ix;
6378 static public Indexers GetIndexersForType (Type caller_type, Type lookup_type, Location loc)
6380 Indexers ix = (Indexers) map [lookup_type];
6385 ix = GetIndexersForTypeOrInterface (caller_type, lookup_type);
6389 Type [] ifaces = TypeManager.GetInterfaces (lookup_type);
6390 if (ifaces != null) {
6391 foreach (Type itype in ifaces) {
6392 ix = GetIndexersForTypeOrInterface (caller_type, itype);
6398 Report.Error (21, loc,
6399 "Type `" + TypeManager.CSharpName (lookup_type) +
6400 "' does not have any indexers defined");
6406 /// Expressions that represent an indexer call.
6408 public class IndexerAccess : Expression, IAssignMethod {
6410 // Points to our "data" repository
6412 MethodInfo get, set;
6414 ArrayList set_arguments;
6415 bool is_base_indexer;
6417 protected Type indexer_type;
6418 protected Type current_type;
6419 protected Expression instance_expr;
6420 protected ArrayList arguments;
6422 public IndexerAccess (ElementAccess ea, Location loc)
6423 : this (ea.Expr, false, loc)
6425 this.arguments = ea.Arguments;
6428 protected IndexerAccess (Expression instance_expr, bool is_base_indexer,
6431 this.instance_expr = instance_expr;
6432 this.is_base_indexer = is_base_indexer;
6433 this.eclass = ExprClass.Value;
6437 protected virtual bool CommonResolve (EmitContext ec)
6439 indexer_type = instance_expr.Type;
6440 current_type = ec.ContainerType;
6445 public override Expression DoResolve (EmitContext ec)
6447 if (!CommonResolve (ec))
6451 // Step 1: Query for all `Item' *properties*. Notice
6452 // that the actual methods are pointed from here.
6454 // This is a group of properties, piles of them.
6457 ilist = Indexers.GetIndexersForType (
6458 current_type, indexer_type, loc);
6461 // Step 2: find the proper match
6463 if (ilist != null && ilist.getters != null && ilist.getters.Count > 0)
6464 get = (MethodInfo) Invocation.OverloadResolve (
6465 ec, new MethodGroupExpr (ilist.getters, loc), arguments, loc);
6468 Error (154, "indexer can not be used in this context, because " +
6469 "it lacks a `get' accessor");
6473 // Only base will allow this invocation to happen.
6475 if (get.IsAbstract && this is BaseIndexerAccess){
6476 Report.Error (205, loc, "Cannot call an abstract base indexer: " + Invocation.FullMethodDesc (get));
6480 type = get.ReturnType;
6481 if (type.IsPointer && !ec.InUnsafe){
6486 eclass = ExprClass.IndexerAccess;
6490 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
6492 if (!CommonResolve (ec))
6495 Type right_type = right_side.Type;
6498 ilist = Indexers.GetIndexersForType (
6499 current_type, indexer_type, loc);
6501 if (ilist != null && ilist.setters != null && ilist.setters.Count > 0){
6502 set_arguments = (ArrayList) arguments.Clone ();
6503 set_arguments.Add (new Argument (right_side, Argument.AType.Expression));
6505 set = (MethodInfo) Invocation.OverloadResolve (
6506 ec, new MethodGroupExpr (ilist.setters, loc), set_arguments, loc);
6510 Error (200, "indexer X.this [" + TypeManager.CSharpName (right_type) +
6511 "] lacks a `set' accessor");
6516 // Only base will allow this invocation to happen.
6518 if (set.IsAbstract && this is BaseIndexerAccess){
6519 Report.Error (205, loc, "Cannot call an abstract base indexer: " + Invocation.FullMethodDesc (set));
6522 type = TypeManager.void_type;
6523 eclass = ExprClass.IndexerAccess;
6527 public override void Emit (EmitContext ec)
6529 Invocation.EmitCall (ec, false, false, instance_expr, get, arguments, loc);
6533 // source is ignored, because we already have a copy of it from the
6534 // LValue resolution and we have already constructed a pre-cached
6535 // version of the arguments (ea.set_arguments);
6537 public void EmitAssign (EmitContext ec, Expression source)
6539 Invocation.EmitCall (ec, false, false, instance_expr, set, set_arguments, loc);
6544 /// The base operator for method names
6546 public class BaseAccess : Expression {
6549 public BaseAccess (string member, Location l)
6551 this.member = member;
6555 public override Expression DoResolve (EmitContext ec)
6557 Expression c = CommonResolve (ec);
6563 // MethodGroups use this opportunity to flag an error on lacking ()
6565 if (!(c is MethodGroupExpr))
6566 return c.Resolve (ec);
6570 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
6572 Expression c = CommonResolve (ec);
6578 // MethodGroups use this opportunity to flag an error on lacking ()
6580 if (! (c is MethodGroupExpr))
6581 return c.DoResolveLValue (ec, right_side);
6586 Expression CommonResolve (EmitContext ec)
6588 Expression member_lookup;
6589 Type current_type = ec.ContainerType;
6590 Type base_type = current_type.BaseType;
6594 Error (1511, "Keyword base is not allowed in static method");
6598 member_lookup = MemberLookup (ec, base_type, base_type, member,
6599 AllMemberTypes, AllBindingFlags, loc);
6600 if (member_lookup == null) {
6601 Error (117, TypeManager.CSharpName (base_type) + " does not " +
6602 "contain a definition for `" + member + "'");
6609 left = new TypeExpr (base_type, loc);
6613 e = MemberAccess.ResolveMemberAccess (ec, member_lookup, left, loc, null);
6615 if (e is PropertyExpr){
6616 PropertyExpr pe = (PropertyExpr) e;
6624 public override void Emit (EmitContext ec)
6626 throw new Exception ("Should never be called");
6631 /// The base indexer operator
6633 public class BaseIndexerAccess : IndexerAccess {
6634 public BaseIndexerAccess (ArrayList args, Location loc)
6635 : base (null, true, loc)
6637 arguments = new ArrayList ();
6638 foreach (Expression tmp in args)
6639 arguments.Add (new Argument (tmp, Argument.AType.Expression));
6642 protected override bool CommonResolve (EmitContext ec)
6644 instance_expr = ec.This;
6646 current_type = ec.ContainerType.BaseType;
6647 indexer_type = current_type;
6649 foreach (Argument a in arguments){
6650 if (!a.Resolve (ec, loc))
6659 /// This class exists solely to pass the Type around and to be a dummy
6660 /// that can be passed to the conversion functions (this is used by
6661 /// foreach implementation to typecast the object return value from
6662 /// get_Current into the proper type. All code has been generated and
6663 /// we only care about the side effect conversions to be performed
6665 /// This is also now used as a placeholder where a no-action expression
6666 /// is needed (the `New' class).
6668 public class EmptyExpression : Expression {
6669 public EmptyExpression ()
6671 type = TypeManager.object_type;
6672 eclass = ExprClass.Value;
6673 loc = Location.Null;
6676 public EmptyExpression (Type t)
6679 eclass = ExprClass.Value;
6680 loc = Location.Null;
6683 public override Expression DoResolve (EmitContext ec)
6688 public override void Emit (EmitContext ec)
6690 // nothing, as we only exist to not do anything.
6694 // This is just because we might want to reuse this bad boy
6695 // instead of creating gazillions of EmptyExpressions.
6696 // (CanConvertImplicit uses it)
6698 public void SetType (Type t)
6704 public class UserCast : Expression {
6708 public UserCast (MethodInfo method, Expression source, Location l)
6710 this.method = method;
6711 this.source = source;
6712 type = method.ReturnType;
6713 eclass = ExprClass.Value;
6717 public override Expression DoResolve (EmitContext ec)
6720 // We are born fully resolved
6725 public override void Emit (EmitContext ec)
6727 ILGenerator ig = ec.ig;
6731 if (method is MethodInfo)
6732 ig.Emit (OpCodes.Call, (MethodInfo) method);
6734 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
6740 // This class is used to "construct" the type during a typecast
6741 // operation. Since the Type.GetType class in .NET can parse
6742 // the type specification, we just use this to construct the type
6743 // one bit at a time.
6745 public class ComposedCast : Expression, ITypeExpression {
6749 public ComposedCast (Expression left, string dim, Location l)
6756 public Expression DoResolveType (EmitContext ec)
6758 Type ltype = ec.DeclSpace.ResolveType (left, false, loc);
6763 // ltype.Fullname is already fully qualified, so we can skip
6764 // a lot of probes, and go directly to TypeManager.LookupType
6766 string cname = ltype.FullName + dim;
6767 type = TypeManager.LookupTypeDirect (cname);
6770 // For arrays of enumerations we are having a problem
6771 // with the direct lookup. Need to investigate.
6773 // For now, fall back to the full lookup in that case.
6775 type = RootContext.LookupType (
6776 ec.DeclSpace, cname, false, loc);
6782 if (!ec.ResolvingTypeTree){
6784 // If the above flag is set, this is being invoked from the ResolveType function.
6785 // Upper layers take care of the type validity in this context.
6787 if (!ec.InUnsafe && type.IsPointer){
6793 eclass = ExprClass.Type;
6797 public override Expression DoResolve (EmitContext ec)
6799 return DoResolveType (ec);
6802 public override void Emit (EmitContext ec)
6804 throw new Exception ("This should never be called");
6807 public override string ToString ()
6814 // This class is used to represent the address of an array, used
6815 // only by the Fixed statement, this is like the C "&a [0]" construct.
6817 public class ArrayPtr : Expression {
6820 public ArrayPtr (Expression array, Location l)
6822 Type array_type = array.Type.GetElementType ();
6826 string array_ptr_type_name = array_type.FullName + "*";
6828 type = Type.GetType (array_ptr_type_name);
6830 ModuleBuilder mb = CodeGen.ModuleBuilder;
6832 type = mb.GetType (array_ptr_type_name);
6835 eclass = ExprClass.Value;
6839 public override void Emit (EmitContext ec)
6841 ILGenerator ig = ec.ig;
6844 IntLiteral.EmitInt (ig, 0);
6845 ig.Emit (OpCodes.Ldelema, array.Type.GetElementType ());
6848 public override Expression DoResolve (EmitContext ec)
6851 // We are born fully resolved
6858 // Used by the fixed statement
6860 public class StringPtr : Expression {
6863 public StringPtr (LocalBuilder b, Location l)
6866 eclass = ExprClass.Value;
6867 type = TypeManager.char_ptr_type;
6871 public override Expression DoResolve (EmitContext ec)
6873 // This should never be invoked, we are born in fully
6874 // initialized state.
6879 public override void Emit (EmitContext ec)
6881 ILGenerator ig = ec.ig;
6883 ig.Emit (OpCodes.Ldloc, b);
6884 ig.Emit (OpCodes.Conv_I);
6885 ig.Emit (OpCodes.Call, TypeManager.int_get_offset_to_string_data);
6886 ig.Emit (OpCodes.Add);
6891 // Implements the `stackalloc' keyword
6893 public class StackAlloc : Expression {
6898 public StackAlloc (Expression type, Expression count, Location l)
6905 public override Expression DoResolve (EmitContext ec)
6907 count = count.Resolve (ec);
6911 if (count.Type != TypeManager.int32_type){
6912 count = ConvertImplicitRequired (ec, count, TypeManager.int32_type, loc);
6917 if (ec.InCatch || ec.InFinally){
6919 "stackalloc can not be used in a catch or finally block");
6923 otype = ec.DeclSpace.ResolveType (t, false, loc);
6928 if (!TypeManager.VerifyUnManaged (otype, loc))
6931 string ptr_name = otype.FullName + "*";
6932 type = Type.GetType (ptr_name);
6934 ModuleBuilder mb = CodeGen.ModuleBuilder;
6936 type = mb.GetType (ptr_name);
6938 eclass = ExprClass.Value;
6943 public override void Emit (EmitContext ec)
6945 int size = GetTypeSize (otype);
6946 ILGenerator ig = ec.ig;
6949 ig.Emit (OpCodes.Sizeof, otype);
6951 IntConstant.EmitInt (ig, size);
6953 ig.Emit (OpCodes.Mul);
6954 ig.Emit (OpCodes.Localloc);