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 {
1163 bool CheckRange (EmitContext ec, long value, Type type, long min, long max)
1165 if (!ec.ConstantCheckState)
1168 if ((value < min) || (value > max)) {
1169 Error (221, "Constant value `" + value + "' cannot be converted " +
1170 "to a `" + TypeManager.CSharpName (type) + "' (use `unchecked' " +
1171 "syntax to override)");
1178 bool CheckRange (EmitContext ec, ulong value, Type type, ulong max)
1180 if (!ec.ConstantCheckState)
1184 Error (221, "Constant value `" + value + "' cannot be converted " +
1185 "to a `" + TypeManager.CSharpName (type) + "' (use `unchecked' " +
1186 "syntax to override)");
1193 bool CheckUnsigned (EmitContext ec, long value, Type type)
1195 if (!ec.ConstantCheckState)
1199 Error (221, "Constant value `" + value + "' cannot be converted " +
1200 "to a `" + TypeManager.CSharpName (type) + "' (use `unchecked' " +
1201 "syntax to override)");
1209 /// Attempts to do a compile-time folding of a constant cast.
1211 Expression TryReduce (EmitContext ec, Type target_type)
1213 if (expr is ByteConstant){
1214 byte v = ((ByteConstant) expr).Value;
1216 if (target_type == TypeManager.sbyte_type) {
1217 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1219 return new SByteConstant ((sbyte) v);
1221 if (target_type == TypeManager.short_type)
1222 return new ShortConstant ((short) v);
1223 if (target_type == TypeManager.ushort_type)
1224 return new UShortConstant ((ushort) v);
1225 if (target_type == TypeManager.int32_type)
1226 return new IntConstant ((int) v);
1227 if (target_type == TypeManager.uint32_type)
1228 return new UIntConstant ((uint) v);
1229 if (target_type == TypeManager.int64_type)
1230 return new LongConstant ((long) v);
1231 if (target_type == TypeManager.uint64_type)
1232 return new ULongConstant ((ulong) v);
1233 if (target_type == TypeManager.float_type)
1234 return new FloatConstant ((float) v);
1235 if (target_type == TypeManager.double_type)
1236 return new DoubleConstant ((double) v);
1237 if (target_type == TypeManager.char_type)
1238 return new CharConstant ((char) v);
1239 if (target_type == TypeManager.decimal_type)
1240 return new DecimalConstant ((decimal) v);
1242 if (expr is SByteConstant){
1243 sbyte v = ((SByteConstant) expr).Value;
1245 if (target_type == TypeManager.byte_type) {
1246 if (!CheckUnsigned (ec, v, target_type))
1248 return new ByteConstant ((byte) v);
1250 if (target_type == TypeManager.short_type)
1251 return new ShortConstant ((short) v);
1252 if (target_type == TypeManager.ushort_type) {
1253 if (!CheckUnsigned (ec, v, target_type))
1255 return new UShortConstant ((ushort) v);
1256 } if (target_type == TypeManager.int32_type)
1257 return new IntConstant ((int) v);
1258 if (target_type == TypeManager.uint32_type) {
1259 if (!CheckUnsigned (ec, v, target_type))
1261 return new UIntConstant ((uint) v);
1262 } if (target_type == TypeManager.int64_type)
1263 return new LongConstant ((long) v);
1264 if (target_type == TypeManager.uint64_type) {
1265 if (!CheckUnsigned (ec, v, target_type))
1267 return new ULongConstant ((ulong) v);
1269 if (target_type == TypeManager.float_type)
1270 return new FloatConstant ((float) v);
1271 if (target_type == TypeManager.double_type)
1272 return new DoubleConstant ((double) v);
1273 if (target_type == TypeManager.char_type) {
1274 if (!CheckUnsigned (ec, v, target_type))
1276 return new CharConstant ((char) v);
1278 if (target_type == TypeManager.decimal_type)
1279 return new DecimalConstant ((decimal) v);
1281 if (expr is ShortConstant){
1282 short v = ((ShortConstant) expr).Value;
1284 if (target_type == TypeManager.byte_type) {
1285 if (!CheckRange (ec, v, target_type, Byte.MinValue, Byte.MaxValue))
1287 return new ByteConstant ((byte) v);
1289 if (target_type == TypeManager.sbyte_type) {
1290 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1292 return new SByteConstant ((sbyte) v);
1294 if (target_type == TypeManager.ushort_type) {
1295 if (!CheckUnsigned (ec, v, target_type))
1297 return new UShortConstant ((ushort) v);
1299 if (target_type == TypeManager.int32_type)
1300 return new IntConstant ((int) v);
1301 if (target_type == TypeManager.uint32_type) {
1302 if (!CheckUnsigned (ec, v, target_type))
1304 return new UIntConstant ((uint) v);
1306 if (target_type == TypeManager.int64_type)
1307 return new LongConstant ((long) v);
1308 if (target_type == TypeManager.uint64_type) {
1309 if (!CheckUnsigned (ec, v, target_type))
1311 return new ULongConstant ((ulong) v);
1313 if (target_type == TypeManager.float_type)
1314 return new FloatConstant ((float) v);
1315 if (target_type == TypeManager.double_type)
1316 return new DoubleConstant ((double) v);
1317 if (target_type == TypeManager.char_type) {
1318 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1320 return new CharConstant ((char) v);
1322 if (target_type == TypeManager.decimal_type)
1323 return new DecimalConstant ((decimal) v);
1325 if (expr is UShortConstant){
1326 ushort v = ((UShortConstant) expr).Value;
1328 if (target_type == TypeManager.byte_type) {
1329 if (!CheckRange (ec, v, target_type, Byte.MinValue, Byte.MaxValue))
1331 return new ByteConstant ((byte) v);
1333 if (target_type == TypeManager.sbyte_type) {
1334 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1336 return new SByteConstant ((sbyte) v);
1338 if (target_type == TypeManager.short_type) {
1339 if (!CheckRange (ec, v, target_type, Int16.MinValue, Int16.MaxValue))
1341 return new ShortConstant ((short) v);
1343 if (target_type == TypeManager.int32_type)
1344 return new IntConstant ((int) v);
1345 if (target_type == TypeManager.uint32_type)
1346 return new UIntConstant ((uint) v);
1347 if (target_type == TypeManager.int64_type)
1348 return new LongConstant ((long) v);
1349 if (target_type == TypeManager.uint64_type)
1350 return new ULongConstant ((ulong) v);
1351 if (target_type == TypeManager.float_type)
1352 return new FloatConstant ((float) v);
1353 if (target_type == TypeManager.double_type)
1354 return new DoubleConstant ((double) v);
1355 if (target_type == TypeManager.char_type) {
1356 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1358 return new CharConstant ((char) v);
1360 if (target_type == TypeManager.decimal_type)
1361 return new DecimalConstant ((decimal) v);
1363 if (expr is IntConstant){
1364 int v = ((IntConstant) expr).Value;
1366 if (target_type == TypeManager.byte_type) {
1367 if (!CheckRange (ec, v, target_type, Byte.MinValue, Byte.MaxValue))
1369 return new ByteConstant ((byte) v);
1371 if (target_type == TypeManager.sbyte_type) {
1372 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1374 return new SByteConstant ((sbyte) v);
1376 if (target_type == TypeManager.short_type) {
1377 if (!CheckRange (ec, v, target_type, Int16.MinValue, Int16.MaxValue))
1379 return new ShortConstant ((short) v);
1381 if (target_type == TypeManager.ushort_type) {
1382 if (!CheckRange (ec, v, target_type, UInt16.MinValue, UInt16.MaxValue))
1384 return new UShortConstant ((ushort) v);
1386 if (target_type == TypeManager.uint32_type) {
1387 if (!CheckRange (ec, v, target_type, Int32.MinValue, Int32.MaxValue))
1389 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 if (!CheckUnsigned (ec, v, target_type))
1396 return new ULongConstant ((ulong) v);
1398 if (target_type == TypeManager.float_type)
1399 return new FloatConstant ((float) v);
1400 if (target_type == TypeManager.double_type)
1401 return new DoubleConstant ((double) v);
1402 if (target_type == TypeManager.char_type) {
1403 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1405 return new CharConstant ((char) v);
1407 if (target_type == TypeManager.decimal_type)
1408 return new DecimalConstant ((decimal) v);
1410 if (expr is UIntConstant){
1411 uint v = ((UIntConstant) expr).Value;
1413 if (target_type == TypeManager.byte_type) {
1414 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1416 return new ByteConstant ((byte) v);
1418 if (target_type == TypeManager.sbyte_type) {
1419 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1421 return new SByteConstant ((sbyte) v);
1423 if (target_type == TypeManager.short_type) {
1424 if (!CheckRange (ec, v, target_type, Int16.MinValue, Int16.MaxValue))
1426 return new ShortConstant ((short) v);
1428 if (target_type == TypeManager.ushort_type) {
1429 if (!CheckRange (ec, v, target_type, UInt16.MinValue, UInt16.MaxValue))
1431 return new UShortConstant ((ushort) v);
1433 if (target_type == TypeManager.int32_type) {
1434 if (!CheckRange (ec, v, target_type, Int32.MinValue, Int32.MaxValue))
1436 return new IntConstant ((int) v);
1438 if (target_type == TypeManager.int64_type)
1439 return new LongConstant ((long) v);
1440 if (target_type == TypeManager.uint64_type)
1441 return new ULongConstant ((ulong) v);
1442 if (target_type == TypeManager.float_type)
1443 return new FloatConstant ((float) v);
1444 if (target_type == TypeManager.double_type)
1445 return new DoubleConstant ((double) v);
1446 if (target_type == TypeManager.char_type) {
1447 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1449 return new CharConstant ((char) v);
1451 if (target_type == TypeManager.decimal_type)
1452 return new DecimalConstant ((decimal) v);
1454 if (expr is LongConstant){
1455 long v = ((LongConstant) expr).Value;
1457 if (target_type == TypeManager.byte_type) {
1458 if (!CheckRange (ec, v, target_type, Byte.MinValue, Byte.MaxValue))
1460 return new ByteConstant ((byte) v);
1462 if (target_type == TypeManager.sbyte_type) {
1463 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1465 return new SByteConstant ((sbyte) v);
1467 if (target_type == TypeManager.short_type) {
1468 if (!CheckRange (ec, v, target_type, Int16.MinValue, Int16.MaxValue))
1470 return new ShortConstant ((short) v);
1472 if (target_type == TypeManager.ushort_type) {
1473 if (!CheckRange (ec, v, target_type, UInt16.MinValue, UInt16.MaxValue))
1475 return new UShortConstant ((ushort) v);
1477 if (target_type == TypeManager.int32_type) {
1478 if (!CheckRange (ec, v, target_type, Int32.MinValue, Int32.MaxValue))
1480 return new IntConstant ((int) v);
1482 if (target_type == TypeManager.uint32_type) {
1483 if (!CheckRange (ec, v, target_type, UInt32.MinValue, UInt32.MaxValue))
1485 return new UIntConstant ((uint) v);
1487 if (target_type == TypeManager.uint64_type) {
1488 if (!CheckUnsigned (ec, v, target_type))
1490 return new ULongConstant ((ulong) v);
1492 if (target_type == TypeManager.float_type)
1493 return new FloatConstant ((float) v);
1494 if (target_type == TypeManager.double_type)
1495 return new DoubleConstant ((double) v);
1496 if (target_type == TypeManager.char_type) {
1497 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1499 return new CharConstant ((char) v);
1501 if (target_type == TypeManager.decimal_type)
1502 return new DecimalConstant ((decimal) v);
1504 if (expr is ULongConstant){
1505 ulong v = ((ULongConstant) expr).Value;
1507 if (target_type == TypeManager.byte_type) {
1508 if (!CheckRange (ec, v, target_type, Byte.MaxValue))
1510 return new ByteConstant ((byte) v);
1512 if (target_type == TypeManager.sbyte_type) {
1513 if (!CheckRange (ec, v, target_type, (ulong) SByte.MaxValue))
1515 return new SByteConstant ((sbyte) v);
1517 if (target_type == TypeManager.short_type) {
1518 if (!CheckRange (ec, v, target_type, (ulong) Int16.MaxValue))
1520 return new ShortConstant ((short) v);
1522 if (target_type == TypeManager.ushort_type) {
1523 if (!CheckRange (ec, v, target_type, UInt16.MaxValue))
1525 return new UShortConstant ((ushort) v);
1527 if (target_type == TypeManager.int32_type) {
1528 if (!CheckRange (ec, v, target_type, Int32.MaxValue))
1530 return new IntConstant ((int) v);
1532 if (target_type == TypeManager.uint32_type) {
1533 if (!CheckRange (ec, v, target_type, UInt32.MaxValue))
1535 return new UIntConstant ((uint) v);
1537 if (target_type == TypeManager.int64_type) {
1538 if (!CheckRange (ec, v, target_type, (ulong) Int64.MaxValue))
1540 return new LongConstant ((long) v);
1542 if (target_type == TypeManager.float_type)
1543 return new FloatConstant ((float) v);
1544 if (target_type == TypeManager.double_type)
1545 return new DoubleConstant ((double) v);
1546 if (target_type == TypeManager.char_type) {
1547 if (!CheckRange (ec, v, target_type, Char.MaxValue))
1549 return new CharConstant ((char) v);
1551 if (target_type == TypeManager.decimal_type)
1552 return new DecimalConstant ((decimal) v);
1554 if (expr is FloatConstant){
1555 float v = ((FloatConstant) expr).Value;
1557 if (target_type == TypeManager.byte_type)
1558 return new ByteConstant ((byte) v);
1559 if (target_type == TypeManager.sbyte_type)
1560 return new SByteConstant ((sbyte) v);
1561 if (target_type == TypeManager.short_type)
1562 return new ShortConstant ((short) v);
1563 if (target_type == TypeManager.ushort_type)
1564 return new UShortConstant ((ushort) v);
1565 if (target_type == TypeManager.int32_type)
1566 return new IntConstant ((int) v);
1567 if (target_type == TypeManager.uint32_type)
1568 return new UIntConstant ((uint) v);
1569 if (target_type == TypeManager.int64_type)
1570 return new LongConstant ((long) v);
1571 if (target_type == TypeManager.uint64_type)
1572 return new ULongConstant ((ulong) v);
1573 if (target_type == TypeManager.double_type)
1574 return new DoubleConstant ((double) v);
1575 if (target_type == TypeManager.char_type)
1576 return new CharConstant ((char) v);
1577 if (target_type == TypeManager.decimal_type)
1578 return new DecimalConstant ((decimal) v);
1580 if (expr is DoubleConstant){
1581 double v = ((DoubleConstant) expr).Value;
1583 if (target_type == TypeManager.byte_type)
1584 return new ByteConstant ((byte) v);
1585 if (target_type == TypeManager.sbyte_type)
1586 return new SByteConstant ((sbyte) v);
1587 if (target_type == TypeManager.short_type)
1588 return new ShortConstant ((short) v);
1589 if (target_type == TypeManager.ushort_type)
1590 return new UShortConstant ((ushort) v);
1591 if (target_type == TypeManager.int32_type)
1592 return new IntConstant ((int) v);
1593 if (target_type == TypeManager.uint32_type)
1594 return new UIntConstant ((uint) v);
1595 if (target_type == TypeManager.int64_type)
1596 return new LongConstant ((long) v);
1597 if (target_type == TypeManager.uint64_type)
1598 return new ULongConstant ((ulong) v);
1599 if (target_type == TypeManager.float_type)
1600 return new FloatConstant ((float) v);
1601 if (target_type == TypeManager.char_type)
1602 return new CharConstant ((char) v);
1603 if (target_type == TypeManager.decimal_type)
1604 return new DecimalConstant ((decimal) v);
1610 public override Expression DoResolve (EmitContext ec)
1612 expr = expr.Resolve (ec);
1616 int errors = Report.Errors;
1618 type = ec.DeclSpace.ResolveType (target_type, false, Location);
1623 eclass = ExprClass.Value;
1625 if (expr is Constant){
1626 Expression e = TryReduce (ec, type);
1632 expr = ConvertExplicit (ec, expr, type, loc);
1636 public override void Emit (EmitContext ec)
1639 // This one will never happen
1641 throw new Exception ("Should not happen");
1646 /// Binary operators
1648 public class Binary : Expression {
1649 public enum Operator : byte {
1650 Multiply, Division, Modulus,
1651 Addition, Subtraction,
1652 LeftShift, RightShift,
1653 LessThan, GreaterThan, LessThanOrEqual, GreaterThanOrEqual,
1654 Equality, Inequality,
1664 Expression left, right;
1667 // After resolution, method might contain the operator overload
1670 protected MethodBase method;
1671 ArrayList Arguments;
1673 bool DelegateOperation;
1675 // This must be kept in sync with Operator!!!
1676 static string [] oper_names;
1680 oper_names = new string [(int) Operator.TOP];
1682 oper_names [(int) Operator.Multiply] = "op_Multiply";
1683 oper_names [(int) Operator.Division] = "op_Division";
1684 oper_names [(int) Operator.Modulus] = "op_Modulus";
1685 oper_names [(int) Operator.Addition] = "op_Addition";
1686 oper_names [(int) Operator.Subtraction] = "op_Subtraction";
1687 oper_names [(int) Operator.LeftShift] = "op_LeftShift";
1688 oper_names [(int) Operator.RightShift] = "op_RightShift";
1689 oper_names [(int) Operator.LessThan] = "op_LessThan";
1690 oper_names [(int) Operator.GreaterThan] = "op_GreaterThan";
1691 oper_names [(int) Operator.LessThanOrEqual] = "op_LessThanOrEqual";
1692 oper_names [(int) Operator.GreaterThanOrEqual] = "op_GreaterThanOrEqual";
1693 oper_names [(int) Operator.Equality] = "op_Equality";
1694 oper_names [(int) Operator.Inequality] = "op_Inequality";
1695 oper_names [(int) Operator.BitwiseAnd] = "op_BitwiseAnd";
1696 oper_names [(int) Operator.BitwiseOr] = "op_BitwiseOr";
1697 oper_names [(int) Operator.ExclusiveOr] = "op_ExclusiveOr";
1698 oper_names [(int) Operator.LogicalOr] = "op_LogicalOr";
1699 oper_names [(int) Operator.LogicalAnd] = "op_LogicalAnd";
1702 public Binary (Operator oper, Expression left, Expression right, Location loc)
1710 public Operator Oper {
1719 public Expression Left {
1728 public Expression Right {
1739 /// Returns a stringified representation of the Operator
1741 static string OperName (Operator oper)
1744 case Operator.Multiply:
1746 case Operator.Division:
1748 case Operator.Modulus:
1750 case Operator.Addition:
1752 case Operator.Subtraction:
1754 case Operator.LeftShift:
1756 case Operator.RightShift:
1758 case Operator.LessThan:
1760 case Operator.GreaterThan:
1762 case Operator.LessThanOrEqual:
1764 case Operator.GreaterThanOrEqual:
1766 case Operator.Equality:
1768 case Operator.Inequality:
1770 case Operator.BitwiseAnd:
1772 case Operator.BitwiseOr:
1774 case Operator.ExclusiveOr:
1776 case Operator.LogicalOr:
1778 case Operator.LogicalAnd:
1782 return oper.ToString ();
1785 public override string ToString ()
1787 return "operator " + OperName (oper) + "(" + left.ToString () + ", " +
1788 right.ToString () + ")";
1791 Expression ForceConversion (EmitContext ec, Expression expr, Type target_type)
1793 if (expr.Type == target_type)
1796 return ConvertImplicit (ec, expr, target_type, loc);
1799 public static void Error_OperatorAmbiguous (Location loc, Operator oper, Type l, Type r)
1802 34, loc, "Operator `" + OperName (oper)
1803 + "' is ambiguous on operands of type `"
1804 + TypeManager.CSharpName (l) + "' "
1805 + "and `" + TypeManager.CSharpName (r)
1809 bool IsOfType (EmitContext ec, Type l, Type r, Type t, bool check_user_conversions)
1811 if ((l == t) || (r == t))
1814 if (!check_user_conversions)
1817 if (ImplicitUserConversionExists (ec, l, t))
1819 else if (ImplicitUserConversionExists (ec, r, t))
1826 // Note that handling the case l == Decimal || r == Decimal
1827 // is taken care of by the Step 1 Operator Overload resolution.
1829 // If `check_user_conv' is true, we also check whether a user-defined conversion
1830 // exists. Note that we only need to do this if both arguments are of a user-defined
1831 // type, otherwise ConvertImplict() already finds the user-defined conversion for us,
1832 // so we don't explicitly check for performance reasons.
1834 bool DoNumericPromotions (EmitContext ec, Type l, Type r, bool check_user_conv)
1836 if (IsOfType (ec, l, r, TypeManager.double_type, check_user_conv)){
1838 // If either operand is of type double, the other operand is
1839 // conveted to type double.
1841 if (r != TypeManager.double_type)
1842 right = ConvertImplicit (ec, right, TypeManager.double_type, loc);
1843 if (l != TypeManager.double_type)
1844 left = ConvertImplicit (ec, left, TypeManager.double_type, loc);
1846 type = TypeManager.double_type;
1847 } else if (IsOfType (ec, l, r, TypeManager.float_type, check_user_conv)){
1849 // if either operand is of type float, the other operand is
1850 // converted to type float.
1852 if (r != TypeManager.double_type)
1853 right = ConvertImplicit (ec, right, TypeManager.float_type, loc);
1854 if (l != TypeManager.double_type)
1855 left = ConvertImplicit (ec, left, TypeManager.float_type, loc);
1856 type = TypeManager.float_type;
1857 } else if (IsOfType (ec, l, r, TypeManager.uint64_type, check_user_conv)){
1861 // If either operand is of type ulong, the other operand is
1862 // converted to type ulong. or an error ocurrs if the other
1863 // operand is of type sbyte, short, int or long
1865 if (l == TypeManager.uint64_type){
1866 if (r != TypeManager.uint64_type){
1867 if (right is IntConstant){
1868 IntConstant ic = (IntConstant) right;
1870 e = TryImplicitIntConversion (l, ic);
1873 } else if (right is LongConstant){
1874 long ll = ((LongConstant) right).Value;
1877 right = new ULongConstant ((ulong) ll);
1879 e = ImplicitNumericConversion (ec, right, l, loc);
1886 if (left is IntConstant){
1887 e = TryImplicitIntConversion (r, (IntConstant) left);
1890 } else if (left is LongConstant){
1891 long ll = ((LongConstant) left).Value;
1894 left = new ULongConstant ((ulong) ll);
1896 e = ImplicitNumericConversion (ec, left, r, loc);
1903 if ((other == TypeManager.sbyte_type) ||
1904 (other == TypeManager.short_type) ||
1905 (other == TypeManager.int32_type) ||
1906 (other == TypeManager.int64_type))
1907 Error_OperatorAmbiguous (loc, oper, l, r);
1908 type = TypeManager.uint64_type;
1909 } else if (IsOfType (ec, l, r, TypeManager.int64_type, check_user_conv)){
1911 // If either operand is of type long, the other operand is converted
1914 if (l != TypeManager.int64_type)
1915 left = ConvertImplicit (ec, left, TypeManager.int64_type, loc);
1916 if (r != TypeManager.int64_type)
1917 right = ConvertImplicit (ec, right, TypeManager.int64_type, loc);
1919 type = TypeManager.int64_type;
1920 } else if (IsOfType (ec, l, r, TypeManager.uint32_type, check_user_conv)){
1922 // If either operand is of type uint, and the other
1923 // operand is of type sbyte, short or int, othe operands are
1924 // converted to type long.
1928 if (l == TypeManager.uint32_type){
1929 if (right is IntConstant){
1930 IntConstant ic = (IntConstant) right;
1934 right = new UIntConstant ((uint) val);
1941 else if (r == TypeManager.uint32_type){
1942 if (left is IntConstant){
1943 IntConstant ic = (IntConstant) left;
1947 left = new UIntConstant ((uint) val);
1956 if ((other == TypeManager.sbyte_type) ||
1957 (other == TypeManager.short_type) ||
1958 (other == TypeManager.int32_type)){
1959 left = ForceConversion (ec, left, TypeManager.int64_type);
1960 right = ForceConversion (ec, right, TypeManager.int64_type);
1961 type = TypeManager.int64_type;
1964 // if either operand is of type uint, the other
1965 // operand is converd to type uint
1967 left = ForceConversion (ec, left, TypeManager.uint32_type);
1968 right = ForceConversion (ec, right, TypeManager.uint32_type);
1969 type = TypeManager.uint32_type;
1971 } else if (l == TypeManager.decimal_type || r == TypeManager.decimal_type){
1972 if (l != TypeManager.decimal_type)
1973 left = ConvertImplicit (ec, left, TypeManager.decimal_type, loc);
1975 if (r != TypeManager.decimal_type)
1976 right = ConvertImplicit (ec, right, TypeManager.decimal_type, loc);
1977 type = TypeManager.decimal_type;
1979 left = ForceConversion (ec, left, TypeManager.int32_type);
1980 right = ForceConversion (ec, right, TypeManager.int32_type);
1982 type = TypeManager.int32_type;
1985 return (left != null) && (right != null);
1988 static public void Error_OperatorCannotBeApplied (Location loc, string name, Type l, Type r)
1990 Report.Error (19, loc,
1991 "Operator " + name + " cannot be applied to operands of type `" +
1992 TypeManager.CSharpName (l) + "' and `" +
1993 TypeManager.CSharpName (r) + "'");
1996 void Error_OperatorCannotBeApplied ()
1998 Error_OperatorCannotBeApplied (loc, OperName (oper), left.Type, right.Type);
2001 static bool is_32_or_64 (Type t)
2003 return (t == TypeManager.int32_type || t == TypeManager.uint32_type ||
2004 t == TypeManager.int64_type || t == TypeManager.uint64_type);
2007 static bool is_unsigned (Type t)
2009 return (t == TypeManager.uint32_type || t == TypeManager.uint64_type ||
2010 t == TypeManager.short_type || t == TypeManager.byte_type);
2013 static bool is_user_defined (Type t)
2015 if (t.IsSubclassOf (TypeManager.value_type) &&
2016 (!TypeManager.IsBuiltinType (t) || t == TypeManager.decimal_type))
2022 Expression CheckShiftArguments (EmitContext ec)
2026 Type r = right.Type;
2028 e = ForceConversion (ec, right, TypeManager.int32_type);
2030 Error_OperatorCannotBeApplied ();
2035 if (((e = ConvertImplicit (ec, left, TypeManager.int32_type, loc)) != null) ||
2036 ((e = ConvertImplicit (ec, left, TypeManager.uint32_type, loc)) != null) ||
2037 ((e = ConvertImplicit (ec, left, TypeManager.int64_type, loc)) != null) ||
2038 ((e = ConvertImplicit (ec, left, TypeManager.uint64_type, loc)) != null)){
2044 Error_OperatorCannotBeApplied ();
2048 Expression ResolveOperator (EmitContext ec)
2051 Type r = right.Type;
2053 bool overload_failed = false;
2056 // Special cases: string comapred to null
2058 if (oper == Operator.Equality || oper == Operator.Inequality){
2059 if ((l == TypeManager.string_type && (right is NullLiteral)) ||
2060 (r == TypeManager.string_type && (left is NullLiteral))){
2061 Type = TypeManager.bool_type;
2068 // Do not perform operator overload resolution when both sides are
2071 if (!(TypeManager.IsCLRType (l) && TypeManager.IsCLRType (r))){
2073 // Step 1: Perform Operator Overload location
2075 Expression left_expr, right_expr;
2077 string op = oper_names [(int) oper];
2079 MethodGroupExpr union;
2080 left_expr = MemberLookup (ec, l, op, MemberTypes.Method, AllBindingFlags, loc);
2082 right_expr = MemberLookup (
2083 ec, r, op, MemberTypes.Method, AllBindingFlags, loc);
2084 union = Invocation.MakeUnionSet (left_expr, right_expr, loc);
2086 union = (MethodGroupExpr) left_expr;
2088 if (union != null) {
2089 Arguments = new ArrayList ();
2090 Arguments.Add (new Argument (left, Argument.AType.Expression));
2091 Arguments.Add (new Argument (right, Argument.AType.Expression));
2093 method = Invocation.OverloadResolve (ec, union, Arguments, Location.Null);
2094 if (method != null) {
2095 MethodInfo mi = (MethodInfo) method;
2097 type = mi.ReturnType;
2100 overload_failed = true;
2106 // Step 2: Default operations on CLI native types.
2110 // Step 0: String concatenation (because overloading will get this wrong)
2112 if (oper == Operator.Addition){
2114 // If any of the arguments is a string, cast to string
2117 if (l == TypeManager.string_type){
2119 if (r == TypeManager.void_type) {
2120 Error_OperatorCannotBeApplied ();
2124 if (r == TypeManager.string_type){
2125 if (left is Constant && right is Constant){
2126 StringConstant ls = (StringConstant) left;
2127 StringConstant rs = (StringConstant) right;
2129 return new StringConstant (
2130 ls.Value + rs.Value);
2133 if (left is Binary){
2134 Binary b = (Binary) left;
2137 // Call String.Concat (string, string, string) or
2138 // String.Concat (string, string, string, string)
2141 if (b.oper == Operator.Addition &&
2142 (b.method == TypeManager.string_concat_string_string_string ||
2143 b.method == TypeManager.string_concat_string_string_string_string)){
2144 ArrayList bargs = b.Arguments;
2145 int count = bargs.Count;
2149 Arguments.Add (new Argument (right, Argument.AType.Expression));
2150 type = TypeManager.string_type;
2151 method = TypeManager.string_concat_string_string_string;
2154 } else if (count == 3){
2156 Arguments.Add (new Argument (right, Argument.AType.Expression));
2157 type = TypeManager.string_type;
2158 method = TypeManager.string_concat_string_string_string_string;
2165 method = TypeManager.string_concat_string_string;
2168 method = TypeManager.string_concat_object_object;
2169 right = ConvertImplicit (ec, right,
2170 TypeManager.object_type, loc);
2172 Error_OperatorCannotBeApplied (loc, OperName (oper), l, r);
2176 type = TypeManager.string_type;
2178 Arguments = new ArrayList ();
2179 Arguments.Add (new Argument (left, Argument.AType.Expression));
2180 Arguments.Add (new Argument (right, Argument.AType.Expression));
2184 } else if (r == TypeManager.string_type){
2187 if (l == TypeManager.void_type) {
2188 Error_OperatorCannotBeApplied ();
2192 method = TypeManager.string_concat_object_object;
2193 left = ConvertImplicit (ec, left, TypeManager.object_type, loc);
2195 Error_OperatorCannotBeApplied (loc, OperName (oper), l, r);
2198 Arguments = new ArrayList ();
2199 Arguments.Add (new Argument (left, Argument.AType.Expression));
2200 Arguments.Add (new Argument (right, Argument.AType.Expression));
2202 type = TypeManager.string_type;
2208 // Transform a + ( - b) into a - b
2210 if (right is Unary){
2211 Unary right_unary = (Unary) right;
2213 if (right_unary.Oper == Unary.Operator.UnaryNegation){
2214 oper = Operator.Subtraction;
2215 right = right_unary.Expr;
2221 if (oper == Operator.Equality || oper == Operator.Inequality){
2222 if (l == TypeManager.bool_type || r == TypeManager.bool_type){
2223 if (r != TypeManager.bool_type || l != TypeManager.bool_type){
2224 Error_OperatorCannotBeApplied ();
2228 type = TypeManager.bool_type;
2233 // operator != (object a, object b)
2234 // operator == (object a, object b)
2236 // For this to be used, both arguments have to be reference-types.
2237 // Read the rationale on the spec (14.9.6)
2239 // Also, if at compile time we know that the classes do not inherit
2240 // one from the other, then we catch the error there.
2242 if (!(l.IsValueType || r.IsValueType)){
2243 type = TypeManager.bool_type;
2248 if (l.IsSubclassOf (r) || r.IsSubclassOf (l))
2252 // Also, a standard conversion must exist from either one
2254 if (!(StandardConversionExists (left, r) ||
2255 StandardConversionExists (right, l))){
2256 Error_OperatorCannotBeApplied ();
2260 // We are going to have to convert to an object to compare
2262 if (l != TypeManager.object_type)
2263 left = new EmptyCast (left, TypeManager.object_type);
2264 if (r != TypeManager.object_type)
2265 right = new EmptyCast (right, TypeManager.object_type);
2268 // FIXME: CSC here catches errors cs254 and cs252
2274 // One of them is a valuetype, but the other one is not.
2276 if (!l.IsValueType || !r.IsValueType) {
2277 Error_OperatorCannotBeApplied ();
2282 // Only perform numeric promotions on:
2283 // +, -, *, /, %, &, |, ^, ==, !=, <, >, <=, >=
2285 if (oper == Operator.Addition || oper == Operator.Subtraction) {
2286 if (l.IsSubclassOf (TypeManager.delegate_type) &&
2287 r.IsSubclassOf (TypeManager.delegate_type)) {
2289 Arguments = new ArrayList ();
2290 Arguments.Add (new Argument (left, Argument.AType.Expression));
2291 Arguments.Add (new Argument (right, Argument.AType.Expression));
2293 if (oper == Operator.Addition)
2294 method = TypeManager.delegate_combine_delegate_delegate;
2296 method = TypeManager.delegate_remove_delegate_delegate;
2299 Error_OperatorCannotBeApplied ();
2303 DelegateOperation = true;
2309 // Pointer arithmetic:
2311 // T* operator + (T* x, int y);
2312 // T* operator + (T* x, uint y);
2313 // T* operator + (T* x, long y);
2314 // T* operator + (T* x, ulong y);
2316 // T* operator + (int y, T* x);
2317 // T* operator + (uint y, T *x);
2318 // T* operator + (long y, T *x);
2319 // T* operator + (ulong y, T *x);
2321 // T* operator - (T* x, int y);
2322 // T* operator - (T* x, uint y);
2323 // T* operator - (T* x, long y);
2324 // T* operator - (T* x, ulong y);
2326 // long operator - (T* x, T *y)
2329 if (r.IsPointer && oper == Operator.Subtraction){
2331 return new PointerArithmetic (
2332 false, left, right, TypeManager.int64_type,
2334 } else if (is_32_or_64 (r))
2335 return new PointerArithmetic (
2336 oper == Operator.Addition, left, right, l, loc);
2337 } else if (r.IsPointer && is_32_or_64 (l) && oper == Operator.Addition)
2338 return new PointerArithmetic (
2339 true, right, left, r, loc);
2343 // Enumeration operators
2345 bool lie = TypeManager.IsEnumType (l);
2346 bool rie = TypeManager.IsEnumType (r);
2350 // U operator - (E e, E f)
2351 if (lie && rie && oper == Operator.Subtraction){
2353 type = TypeManager.EnumToUnderlying (l);
2356 Error_OperatorCannotBeApplied ();
2361 // operator + (E e, U x)
2362 // operator - (E e, U x)
2364 if (oper == Operator.Addition || oper == Operator.Subtraction){
2365 Type enum_type = lie ? l : r;
2366 Type other_type = lie ? r : l;
2367 Type underlying_type = TypeManager.EnumToUnderlying (enum_type);
2370 if (underlying_type != other_type){
2371 Error_OperatorCannotBeApplied ();
2380 temp = ConvertImplicit (ec, right, l, loc);
2384 Error_OperatorCannotBeApplied ();
2388 temp = ConvertImplicit (ec, left, r, loc);
2393 Error_OperatorCannotBeApplied ();
2398 if (oper == Operator.Equality || oper == Operator.Inequality ||
2399 oper == Operator.LessThanOrEqual || oper == Operator.LessThan ||
2400 oper == Operator.GreaterThanOrEqual || oper == Operator.GreaterThan){
2401 type = TypeManager.bool_type;
2405 if (oper == Operator.BitwiseAnd ||
2406 oper == Operator.BitwiseOr ||
2407 oper == Operator.ExclusiveOr){
2411 Error_OperatorCannotBeApplied ();
2415 if (oper == Operator.LeftShift || oper == Operator.RightShift)
2416 return CheckShiftArguments (ec);
2418 if (oper == Operator.LogicalOr || oper == Operator.LogicalAnd){
2419 if (l != TypeManager.bool_type || r != TypeManager.bool_type){
2420 Error_OperatorCannotBeApplied ();
2424 type = TypeManager.bool_type;
2429 // operator & (bool x, bool y)
2430 // operator | (bool x, bool y)
2431 // operator ^ (bool x, bool y)
2433 if (l == TypeManager.bool_type && r == TypeManager.bool_type){
2434 if (oper == Operator.BitwiseAnd ||
2435 oper == Operator.BitwiseOr ||
2436 oper == Operator.ExclusiveOr){
2443 // Pointer comparison
2445 if (l.IsPointer && r.IsPointer){
2446 if (oper == Operator.Equality || oper == Operator.Inequality ||
2447 oper == Operator.LessThan || oper == Operator.LessThanOrEqual ||
2448 oper == Operator.GreaterThan || oper == Operator.GreaterThanOrEqual){
2449 type = TypeManager.bool_type;
2455 // We are dealing with numbers
2457 if (overload_failed){
2458 Error_OperatorCannotBeApplied ();
2463 // This will leave left or right set to null if there is an error
2465 bool check_user_conv = is_user_defined (l) && is_user_defined (r);
2466 DoNumericPromotions (ec, l, r, check_user_conv);
2467 if (left == null || right == null){
2468 Error_OperatorCannotBeApplied (loc, OperName (oper), l, r);
2473 // reload our cached types if required
2478 if (oper == Operator.BitwiseAnd ||
2479 oper == Operator.BitwiseOr ||
2480 oper == Operator.ExclusiveOr){
2482 if (!((l == TypeManager.int32_type) ||
2483 (l == TypeManager.uint32_type) ||
2484 (l == TypeManager.int64_type) ||
2485 (l == TypeManager.uint64_type)))
2488 Error_OperatorCannotBeApplied ();
2493 if (oper == Operator.Equality ||
2494 oper == Operator.Inequality ||
2495 oper == Operator.LessThanOrEqual ||
2496 oper == Operator.LessThan ||
2497 oper == Operator.GreaterThanOrEqual ||
2498 oper == Operator.GreaterThan){
2499 type = TypeManager.bool_type;
2505 public override Expression DoResolve (EmitContext ec)
2507 left = left.Resolve (ec);
2508 right = right.Resolve (ec);
2510 if (left == null || right == null)
2513 eclass = ExprClass.Value;
2515 Constant rc = right as Constant;
2516 Constant lc = left as Constant;
2518 if (rc != null & lc != null){
2519 Expression e = ConstantFold.BinaryFold (
2520 ec, oper, lc, rc, loc);
2525 return ResolveOperator (ec);
2529 /// EmitBranchable is called from Statement.EmitBoolExpression in the
2530 /// context of a conditional bool expression. This function will return
2531 /// false if it is was possible to use EmitBranchable, or true if it was.
2533 /// The expression's code is generated, and we will generate a branch to `target'
2534 /// if the resulting expression value is equal to isTrue
2536 public bool EmitBranchable (EmitContext ec, Label target, bool onTrue)
2541 ILGenerator ig = ec.ig;
2544 // This is more complicated than it looks, but its just to avoid
2545 // duplicated tests: basically, we allow ==, !=, >, <, >= and <=
2546 // but on top of that we want for == and != to use a special path
2547 // if we are comparing against null
2549 if (oper == Operator.Equality || oper == Operator.Inequality){
2550 bool my_on_true = oper == Operator.Inequality ? onTrue : !onTrue;
2552 if (left is NullLiteral){
2555 ig.Emit (OpCodes.Brtrue, target);
2557 ig.Emit (OpCodes.Brfalse, target);
2559 } else if (right is NullLiteral){
2562 ig.Emit (OpCodes.Brtrue, target);
2564 ig.Emit (OpCodes.Brfalse, target);
2566 } else if (left is BoolConstant){
2568 if (my_on_true != ((BoolConstant) left).Value)
2569 ig.Emit (OpCodes.Brtrue, target);
2571 ig.Emit (OpCodes.Brfalse, target);
2573 } else if (right is BoolConstant){
2575 if (my_on_true != ((BoolConstant) right).Value)
2576 ig.Emit (OpCodes.Brtrue, target);
2578 ig.Emit (OpCodes.Brfalse, target);
2582 } else if (oper == Operator.LogicalAnd){
2583 if (left is Binary){
2584 Binary left_binary = (Binary) left;
2587 Label tests_end = ig.DefineLabel ();
2589 if (left_binary.EmitBranchable (ec, tests_end, false)){
2590 if (right is Binary){
2591 Binary right_binary = (Binary) right;
2593 if (right_binary.EmitBranchable (ec, target, true)){
2594 ig.MarkLabel (tests_end);
2599 ig.Emit (OpCodes.Brtrue, target);
2600 ig.MarkLabel (tests_end);
2604 if (left_binary.EmitBranchable (ec, target, false)){
2605 if (right is Binary){
2606 Binary right_binary = (Binary) right;
2608 if (right_binary.EmitBranchable (ec, target, false))
2613 ig.Emit (OpCodes.Brtrue, target);
2615 ig.Emit (OpCodes.Brfalse, target);
2620 // Give up, and let the regular Emit work, but we could
2621 // also optimize the left-non-Branchable, but-right-Branchable
2625 } else if (oper == Operator.LogicalOr){
2626 if (left is Binary){
2627 Binary left_binary = (Binary) left;
2630 if (left_binary.EmitBranchable (ec, target, true)){
2631 if (right is Binary){
2632 Binary right_binary = (Binary) right;
2634 if (right_binary.EmitBranchable (ec, target, true))
2638 ig.Emit (OpCodes.Brtrue, target);
2643 // Give up, and let the regular Emit work, but we could
2644 // also optimize the left-non-Branchable, but-right-Branchable
2647 Label tests_end = ig.DefineLabel ();
2649 if (left_binary.EmitBranchable (ec, tests_end, true)){
2650 if (right is Binary){
2651 Binary right_binary = (Binary) right;
2653 if (right_binary.EmitBranchable (ec, target, false)){
2654 ig.MarkLabel (tests_end);
2659 ig.Emit (OpCodes.Brfalse, target);
2660 ig.MarkLabel (tests_end);
2667 } else if (!(oper == Operator.LessThan ||
2668 oper == Operator.GreaterThan ||
2669 oper == Operator.LessThanOrEqual ||
2670 oper == Operator.GreaterThanOrEqual))
2676 bool isUnsigned = is_unsigned (left.Type);
2679 case Operator.Equality:
2681 ig.Emit (OpCodes.Beq, target);
2683 ig.Emit (OpCodes.Bne_Un, target);
2686 case Operator.Inequality:
2688 ig.Emit (OpCodes.Bne_Un, target);
2690 ig.Emit (OpCodes.Beq, target);
2693 case Operator.LessThan:
2696 ig.Emit (OpCodes.Blt_Un, target);
2698 ig.Emit (OpCodes.Blt, target);
2701 ig.Emit (OpCodes.Bge_Un, target);
2703 ig.Emit (OpCodes.Bge, target);
2706 case Operator.GreaterThan:
2709 ig.Emit (OpCodes.Bgt_Un, target);
2711 ig.Emit (OpCodes.Bgt, target);
2714 ig.Emit (OpCodes.Ble_Un, target);
2716 ig.Emit (OpCodes.Ble, target);
2719 case Operator.LessThanOrEqual:
2722 ig.Emit (OpCodes.Ble_Un, target);
2724 ig.Emit (OpCodes.Ble, target);
2727 ig.Emit (OpCodes.Bgt_Un, target);
2729 ig.Emit (OpCodes.Bgt, target);
2733 case Operator.GreaterThanOrEqual:
2736 ig.Emit (OpCodes.Bge_Un, target);
2738 ig.Emit (OpCodes.Bge, target);
2741 ig.Emit (OpCodes.Blt_Un, target);
2743 ig.Emit (OpCodes.Blt, target);
2753 public override void Emit (EmitContext ec)
2755 ILGenerator ig = ec.ig;
2757 Type r = right.Type;
2760 if (method != null) {
2762 // Note that operators are static anyway
2764 if (Arguments != null)
2765 Invocation.EmitArguments (ec, method, Arguments);
2767 if (method is MethodInfo)
2768 ig.Emit (OpCodes.Call, (MethodInfo) method);
2770 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
2772 if (DelegateOperation)
2773 ig.Emit (OpCodes.Castclass, type);
2779 // Handle short-circuit operators differently
2782 if (oper == Operator.LogicalAnd){
2783 Label load_zero = ig.DefineLabel ();
2784 Label end = ig.DefineLabel ();
2785 bool process = true;
2787 if (left is Binary){
2788 Binary left_binary = (Binary) left;
2790 if (left_binary.EmitBranchable (ec, load_zero, false)){
2792 ig.Emit (OpCodes.Br, end);
2799 ig.Emit (OpCodes.Brfalse, load_zero);
2801 ig.Emit (OpCodes.Br, end);
2803 ig.MarkLabel (load_zero);
2804 ig.Emit (OpCodes.Ldc_I4_0);
2807 } else if (oper == Operator.LogicalOr){
2808 Label load_one = ig.DefineLabel ();
2809 Label end = ig.DefineLabel ();
2810 bool process = true;
2812 if (left is Binary){
2813 Binary left_binary = (Binary) left;
2815 if (left_binary.EmitBranchable (ec, load_one, true)){
2817 ig.Emit (OpCodes.Br, end);
2824 ig.Emit (OpCodes.Brtrue, load_one);
2826 ig.Emit (OpCodes.Br, end);
2828 ig.MarkLabel (load_one);
2829 ig.Emit (OpCodes.Ldc_I4_1);
2837 bool isUnsigned = is_unsigned (left.Type);
2839 case Operator.Multiply:
2841 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
2842 opcode = OpCodes.Mul_Ovf;
2843 else if (isUnsigned)
2844 opcode = OpCodes.Mul_Ovf_Un;
2846 opcode = OpCodes.Mul;
2848 opcode = OpCodes.Mul;
2852 case Operator.Division:
2854 opcode = OpCodes.Div_Un;
2856 opcode = OpCodes.Div;
2859 case Operator.Modulus:
2861 opcode = OpCodes.Rem_Un;
2863 opcode = OpCodes.Rem;
2866 case Operator.Addition:
2868 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
2869 opcode = OpCodes.Add_Ovf;
2870 else if (isUnsigned)
2871 opcode = OpCodes.Add_Ovf_Un;
2873 opcode = OpCodes.Add;
2875 opcode = OpCodes.Add;
2878 case Operator.Subtraction:
2880 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
2881 opcode = OpCodes.Sub_Ovf;
2882 else if (isUnsigned)
2883 opcode = OpCodes.Sub_Ovf_Un;
2885 opcode = OpCodes.Sub;
2887 opcode = OpCodes.Sub;
2890 case Operator.RightShift:
2892 opcode = OpCodes.Shr_Un;
2894 opcode = OpCodes.Shr;
2897 case Operator.LeftShift:
2898 opcode = OpCodes.Shl;
2901 case Operator.Equality:
2902 opcode = OpCodes.Ceq;
2905 case Operator.Inequality:
2906 ig.Emit (OpCodes.Ceq);
2907 ig.Emit (OpCodes.Ldc_I4_0);
2909 opcode = OpCodes.Ceq;
2912 case Operator.LessThan:
2914 opcode = OpCodes.Clt_Un;
2916 opcode = OpCodes.Clt;
2919 case Operator.GreaterThan:
2921 opcode = OpCodes.Cgt_Un;
2923 opcode = OpCodes.Cgt;
2926 case Operator.LessThanOrEqual:
2928 ig.Emit (OpCodes.Cgt_Un);
2930 ig.Emit (OpCodes.Cgt);
2931 ig.Emit (OpCodes.Ldc_I4_0);
2933 opcode = OpCodes.Ceq;
2936 case Operator.GreaterThanOrEqual:
2938 ig.Emit (OpCodes.Clt_Un);
2940 ig.Emit (OpCodes.Clt);
2942 ig.Emit (OpCodes.Ldc_I4_1);
2944 opcode = OpCodes.Sub;
2947 case Operator.BitwiseOr:
2948 opcode = OpCodes.Or;
2951 case Operator.BitwiseAnd:
2952 opcode = OpCodes.And;
2955 case Operator.ExclusiveOr:
2956 opcode = OpCodes.Xor;
2960 throw new Exception ("This should not happen: Operator = "
2961 + oper.ToString ());
2967 public bool IsBuiltinOperator {
2969 return method == null;
2974 public class PointerArithmetic : Expression {
2975 Expression left, right;
2979 // We assume that `l' is always a pointer
2981 public PointerArithmetic (bool is_addition, Expression l, Expression r, Type t,
2985 eclass = ExprClass.Variable;
2989 is_add = is_addition;
2992 public override Expression DoResolve (EmitContext ec)
2995 // We are born fully resolved
3000 public override void Emit (EmitContext ec)
3002 Type op_type = left.Type;
3003 ILGenerator ig = ec.ig;
3004 int size = GetTypeSize (op_type.GetElementType ());
3006 if (right.Type.IsPointer){
3008 // handle (pointer - pointer)
3012 ig.Emit (OpCodes.Sub);
3016 ig.Emit (OpCodes.Sizeof, op_type);
3018 IntLiteral.EmitInt (ig, size);
3019 ig.Emit (OpCodes.Div);
3021 ig.Emit (OpCodes.Conv_I8);
3024 // handle + and - on (pointer op int)
3027 ig.Emit (OpCodes.Conv_I);
3031 ig.Emit (OpCodes.Sizeof, op_type);
3033 IntLiteral.EmitInt (ig, size);
3034 ig.Emit (OpCodes.Mul);
3037 ig.Emit (OpCodes.Add);
3039 ig.Emit (OpCodes.Sub);
3045 /// Implements the ternary conditional operator (?:)
3047 public class Conditional : Expression {
3048 Expression expr, trueExpr, falseExpr;
3050 public Conditional (Expression expr, Expression trueExpr, Expression falseExpr, Location l)
3053 this.trueExpr = trueExpr;
3054 this.falseExpr = falseExpr;
3058 public Expression Expr {
3064 public Expression TrueExpr {
3070 public Expression FalseExpr {
3076 public override Expression DoResolve (EmitContext ec)
3078 expr = expr.Resolve (ec);
3083 if (expr.Type != TypeManager.bool_type)
3084 expr = Expression.ConvertImplicitRequired (
3085 ec, expr, TypeManager.bool_type, loc);
3087 trueExpr = trueExpr.Resolve (ec);
3088 falseExpr = falseExpr.Resolve (ec);
3090 if (trueExpr == null || falseExpr == null)
3093 eclass = ExprClass.Value;
3094 if (trueExpr.Type == falseExpr.Type)
3095 type = trueExpr.Type;
3098 Type true_type = trueExpr.Type;
3099 Type false_type = falseExpr.Type;
3101 if (trueExpr is NullLiteral){
3104 } else if (falseExpr is NullLiteral){
3110 // First, if an implicit conversion exists from trueExpr
3111 // to falseExpr, then the result type is of type falseExpr.Type
3113 conv = ConvertImplicit (ec, trueExpr, false_type, loc);
3116 // Check if both can convert implicitl to each other's type
3118 if (ConvertImplicit (ec, falseExpr, true_type, loc) != null){
3120 "Can not compute type of conditional expression " +
3121 "as `" + TypeManager.CSharpName (trueExpr.Type) +
3122 "' and `" + TypeManager.CSharpName (falseExpr.Type) +
3123 "' convert implicitly to each other");
3128 } else if ((conv = ConvertImplicit(ec, falseExpr, true_type,loc))!= null){
3132 Error (173, "The type of the conditional expression can " +
3133 "not be computed because there is no implicit conversion" +
3134 " from `" + TypeManager.CSharpName (trueExpr.Type) + "'" +
3135 " and `" + TypeManager.CSharpName (falseExpr.Type) + "'");
3140 if (expr is BoolConstant){
3141 BoolConstant bc = (BoolConstant) expr;
3152 public override void Emit (EmitContext ec)
3154 ILGenerator ig = ec.ig;
3155 Label false_target = ig.DefineLabel ();
3156 Label end_target = ig.DefineLabel ();
3158 Statement.EmitBoolExpression (ec, expr, false_target, false);
3160 ig.Emit (OpCodes.Br, end_target);
3161 ig.MarkLabel (false_target);
3162 falseExpr.Emit (ec);
3163 ig.MarkLabel (end_target);
3171 public class LocalVariableReference : Expression, IAssignMethod, IMemoryLocation, IVariable {
3172 public readonly string Name;
3173 public readonly Block Block;
3174 VariableInfo variable_info;
3177 public LocalVariableReference (Block block, string name, Location l)
3182 eclass = ExprClass.Variable;
3185 // Setting `is_readonly' to false will allow you to create a writable
3186 // reference to a read-only variable. This is used by foreach and using.
3187 public LocalVariableReference (Block block, string name, Location l,
3188 VariableInfo variable_info, bool is_readonly)
3189 : this (block, name, l)
3191 this.variable_info = variable_info;
3192 this.is_readonly = is_readonly;
3195 public VariableInfo VariableInfo {
3197 if (variable_info == null) {
3198 variable_info = Block.GetVariableInfo (Name);
3199 is_readonly = variable_info.ReadOnly;
3201 return variable_info;
3205 public bool IsAssigned (EmitContext ec, Location loc)
3207 return VariableInfo.IsAssigned (ec, loc);
3210 public bool IsFieldAssigned (EmitContext ec, string name, Location loc)
3212 return VariableInfo.IsFieldAssigned (ec, name, loc);
3215 public void SetAssigned (EmitContext ec)
3217 VariableInfo.SetAssigned (ec);
3220 public void SetFieldAssigned (EmitContext ec, string name)
3222 VariableInfo.SetFieldAssigned (ec, name);
3225 public bool IsReadOnly {
3227 if (variable_info == null) {
3228 variable_info = Block.GetVariableInfo (Name);
3229 is_readonly = variable_info.ReadOnly;
3235 public override Expression DoResolve (EmitContext ec)
3237 VariableInfo vi = VariableInfo;
3240 e = Block.GetConstantExpression (Name);
3246 if (ec.DoFlowAnalysis && !IsAssigned (ec, loc))
3249 type = vi.VariableType;
3253 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
3255 VariableInfo vi = VariableInfo;
3257 if (ec.DoFlowAnalysis)
3258 ec.SetVariableAssigned (vi);
3260 Expression e = DoResolve (ec);
3266 Error (1604, "cannot assign to `" + Name + "' because it is readonly");
3273 public override void Emit (EmitContext ec)
3275 VariableInfo vi = VariableInfo;
3276 ILGenerator ig = ec.ig;
3278 ig.Emit (OpCodes.Ldloc, vi.LocalBuilder);
3282 public void EmitAssign (EmitContext ec, Expression source)
3284 ILGenerator ig = ec.ig;
3285 VariableInfo vi = VariableInfo;
3291 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3294 public void AddressOf (EmitContext ec, AddressOp mode)
3296 VariableInfo vi = VariableInfo;
3298 ec.ig.Emit (OpCodes.Ldloca, vi.LocalBuilder);
3303 /// This represents a reference to a parameter in the intermediate
3306 public class ParameterReference : Expression, IAssignMethod, IMemoryLocation, IVariable {
3310 public Parameter.Modifier mod;
3311 public bool is_ref, is_out;
3313 public ParameterReference (Parameters pars, int idx, string name, Location loc)
3319 eclass = ExprClass.Variable;
3322 public bool IsAssigned (EmitContext ec, Location loc)
3324 if (!is_out || !ec.DoFlowAnalysis)
3327 if (!ec.CurrentBranching.IsParameterAssigned (idx)) {
3328 Report.Error (165, loc,
3329 "Use of unassigned local variable `" + name + "'");
3336 public bool IsFieldAssigned (EmitContext ec, string field_name, Location loc)
3338 if (!is_out || !ec.DoFlowAnalysis)
3341 if (ec.CurrentBranching.IsParameterAssigned (idx))
3344 if (!ec.CurrentBranching.IsParameterAssigned (idx, field_name)) {
3345 Report.Error (170, loc,
3346 "Use of possibly unassigned field `" + field_name + "'");
3353 public void SetAssigned (EmitContext ec)
3355 if (is_out && ec.DoFlowAnalysis)
3356 ec.CurrentBranching.SetParameterAssigned (idx);
3359 public void SetFieldAssigned (EmitContext ec, string field_name)
3361 if (is_out && ec.DoFlowAnalysis)
3362 ec.CurrentBranching.SetParameterAssigned (idx, field_name);
3366 // Notice that for ref/out parameters, the type exposed is not the
3367 // same type exposed externally.
3370 // externally we expose "int&"
3371 // here we expose "int".
3373 // We record this in "is_ref". This means that the type system can treat
3374 // the type as it is expected, but when we generate the code, we generate
3375 // the alternate kind of code.
3377 public override Expression DoResolve (EmitContext ec)
3379 type = pars.GetParameterInfo (ec.DeclSpace, idx, out mod);
3380 is_ref = (mod & Parameter.Modifier.ISBYREF) != 0;
3381 is_out = (mod & Parameter.Modifier.OUT) != 0;
3382 eclass = ExprClass.Variable;
3384 if (is_out && ec.DoFlowAnalysis && !IsAssigned (ec, loc))
3390 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
3392 type = pars.GetParameterInfo (ec.DeclSpace, idx, out mod);
3393 is_ref = (mod & Parameter.Modifier.ISBYREF) != 0;
3394 is_out = (mod & Parameter.Modifier.OUT) != 0;
3395 eclass = ExprClass.Variable;
3397 if (is_out && ec.DoFlowAnalysis)
3398 ec.SetParameterAssigned (idx);
3403 static void EmitLdArg (ILGenerator ig, int x)
3407 case 0: ig.Emit (OpCodes.Ldarg_0); break;
3408 case 1: ig.Emit (OpCodes.Ldarg_1); break;
3409 case 2: ig.Emit (OpCodes.Ldarg_2); break;
3410 case 3: ig.Emit (OpCodes.Ldarg_3); break;
3411 default: ig.Emit (OpCodes.Ldarg_S, (byte) x); break;
3414 ig.Emit (OpCodes.Ldarg, x);
3418 // This method is used by parameters that are references, that are
3419 // being passed as references: we only want to pass the pointer (that
3420 // is already stored in the parameter, not the address of the pointer,
3421 // and not the value of the variable).
3423 public void EmitLoad (EmitContext ec)
3425 ILGenerator ig = ec.ig;
3431 EmitLdArg (ig, arg_idx);
3434 public override void Emit (EmitContext ec)
3436 ILGenerator ig = ec.ig;
3442 EmitLdArg (ig, arg_idx);
3448 // If we are a reference, we loaded on the stack a pointer
3449 // Now lets load the real value
3451 LoadFromPtr (ig, type);
3454 public void EmitAssign (EmitContext ec, Expression source)
3456 ILGenerator ig = ec.ig;
3463 EmitLdArg (ig, arg_idx);
3468 StoreFromPtr (ig, type);
3471 ig.Emit (OpCodes.Starg_S, (byte) arg_idx);
3473 ig.Emit (OpCodes.Starg, arg_idx);
3477 public void AddressOf (EmitContext ec, AddressOp mode)
3486 ec.ig.Emit (OpCodes.Ldarg_S, (byte) arg_idx);
3488 ec.ig.Emit (OpCodes.Ldarg, arg_idx);
3491 ec.ig.Emit (OpCodes.Ldarga_S, (byte) arg_idx);
3493 ec.ig.Emit (OpCodes.Ldarga, arg_idx);
3500 /// Used for arguments to New(), Invocation()
3502 public class Argument {
3503 public enum AType : byte {
3509 public readonly AType ArgType;
3510 public Expression Expr;
3512 public Argument (Expression expr, AType type)
3515 this.ArgType = type;
3520 if (ArgType == AType.Ref || ArgType == AType.Out)
3521 return TypeManager.LookupType (Expr.Type.ToString () + "&");
3527 public Parameter.Modifier GetParameterModifier ()
3531 return Parameter.Modifier.OUT | Parameter.Modifier.ISBYREF;
3534 return Parameter.Modifier.REF | Parameter.Modifier.ISBYREF;
3537 return Parameter.Modifier.NONE;
3541 public static string FullDesc (Argument a)
3543 return (a.ArgType == AType.Ref ? "ref " :
3544 (a.ArgType == AType.Out ? "out " : "")) +
3545 TypeManager.CSharpName (a.Expr.Type);
3548 public bool ResolveMethodGroup (EmitContext ec, Location loc)
3550 // FIXME: csc doesn't report any error if you try to use `ref' or
3551 // `out' in a delegate creation expression.
3552 Expr = Expr.Resolve (ec, ResolveFlags.VariableOrValue | ResolveFlags.MethodGroup);
3559 public bool Resolve (EmitContext ec, Location loc)
3561 if (ArgType == AType.Ref) {
3562 Expr = Expr.Resolve (ec);
3566 Expr = Expr.ResolveLValue (ec, Expr);
3567 } else if (ArgType == AType.Out)
3568 Expr = Expr.ResolveLValue (ec, new EmptyExpression ());
3570 Expr = Expr.Resolve (ec);
3575 if (ArgType == AType.Expression)
3578 if (Expr.eclass != ExprClass.Variable){
3580 // We just probe to match the CSC output
3582 if (Expr.eclass == ExprClass.PropertyAccess ||
3583 Expr.eclass == ExprClass.IndexerAccess){
3586 "A property or indexer can not be passed as an out or ref " +
3591 "An lvalue is required as an argument to out or ref");
3599 public void Emit (EmitContext ec)
3602 // Ref and Out parameters need to have their addresses taken.
3604 // ParameterReferences might already be references, so we want
3605 // to pass just the value
3607 if (ArgType == AType.Ref || ArgType == AType.Out){
3608 AddressOp mode = AddressOp.Store;
3610 if (ArgType == AType.Ref)
3611 mode |= AddressOp.Load;
3613 if (Expr is ParameterReference){
3614 ParameterReference pr = (ParameterReference) Expr;
3620 pr.AddressOf (ec, mode);
3623 ((IMemoryLocation)Expr).AddressOf (ec, mode);
3630 /// Invocation of methods or delegates.
3632 public class Invocation : ExpressionStatement {
3633 public readonly ArrayList Arguments;
3636 MethodBase method = null;
3639 static Hashtable method_parameter_cache;
3641 static Invocation ()
3643 method_parameter_cache = new PtrHashtable ();
3647 // arguments is an ArrayList, but we do not want to typecast,
3648 // as it might be null.
3650 // FIXME: only allow expr to be a method invocation or a
3651 // delegate invocation (7.5.5)
3653 public Invocation (Expression expr, ArrayList arguments, Location l)
3656 Arguments = arguments;
3660 public Expression Expr {
3667 /// Returns the Parameters (a ParameterData interface) for the
3670 public static ParameterData GetParameterData (MethodBase mb)
3672 object pd = method_parameter_cache [mb];
3676 return (ParameterData) pd;
3679 ip = TypeManager.LookupParametersByBuilder (mb);
3681 method_parameter_cache [mb] = ip;
3683 return (ParameterData) ip;
3685 ParameterInfo [] pi = mb.GetParameters ();
3686 ReflectionParameters rp = new ReflectionParameters (pi);
3687 method_parameter_cache [mb] = rp;
3689 return (ParameterData) rp;
3694 /// Determines "better conversion" as specified in 7.4.2.3
3695 /// Returns : 1 if a->p is better
3696 /// 0 if a->q or neither is better
3698 static int BetterConversion (EmitContext ec, Argument a, Type p, Type q, Location loc)
3700 Type argument_type = a.Type;
3701 Expression argument_expr = a.Expr;
3703 if (argument_type == null)
3704 throw new Exception ("Expression of type " + a.Expr + " does not resolve its type");
3707 // This is a special case since csc behaves this way. I can't find
3708 // it anywhere in the spec but oh well ...
3710 if (argument_expr is NullLiteral && p == TypeManager.string_type && q == TypeManager.object_type)
3712 else if (argument_expr is NullLiteral && p == TypeManager.object_type && q == TypeManager.string_type)
3718 if (argument_type == p)
3721 if (argument_type == q)
3725 // Now probe whether an implicit constant expression conversion
3728 // An implicit constant expression conversion permits the following
3731 // * A constant-expression of type `int' can be converted to type
3732 // sbyte, byute, short, ushort, uint, ulong provided the value of
3733 // of the expression is withing the range of the destination type.
3735 // * A constant-expression of type long can be converted to type
3736 // ulong, provided the value of the constant expression is not negative
3738 // FIXME: Note that this assumes that constant folding has
3739 // taken place. We dont do constant folding yet.
3742 if (argument_expr is IntConstant){
3743 IntConstant ei = (IntConstant) argument_expr;
3744 int value = ei.Value;
3746 if (p == TypeManager.sbyte_type){
3747 if (value >= SByte.MinValue && value <= SByte.MaxValue)
3749 } else if (p == TypeManager.byte_type){
3750 if (q == TypeManager.sbyte_type &&
3751 value >= SByte.MinValue && value <= SByte.MaxValue)
3753 else if (Byte.MinValue >= 0 && value <= Byte.MaxValue)
3755 } else if (p == TypeManager.short_type){
3756 if (value >= Int16.MinValue && value <= Int16.MaxValue)
3758 } else if (p == TypeManager.ushort_type){
3759 if (q == TypeManager.short_type &&
3760 value >= Int16.MinValue && value <= Int16.MaxValue)
3762 else if (value >= UInt16.MinValue && value <= UInt16.MaxValue)
3764 } else if (p == TypeManager.int32_type){
3765 if (value >= Int32.MinValue && value <= Int32.MaxValue)
3767 } else if (p == TypeManager.uint32_type){
3769 // we can optimize this case: a positive int32
3770 // always fits on a uint32
3774 } else if (p == TypeManager.uint64_type){
3776 // we can optimize this case: a positive int32
3777 // always fits on a uint64
3779 if (q == TypeManager.int64_type)
3781 else if (value >= 0)
3783 } else if (p == TypeManager.int64_type){
3786 } else if (argument_type == TypeManager.int64_type && argument_expr is LongConstant){
3787 LongConstant lc = (LongConstant) argument_expr;
3789 if (p == TypeManager.uint64_type){
3796 Expression tmp = ConvertImplicit (ec, argument_expr, p, loc);
3804 Expression p_tmp = new EmptyExpression (p);
3805 Expression q_tmp = new EmptyExpression (q);
3807 if (ImplicitConversionExists (ec, p_tmp, q) == true &&
3808 ImplicitConversionExists (ec, q_tmp, p) == false)
3811 if (p == TypeManager.sbyte_type)
3812 if (q == TypeManager.byte_type || q == TypeManager.ushort_type ||
3813 q == TypeManager.uint32_type || q == TypeManager.uint64_type)
3816 if (p == TypeManager.short_type)
3817 if (q == TypeManager.ushort_type || q == TypeManager.uint32_type ||
3818 q == TypeManager.uint64_type)
3821 if (p == TypeManager.int32_type)
3822 if (q == TypeManager.uint32_type || q == TypeManager.uint64_type)
3825 if (p == TypeManager.int64_type)
3826 if (q == TypeManager.uint64_type)
3833 /// Determines "Better function"
3836 /// and returns an integer indicating :
3837 /// 0 if candidate ain't better
3838 /// 1 if candidate is better than the current best match
3840 static int BetterFunction (EmitContext ec, ArrayList args,
3841 MethodBase candidate, MethodBase best,
3842 bool expanded_form, Location loc)
3844 ParameterData candidate_pd = GetParameterData (candidate);
3845 ParameterData best_pd;
3851 argument_count = args.Count;
3853 int cand_count = candidate_pd.Count;
3855 if (cand_count == 0 && argument_count == 0)
3858 if (candidate_pd.ParameterModifier (cand_count - 1) != Parameter.Modifier.PARAMS)
3859 if (cand_count != argument_count)
3865 if (argument_count == 0 && cand_count == 1 &&
3866 candidate_pd.ParameterModifier (cand_count - 1) == Parameter.Modifier.PARAMS)
3869 for (int j = argument_count; j > 0;) {
3872 Argument a = (Argument) args [j];
3873 Type t = candidate_pd.ParameterType (j);
3875 if (candidate_pd.ParameterModifier (j) == Parameter.Modifier.PARAMS)
3877 t = t.GetElementType ();
3879 x = BetterConversion (ec, a, t, null, loc);
3891 best_pd = GetParameterData (best);
3893 int rating1 = 0, rating2 = 0;
3895 for (int j = 0; j < argument_count; ++j) {
3898 Argument a = (Argument) args [j];
3900 Type ct = candidate_pd.ParameterType (j);
3901 Type bt = best_pd.ParameterType (j);
3903 if (candidate_pd.ParameterModifier (j) == Parameter.Modifier.PARAMS)
3905 ct = ct.GetElementType ();
3907 if (best_pd.ParameterModifier (j) == Parameter.Modifier.PARAMS)
3909 bt = bt.GetElementType ();
3911 x = BetterConversion (ec, a, ct, bt, loc);
3912 y = BetterConversion (ec, a, bt, ct, loc);
3921 if (rating1 > rating2)
3927 public static string FullMethodDesc (MethodBase mb)
3929 string ret_type = "";
3931 if (mb is MethodInfo)
3932 ret_type = TypeManager.CSharpName (((MethodInfo) mb).ReturnType);
3934 StringBuilder sb = new StringBuilder (ret_type);
3936 sb.Append (mb.ReflectedType.ToString ());
3938 sb.Append (mb.Name);
3940 ParameterData pd = GetParameterData (mb);
3942 int count = pd.Count;
3945 for (int i = count; i > 0; ) {
3948 sb.Append (pd.ParameterDesc (count - i - 1));
3954 return sb.ToString ();
3957 public static MethodGroupExpr MakeUnionSet (Expression mg1, Expression mg2, Location loc)
3959 MemberInfo [] miset;
3960 MethodGroupExpr union;
3965 return (MethodGroupExpr) mg2;
3968 return (MethodGroupExpr) mg1;
3971 MethodGroupExpr left_set = null, right_set = null;
3972 int length1 = 0, length2 = 0;
3974 left_set = (MethodGroupExpr) mg1;
3975 length1 = left_set.Methods.Length;
3977 right_set = (MethodGroupExpr) mg2;
3978 length2 = right_set.Methods.Length;
3980 ArrayList common = new ArrayList ();
3982 foreach (MethodBase l in left_set.Methods){
3983 foreach (MethodBase r in right_set.Methods){
3991 miset = new MemberInfo [length1 + length2 - common.Count];
3992 left_set.Methods.CopyTo (miset, 0);
3996 foreach (MemberInfo mi in right_set.Methods){
3997 if (!common.Contains (mi))
4001 union = new MethodGroupExpr (miset, loc);
4007 /// Determines is the candidate method, if a params method, is applicable
4008 /// in its expanded form to the given set of arguments
4010 static bool IsParamsMethodApplicable (EmitContext ec, ArrayList arguments, MethodBase candidate)
4014 if (arguments == null)
4017 arg_count = arguments.Count;
4019 ParameterData pd = GetParameterData (candidate);
4021 int pd_count = pd.Count;
4026 if (pd.ParameterModifier (pd_count - 1) != Parameter.Modifier.PARAMS)
4029 if (pd_count - 1 > arg_count)
4032 if (pd_count == 1 && arg_count == 0)
4036 // If we have come this far, the case which remains is when the number of parameters
4037 // is less than or equal to the argument count.
4039 for (int i = 0; i < pd_count - 1; ++i) {
4041 Argument a = (Argument) arguments [i];
4043 Parameter.Modifier a_mod = a.GetParameterModifier () &
4044 ~(Parameter.Modifier.OUT | Parameter.Modifier.REF);
4045 Parameter.Modifier p_mod = pd.ParameterModifier (i) &
4046 ~(Parameter.Modifier.OUT | Parameter.Modifier.REF);
4048 if (a_mod == p_mod) {
4050 if (a_mod == Parameter.Modifier.NONE)
4051 if (!ImplicitConversionExists (ec, a.Expr, pd.ParameterType (i)))
4054 if ((a_mod & Parameter.Modifier.ISBYREF) != 0) {
4055 Type pt = pd.ParameterType (i);
4058 pt = TypeManager.LookupType (pt.FullName + "&");
4068 Type element_type = pd.ParameterType (pd_count - 1).GetElementType ();
4070 for (int i = pd_count - 1; i < arg_count; i++) {
4071 Argument a = (Argument) arguments [i];
4073 if (!StandardConversionExists (a.Expr, element_type))
4081 /// Determines if the candidate method is applicable (section 14.4.2.1)
4082 /// to the given set of arguments
4084 static bool IsApplicable (EmitContext ec, ArrayList arguments, MethodBase candidate)
4088 if (arguments == null)
4091 arg_count = arguments.Count;
4093 ParameterData pd = GetParameterData (candidate);
4095 int pd_count = pd.Count;
4097 if (arg_count != pd.Count)
4100 for (int i = arg_count; i > 0; ) {
4103 Argument a = (Argument) arguments [i];
4105 Parameter.Modifier a_mod = a.GetParameterModifier () &
4106 ~(Parameter.Modifier.OUT | Parameter.Modifier.REF);
4107 Parameter.Modifier p_mod = pd.ParameterModifier (i) &
4108 ~(Parameter.Modifier.OUT | Parameter.Modifier.REF);
4110 if (a_mod == p_mod ||
4111 (a_mod == Parameter.Modifier.NONE && p_mod == Parameter.Modifier.PARAMS)) {
4112 if (a_mod == Parameter.Modifier.NONE)
4113 if (!ImplicitConversionExists (ec, a.Expr, pd.ParameterType (i)))
4116 if ((a_mod & Parameter.Modifier.ISBYREF) != 0) {
4117 Type pt = pd.ParameterType (i);
4120 pt = TypeManager.LookupType (pt.FullName + "&");
4135 /// Find the Applicable Function Members (7.4.2.1)
4137 /// me: Method Group expression with the members to select.
4138 /// it might contain constructors or methods (or anything
4139 /// that maps to a method).
4141 /// Arguments: ArrayList containing resolved Argument objects.
4143 /// loc: The location if we want an error to be reported, or a Null
4144 /// location for "probing" purposes.
4146 /// Returns: The MethodBase (either a ConstructorInfo or a MethodInfo)
4147 /// that is the best match of me on Arguments.
4150 public static MethodBase OverloadResolve (EmitContext ec, MethodGroupExpr me,
4151 ArrayList Arguments, Location loc)
4153 ArrayList afm = new ArrayList ();
4154 MethodBase method = null;
4155 Type current_type = null;
4157 ArrayList candidates = new ArrayList ();
4160 foreach (MethodBase candidate in me.Methods){
4163 // If we're going one level higher in the class hierarchy, abort if
4164 // we already found an applicable method.
4165 if (candidate.DeclaringType != current_type) {
4166 current_type = candidate.DeclaringType;
4171 // Check if candidate is applicable (section 14.4.2.1)
4172 if (!IsApplicable (ec, Arguments, candidate))
4175 candidates.Add (candidate);
4176 x = BetterFunction (ec, Arguments, candidate, method, false, loc);
4184 if (Arguments == null)
4187 argument_count = Arguments.Count;
4190 // Now we see if we can find params functions, applicable in their expanded form
4191 // since if they were applicable in their normal form, they would have been selected
4194 bool chose_params_expanded = false;
4196 if (method == null) {
4197 candidates = new ArrayList ();
4198 foreach (MethodBase candidate in me.Methods){
4199 if (!IsParamsMethodApplicable (ec, Arguments, candidate))
4202 candidates.Add (candidate);
4204 int x = BetterFunction (ec, Arguments, candidate, method, true, loc);
4209 chose_params_expanded = true;
4213 if (method == null) {
4215 // Okay so we have failed to find anything so we
4216 // return by providing info about the closest match
4218 for (int i = 0; i < me.Methods.Length; ++i) {
4220 MethodBase c = (MethodBase) me.Methods [i];
4221 ParameterData pd = GetParameterData (c);
4223 if (pd.Count != argument_count)
4226 VerifyArgumentsCompat (ec, Arguments, argument_count, c, false,
4234 // Now check that there are no ambiguities i.e the selected method
4235 // should be better than all the others
4238 foreach (MethodBase candidate in candidates){
4239 if (candidate == method)
4243 // If a normal method is applicable in the sense that it has the same
4244 // number of arguments, then the expanded params method is never applicable
4245 // so we debar the params method.
4247 if (IsParamsMethodApplicable (ec, Arguments, candidate) &&
4248 IsApplicable (ec, Arguments, method))
4251 int x = BetterFunction (ec, Arguments, method, candidate,
4252 chose_params_expanded, loc);
4257 "Ambiguous call when selecting function due to implicit casts");
4263 // And now check if the arguments are all compatible, perform conversions
4264 // if necessary etc. and return if everything is all right
4267 if (!VerifyArgumentsCompat (ec, Arguments, argument_count, method,
4268 chose_params_expanded, null, loc))
4274 public static bool VerifyArgumentsCompat (EmitContext ec, ArrayList Arguments,
4277 bool chose_params_expanded,
4281 ParameterData pd = GetParameterData (method);
4282 int pd_count = pd.Count;
4284 for (int j = 0; j < argument_count; j++) {
4285 Argument a = (Argument) Arguments [j];
4286 Expression a_expr = a.Expr;
4287 Type parameter_type = pd.ParameterType (j);
4289 if (pd.ParameterModifier (j) == Parameter.Modifier.PARAMS &&
4290 chose_params_expanded)
4291 parameter_type = TypeManager.TypeToCoreType (parameter_type.GetElementType ());
4293 if (a.Type != parameter_type){
4296 conv = ConvertImplicit (ec, a_expr, parameter_type, loc);
4299 if (!Location.IsNull (loc)) {
4300 if (delegate_type == null)
4301 Report.Error (1502, loc,
4302 "The best overloaded match for method '" +
4303 FullMethodDesc (method) +
4304 "' has some invalid arguments");
4306 Report.Error (1594, loc,
4307 "Delegate '" + delegate_type.ToString () +
4308 "' has some invalid arguments.");
4309 Report.Error (1503, loc,
4310 "Argument " + (j+1) +
4311 ": Cannot convert from '" + Argument.FullDesc (a)
4312 + "' to '" + pd.ParameterDesc (j) + "'");
4319 // Update the argument with the implicit conversion
4325 Parameter.Modifier a_mod = a.GetParameterModifier () &
4326 ~(Parameter.Modifier.OUT | Parameter.Modifier.REF);
4327 Parameter.Modifier p_mod = pd.ParameterModifier (j) &
4328 ~(Parameter.Modifier.OUT | Parameter.Modifier.REF);
4331 if (a_mod != p_mod &&
4332 pd.ParameterModifier (pd_count - 1) != Parameter.Modifier.PARAMS) {
4333 if (!Location.IsNull (loc)) {
4334 Console.WriteLine ("A:P: " + a.GetParameterModifier ());
4335 Console.WriteLine ("PP:: " + pd.ParameterModifier (j));
4336 Console.WriteLine ("PT: " + parameter_type.IsByRef);
4337 Report.Error (1502, loc,
4338 "The best overloaded match for method '" + FullMethodDesc (method)+
4339 "' has some invalid arguments");
4340 Report.Error (1503, loc,
4341 "Argument " + (j+1) +
4342 ": Cannot convert from '" + Argument.FullDesc (a)
4343 + "' to '" + pd.ParameterDesc (j) + "'");
4353 public override Expression DoResolve (EmitContext ec)
4356 // First, resolve the expression that is used to
4357 // trigger the invocation
4359 if (expr is BaseAccess)
4362 expr = expr.Resolve (ec, ResolveFlags.VariableOrValue | ResolveFlags.MethodGroup);
4366 if (!(expr is MethodGroupExpr)) {
4367 Type expr_type = expr.Type;
4369 if (expr_type != null){
4370 bool IsDelegate = TypeManager.IsDelegateType (expr_type);
4372 return (new DelegateInvocation (
4373 this.expr, Arguments, loc)).Resolve (ec);
4377 if (!(expr is MethodGroupExpr)){
4378 expr.Error118 (ResolveFlags.MethodGroup);
4383 // Next, evaluate all the expressions in the argument list
4385 if (Arguments != null){
4386 foreach (Argument a in Arguments){
4387 if (!a.Resolve (ec, loc))
4392 MethodGroupExpr mg = (MethodGroupExpr) expr;
4393 method = OverloadResolve (ec, mg, Arguments, loc);
4395 if (method == null){
4397 "Could not find any applicable function for this argument list");
4401 MethodInfo mi = method as MethodInfo;
4403 type = TypeManager.TypeToCoreType (mi.ReturnType);
4404 if (!mi.IsStatic && !mg.IsExplicitImpl && (mg.InstanceExpression == null))
4405 SimpleName.Error_ObjectRefRequired (ec, loc, mi.Name);
4408 if (type.IsPointer){
4416 // Only base will allow this invocation to happen.
4418 if (is_base && method.IsAbstract){
4419 Report.Error (205, loc, "Cannot call an abstract base member: " +
4420 FullMethodDesc (method));
4424 eclass = ExprClass.Value;
4429 // Emits the list of arguments as an array
4431 static void EmitParams (EmitContext ec, int idx, ArrayList arguments)
4433 ILGenerator ig = ec.ig;
4434 int count = arguments.Count - idx;
4435 Argument a = (Argument) arguments [idx];
4436 Type t = a.Expr.Type;
4437 string array_type = t.FullName + "[]";
4440 array = ig.DeclareLocal (TypeManager.LookupType (array_type));
4441 IntConstant.EmitInt (ig, count);
4442 ig.Emit (OpCodes.Newarr, TypeManager.TypeToCoreType (t));
4443 ig.Emit (OpCodes.Stloc, array);
4445 int top = arguments.Count;
4446 for (int j = idx; j < top; j++){
4447 a = (Argument) arguments [j];
4449 ig.Emit (OpCodes.Ldloc, array);
4450 IntConstant.EmitInt (ig, j - idx);
4453 OpCode op = ArrayAccess.GetStoreOpcode (t, out is_stobj);
4455 ig.Emit (OpCodes.Ldelema, t);
4460 ig.Emit (OpCodes.Stobj, t);
4464 ig.Emit (OpCodes.Ldloc, array);
4468 /// Emits a list of resolved Arguments that are in the arguments
4471 /// The MethodBase argument might be null if the
4472 /// emission of the arguments is known not to contain
4473 /// a `params' field (for example in constructors or other routines
4474 /// that keep their arguments in this structure)
4476 public static void EmitArguments (EmitContext ec, MethodBase mb, ArrayList arguments)
4480 pd = GetParameterData (mb);
4485 // If we are calling a params method with no arguments, special case it
4487 if (arguments == null){
4488 if (pd != null && pd.Count > 0 &&
4489 pd.ParameterModifier (0) == Parameter.Modifier.PARAMS){
4490 ILGenerator ig = ec.ig;
4492 IntConstant.EmitInt (ig, 0);
4493 ig.Emit (OpCodes.Newarr, pd.ParameterType (0).GetElementType ());
4499 int top = arguments.Count;
4501 for (int i = 0; i < top; i++){
4502 Argument a = (Argument) arguments [i];
4505 if (pd.ParameterModifier (i) == Parameter.Modifier.PARAMS){
4507 // Special case if we are passing the same data as the
4508 // params argument, do not put it in an array.
4510 if (pd.ParameterType (i) == a.Type)
4513 EmitParams (ec, i, arguments);
4521 if (pd != null && pd.Count > top &&
4522 pd.ParameterModifier (top) == Parameter.Modifier.PARAMS){
4523 ILGenerator ig = ec.ig;
4525 IntConstant.EmitInt (ig, 0);
4526 ig.Emit (OpCodes.Newarr, pd.ParameterType (top).GetElementType ());
4531 /// is_base tells whether we want to force the use of the `call'
4532 /// opcode instead of using callvirt. Call is required to call
4533 /// a specific method, while callvirt will always use the most
4534 /// recent method in the vtable.
4536 /// is_static tells whether this is an invocation on a static method
4538 /// instance_expr is an expression that represents the instance
4539 /// it must be non-null if is_static is false.
4541 /// method is the method to invoke.
4543 /// Arguments is the list of arguments to pass to the method or constructor.
4545 public static void EmitCall (EmitContext ec, bool is_base,
4546 bool is_static, Expression instance_expr,
4547 MethodBase method, ArrayList Arguments, Location loc)
4549 ILGenerator ig = ec.ig;
4550 bool struct_call = false;
4552 Type decl_type = method.DeclaringType;
4554 if (!RootContext.StdLib) {
4555 // Replace any calls to the system's System.Array type with calls to
4556 // the newly created one.
4557 if (method == TypeManager.system_int_array_get_length)
4558 method = TypeManager.int_array_get_length;
4559 else if (method == TypeManager.system_int_array_get_rank)
4560 method = TypeManager.int_array_get_rank;
4561 else if (method == TypeManager.system_object_array_clone)
4562 method = TypeManager.object_array_clone;
4563 else if (method == TypeManager.system_int_array_get_length_int)
4564 method = TypeManager.int_array_get_length_int;
4565 else if (method == TypeManager.system_int_array_get_lower_bound_int)
4566 method = TypeManager.int_array_get_lower_bound_int;
4567 else if (method == TypeManager.system_int_array_get_upper_bound_int)
4568 method = TypeManager.int_array_get_upper_bound_int;
4569 else if (method == TypeManager.system_void_array_copyto_array_int)
4570 method = TypeManager.void_array_copyto_array_int;
4574 // This checks the `ConditionalAttribute' on the method, and the
4575 // ObsoleteAttribute
4577 TypeManager.MethodFlags flags = TypeManager.GetMethodFlags (method, loc);
4578 if ((flags & TypeManager.MethodFlags.IsObsoleteError) != 0)
4580 if ((flags & TypeManager.MethodFlags.ShouldIgnore) != 0)
4584 if (decl_type.IsValueType)
4587 // If this is ourselves, push "this"
4589 if (instance_expr == null){
4590 ig.Emit (OpCodes.Ldarg_0);
4593 // Push the instance expression
4595 if (instance_expr.Type.IsValueType){
4597 // Special case: calls to a function declared in a
4598 // reference-type with a value-type argument need
4599 // to have their value boxed.
4602 if (decl_type.IsValueType){
4604 // If the expression implements IMemoryLocation, then
4605 // we can optimize and use AddressOf on the
4608 // If not we have to use some temporary storage for
4610 if (instance_expr is IMemoryLocation){
4611 ((IMemoryLocation)instance_expr).
4612 AddressOf (ec, AddressOp.LoadStore);
4615 Type t = instance_expr.Type;
4617 instance_expr.Emit (ec);
4618 LocalBuilder temp = ig.DeclareLocal (t);
4619 ig.Emit (OpCodes.Stloc, temp);
4620 ig.Emit (OpCodes.Ldloca, temp);
4623 instance_expr.Emit (ec);
4624 ig.Emit (OpCodes.Box, instance_expr.Type);
4627 instance_expr.Emit (ec);
4631 EmitArguments (ec, method, Arguments);
4633 if (is_static || struct_call || is_base){
4634 if (method is MethodInfo) {
4635 ig.Emit (OpCodes.Call, (MethodInfo) method);
4637 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
4639 if (method is MethodInfo)
4640 ig.Emit (OpCodes.Callvirt, (MethodInfo) method);
4642 ig.Emit (OpCodes.Callvirt, (ConstructorInfo) method);
4646 public override void Emit (EmitContext ec)
4648 MethodGroupExpr mg = (MethodGroupExpr) this.expr;
4651 ec, is_base, method.IsStatic, mg.InstanceExpression, method, Arguments, loc);
4654 public override void EmitStatement (EmitContext ec)
4659 // Pop the return value if there is one
4661 if (method is MethodInfo){
4662 Type ret = ((MethodInfo)method).ReturnType;
4663 if (TypeManager.TypeToCoreType (ret) != TypeManager.void_type)
4664 ec.ig.Emit (OpCodes.Pop);
4670 // This class is used to "disable" the code generation for the
4671 // temporary variable when initializing value types.
4673 class EmptyAddressOf : EmptyExpression, IMemoryLocation {
4674 public void AddressOf (EmitContext ec, AddressOp Mode)
4681 /// Implements the new expression
4683 public class New : ExpressionStatement {
4684 public readonly ArrayList Arguments;
4685 public readonly Expression RequestedType;
4687 MethodBase method = null;
4690 // If set, the new expression is for a value_target, and
4691 // we will not leave anything on the stack.
4693 Expression value_target;
4694 bool value_target_set = false;
4696 public New (Expression requested_type, ArrayList arguments, Location l)
4698 RequestedType = requested_type;
4699 Arguments = arguments;
4703 public Expression ValueTypeVariable {
4705 return value_target;
4709 value_target = value;
4710 value_target_set = true;
4715 // This function is used to disable the following code sequence for
4716 // value type initialization:
4718 // AddressOf (temporary)
4722 // Instead the provide will have provided us with the address on the
4723 // stack to store the results.
4725 static Expression MyEmptyExpression;
4727 public void DisableTemporaryValueType ()
4729 if (MyEmptyExpression == null)
4730 MyEmptyExpression = new EmptyAddressOf ();
4733 // To enable this, look into:
4734 // test-34 and test-89 and self bootstrapping.
4736 // For instance, we can avoid a copy by using `newobj'
4737 // instead of Call + Push-temp on value types.
4738 // value_target = MyEmptyExpression;
4741 public override Expression DoResolve (EmitContext ec)
4743 type = ec.DeclSpace.ResolveType (RequestedType, false, loc);
4748 bool IsDelegate = TypeManager.IsDelegateType (type);
4751 return (new NewDelegate (type, Arguments, loc)).Resolve (ec);
4753 if (type.IsInterface || type.IsAbstract){
4755 144, "It is not possible to create instances of interfaces " +
4756 "or abstract classes");
4760 bool is_struct = false;
4761 is_struct = type.IsValueType;
4762 eclass = ExprClass.Value;
4765 // SRE returns a match for .ctor () on structs (the object constructor),
4766 // so we have to manually ignore it.
4768 if (is_struct && Arguments == null)
4772 ml = MemberLookupFinal (ec, null, type, ".ctor",
4773 MemberTypes.Constructor,
4774 AllBindingFlags | BindingFlags.DeclaredOnly, loc);
4779 if (! (ml is MethodGroupExpr)){
4781 ml.Error118 ("method group");
4787 if (Arguments != null){
4788 foreach (Argument a in Arguments){
4789 if (!a.Resolve (ec, loc))
4794 method = Invocation.OverloadResolve (ec, (MethodGroupExpr) ml,
4799 if (method == null) {
4800 if (!is_struct || Arguments.Count > 0) {
4802 "New invocation: Can not find a constructor for " +
4803 "this argument list");
4811 // This DoEmit can be invoked in two contexts:
4812 // * As a mechanism that will leave a value on the stack (new object)
4813 // * As one that wont (init struct)
4815 // You can control whether a value is required on the stack by passing
4816 // need_value_on_stack. The code *might* leave a value on the stack
4817 // so it must be popped manually
4819 // If we are dealing with a ValueType, we have a few
4820 // situations to deal with:
4822 // * The target is a ValueType, and we have been provided
4823 // the instance (this is easy, we are being assigned).
4825 // * The target of New is being passed as an argument,
4826 // to a boxing operation or a function that takes a
4829 // In this case, we need to create a temporary variable
4830 // that is the argument of New.
4832 // Returns whether a value is left on the stack
4834 bool DoEmit (EmitContext ec, bool need_value_on_stack)
4836 bool is_value_type = type.IsValueType;
4837 ILGenerator ig = ec.ig;
4842 // Allow DoEmit() to be called multiple times.
4843 // We need to create a new LocalTemporary each time since
4844 // you can't share LocalBuilders among ILGeneators.
4845 if (!value_target_set)
4846 value_target = new LocalTemporary (ec, type);
4848 ml = (IMemoryLocation) value_target;
4849 ml.AddressOf (ec, AddressOp.Store);
4853 Invocation.EmitArguments (ec, method, Arguments);
4857 ig.Emit (OpCodes.Initobj, type);
4859 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
4860 if (need_value_on_stack){
4861 value_target.Emit (ec);
4866 ig.Emit (OpCodes.Newobj, (ConstructorInfo) method);
4871 public override void Emit (EmitContext ec)
4876 public override void EmitStatement (EmitContext ec)
4878 if (DoEmit (ec, false))
4879 ec.ig.Emit (OpCodes.Pop);
4884 /// 14.5.10.2: Represents an array creation expression.
4888 /// There are two possible scenarios here: one is an array creation
4889 /// expression that specifies the dimensions and optionally the
4890 /// initialization data and the other which does not need dimensions
4891 /// specified but where initialization data is mandatory.
4893 public class ArrayCreation : ExpressionStatement {
4894 Expression requested_base_type;
4895 ArrayList initializers;
4898 // The list of Argument types.
4899 // This is used to construct the `newarray' or constructor signature
4901 ArrayList arguments;
4904 // Method used to create the array object.
4906 MethodBase new_method = null;
4908 Type array_element_type;
4909 Type underlying_type;
4910 bool is_one_dimensional = false;
4911 bool is_builtin_type = false;
4912 bool expect_initializers = false;
4913 int num_arguments = 0;
4917 ArrayList array_data;
4922 // The number of array initializers that we can handle
4923 // via the InitializeArray method - through EmitStaticInitializers
4925 int num_automatic_initializers;
4927 const int max_automatic_initializers = 6;
4929 public ArrayCreation (Expression requested_base_type, ArrayList exprs, string rank, ArrayList initializers, Location l)
4931 this.requested_base_type = requested_base_type;
4932 this.initializers = initializers;
4936 arguments = new ArrayList ();
4938 foreach (Expression e in exprs) {
4939 arguments.Add (new Argument (e, Argument.AType.Expression));
4944 public ArrayCreation (Expression requested_base_type, string rank, ArrayList initializers, Location l)
4946 this.requested_base_type = requested_base_type;
4947 this.initializers = initializers;
4951 //this.rank = rank.Substring (0, rank.LastIndexOf ("["));
4953 //string tmp = rank.Substring (rank.LastIndexOf ("["));
4955 //dimensions = tmp.Length - 1;
4956 expect_initializers = true;
4959 public Expression FormArrayType (Expression base_type, int idx_count, string rank)
4961 StringBuilder sb = new StringBuilder (rank);
4964 for (int i = 1; i < idx_count; i++)
4969 return new ComposedCast (base_type, sb.ToString (), loc);
4972 void Error_IncorrectArrayInitializer ()
4974 Error (178, "Incorrectly structured array initializer");
4977 public bool CheckIndices (EmitContext ec, ArrayList probe, int idx, bool specified_dims)
4979 if (specified_dims) {
4980 Argument a = (Argument) arguments [idx];
4982 if (!a.Resolve (ec, loc))
4985 if (!(a.Expr is Constant)) {
4986 Error (150, "A constant value is expected");
4990 int value = (int) ((Constant) a.Expr).GetValue ();
4992 if (value != probe.Count) {
4993 Error_IncorrectArrayInitializer ();
4997 bounds [idx] = value;
5000 int child_bounds = -1;
5001 foreach (object o in probe) {
5002 if (o is ArrayList) {
5003 int current_bounds = ((ArrayList) o).Count;
5005 if (child_bounds == -1)
5006 child_bounds = current_bounds;
5008 else if (child_bounds != current_bounds){
5009 Error_IncorrectArrayInitializer ();
5012 bool ret = CheckIndices (ec, (ArrayList) o, idx + 1, specified_dims);
5016 if (child_bounds != -1){
5017 Error_IncorrectArrayInitializer ();
5021 Expression tmp = (Expression) o;
5022 tmp = tmp.Resolve (ec);
5026 // Console.WriteLine ("I got: " + tmp);
5027 // Handle initialization from vars, fields etc.
5029 Expression conv = ConvertImplicitRequired (
5030 ec, tmp, underlying_type, loc);
5035 if (conv is StringConstant)
5036 array_data.Add (conv);
5037 else if (conv is Constant) {
5038 array_data.Add (conv);
5039 num_automatic_initializers++;
5041 array_data.Add (conv);
5048 public void UpdateIndices (EmitContext ec)
5051 for (ArrayList probe = initializers; probe != null;) {
5052 if (probe.Count > 0 && probe [0] is ArrayList) {
5053 Expression e = new IntConstant (probe.Count);
5054 arguments.Add (new Argument (e, Argument.AType.Expression));
5056 bounds [i++] = probe.Count;
5058 probe = (ArrayList) probe [0];
5061 Expression e = new IntConstant (probe.Count);
5062 arguments.Add (new Argument (e, Argument.AType.Expression));
5064 bounds [i++] = probe.Count;
5071 public bool ValidateInitializers (EmitContext ec, Type array_type)
5073 if (initializers == null) {
5074 if (expect_initializers)
5080 if (underlying_type == null)
5084 // We use this to store all the date values in the order in which we
5085 // will need to store them in the byte blob later
5087 array_data = new ArrayList ();
5088 bounds = new Hashtable ();
5092 if (arguments != null) {
5093 ret = CheckIndices (ec, initializers, 0, true);
5096 arguments = new ArrayList ();
5098 ret = CheckIndices (ec, initializers, 0, false);
5105 if (arguments.Count != dimensions) {
5106 Error_IncorrectArrayInitializer ();
5114 void Error_NegativeArrayIndex ()
5116 Error (284, "Can not create array with a negative size");
5120 // Converts `source' to an int, uint, long or ulong.
5122 Expression ExpressionToArrayArgument (EmitContext ec, Expression source)
5126 bool old_checked = ec.CheckState;
5127 ec.CheckState = true;
5129 target = ConvertImplicit (ec, source, TypeManager.int32_type, loc);
5130 if (target == null){
5131 target = ConvertImplicit (ec, source, TypeManager.uint32_type, loc);
5132 if (target == null){
5133 target = ConvertImplicit (ec, source, TypeManager.int64_type, loc);
5134 if (target == null){
5135 target = ConvertImplicit (ec, source, TypeManager.uint64_type, loc);
5137 Expression.Error_CannotConvertImplicit (loc, source.Type, TypeManager.int32_type);
5141 ec.CheckState = old_checked;
5144 // Only positive constants are allowed at compile time
5146 if (target is Constant){
5147 if (target is IntConstant){
5148 if (((IntConstant) target).Value < 0){
5149 Error_NegativeArrayIndex ();
5154 if (target is LongConstant){
5155 if (((LongConstant) target).Value < 0){
5156 Error_NegativeArrayIndex ();
5167 // Creates the type of the array
5169 bool LookupType (EmitContext ec)
5171 StringBuilder array_qualifier = new StringBuilder (rank);
5174 // `In the first form allocates an array instace of the type that results
5175 // from deleting each of the individual expression from the expression list'
5177 if (num_arguments > 0) {
5178 array_qualifier.Append ("[");
5179 for (int i = num_arguments-1; i > 0; i--)
5180 array_qualifier.Append (",");
5181 array_qualifier.Append ("]");
5187 Expression array_type_expr;
5188 array_type_expr = new ComposedCast (requested_base_type, array_qualifier.ToString (), loc);
5189 type = ec.DeclSpace.ResolveType (array_type_expr, false, loc);
5194 underlying_type = type;
5195 if (underlying_type.IsArray)
5196 underlying_type = TypeManager.TypeToCoreType (underlying_type.GetElementType ());
5197 dimensions = type.GetArrayRank ();
5202 public override Expression DoResolve (EmitContext ec)
5206 if (!LookupType (ec))
5210 // First step is to validate the initializers and fill
5211 // in any missing bits
5213 if (!ValidateInitializers (ec, type))
5216 if (arguments == null)
5219 arg_count = arguments.Count;
5220 foreach (Argument a in arguments){
5221 if (!a.Resolve (ec, loc))
5224 Expression real_arg = ExpressionToArrayArgument (ec, a.Expr, loc);
5225 if (real_arg == null)
5232 array_element_type = TypeManager.TypeToCoreType (type.GetElementType ());
5234 if (arg_count == 1) {
5235 is_one_dimensional = true;
5236 eclass = ExprClass.Value;
5240 is_builtin_type = TypeManager.IsBuiltinType (type);
5242 if (is_builtin_type) {
5245 ml = MemberLookup (ec, type, ".ctor", MemberTypes.Constructor,
5246 AllBindingFlags, loc);
5248 if (!(ml is MethodGroupExpr)) {
5249 ml.Error118 ("method group");
5254 Error (-6, "New invocation: Can not find a constructor for " +
5255 "this argument list");
5259 new_method = Invocation.OverloadResolve (ec, (MethodGroupExpr) ml, arguments, loc);
5261 if (new_method == null) {
5262 Error (-6, "New invocation: Can not find a constructor for " +
5263 "this argument list");
5267 eclass = ExprClass.Value;
5270 ModuleBuilder mb = CodeGen.ModuleBuilder;
5271 ArrayList args = new ArrayList ();
5273 if (arguments != null) {
5274 for (int i = 0; i < arg_count; i++)
5275 args.Add (TypeManager.int32_type);
5278 Type [] arg_types = null;
5281 arg_types = new Type [args.Count];
5283 args.CopyTo (arg_types, 0);
5285 new_method = mb.GetArrayMethod (type, ".ctor", CallingConventions.HasThis, null,
5288 if (new_method == null) {
5289 Error (-6, "New invocation: Can not find a constructor for " +
5290 "this argument list");
5294 eclass = ExprClass.Value;
5299 public static byte [] MakeByteBlob (ArrayList array_data, Type underlying_type, Location loc)
5304 int count = array_data.Count;
5306 if (underlying_type.IsEnum)
5307 underlying_type = TypeManager.EnumToUnderlying (underlying_type);
5309 factor = GetTypeSize (underlying_type);
5311 throw new Exception ("unrecognized type in MakeByteBlob: " + underlying_type);
5313 data = new byte [(count * factor + 4) & ~3];
5316 for (int i = 0; i < count; ++i) {
5317 object v = array_data [i];
5319 if (v is EnumConstant)
5320 v = ((EnumConstant) v).Child;
5322 if (v is Constant && !(v is StringConstant))
5323 v = ((Constant) v).GetValue ();
5329 if (underlying_type == TypeManager.int64_type){
5330 if (!(v is Expression)){
5331 long val = (long) v;
5333 for (int j = 0; j < factor; ++j) {
5334 data [idx + j] = (byte) (val & 0xFF);
5338 } else if (underlying_type == TypeManager.uint64_type){
5339 if (!(v is Expression)){
5340 ulong val = (ulong) v;
5342 for (int j = 0; j < factor; ++j) {
5343 data [idx + j] = (byte) (val & 0xFF);
5347 } else if (underlying_type == TypeManager.float_type) {
5348 if (!(v is Expression)){
5349 element = BitConverter.GetBytes ((float) v);
5351 for (int j = 0; j < factor; ++j)
5352 data [idx + j] = element [j];
5354 } else if (underlying_type == TypeManager.double_type) {
5355 if (!(v is Expression)){
5356 element = BitConverter.GetBytes ((double) v);
5358 for (int j = 0; j < factor; ++j)
5359 data [idx + j] = element [j];
5361 } else if (underlying_type == TypeManager.char_type){
5362 if (!(v is Expression)){
5363 int val = (int) ((char) v);
5365 data [idx] = (byte) (val & 0xff);
5366 data [idx+1] = (byte) (val >> 8);
5368 } else if (underlying_type == TypeManager.short_type){
5369 if (!(v is Expression)){
5370 int val = (int) ((short) v);
5372 data [idx] = (byte) (val & 0xff);
5373 data [idx+1] = (byte) (val >> 8);
5375 } else if (underlying_type == TypeManager.ushort_type){
5376 if (!(v is Expression)){
5377 int val = (int) ((ushort) v);
5379 data [idx] = (byte) (val & 0xff);
5380 data [idx+1] = (byte) (val >> 8);
5382 } else if (underlying_type == TypeManager.int32_type) {
5383 if (!(v is Expression)){
5386 data [idx] = (byte) (val & 0xff);
5387 data [idx+1] = (byte) ((val >> 8) & 0xff);
5388 data [idx+2] = (byte) ((val >> 16) & 0xff);
5389 data [idx+3] = (byte) (val >> 24);
5391 } else if (underlying_type == TypeManager.uint32_type) {
5392 if (!(v is Expression)){
5393 uint val = (uint) v;
5395 data [idx] = (byte) (val & 0xff);
5396 data [idx+1] = (byte) ((val >> 8) & 0xff);
5397 data [idx+2] = (byte) ((val >> 16) & 0xff);
5398 data [idx+3] = (byte) (val >> 24);
5400 } else if (underlying_type == TypeManager.sbyte_type) {
5401 if (!(v is Expression)){
5402 sbyte val = (sbyte) v;
5403 data [idx] = (byte) val;
5405 } else if (underlying_type == TypeManager.byte_type) {
5406 if (!(v is Expression)){
5407 byte val = (byte) v;
5408 data [idx] = (byte) val;
5410 } else if (underlying_type == TypeManager.bool_type) {
5411 if (!(v is Expression)){
5412 bool val = (bool) v;
5413 data [idx] = (byte) (val ? 1 : 0);
5415 } else if (underlying_type == TypeManager.decimal_type){
5416 if (!(v is Expression)){
5417 int [] bits = Decimal.GetBits ((decimal) v);
5420 for (int j = 0; j < 4; j++){
5421 data [p++] = (byte) (bits [j] & 0xff);
5422 data [p++] = (byte) ((bits [j] >> 8) & 0xff);
5423 data [p++] = (byte) ((bits [j] >> 16) & 0xff);
5424 data [p++] = (byte) (bits [j] >> 24);
5428 throw new Exception ("Unrecognized type in MakeByteBlob: " + underlying_type);
5437 // Emits the initializers for the array
5439 void EmitStaticInitializers (EmitContext ec, bool is_expression)
5442 // First, the static data
5445 ILGenerator ig = ec.ig;
5447 byte [] data = MakeByteBlob (array_data, underlying_type, loc);
5449 fb = RootContext.MakeStaticData (data);
5452 ig.Emit (OpCodes.Dup);
5453 ig.Emit (OpCodes.Ldtoken, fb);
5454 ig.Emit (OpCodes.Call,
5455 TypeManager.void_initializearray_array_fieldhandle);
5459 // Emits pieces of the array that can not be computed at compile
5460 // time (variables and string locations).
5462 // This always expect the top value on the stack to be the array
5464 void EmitDynamicInitializers (EmitContext ec, bool is_expression)
5466 ILGenerator ig = ec.ig;
5467 int dims = bounds.Count;
5468 int [] current_pos = new int [dims];
5469 int top = array_data.Count;
5470 LocalBuilder temp = ig.DeclareLocal (type);
5472 ig.Emit (OpCodes.Stloc, temp);
5474 MethodInfo set = null;
5478 ModuleBuilder mb = null;
5479 mb = CodeGen.ModuleBuilder;
5480 args = new Type [dims + 1];
5483 for (j = 0; j < dims; j++)
5484 args [j] = TypeManager.int32_type;
5486 args [j] = array_element_type;
5488 set = mb.GetArrayMethod (
5490 CallingConventions.HasThis | CallingConventions.Standard,
5491 TypeManager.void_type, args);
5494 for (int i = 0; i < top; i++){
5496 Expression e = null;
5498 if (array_data [i] is Expression)
5499 e = (Expression) array_data [i];
5503 // Basically we do this for string literals and
5504 // other non-literal expressions
5506 if (e is EnumConstant){
5507 e = ((EnumConstant) e).Child;
5510 if (e is StringConstant || !(e is Constant) ||
5511 num_automatic_initializers <= max_automatic_initializers) {
5512 Type etype = e.Type;
5514 ig.Emit (OpCodes.Ldloc, temp);
5516 for (int idx = 0; idx < dims; idx++)
5517 IntConstant.EmitInt (ig, current_pos [idx]);
5520 // If we are dealing with a struct, get the
5521 // address of it, so we can store it.
5524 etype.IsSubclassOf (TypeManager.value_type) &&
5525 (!TypeManager.IsBuiltinType (etype) ||
5526 etype == TypeManager.decimal_type)) {
5531 // Let new know that we are providing
5532 // the address where to store the results
5534 n.DisableTemporaryValueType ();
5537 ig.Emit (OpCodes.Ldelema, etype);
5543 ArrayAccess.EmitStoreOpcode (ig, array_element_type);
5545 ig.Emit (OpCodes.Call, set);
5552 for (int j = dims - 1; j >= 0; j--){
5554 if (current_pos [j] < (int) bounds [j])
5556 current_pos [j] = 0;
5561 ig.Emit (OpCodes.Ldloc, temp);
5564 void EmitArrayArguments (EmitContext ec)
5566 ILGenerator ig = ec.ig;
5568 foreach (Argument a in arguments) {
5569 Type atype = a.Type;
5572 if (atype == TypeManager.uint64_type)
5573 ig.Emit (OpCodes.Conv_Ovf_U4);
5574 else if (atype == TypeManager.int64_type)
5575 ig.Emit (OpCodes.Conv_Ovf_I4);
5579 void DoEmit (EmitContext ec, bool is_statement)
5581 ILGenerator ig = ec.ig;
5583 EmitArrayArguments (ec);
5584 if (is_one_dimensional)
5585 ig.Emit (OpCodes.Newarr, array_element_type);
5587 if (is_builtin_type)
5588 ig.Emit (OpCodes.Newobj, (ConstructorInfo) new_method);
5590 ig.Emit (OpCodes.Newobj, (MethodInfo) new_method);
5593 if (initializers != null){
5595 // FIXME: Set this variable correctly.
5597 bool dynamic_initializers = true;
5599 if (underlying_type != TypeManager.string_type &&
5600 underlying_type != TypeManager.object_type) {
5601 if (num_automatic_initializers > max_automatic_initializers)
5602 EmitStaticInitializers (ec, dynamic_initializers || !is_statement);
5605 if (dynamic_initializers)
5606 EmitDynamicInitializers (ec, !is_statement);
5610 public override void Emit (EmitContext ec)
5615 public override void EmitStatement (EmitContext ec)
5623 /// Represents the `this' construct
5625 public class This : Expression, IAssignMethod, IMemoryLocation, IVariable {
5630 public This (Block block, Location loc)
5636 public This (Location loc)
5641 public bool IsAssigned (EmitContext ec, Location loc)
5646 return vi.IsAssigned (ec, loc);
5649 public bool IsFieldAssigned (EmitContext ec, string field_name, Location loc)
5654 return vi.IsFieldAssigned (ec, field_name, loc);
5657 public void SetAssigned (EmitContext ec)
5660 vi.SetAssigned (ec);
5663 public void SetFieldAssigned (EmitContext ec, string field_name)
5666 vi.SetFieldAssigned (ec, field_name);
5669 public override Expression DoResolve (EmitContext ec)
5671 eclass = ExprClass.Variable;
5672 type = ec.ContainerType;
5675 Error (26, "Keyword this not valid in static code");
5680 vi = block.ThisVariable;
5685 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
5689 VariableInfo vi = ec.CurrentBlock.ThisVariable;
5691 vi.SetAssigned (ec);
5693 if (ec.TypeContainer is Class){
5694 Error (1604, "Cannot assign to `this'");
5701 public override void Emit (EmitContext ec)
5703 ILGenerator ig = ec.ig;
5705 ig.Emit (OpCodes.Ldarg_0);
5706 if (ec.TypeContainer is Struct)
5707 ig.Emit (OpCodes.Ldobj, type);
5710 public void EmitAssign (EmitContext ec, Expression source)
5712 ILGenerator ig = ec.ig;
5714 if (ec.TypeContainer is Struct){
5715 ig.Emit (OpCodes.Ldarg_0);
5717 ig.Emit (OpCodes.Stobj, type);
5720 ig.Emit (OpCodes.Starg, 0);
5724 public void AddressOf (EmitContext ec, AddressOp mode)
5726 ec.ig.Emit (OpCodes.Ldarg_0);
5729 // FIGURE OUT WHY LDARG_S does not work
5731 // consider: struct X { int val; int P { set { val = value; }}}
5733 // Yes, this looks very bad. Look at `NOTAS' for
5735 // ec.ig.Emit (OpCodes.Ldarga_S, (byte) 0);
5740 /// Implements the typeof operator
5742 public class TypeOf : Expression {
5743 public readonly Expression QueriedType;
5746 public TypeOf (Expression queried_type, Location l)
5748 QueriedType = queried_type;
5752 public override Expression DoResolve (EmitContext ec)
5754 typearg = ec.DeclSpace.ResolveType (QueriedType, false, loc);
5756 if (typearg == null)
5759 type = TypeManager.type_type;
5760 eclass = ExprClass.Type;
5764 public override void Emit (EmitContext ec)
5766 ec.ig.Emit (OpCodes.Ldtoken, typearg);
5767 ec.ig.Emit (OpCodes.Call, TypeManager.system_type_get_type_from_handle);
5770 public Type TypeArg {
5771 get { return typearg; }
5776 /// Implements the sizeof expression
5778 public class SizeOf : Expression {
5779 public readonly Expression QueriedType;
5782 public SizeOf (Expression queried_type, Location l)
5784 this.QueriedType = queried_type;
5788 public override Expression DoResolve (EmitContext ec)
5791 Error (233, "Sizeof may only be used in an unsafe context " +
5792 "(consider using System.Runtime.InteropServices.Marshal.Sizeof");
5796 type_queried = ec.DeclSpace.ResolveType (QueriedType, false, loc);
5797 if (type_queried == null)
5800 if (!TypeManager.IsUnmanagedType (type_queried)){
5801 Report.Error (208, "Cannot take the size of an unmanaged type (" + TypeManager.CSharpName (type_queried) + ")");
5805 type = TypeManager.int32_type;
5806 eclass = ExprClass.Value;
5810 public override void Emit (EmitContext ec)
5812 int size = GetTypeSize (type_queried);
5815 ec.ig.Emit (OpCodes.Sizeof, type_queried);
5817 IntConstant.EmitInt (ec.ig, size);
5822 /// Implements the member access expression
5824 public class MemberAccess : Expression, ITypeExpression {
5825 public readonly string Identifier;
5827 Expression member_lookup;
5829 public MemberAccess (Expression expr, string id, Location l)
5836 public Expression Expr {
5842 static void error176 (Location loc, string name)
5844 Report.Error (176, loc, "Static member `" +
5845 name + "' cannot be accessed " +
5846 "with an instance reference, qualify with a " +
5847 "type name instead");
5850 static bool IdenticalNameAndTypeName (EmitContext ec, Expression left_original, Location loc)
5852 if (left_original == null)
5855 if (!(left_original is SimpleName))
5858 SimpleName sn = (SimpleName) left_original;
5860 Type t = RootContext.LookupType (ec.DeclSpace, sn.Name, true, loc);
5867 public static Expression ResolveMemberAccess (EmitContext ec, Expression member_lookup,
5868 Expression left, Location loc,
5869 Expression left_original)
5871 bool left_is_type, left_is_explicit;
5873 // If `left' is null, then we're called from SimpleNameResolve and this is
5874 // a member in the currently defining class.
5876 left_is_type = ec.IsStatic || ec.IsFieldInitializer;
5877 left_is_explicit = false;
5879 // Implicitly default to `this' unless we're static.
5880 if (!ec.IsStatic && !ec.IsFieldInitializer && !ec.InEnumContext)
5883 left_is_type = left is TypeExpr;
5884 left_is_explicit = true;
5887 if (member_lookup is FieldExpr){
5888 FieldExpr fe = (FieldExpr) member_lookup;
5889 FieldInfo fi = fe.FieldInfo;
5890 Type decl_type = fi.DeclaringType;
5892 if (fi is FieldBuilder) {
5893 Const c = TypeManager.LookupConstant ((FieldBuilder) fi);
5896 object o = c.LookupConstantValue (ec);
5897 object real_value = ((Constant) c.Expr).GetValue ();
5899 return Constantify (real_value, fi.FieldType);
5904 Type t = fi.FieldType;
5908 if (fi is FieldBuilder)
5909 o = TypeManager.GetValue ((FieldBuilder) fi);
5911 o = fi.GetValue (fi);
5913 if (decl_type.IsSubclassOf (TypeManager.enum_type)) {
5914 if (left_is_explicit && !left_is_type &&
5915 !IdenticalNameAndTypeName (ec, left_original, loc)) {
5916 error176 (loc, fe.FieldInfo.Name);
5920 Expression enum_member = MemberLookup (
5921 ec, decl_type, "value__", MemberTypes.Field,
5922 AllBindingFlags, loc);
5924 Enum en = TypeManager.LookupEnum (decl_type);
5928 c = Constantify (o, en.UnderlyingType);
5930 c = Constantify (o, enum_member.Type);
5932 return new EnumConstant (c, decl_type);
5935 Expression exp = Constantify (o, t);
5937 if (left_is_explicit && !left_is_type) {
5938 error176 (loc, fe.FieldInfo.Name);
5945 if (fi.FieldType.IsPointer && !ec.InUnsafe){
5951 if (member_lookup is EventExpr) {
5953 EventExpr ee = (EventExpr) member_lookup;
5956 // If the event is local to this class, we transform ourselves into
5960 if (ee.EventInfo.DeclaringType == ec.ContainerType) {
5961 MemberInfo mi = GetFieldFromEvent (ee);
5965 // If this happens, then we have an event with its own
5966 // accessors and private field etc so there's no need
5967 // to transform ourselves : we should instead flag an error
5969 Assign.error70 (ee.EventInfo, loc);
5973 Expression ml = ExprClassFromMemberInfo (ec, mi, loc);
5976 Report.Error (-200, loc, "Internal error!!");
5980 return ResolveMemberAccess (ec, ml, left, loc, left_original);
5984 if (member_lookup is IMemberExpr) {
5985 IMemberExpr me = (IMemberExpr) member_lookup;
5988 MethodGroupExpr mg = me as MethodGroupExpr;
5989 if ((mg != null) && left_is_explicit && left.Type.IsInterface)
5990 mg.IsExplicitImpl = left_is_explicit;
5993 if (IdenticalNameAndTypeName (ec, left_original, loc))
5994 return member_lookup;
5996 SimpleName.Error_ObjectRefRequired (ec, loc, me.Name);
6001 if (!me.IsInstance){
6002 if (IdenticalNameAndTypeName (ec, left_original, loc))
6003 return member_lookup;
6005 if (left_is_explicit) {
6006 error176 (loc, me.Name);
6012 // Since we can not check for instance objects in SimpleName,
6013 // becaue of the rule that allows types and variables to share
6014 // the name (as long as they can be de-ambiguated later, see
6015 // IdenticalNameAndTypeName), we have to check whether left
6016 // is an instance variable in a static context
6018 // However, if the left-hand value is explicitly given, then
6019 // it is already our instance expression, so we aren't in
6023 if (ec.IsStatic && !left_is_explicit && left is IMemberExpr){
6024 IMemberExpr mexp = (IMemberExpr) left;
6026 if (!mexp.IsStatic){
6027 SimpleName.Error_ObjectRefRequired (ec, loc, mexp.Name);
6032 me.InstanceExpression = left;
6035 return member_lookup;
6038 if (member_lookup is TypeExpr){
6039 member_lookup.Resolve (ec, ResolveFlags.Type);
6040 return member_lookup;
6043 Console.WriteLine ("Left is: " + left);
6044 Report.Error (-100, loc, "Support for [" + member_lookup + "] is not present yet");
6045 Environment.Exit (0);
6049 public Expression DoResolve (EmitContext ec, Expression right_side, ResolveFlags flags)
6052 throw new Exception ();
6054 // Resolve the expression with flow analysis turned off, we'll do the definite
6055 // assignment checks later. This is because we don't know yet what the expression
6056 // will resolve to - it may resolve to a FieldExpr and in this case we must do the
6057 // definite assignment check on the actual field and not on the whole struct.
6060 Expression original = expr;
6061 expr = expr.Resolve (ec, flags | ResolveFlags.DisableFlowAnalysis);
6066 if (expr is SimpleName){
6067 SimpleName child_expr = (SimpleName) expr;
6069 Expression new_expr = new SimpleName (child_expr.Name, Identifier, loc);
6071 return new_expr.Resolve (ec, flags);
6075 // TODO: I mailed Ravi about this, and apparently we can get rid
6076 // of this and put it in the right place.
6078 // Handle enums here when they are in transit.
6079 // Note that we cannot afford to hit MemberLookup in this case because
6080 // it will fail to find any members at all
6083 int errors = Report.Errors;
6085 Type expr_type = expr.Type;
6086 if ((expr is TypeExpr) && (expr_type.IsSubclassOf (TypeManager.enum_type))){
6088 Enum en = TypeManager.LookupEnum (expr_type);
6091 object value = en.LookupEnumValue (ec, Identifier, loc);
6094 Constant c = Constantify (value, en.UnderlyingType);
6095 return new EnumConstant (c, expr_type);
6100 if (expr_type.IsPointer){
6101 Error (23, "The `.' operator can not be applied to pointer operands (" +
6102 TypeManager.CSharpName (expr_type) + ")");
6106 member_lookup = MemberLookupFinal (ec, expr_type, expr_type, Identifier, loc);
6107 if (member_lookup == null)
6110 if (member_lookup is TypeExpr){
6111 member_lookup.Resolve (ec, ResolveFlags.Type);
6112 return member_lookup;
6113 } else if ((flags & ResolveFlags.MaskExprClass) == ResolveFlags.Type)
6116 member_lookup = ResolveMemberAccess (ec, member_lookup, expr, loc, original);
6117 if (member_lookup == null)
6120 // The following DoResolve/DoResolveLValue will do the definite assignment
6123 if (right_side != null)
6124 member_lookup = member_lookup.DoResolveLValue (ec, right_side);
6126 member_lookup = member_lookup.DoResolve (ec);
6128 return member_lookup;
6131 public override Expression DoResolve (EmitContext ec)
6133 return DoResolve (ec, null, ResolveFlags.VariableOrValue |
6134 ResolveFlags.SimpleName | ResolveFlags.Type);
6137 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
6139 return DoResolve (ec, right_side, ResolveFlags.VariableOrValue |
6140 ResolveFlags.SimpleName | ResolveFlags.Type);
6143 public Expression DoResolveType (EmitContext ec)
6145 return DoResolve (ec, null, ResolveFlags.Type);
6148 public override void Emit (EmitContext ec)
6150 throw new Exception ("Should not happen");
6153 public override string ToString ()
6155 return expr + "." + Identifier;
6160 /// Implements checked expressions
6162 public class CheckedExpr : Expression {
6164 public Expression Expr;
6166 public CheckedExpr (Expression e, Location l)
6172 public override Expression DoResolve (EmitContext ec)
6174 bool last_const_check = ec.ConstantCheckState;
6176 ec.ConstantCheckState = true;
6177 Expr = Expr.Resolve (ec);
6178 ec.ConstantCheckState = last_const_check;
6183 if (Expr is Constant)
6186 eclass = Expr.eclass;
6191 public override void Emit (EmitContext ec)
6193 bool last_check = ec.CheckState;
6194 bool last_const_check = ec.ConstantCheckState;
6196 ec.CheckState = true;
6197 ec.ConstantCheckState = true;
6199 ec.CheckState = last_check;
6200 ec.ConstantCheckState = last_const_check;
6206 /// Implements the unchecked expression
6208 public class UnCheckedExpr : Expression {
6210 public Expression Expr;
6212 public UnCheckedExpr (Expression e, Location l)
6218 public override Expression DoResolve (EmitContext ec)
6220 bool last_const_check = ec.ConstantCheckState;
6222 ec.ConstantCheckState = false;
6223 Expr = Expr.Resolve (ec);
6224 ec.ConstantCheckState = last_const_check;
6229 if (Expr is Constant)
6232 eclass = Expr.eclass;
6237 public override void Emit (EmitContext ec)
6239 bool last_check = ec.CheckState;
6240 bool last_const_check = ec.ConstantCheckState;
6242 ec.CheckState = false;
6243 ec.ConstantCheckState = false;
6245 ec.CheckState = last_check;
6246 ec.ConstantCheckState = last_const_check;
6252 /// An Element Access expression.
6254 /// During semantic analysis these are transformed into
6255 /// IndexerAccess or ArrayAccess
6257 public class ElementAccess : Expression {
6258 public ArrayList Arguments;
6259 public Expression Expr;
6261 public ElementAccess (Expression e, ArrayList e_list, Location l)
6270 Arguments = new ArrayList ();
6271 foreach (Expression tmp in e_list)
6272 Arguments.Add (new Argument (tmp, Argument.AType.Expression));
6276 bool CommonResolve (EmitContext ec)
6278 Expr = Expr.Resolve (ec);
6283 if (Arguments == null)
6286 foreach (Argument a in Arguments){
6287 if (!a.Resolve (ec, loc))
6294 Expression MakePointerAccess ()
6298 if (t == TypeManager.void_ptr_type){
6301 "The array index operation is not valid for void pointers");
6304 if (Arguments.Count != 1){
6307 "A pointer must be indexed by a single value");
6310 Expression p = new PointerArithmetic (true, Expr, ((Argument)Arguments [0]).Expr,
6312 return new Indirection (p, loc);
6315 public override Expression DoResolve (EmitContext ec)
6317 if (!CommonResolve (ec))
6321 // We perform some simple tests, and then to "split" the emit and store
6322 // code we create an instance of a different class, and return that.
6324 // I am experimenting with this pattern.
6329 return (new ArrayAccess (this, loc)).Resolve (ec);
6330 else if (t.IsPointer)
6331 return MakePointerAccess ();
6333 return (new IndexerAccess (this, loc)).Resolve (ec);
6336 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
6338 if (!CommonResolve (ec))
6343 return (new ArrayAccess (this, loc)).ResolveLValue (ec, right_side);
6344 else if (t.IsPointer)
6345 return MakePointerAccess ();
6347 return (new IndexerAccess (this, loc)).ResolveLValue (ec, right_side);
6350 public override void Emit (EmitContext ec)
6352 throw new Exception ("Should never be reached");
6357 /// Implements array access
6359 public class ArrayAccess : Expression, IAssignMethod, IMemoryLocation {
6361 // Points to our "data" repository
6365 LocalTemporary [] cached_locations;
6367 public ArrayAccess (ElementAccess ea_data, Location l)
6370 eclass = ExprClass.Variable;
6374 public override Expression DoResolve (EmitContext ec)
6376 ExprClass eclass = ea.Expr.eclass;
6379 // As long as the type is valid
6380 if (!(eclass == ExprClass.Variable || eclass == ExprClass.PropertyAccess ||
6381 eclass == ExprClass.Value)) {
6382 ea.Expr.Error118 ("variable or value");
6387 Type t = ea.Expr.Type;
6388 if (t.GetArrayRank () != ea.Arguments.Count){
6390 "Incorrect number of indexes for array " +
6391 " expected: " + t.GetArrayRank () + " got: " +
6392 ea.Arguments.Count);
6395 type = TypeManager.TypeToCoreType (t.GetElementType ());
6396 if (type.IsPointer && !ec.InUnsafe){
6397 UnsafeError (ea.Location);
6401 foreach (Argument a in ea.Arguments){
6402 Type argtype = a.Type;
6404 if (argtype == TypeManager.int32_type ||
6405 argtype == TypeManager.uint32_type ||
6406 argtype == TypeManager.int64_type ||
6407 argtype == TypeManager.uint64_type)
6411 // Mhm. This is strage, because the Argument.Type is not the same as
6412 // Argument.Expr.Type: the value changes depending on the ref/out setting.
6414 // Wonder if I will run into trouble for this.
6416 a.Expr = ExpressionToArrayArgument (ec, a.Expr, ea.Location);
6421 eclass = ExprClass.Variable;
6427 /// Emits the right opcode to load an object of Type `t'
6428 /// from an array of T
6430 static public void EmitLoadOpcode (ILGenerator ig, Type type)
6432 if (type == TypeManager.byte_type || type == TypeManager.bool_type)
6433 ig.Emit (OpCodes.Ldelem_U1);
6434 else if (type == TypeManager.sbyte_type)
6435 ig.Emit (OpCodes.Ldelem_I1);
6436 else if (type == TypeManager.short_type)
6437 ig.Emit (OpCodes.Ldelem_I2);
6438 else if (type == TypeManager.ushort_type || type == TypeManager.char_type)
6439 ig.Emit (OpCodes.Ldelem_U2);
6440 else if (type == TypeManager.int32_type)
6441 ig.Emit (OpCodes.Ldelem_I4);
6442 else if (type == TypeManager.uint32_type)
6443 ig.Emit (OpCodes.Ldelem_U4);
6444 else if (type == TypeManager.uint64_type)
6445 ig.Emit (OpCodes.Ldelem_I8);
6446 else if (type == TypeManager.int64_type)
6447 ig.Emit (OpCodes.Ldelem_I8);
6448 else if (type == TypeManager.float_type)
6449 ig.Emit (OpCodes.Ldelem_R4);
6450 else if (type == TypeManager.double_type)
6451 ig.Emit (OpCodes.Ldelem_R8);
6452 else if (type == TypeManager.intptr_type)
6453 ig.Emit (OpCodes.Ldelem_I);
6454 else if (type.IsValueType){
6455 ig.Emit (OpCodes.Ldelema, type);
6456 ig.Emit (OpCodes.Ldobj, type);
6458 ig.Emit (OpCodes.Ldelem_Ref);
6462 /// Emits the right opcode to store an object of Type `t'
6463 /// from an array of T.
6465 static public void EmitStoreOpcode (ILGenerator ig, Type t)
6468 OpCode op = GetStoreOpcode (t, out is_stobj);
6470 ig.Emit (OpCodes.Stobj, t);
6476 /// Returns the right opcode to store an object of Type `t'
6477 /// from an array of T.
6479 static public OpCode GetStoreOpcode (Type t, out bool is_stobj)
6482 t = TypeManager.TypeToCoreType (t);
6483 if (TypeManager.IsEnumType (t) && t != TypeManager.enum_type)
6484 t = TypeManager.EnumToUnderlying (t);
6485 if (t == TypeManager.byte_type || t == TypeManager.sbyte_type ||
6486 t == TypeManager.bool_type)
6487 return OpCodes.Stelem_I1;
6488 else if (t == TypeManager.short_type || t == TypeManager.ushort_type ||
6489 t == TypeManager.char_type)
6490 return OpCodes.Stelem_I2;
6491 else if (t == TypeManager.int32_type || t == TypeManager.uint32_type)
6492 return OpCodes.Stelem_I4;
6493 else if (t == TypeManager.int64_type || t == TypeManager.uint64_type)
6494 return OpCodes.Stelem_I8;
6495 else if (t == TypeManager.float_type)
6496 return OpCodes.Stelem_R4;
6497 else if (t == TypeManager.double_type)
6498 return OpCodes.Stelem_R8;
6499 else if (t == TypeManager.intptr_type)
6500 return OpCodes.Stelem_I;
6501 else if (t.IsValueType) {
6503 return OpCodes.Stobj;
6505 return OpCodes.Stelem_Ref;
6508 MethodInfo FetchGetMethod ()
6510 ModuleBuilder mb = CodeGen.ModuleBuilder;
6511 int arg_count = ea.Arguments.Count;
6512 Type [] args = new Type [arg_count];
6515 for (int i = 0; i < arg_count; i++){
6516 //args [i++] = a.Type;
6517 args [i] = TypeManager.int32_type;
6520 get = mb.GetArrayMethod (
6521 ea.Expr.Type, "Get",
6522 CallingConventions.HasThis |
6523 CallingConventions.Standard,
6529 MethodInfo FetchAddressMethod ()
6531 ModuleBuilder mb = CodeGen.ModuleBuilder;
6532 int arg_count = ea.Arguments.Count;
6533 Type [] args = new Type [arg_count];
6535 string ptr_type_name;
6538 ptr_type_name = type.FullName + "&";
6539 ret_type = Type.GetType (ptr_type_name);
6542 // It is a type defined by the source code we are compiling
6544 if (ret_type == null){
6545 ret_type = mb.GetType (ptr_type_name);
6548 for (int i = 0; i < arg_count; i++){
6549 //args [i++] = a.Type;
6550 args [i] = TypeManager.int32_type;
6553 address = mb.GetArrayMethod (
6554 ea.Expr.Type, "Address",
6555 CallingConventions.HasThis |
6556 CallingConventions.Standard,
6563 // Load the array arguments into the stack.
6565 // If we have been requested to cache the values (cached_locations array
6566 // initialized), then load the arguments the first time and store them
6567 // in locals. otherwise load from local variables.
6569 void LoadArrayAndArguments (EmitContext ec)
6571 ILGenerator ig = ec.ig;
6573 if (cached_locations == null){
6575 foreach (Argument a in ea.Arguments){
6576 Type argtype = a.Expr.Type;
6580 if (argtype == TypeManager.int64_type)
6581 ig.Emit (OpCodes.Conv_Ovf_I);
6582 else if (argtype == TypeManager.uint64_type)
6583 ig.Emit (OpCodes.Conv_Ovf_I_Un);
6588 if (cached_locations [0] == null){
6589 cached_locations [0] = new LocalTemporary (ec, ea.Expr.Type);
6591 ig.Emit (OpCodes.Dup);
6592 cached_locations [0].Store (ec);
6596 foreach (Argument a in ea.Arguments){
6597 Type argtype = a.Expr.Type;
6599 cached_locations [j] = new LocalTemporary (ec, TypeManager.intptr_type /* a.Expr.Type */);
6601 if (argtype == TypeManager.int64_type)
6602 ig.Emit (OpCodes.Conv_Ovf_I);
6603 else if (argtype == TypeManager.uint64_type)
6604 ig.Emit (OpCodes.Conv_Ovf_I_Un);
6606 ig.Emit (OpCodes.Dup);
6607 cached_locations [j].Store (ec);
6613 foreach (LocalTemporary lt in cached_locations)
6617 public new void CacheTemporaries (EmitContext ec)
6619 cached_locations = new LocalTemporary [ea.Arguments.Count + 1];
6622 public override void Emit (EmitContext ec)
6624 int rank = ea.Expr.Type.GetArrayRank ();
6625 ILGenerator ig = ec.ig;
6627 LoadArrayAndArguments (ec);
6630 EmitLoadOpcode (ig, type);
6634 method = FetchGetMethod ();
6635 ig.Emit (OpCodes.Call, method);
6639 public void EmitAssign (EmitContext ec, Expression source)
6641 int rank = ea.Expr.Type.GetArrayRank ();
6642 ILGenerator ig = ec.ig;
6643 Type t = source.Type;
6645 LoadArrayAndArguments (ec);
6648 // The stobj opcode used by value types will need
6649 // an address on the stack, not really an array/array
6653 if (t == TypeManager.enum_type || t == TypeManager.decimal_type ||
6654 (t.IsSubclassOf (TypeManager.value_type) && !TypeManager.IsEnumType (t) && !TypeManager.IsBuiltinType (t)))
6655 ig.Emit (OpCodes.Ldelema, t);
6661 EmitStoreOpcode (ig, t);
6663 ModuleBuilder mb = CodeGen.ModuleBuilder;
6664 int arg_count = ea.Arguments.Count;
6665 Type [] args = new Type [arg_count + 1];
6668 for (int i = 0; i < arg_count; i++){
6669 //args [i++] = a.Type;
6670 args [i] = TypeManager.int32_type;
6673 args [arg_count] = type;
6675 set = mb.GetArrayMethod (
6676 ea.Expr.Type, "Set",
6677 CallingConventions.HasThis |
6678 CallingConventions.Standard,
6679 TypeManager.void_type, args);
6681 ig.Emit (OpCodes.Call, set);
6685 public void AddressOf (EmitContext ec, AddressOp mode)
6687 int rank = ea.Expr.Type.GetArrayRank ();
6688 ILGenerator ig = ec.ig;
6690 LoadArrayAndArguments (ec);
6693 ig.Emit (OpCodes.Ldelema, type);
6695 MethodInfo address = FetchAddressMethod ();
6696 ig.Emit (OpCodes.Call, address);
6703 public ArrayList getters, setters;
6704 static Hashtable map;
6708 map = new Hashtable ();
6711 Indexers (MemberInfo [] mi)
6713 foreach (PropertyInfo property in mi){
6714 MethodInfo get, set;
6716 get = property.GetGetMethod (true);
6718 if (getters == null)
6719 getters = new ArrayList ();
6724 set = property.GetSetMethod (true);
6726 if (setters == null)
6727 setters = new ArrayList ();
6733 static private Indexers GetIndexersForTypeOrInterface (Type caller_type, Type lookup_type)
6735 Indexers ix = (Indexers) map [lookup_type];
6740 string p_name = TypeManager.IndexerPropertyName (lookup_type);
6742 MemberInfo [] mi = TypeManager.MemberLookup (
6743 caller_type, caller_type, lookup_type, MemberTypes.Property,
6744 BindingFlags.Public | BindingFlags.Instance |
6745 BindingFlags.DeclaredOnly, p_name);
6747 if (mi == null || mi.Length == 0)
6750 ix = new Indexers (mi);
6751 map [lookup_type] = ix;
6756 static public Indexers GetIndexersForType (Type caller_type, Type lookup_type, Location loc)
6758 Indexers ix = (Indexers) map [lookup_type];
6763 ix = GetIndexersForTypeOrInterface (caller_type, lookup_type);
6767 Type [] ifaces = TypeManager.GetInterfaces (lookup_type);
6768 if (ifaces != null) {
6769 foreach (Type itype in ifaces) {
6770 ix = GetIndexersForTypeOrInterface (caller_type, itype);
6781 /// Expressions that represent an indexer call.
6783 public class IndexerAccess : Expression, IAssignMethod {
6785 // Points to our "data" repository
6787 MethodInfo get, set;
6789 ArrayList set_arguments;
6790 bool is_base_indexer;
6792 protected Type indexer_type;
6793 protected Type current_type;
6794 protected Expression instance_expr;
6795 protected ArrayList arguments;
6797 public IndexerAccess (ElementAccess ea, Location loc)
6798 : this (ea.Expr, false, loc)
6800 this.arguments = ea.Arguments;
6803 protected IndexerAccess (Expression instance_expr, bool is_base_indexer,
6806 this.instance_expr = instance_expr;
6807 this.is_base_indexer = is_base_indexer;
6808 this.eclass = ExprClass.Value;
6812 protected virtual bool CommonResolve (EmitContext ec)
6814 indexer_type = instance_expr.Type;
6815 current_type = ec.ContainerType;
6820 public override Expression DoResolve (EmitContext ec)
6822 if (!CommonResolve (ec))
6826 // Step 1: Query for all `Item' *properties*. Notice
6827 // that the actual methods are pointed from here.
6829 // This is a group of properties, piles of them.
6831 bool found_any = false, found_any_getters = false;
6832 Type lookup_type = indexer_type;
6833 while (lookup_type != null) {
6834 ilist = Indexers.GetIndexersForType (current_type, lookup_type, loc);
6836 if (ilist == null) {
6837 lookup_type = lookup_type.BaseType;
6844 // Step 2: find the proper match
6846 if (ilist.getters != null && ilist.getters.Count > 0) {
6847 found_any_getters = true;
6848 get = (MethodInfo) Invocation.OverloadResolve (
6849 ec, new MethodGroupExpr (ilist.getters, loc), arguments, loc);
6855 lookup_type = lookup_type.BaseType;
6859 Report.Error (21, loc,
6860 "Type `" + TypeManager.CSharpName (indexer_type) +
6861 "' does not have any indexers defined");
6865 if (!found_any_getters) {
6866 Error (154, "indexer can not be used in this context, because " +
6867 "it lacks a `get' accessor");
6872 Error (1501, "No Overload for method `this' takes `" +
6873 arguments.Count + "' arguments");
6878 // Only base will allow this invocation to happen.
6880 if (get.IsAbstract && this is BaseIndexerAccess){
6881 Report.Error (205, loc, "Cannot call an abstract base indexer: " + Invocation.FullMethodDesc (get));
6885 type = get.ReturnType;
6886 if (type.IsPointer && !ec.InUnsafe){
6891 eclass = ExprClass.IndexerAccess;
6895 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
6897 if (!CommonResolve (ec))
6900 Type right_type = right_side.Type;
6902 bool found_any = false, found_any_setters = false;
6903 Type lookup_type = indexer_type;
6904 while (lookup_type != null) {
6905 ilist = Indexers.GetIndexersForType (current_type, lookup_type, loc);
6907 if (ilist == null) {
6908 lookup_type = lookup_type.BaseType;
6914 if (ilist.setters != null && ilist.setters.Count > 0) {
6915 found_any_setters = true;
6917 set_arguments = (ArrayList) arguments.Clone ();
6918 set_arguments.Add (new Argument (right_side, Argument.AType.Expression));
6919 set = (MethodInfo) Invocation.OverloadResolve (
6920 ec, new MethodGroupExpr (ilist.setters, loc), set_arguments, loc);
6927 lookup_type = lookup_type.BaseType;
6931 Report.Error (21, loc,
6932 "Type `" + TypeManager.CSharpName (indexer_type) +
6933 "' does not have any indexers defined");
6937 if (!found_any_setters) {
6938 Error (154, "indexer can not be used in this context, because " +
6939 "it lacks a `set' accessor");
6944 Error (1501, "No Overload for method `this' takes `" +
6945 arguments.Count + "' arguments");
6950 // Only base will allow this invocation to happen.
6952 if (set.IsAbstract && this is BaseIndexerAccess){
6953 Report.Error (205, loc, "Cannot call an abstract base indexer: " + Invocation.FullMethodDesc (set));
6956 type = TypeManager.void_type;
6957 eclass = ExprClass.IndexerAccess;
6961 public override void Emit (EmitContext ec)
6963 Invocation.EmitCall (ec, false, false, instance_expr, get, arguments, loc);
6967 // source is ignored, because we already have a copy of it from the
6968 // LValue resolution and we have already constructed a pre-cached
6969 // version of the arguments (ea.set_arguments);
6971 public void EmitAssign (EmitContext ec, Expression source)
6973 Invocation.EmitCall (ec, false, false, instance_expr, set, set_arguments, loc);
6978 /// The base operator for method names
6980 public class BaseAccess : Expression {
6983 public BaseAccess (string member, Location l)
6985 this.member = member;
6989 public override Expression DoResolve (EmitContext ec)
6991 Expression c = CommonResolve (ec);
6997 // MethodGroups use this opportunity to flag an error on lacking ()
6999 if (!(c is MethodGroupExpr))
7000 return c.Resolve (ec);
7004 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
7006 Expression c = CommonResolve (ec);
7012 // MethodGroups use this opportunity to flag an error on lacking ()
7014 if (! (c is MethodGroupExpr))
7015 return c.DoResolveLValue (ec, right_side);
7020 Expression CommonResolve (EmitContext ec)
7022 Expression member_lookup;
7023 Type current_type = ec.ContainerType;
7024 Type base_type = current_type.BaseType;
7028 Error (1511, "Keyword base is not allowed in static method");
7032 member_lookup = MemberLookup (ec, ec.ContainerType, null, base_type, member,
7033 AllMemberTypes, AllBindingFlags, loc);
7034 if (member_lookup == null) {
7035 MemberLookupFailed (ec, base_type, base_type, member, null, loc);
7042 left = new TypeExpr (base_type, loc);
7046 e = MemberAccess.ResolveMemberAccess (ec, member_lookup, left, loc, null);
7048 if (e is PropertyExpr){
7049 PropertyExpr pe = (PropertyExpr) e;
7057 public override void Emit (EmitContext ec)
7059 throw new Exception ("Should never be called");
7064 /// The base indexer operator
7066 public class BaseIndexerAccess : IndexerAccess {
7067 public BaseIndexerAccess (ArrayList args, Location loc)
7068 : base (null, true, loc)
7070 arguments = new ArrayList ();
7071 foreach (Expression tmp in args)
7072 arguments.Add (new Argument (tmp, Argument.AType.Expression));
7075 protected override bool CommonResolve (EmitContext ec)
7077 instance_expr = ec.This;
7079 current_type = ec.ContainerType.BaseType;
7080 indexer_type = current_type;
7082 foreach (Argument a in arguments){
7083 if (!a.Resolve (ec, loc))
7092 /// This class exists solely to pass the Type around and to be a dummy
7093 /// that can be passed to the conversion functions (this is used by
7094 /// foreach implementation to typecast the object return value from
7095 /// get_Current into the proper type. All code has been generated and
7096 /// we only care about the side effect conversions to be performed
7098 /// This is also now used as a placeholder where a no-action expression
7099 /// is needed (the `New' class).
7101 public class EmptyExpression : Expression {
7102 public EmptyExpression ()
7104 type = TypeManager.object_type;
7105 eclass = ExprClass.Value;
7106 loc = Location.Null;
7109 public EmptyExpression (Type t)
7112 eclass = ExprClass.Value;
7113 loc = Location.Null;
7116 public override Expression DoResolve (EmitContext ec)
7121 public override void Emit (EmitContext ec)
7123 // nothing, as we only exist to not do anything.
7127 // This is just because we might want to reuse this bad boy
7128 // instead of creating gazillions of EmptyExpressions.
7129 // (CanConvertImplicit uses it)
7131 public void SetType (Type t)
7137 public class UserCast : Expression {
7141 public UserCast (MethodInfo method, Expression source, Location l)
7143 this.method = method;
7144 this.source = source;
7145 type = method.ReturnType;
7146 eclass = ExprClass.Value;
7150 public override Expression DoResolve (EmitContext ec)
7153 // We are born fully resolved
7158 public override void Emit (EmitContext ec)
7160 ILGenerator ig = ec.ig;
7164 if (method is MethodInfo)
7165 ig.Emit (OpCodes.Call, (MethodInfo) method);
7167 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
7173 // This class is used to "construct" the type during a typecast
7174 // operation. Since the Type.GetType class in .NET can parse
7175 // the type specification, we just use this to construct the type
7176 // one bit at a time.
7178 public class ComposedCast : Expression, ITypeExpression {
7182 public ComposedCast (Expression left, string dim, Location l)
7189 public Expression DoResolveType (EmitContext ec)
7191 Type ltype = ec.DeclSpace.ResolveType (left, false, loc);
7196 // ltype.Fullname is already fully qualified, so we can skip
7197 // a lot of probes, and go directly to TypeManager.LookupType
7199 string cname = ltype.FullName + dim;
7200 type = TypeManager.LookupTypeDirect (cname);
7203 // For arrays of enumerations we are having a problem
7204 // with the direct lookup. Need to investigate.
7206 // For now, fall back to the full lookup in that case.
7208 type = RootContext.LookupType (
7209 ec.DeclSpace, cname, false, loc);
7215 if (!ec.ResolvingTypeTree){
7217 // If the above flag is set, this is being invoked from the ResolveType function.
7218 // Upper layers take care of the type validity in this context.
7220 if (!ec.InUnsafe && type.IsPointer){
7226 eclass = ExprClass.Type;
7230 public override Expression DoResolve (EmitContext ec)
7232 return DoResolveType (ec);
7235 public override void Emit (EmitContext ec)
7237 throw new Exception ("This should never be called");
7240 public override string ToString ()
7247 // This class is used to represent the address of an array, used
7248 // only by the Fixed statement, this is like the C "&a [0]" construct.
7250 public class ArrayPtr : Expression {
7253 public ArrayPtr (Expression array, Location l)
7255 Type array_type = array.Type.GetElementType ();
7259 string array_ptr_type_name = array_type.FullName + "*";
7261 type = Type.GetType (array_ptr_type_name);
7263 ModuleBuilder mb = CodeGen.ModuleBuilder;
7265 type = mb.GetType (array_ptr_type_name);
7268 eclass = ExprClass.Value;
7272 public override void Emit (EmitContext ec)
7274 ILGenerator ig = ec.ig;
7277 IntLiteral.EmitInt (ig, 0);
7278 ig.Emit (OpCodes.Ldelema, array.Type.GetElementType ());
7281 public override Expression DoResolve (EmitContext ec)
7284 // We are born fully resolved
7291 // Used by the fixed statement
7293 public class StringPtr : Expression {
7296 public StringPtr (LocalBuilder b, Location l)
7299 eclass = ExprClass.Value;
7300 type = TypeManager.char_ptr_type;
7304 public override Expression DoResolve (EmitContext ec)
7306 // This should never be invoked, we are born in fully
7307 // initialized state.
7312 public override void Emit (EmitContext ec)
7314 ILGenerator ig = ec.ig;
7316 ig.Emit (OpCodes.Ldloc, b);
7317 ig.Emit (OpCodes.Conv_I);
7318 ig.Emit (OpCodes.Call, TypeManager.int_get_offset_to_string_data);
7319 ig.Emit (OpCodes.Add);
7324 // Implements the `stackalloc' keyword
7326 public class StackAlloc : Expression {
7331 public StackAlloc (Expression type, Expression count, Location l)
7338 public override Expression DoResolve (EmitContext ec)
7340 count = count.Resolve (ec);
7344 if (count.Type != TypeManager.int32_type){
7345 count = ConvertImplicitRequired (ec, count, TypeManager.int32_type, loc);
7350 if (ec.InCatch || ec.InFinally){
7352 "stackalloc can not be used in a catch or finally block");
7356 otype = ec.DeclSpace.ResolveType (t, false, loc);
7361 if (!TypeManager.VerifyUnManaged (otype, loc))
7364 string ptr_name = otype.FullName + "*";
7365 type = Type.GetType (ptr_name);
7367 ModuleBuilder mb = CodeGen.ModuleBuilder;
7369 type = mb.GetType (ptr_name);
7371 eclass = ExprClass.Value;
7376 public override void Emit (EmitContext ec)
7378 int size = GetTypeSize (otype);
7379 ILGenerator ig = ec.ig;
7382 ig.Emit (OpCodes.Sizeof, otype);
7384 IntConstant.EmitInt (ig, size);
7386 ig.Emit (OpCodes.Mul);
7387 ig.Emit (OpCodes.Localloc);