2 // expression.cs: Expression representation for the IL tree.
5 // Miguel de Icaza (miguel@ximian.com)
7 // (C) 2001, 2002, 2003 Ximian, Inc.
8 // (C) 2003, 2004 Novell, Inc.
12 namespace Mono.CSharp {
14 using System.Collections;
15 using System.Reflection;
16 using System.Reflection.Emit;
20 /// This is just a helper class, it is generated by Unary, UnaryMutator
21 /// when an overloaded method has been found. It just emits the code for a
24 public class StaticCallExpr : ExpressionStatement {
28 public StaticCallExpr (MethodInfo m, ArrayList a, Location l)
34 eclass = ExprClass.Value;
38 public override Expression DoResolve (EmitContext ec)
41 // We are born fully resolved
46 public override void Emit (EmitContext ec)
49 Invocation.EmitArguments (ec, mi, args);
51 ec.ig.Emit (OpCodes.Call, mi);
55 static public Expression MakeSimpleCall (EmitContext ec, MethodGroupExpr mg,
56 Expression e, Location loc)
61 args = new ArrayList (1);
62 Argument a = new Argument (e, Argument.AType.Expression);
64 // We need to resolve the arguments before sending them in !
65 if (!a.Resolve (ec, loc))
69 method = Invocation.OverloadResolve (ec, (MethodGroupExpr) mg, args, loc);
74 return new StaticCallExpr ((MethodInfo) method, args, loc);
77 public override void EmitStatement (EmitContext ec)
80 if (TypeManager.TypeToCoreType (type) != TypeManager.void_type)
81 ec.ig.Emit (OpCodes.Pop);
85 public class ParenthesizedExpression : Expression
87 public Expression Expr;
89 public ParenthesizedExpression (Expression expr, Location loc)
95 public override Expression DoResolve (EmitContext ec)
97 Expr = Expr.Resolve (ec);
101 public override void Emit (EmitContext ec)
103 throw new Exception ("Should not happen");
108 /// Unary expressions.
112 /// Unary implements unary expressions. It derives from
113 /// ExpressionStatement becuase the pre/post increment/decrement
114 /// operators can be used in a statement context.
116 public class Unary : Expression {
117 public enum Operator : byte {
118 UnaryPlus, UnaryNegation, LogicalNot, OnesComplement,
119 Indirection, AddressOf, TOP
122 public Operator Oper;
123 public Expression Expr;
125 public Unary (Operator op, Expression expr, Location loc)
133 /// Returns a stringified representation of the Operator
135 static public string OperName (Operator oper)
138 case Operator.UnaryPlus:
140 case Operator.UnaryNegation:
142 case Operator.LogicalNot:
144 case Operator.OnesComplement:
146 case Operator.AddressOf:
148 case Operator.Indirection:
152 return oper.ToString ();
155 public static readonly string [] oper_names;
159 oper_names = new string [(int)Operator.TOP];
161 oper_names [(int) Operator.UnaryPlus] = "op_UnaryPlus";
162 oper_names [(int) Operator.UnaryNegation] = "op_UnaryNegation";
163 oper_names [(int) Operator.LogicalNot] = "op_LogicalNot";
164 oper_names [(int) Operator.OnesComplement] = "op_OnesComplement";
165 oper_names [(int) Operator.Indirection] = "op_Indirection";
166 oper_names [(int) Operator.AddressOf] = "op_AddressOf";
169 void Error23 (Type t)
172 23, "Operator " + OperName (Oper) +
173 " cannot be applied to operand of type `" +
174 TypeManager.CSharpName (t) + "'");
178 /// The result has been already resolved:
180 /// FIXME: a minus constant -128 sbyte cant be turned into a
183 static Expression TryReduceNegative (Constant expr)
187 if (expr is IntConstant)
188 e = new IntConstant (-((IntConstant) expr).Value);
189 else if (expr is UIntConstant){
190 uint value = ((UIntConstant) expr).Value;
192 if (value < 2147483649)
193 return new IntConstant (-(int)value);
195 e = new LongConstant (-value);
197 else if (expr is LongConstant)
198 e = new LongConstant (-((LongConstant) expr).Value);
199 else if (expr is ULongConstant){
200 ulong value = ((ULongConstant) expr).Value;
202 if (value < 9223372036854775809)
203 return new LongConstant(-(long)value);
205 else if (expr is FloatConstant)
206 e = new FloatConstant (-((FloatConstant) expr).Value);
207 else if (expr is DoubleConstant)
208 e = new DoubleConstant (-((DoubleConstant) expr).Value);
209 else if (expr is DecimalConstant)
210 e = new DecimalConstant (-((DecimalConstant) expr).Value);
211 else if (expr is ShortConstant)
212 e = new IntConstant (-((ShortConstant) expr).Value);
213 else if (expr is UShortConstant)
214 e = new IntConstant (-((UShortConstant) expr).Value);
219 // This routine will attempt to simplify the unary expression when the
220 // argument is a constant. The result is returned in `result' and the
221 // function returns true or false depending on whether a reduction
222 // was performed or not
224 bool Reduce (EmitContext ec, Constant e, out Expression result)
226 Type expr_type = e.Type;
229 case Operator.UnaryPlus:
233 case Operator.UnaryNegation:
234 result = TryReduceNegative (e);
237 case Operator.LogicalNot:
238 if (expr_type != TypeManager.bool_type) {
244 BoolConstant b = (BoolConstant) e;
245 result = new BoolConstant (!(b.Value));
248 case Operator.OnesComplement:
249 if (!((expr_type == TypeManager.int32_type) ||
250 (expr_type == TypeManager.uint32_type) ||
251 (expr_type == TypeManager.int64_type) ||
252 (expr_type == TypeManager.uint64_type) ||
253 (expr_type.IsSubclassOf (TypeManager.enum_type)))){
256 if (Convert.ImplicitConversionExists (ec, e, TypeManager.int32_type)){
257 result = new Cast (new TypeExpression (TypeManager.int32_type, loc), e, loc);
258 result = result.Resolve (ec);
259 } else if (Convert.ImplicitConversionExists (ec, e, TypeManager.uint32_type)){
260 result = new Cast (new TypeExpression (TypeManager.uint32_type, loc), e, loc);
261 result = result.Resolve (ec);
262 } else if (Convert.ImplicitConversionExists (ec, e, TypeManager.int64_type)){
263 result = new Cast (new TypeExpression (TypeManager.int64_type, loc), e, loc);
264 result = result.Resolve (ec);
265 } else if (Convert.ImplicitConversionExists (ec, e, TypeManager.uint64_type)){
266 result = new Cast (new TypeExpression (TypeManager.uint64_type, loc), e, loc);
267 result = result.Resolve (ec);
270 if (result == null || !(result is Constant)){
276 expr_type = result.Type;
277 e = (Constant) result;
280 if (e is EnumConstant){
281 EnumConstant enum_constant = (EnumConstant) e;
284 if (Reduce (ec, enum_constant.Child, out reduced)){
285 result = new EnumConstant ((Constant) reduced, enum_constant.Type);
293 if (expr_type == TypeManager.int32_type){
294 result = new IntConstant (~ ((IntConstant) e).Value);
295 } else if (expr_type == TypeManager.uint32_type){
296 result = new UIntConstant (~ ((UIntConstant) e).Value);
297 } else if (expr_type == TypeManager.int64_type){
298 result = new LongConstant (~ ((LongConstant) e).Value);
299 } else if (expr_type == TypeManager.uint64_type){
300 result = new ULongConstant (~ ((ULongConstant) e).Value);
308 case Operator.AddressOf:
312 case Operator.Indirection:
316 throw new Exception ("Can not constant fold: " + Oper.ToString());
319 Expression ResolveOperator (EmitContext ec)
321 Type expr_type = Expr.Type;
324 // Step 1: Perform Operator Overload location
329 op_name = oper_names [(int) Oper];
331 mg = MemberLookup (ec, expr_type, op_name, MemberTypes.Method, AllBindingFlags, loc);
334 Expression e = StaticCallExpr.MakeSimpleCall (
335 ec, (MethodGroupExpr) mg, Expr, loc);
345 // Only perform numeric promotions on:
348 if (expr_type == null)
352 // Step 2: Default operations on CLI native types.
355 // Attempt to use a constant folding operation.
356 if (Expr is Constant){
359 if (Reduce (ec, (Constant) Expr, out result))
364 case Operator.LogicalNot:
365 if (expr_type != TypeManager.bool_type) {
366 Expr = ResolveBoolean (ec, Expr, loc);
373 type = TypeManager.bool_type;
376 case Operator.OnesComplement:
377 if (!((expr_type == TypeManager.int32_type) ||
378 (expr_type == TypeManager.uint32_type) ||
379 (expr_type == TypeManager.int64_type) ||
380 (expr_type == TypeManager.uint64_type) ||
381 (expr_type.IsSubclassOf (TypeManager.enum_type)))){
384 e = Convert.ImplicitConversion (ec, Expr, TypeManager.int32_type, loc);
386 type = TypeManager.int32_type;
389 e = Convert.ImplicitConversion (ec, Expr, TypeManager.uint32_type, loc);
391 type = TypeManager.uint32_type;
394 e = Convert.ImplicitConversion (ec, Expr, TypeManager.int64_type, loc);
396 type = TypeManager.int64_type;
399 e = Convert.ImplicitConversion (ec, Expr, TypeManager.uint64_type, loc);
401 type = TypeManager.uint64_type;
410 case Operator.AddressOf:
411 if (Expr.eclass != ExprClass.Variable){
412 Error (211, "Cannot take the address of non-variables");
421 if (!TypeManager.VerifyUnManaged (Expr.Type, loc)){
425 IVariable variable = Expr as IVariable;
426 if (!ec.InFixedInitializer && ((variable == null) || !variable.VerifyFixed (false))) {
427 Error (212, "You can only take the address of an unfixed expression inside " +
428 "of a fixed statement initializer");
432 // According to the specs, a variable is considered definitely assigned if you take
434 if ((variable != null) && (variable.VariableInfo != null))
435 variable.VariableInfo.SetAssigned (ec);
437 type = TypeManager.GetPointerType (Expr.Type);
440 case Operator.Indirection:
446 if (!expr_type.IsPointer){
447 Error (193, "The * or -> operator can only be applied to pointers");
452 // We create an Indirection expression, because
453 // it can implement the IMemoryLocation.
455 return new Indirection (Expr, loc);
457 case Operator.UnaryPlus:
459 // A plus in front of something is just a no-op, so return the child.
463 case Operator.UnaryNegation:
465 // Deals with -literals
466 // int operator- (int x)
467 // long operator- (long x)
468 // float operator- (float f)
469 // double operator- (double d)
470 // decimal operator- (decimal d)
472 Expression expr = null;
475 // transform - - expr into expr
478 Unary unary = (Unary) Expr;
480 if (unary.Oper == Operator.UnaryNegation)
485 // perform numeric promotions to int,
489 // The following is inneficient, because we call
490 // ImplicitConversion too many times.
492 // It is also not clear if we should convert to Float
493 // or Double initially.
495 if (expr_type == TypeManager.uint32_type){
497 // FIXME: handle exception to this rule that
498 // permits the int value -2147483648 (-2^31) to
499 // bt wrote as a decimal interger literal
501 type = TypeManager.int64_type;
502 Expr = Convert.ImplicitConversion (ec, Expr, type, loc);
506 if (expr_type == TypeManager.uint64_type){
508 // FIXME: Handle exception of `long value'
509 // -92233720368547758087 (-2^63) to be wrote as
510 // decimal integer literal.
516 if (expr_type == TypeManager.float_type){
521 expr = Convert.ImplicitConversion (ec, Expr, TypeManager.int32_type, loc);
528 expr = Convert.ImplicitConversion (ec, Expr, TypeManager.int64_type, loc);
535 expr = Convert.ImplicitConversion (ec, Expr, TypeManager.double_type, loc);
546 Error (187, "No such operator '" + OperName (Oper) + "' defined for type '" +
547 TypeManager.CSharpName (expr_type) + "'");
551 public override Expression DoResolve (EmitContext ec)
553 if (Oper == Operator.AddressOf)
554 Expr = Expr.ResolveLValue (ec, new EmptyExpression ());
556 Expr = Expr.Resolve (ec);
561 eclass = ExprClass.Value;
562 return ResolveOperator (ec);
565 public override void Emit (EmitContext ec)
567 ILGenerator ig = ec.ig;
570 case Operator.UnaryPlus:
571 throw new Exception ("This should be caught by Resolve");
573 case Operator.UnaryNegation:
575 ig.Emit (OpCodes.Ldc_I4_0);
576 if (type == TypeManager.int64_type)
577 ig.Emit (OpCodes.Conv_U8);
579 ig.Emit (OpCodes.Sub_Ovf);
582 ig.Emit (OpCodes.Neg);
587 case Operator.LogicalNot:
589 ig.Emit (OpCodes.Ldc_I4_0);
590 ig.Emit (OpCodes.Ceq);
593 case Operator.OnesComplement:
595 ig.Emit (OpCodes.Not);
598 case Operator.AddressOf:
599 ((IMemoryLocation)Expr).AddressOf (ec, AddressOp.LoadStore);
603 throw new Exception ("This should not happen: Operator = "
608 public override void EmitBranchable (EmitContext ec, Label target, bool onTrue)
610 if (Oper == Operator.LogicalNot)
611 Expr.EmitBranchable (ec, target, !onTrue);
613 base.EmitBranchable (ec, target, onTrue);
616 public override string ToString ()
618 return "Unary (" + Oper + ", " + Expr + ")";
624 // Unary operators are turned into Indirection expressions
625 // after semantic analysis (this is so we can take the address
626 // of an indirection).
628 public class Indirection : Expression, IMemoryLocation, IAssignMethod {
630 LocalTemporary temporary;
633 public Indirection (Expression expr, Location l)
636 this.type = TypeManager.GetElementType (expr.Type);
637 eclass = ExprClass.Variable;
641 void LoadExprValue (EmitContext ec)
645 public override void Emit (EmitContext ec)
647 ILGenerator ig = ec.ig;
649 if (temporary != null){
650 if (have_temporary) {
654 ec.ig.Emit (OpCodes.Dup);
655 temporary.Store (ec);
656 have_temporary = true;
661 LoadFromPtr (ig, Type);
664 public void EmitAssign (EmitContext ec, Expression source)
666 if (temporary != null){
671 ec.ig.Emit (OpCodes.Dup);
672 temporary.Store (ec);
673 have_temporary = true;
679 StoreFromPtr (ec.ig, type);
682 public void AddressOf (EmitContext ec, AddressOp Mode)
684 if (temporary != null){
690 ec.ig.Emit (OpCodes.Dup);
691 temporary.Store (ec);
692 have_temporary = true;
697 public override Expression DoResolve (EmitContext ec)
700 // Born fully resolved
705 public new void CacheTemporaries (EmitContext ec)
707 temporary = new LocalTemporary (ec, expr.Type);
710 public override string ToString ()
712 return "*(" + expr + ")";
717 /// Unary Mutator expressions (pre and post ++ and --)
721 /// UnaryMutator implements ++ and -- expressions. It derives from
722 /// ExpressionStatement becuase the pre/post increment/decrement
723 /// operators can be used in a statement context.
725 /// FIXME: Idea, we could split this up in two classes, one simpler
726 /// for the common case, and one with the extra fields for more complex
727 /// classes (indexers require temporary access; overloaded require method)
730 public class UnaryMutator : ExpressionStatement {
732 public enum Mode : byte {
739 PreDecrement = IsDecrement,
740 PostIncrement = IsPost,
741 PostDecrement = IsPost | IsDecrement
746 LocalTemporary temp_storage;
749 // This is expensive for the simplest case.
753 public UnaryMutator (Mode m, Expression e, Location l)
760 static string OperName (Mode mode)
762 return (mode == Mode.PreIncrement || mode == Mode.PostIncrement) ?
766 void Error23 (Type t)
769 23, "Operator " + OperName (mode) +
770 " cannot be applied to operand of type `" +
771 TypeManager.CSharpName (t) + "'");
775 /// Returns whether an object of type `t' can be incremented
776 /// or decremented with add/sub (ie, basically whether we can
777 /// use pre-post incr-decr operations on it, but it is not a
778 /// System.Decimal, which we require operator overloading to catch)
780 static bool IsIncrementableNumber (Type t)
782 return (t == TypeManager.sbyte_type) ||
783 (t == TypeManager.byte_type) ||
784 (t == TypeManager.short_type) ||
785 (t == TypeManager.ushort_type) ||
786 (t == TypeManager.int32_type) ||
787 (t == TypeManager.uint32_type) ||
788 (t == TypeManager.int64_type) ||
789 (t == TypeManager.uint64_type) ||
790 (t == TypeManager.char_type) ||
791 (t.IsSubclassOf (TypeManager.enum_type)) ||
792 (t == TypeManager.float_type) ||
793 (t == TypeManager.double_type) ||
794 (t.IsPointer && t != TypeManager.void_ptr_type);
797 Expression ResolveOperator (EmitContext ec)
799 Type expr_type = expr.Type;
802 // Step 1: Perform Operator Overload location
807 if (mode == Mode.PreIncrement || mode == Mode.PostIncrement)
808 op_name = "op_Increment";
810 op_name = "op_Decrement";
812 mg = MemberLookup (ec, expr_type, op_name, MemberTypes.Method, AllBindingFlags, loc);
814 if (mg == null && expr_type.BaseType != null)
815 mg = MemberLookup (ec, expr_type.BaseType, op_name,
816 MemberTypes.Method, AllBindingFlags, loc);
819 method = StaticCallExpr.MakeSimpleCall (
820 ec, (MethodGroupExpr) mg, expr, loc);
827 // The operand of the prefix/postfix increment decrement operators
828 // should be an expression that is classified as a variable,
829 // a property access or an indexer access
832 if (expr.eclass == ExprClass.Variable){
833 LocalVariableReference var = expr as LocalVariableReference;
834 if ((var != null) && var.IsReadOnly)
835 Error (1604, "cannot assign to `" + var.Name + "' because it is readonly");
836 if (IsIncrementableNumber (expr_type) ||
837 expr_type == TypeManager.decimal_type){
840 } else if (expr.eclass == ExprClass.IndexerAccess){
841 IndexerAccess ia = (IndexerAccess) expr;
843 temp_storage = new LocalTemporary (ec, expr.Type);
845 expr = ia.ResolveLValue (ec, temp_storage);
850 } else if (expr.eclass == ExprClass.PropertyAccess){
851 PropertyExpr pe = (PropertyExpr) expr;
853 if (pe.VerifyAssignable ())
858 expr.Error_UnexpectedKind ("variable, indexer or property access");
862 Error (187, "No such operator '" + OperName (mode) + "' defined for type '" +
863 TypeManager.CSharpName (expr_type) + "'");
867 public override Expression DoResolve (EmitContext ec)
869 expr = expr.Resolve (ec);
874 eclass = ExprClass.Value;
875 return ResolveOperator (ec);
878 static int PtrTypeSize (Type t)
880 return GetTypeSize (TypeManager.GetElementType (t));
884 // Loads the proper "1" into the stack based on the type, then it emits the
885 // opcode for the operation requested
887 void LoadOneAndEmitOp (EmitContext ec, Type t)
890 // Measure if getting the typecode and using that is more/less efficient
891 // that comparing types. t.GetTypeCode() is an internal call.
893 ILGenerator ig = ec.ig;
895 if (t == TypeManager.uint64_type || t == TypeManager.int64_type)
896 LongConstant.EmitLong (ig, 1);
897 else if (t == TypeManager.double_type)
898 ig.Emit (OpCodes.Ldc_R8, 1.0);
899 else if (t == TypeManager.float_type)
900 ig.Emit (OpCodes.Ldc_R4, 1.0F);
901 else if (t.IsPointer){
902 int n = PtrTypeSize (t);
905 ig.Emit (OpCodes.Sizeof, t);
907 IntConstant.EmitInt (ig, n);
909 ig.Emit (OpCodes.Ldc_I4_1);
912 // Now emit the operation
915 if (t == TypeManager.int32_type ||
916 t == TypeManager.int64_type){
917 if ((mode & Mode.IsDecrement) != 0)
918 ig.Emit (OpCodes.Sub_Ovf);
920 ig.Emit (OpCodes.Add_Ovf);
921 } else if (t == TypeManager.uint32_type ||
922 t == TypeManager.uint64_type){
923 if ((mode & Mode.IsDecrement) != 0)
924 ig.Emit (OpCodes.Sub_Ovf_Un);
926 ig.Emit (OpCodes.Add_Ovf_Un);
928 if ((mode & Mode.IsDecrement) != 0)
929 ig.Emit (OpCodes.Sub_Ovf);
931 ig.Emit (OpCodes.Add_Ovf);
934 if ((mode & Mode.IsDecrement) != 0)
935 ig.Emit (OpCodes.Sub);
937 ig.Emit (OpCodes.Add);
940 if (t == TypeManager.sbyte_type){
942 ig.Emit (OpCodes.Conv_Ovf_I1);
944 ig.Emit (OpCodes.Conv_I1);
945 } else if (t == TypeManager.byte_type){
947 ig.Emit (OpCodes.Conv_Ovf_U1);
949 ig.Emit (OpCodes.Conv_U1);
950 } else if (t == TypeManager.short_type){
952 ig.Emit (OpCodes.Conv_Ovf_I2);
954 ig.Emit (OpCodes.Conv_I2);
955 } else if (t == TypeManager.ushort_type || t == TypeManager.char_type){
957 ig.Emit (OpCodes.Conv_Ovf_U2);
959 ig.Emit (OpCodes.Conv_U2);
964 static EmptyExpression empty_expr;
966 void EmitCode (EmitContext ec, bool is_expr)
968 ILGenerator ig = ec.ig;
969 IAssignMethod ia = (IAssignMethod) expr;
970 Type expr_type = expr.Type;
972 ia.CacheTemporaries (ec);
974 if (temp_storage == null){
976 // Temporary improvement: if we are dealing with something that does
977 // not require complicated instance setup, avoid using a temporary
979 // For now: only localvariables when not remapped
982 if (method == null &&
983 ((expr is LocalVariableReference) ||(expr is FieldExpr && ((FieldExpr) expr).FieldInfo.IsStatic))){
984 if (empty_expr == null)
985 empty_expr = new EmptyExpression ();
988 case Mode.PreIncrement:
989 case Mode.PreDecrement:
992 LoadOneAndEmitOp (ec, expr_type);
994 ig.Emit (OpCodes.Dup);
995 ia.EmitAssign (ec, empty_expr);
998 case Mode.PostIncrement:
999 case Mode.PostDecrement:
1002 ig.Emit (OpCodes.Dup);
1004 LoadOneAndEmitOp (ec, expr_type);
1005 ia.EmitAssign (ec, empty_expr);
1010 temp_storage = new LocalTemporary (ec, expr_type);
1014 case Mode.PreIncrement:
1015 case Mode.PreDecrement:
1016 if (method == null){
1019 LoadOneAndEmitOp (ec, expr_type);
1023 temp_storage.Store (ec);
1024 ia.EmitAssign (ec, temp_storage);
1026 temp_storage.Emit (ec);
1029 case Mode.PostIncrement:
1030 case Mode.PostDecrement:
1034 if (method == null){
1038 ig.Emit (OpCodes.Dup);
1040 LoadOneAndEmitOp (ec, expr_type);
1045 temp_storage.Store (ec);
1046 ia.EmitAssign (ec, temp_storage);
1050 temp_storage.Release (ec);
1053 public override void Emit (EmitContext ec)
1055 EmitCode (ec, true);
1059 public override void EmitStatement (EmitContext ec)
1061 EmitCode (ec, false);
1067 /// Base class for the `Is' and `As' classes.
1071 /// FIXME: Split this in two, and we get to save the `Operator' Oper
1074 public abstract class Probe : Expression {
1075 public readonly Expression ProbeType;
1076 protected Expression expr;
1077 protected Type probe_type;
1079 public Probe (Expression expr, Expression probe_type, Location l)
1081 ProbeType = probe_type;
1086 public Expression Expr {
1092 public override Expression DoResolve (EmitContext ec)
1094 probe_type = ec.DeclSpace.ResolveType (ProbeType, false, loc);
1096 if (probe_type == null)
1099 expr = expr.Resolve (ec);
1108 /// Implementation of the `is' operator.
1110 public class Is : Probe {
1111 public Is (Expression expr, Expression probe_type, Location l)
1112 : base (expr, probe_type, l)
1117 AlwaysTrue, AlwaysNull, AlwaysFalse, LeaveOnStack, Probe
1122 public override void Emit (EmitContext ec)
1124 ILGenerator ig = ec.ig;
1129 case Action.AlwaysFalse:
1130 ig.Emit (OpCodes.Pop);
1131 IntConstant.EmitInt (ig, 0);
1133 case Action.AlwaysTrue:
1134 ig.Emit (OpCodes.Pop);
1135 IntConstant.EmitInt (ig, 1);
1137 case Action.LeaveOnStack:
1138 // the `e != null' rule.
1139 ig.Emit (OpCodes.Ldnull);
1140 ig.Emit (OpCodes.Ceq);
1141 ig.Emit (OpCodes.Ldc_I4_0);
1142 ig.Emit (OpCodes.Ceq);
1145 ig.Emit (OpCodes.Isinst, probe_type);
1146 ig.Emit (OpCodes.Ldnull);
1147 ig.Emit (OpCodes.Cgt_Un);
1150 throw new Exception ("never reached");
1153 public override void EmitBranchable (EmitContext ec, Label target, bool onTrue)
1155 ILGenerator ig = ec.ig;
1158 case Action.AlwaysFalse:
1160 ig.Emit (OpCodes.Br, target);
1163 case Action.AlwaysTrue:
1165 ig.Emit (OpCodes.Br, target);
1168 case Action.LeaveOnStack:
1169 // the `e != null' rule.
1171 ig.Emit (onTrue ? OpCodes.Brtrue : OpCodes.Brfalse, target);
1175 ig.Emit (OpCodes.Isinst, probe_type);
1176 ig.Emit (onTrue ? OpCodes.Brtrue : OpCodes.Brfalse, target);
1179 throw new Exception ("never reached");
1182 public override Expression DoResolve (EmitContext ec)
1184 Expression e = base.DoResolve (ec);
1186 if ((e == null) || (expr == null))
1189 Type etype = expr.Type;
1190 bool warning_always_matches = false;
1191 bool warning_never_matches = false;
1193 type = TypeManager.bool_type;
1194 eclass = ExprClass.Value;
1197 // First case, if at compile time, there is an implicit conversion
1198 // then e != null (objects) or true (value types)
1200 e = Convert.ImplicitConversionStandard (ec, expr, probe_type, loc);
1203 if (etype.IsValueType)
1204 action = Action.AlwaysTrue;
1206 action = Action.LeaveOnStack;
1208 warning_always_matches = true;
1209 } else if (Convert.ExplicitReferenceConversionExists (etype, probe_type)){
1211 // Second case: explicit reference convresion
1213 if (expr is NullLiteral)
1214 action = Action.AlwaysFalse;
1216 action = Action.Probe;
1218 action = Action.AlwaysFalse;
1219 warning_never_matches = true;
1222 if (RootContext.WarningLevel >= 1){
1223 if (warning_always_matches)
1224 Warning (183, "The expression is always of type `" +
1225 TypeManager.CSharpName (probe_type) + "'");
1226 else if (warning_never_matches){
1227 if (!(probe_type.IsInterface || expr.Type.IsInterface))
1229 "The expression is never of type `" +
1230 TypeManager.CSharpName (probe_type) + "'");
1239 /// Implementation of the `as' operator.
1241 public class As : Probe {
1242 public As (Expression expr, Expression probe_type, Location l)
1243 : base (expr, probe_type, l)
1247 bool do_isinst = false;
1249 public override void Emit (EmitContext ec)
1251 ILGenerator ig = ec.ig;
1256 ig.Emit (OpCodes.Isinst, probe_type);
1259 static void Error_CannotConvertType (Type source, Type target, Location loc)
1262 39, loc, "as operator can not convert from `" +
1263 TypeManager.CSharpName (source) + "' to `" +
1264 TypeManager.CSharpName (target) + "'");
1267 public override Expression DoResolve (EmitContext ec)
1269 Expression e = base.DoResolve (ec);
1275 eclass = ExprClass.Value;
1276 Type etype = expr.Type;
1278 if (TypeManager.IsValueType (probe_type)){
1279 Report.Error (77, loc, "The as operator should be used with a reference type only (" +
1280 TypeManager.CSharpName (probe_type) + " is a value type)");
1285 e = Convert.ImplicitConversion (ec, expr, probe_type, loc);
1292 if (Convert.ExplicitReferenceConversionExists (etype, probe_type)){
1297 Error_CannotConvertType (etype, probe_type, loc);
1303 /// This represents a typecast in the source language.
1305 /// FIXME: Cast expressions have an unusual set of parsing
1306 /// rules, we need to figure those out.
1308 public class Cast : Expression {
1309 Expression target_type;
1312 public Cast (Expression cast_type, Expression expr, Location loc)
1314 this.target_type = cast_type;
1319 public Expression TargetType {
1325 public Expression Expr {
1334 bool CheckRange (EmitContext ec, long value, Type type, long min, long max)
1336 if (!ec.ConstantCheckState)
1339 if ((value < min) || (value > max)) {
1340 Error (221, "Constant value `" + value + "' cannot be converted " +
1341 "to a `" + TypeManager.CSharpName (type) + "' (use `unchecked' " +
1342 "syntax to override)");
1349 bool CheckRange (EmitContext ec, ulong value, Type type, ulong max)
1351 if (!ec.ConstantCheckState)
1355 Error (221, "Constant value `" + value + "' cannot be converted " +
1356 "to a `" + TypeManager.CSharpName (type) + "' (use `unchecked' " +
1357 "syntax to override)");
1364 bool CheckUnsigned (EmitContext ec, long value, Type type)
1366 if (!ec.ConstantCheckState)
1370 Error (221, "Constant value `" + value + "' cannot be converted " +
1371 "to a `" + TypeManager.CSharpName (type) + "' (use `unchecked' " +
1372 "syntax to override)");
1380 /// Attempts to do a compile-time folding of a constant cast.
1382 Expression TryReduce (EmitContext ec, Type target_type)
1384 Expression real_expr = expr;
1385 if (real_expr is EnumConstant)
1386 real_expr = ((EnumConstant) real_expr).Child;
1388 if (real_expr is ByteConstant){
1389 byte v = ((ByteConstant) real_expr).Value;
1391 if (target_type == TypeManager.sbyte_type) {
1392 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1394 return new SByteConstant ((sbyte) v);
1396 if (target_type == TypeManager.short_type)
1397 return new ShortConstant ((short) v);
1398 if (target_type == TypeManager.ushort_type)
1399 return new UShortConstant ((ushort) v);
1400 if (target_type == TypeManager.int32_type)
1401 return new IntConstant ((int) v);
1402 if (target_type == TypeManager.uint32_type)
1403 return new UIntConstant ((uint) v);
1404 if (target_type == TypeManager.int64_type)
1405 return new LongConstant ((long) v);
1406 if (target_type == TypeManager.uint64_type)
1407 return new ULongConstant ((ulong) v);
1408 if (target_type == TypeManager.float_type)
1409 return new FloatConstant ((float) v);
1410 if (target_type == TypeManager.double_type)
1411 return new DoubleConstant ((double) v);
1412 if (target_type == TypeManager.char_type)
1413 return new CharConstant ((char) v);
1414 if (target_type == TypeManager.decimal_type)
1415 return new DecimalConstant ((decimal) v);
1417 if (real_expr is SByteConstant){
1418 sbyte v = ((SByteConstant) real_expr).Value;
1420 if (target_type == TypeManager.byte_type) {
1421 if (!CheckUnsigned (ec, v, target_type))
1423 return new ByteConstant ((byte) v);
1425 if (target_type == TypeManager.short_type)
1426 return new ShortConstant ((short) v);
1427 if (target_type == TypeManager.ushort_type) {
1428 if (!CheckUnsigned (ec, v, target_type))
1430 return new UShortConstant ((ushort) v);
1431 } if (target_type == TypeManager.int32_type)
1432 return new IntConstant ((int) v);
1433 if (target_type == TypeManager.uint32_type) {
1434 if (!CheckUnsigned (ec, v, target_type))
1436 return new UIntConstant ((uint) v);
1437 } if (target_type == TypeManager.int64_type)
1438 return new LongConstant ((long) v);
1439 if (target_type == TypeManager.uint64_type) {
1440 if (!CheckUnsigned (ec, v, target_type))
1442 return new ULongConstant ((ulong) v);
1444 if (target_type == TypeManager.float_type)
1445 return new FloatConstant ((float) v);
1446 if (target_type == TypeManager.double_type)
1447 return new DoubleConstant ((double) v);
1448 if (target_type == TypeManager.char_type) {
1449 if (!CheckUnsigned (ec, v, target_type))
1451 return new CharConstant ((char) v);
1453 if (target_type == TypeManager.decimal_type)
1454 return new DecimalConstant ((decimal) v);
1456 if (real_expr is ShortConstant){
1457 short v = ((ShortConstant) real_expr).Value;
1459 if (target_type == TypeManager.byte_type) {
1460 if (!CheckRange (ec, v, target_type, Byte.MinValue, Byte.MaxValue))
1462 return new ByteConstant ((byte) v);
1464 if (target_type == TypeManager.sbyte_type) {
1465 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1467 return new SByteConstant ((sbyte) v);
1469 if (target_type == TypeManager.ushort_type) {
1470 if (!CheckUnsigned (ec, v, target_type))
1472 return new UShortConstant ((ushort) v);
1474 if (target_type == TypeManager.int32_type)
1475 return new IntConstant ((int) v);
1476 if (target_type == TypeManager.uint32_type) {
1477 if (!CheckUnsigned (ec, v, target_type))
1479 return new UIntConstant ((uint) v);
1481 if (target_type == TypeManager.int64_type)
1482 return new LongConstant ((long) v);
1483 if (target_type == TypeManager.uint64_type) {
1484 if (!CheckUnsigned (ec, v, target_type))
1486 return new ULongConstant ((ulong) v);
1488 if (target_type == TypeManager.float_type)
1489 return new FloatConstant ((float) v);
1490 if (target_type == TypeManager.double_type)
1491 return new DoubleConstant ((double) v);
1492 if (target_type == TypeManager.char_type) {
1493 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1495 return new CharConstant ((char) v);
1497 if (target_type == TypeManager.decimal_type)
1498 return new DecimalConstant ((decimal) v);
1500 if (real_expr is UShortConstant){
1501 ushort v = ((UShortConstant) real_expr).Value;
1503 if (target_type == TypeManager.byte_type) {
1504 if (!CheckRange (ec, v, target_type, Byte.MinValue, Byte.MaxValue))
1506 return new ByteConstant ((byte) v);
1508 if (target_type == TypeManager.sbyte_type) {
1509 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1511 return new SByteConstant ((sbyte) v);
1513 if (target_type == TypeManager.short_type) {
1514 if (!CheckRange (ec, v, target_type, Int16.MinValue, Int16.MaxValue))
1516 return new ShortConstant ((short) v);
1518 if (target_type == TypeManager.int32_type)
1519 return new IntConstant ((int) v);
1520 if (target_type == TypeManager.uint32_type)
1521 return new UIntConstant ((uint) v);
1522 if (target_type == TypeManager.int64_type)
1523 return new LongConstant ((long) v);
1524 if (target_type == TypeManager.uint64_type)
1525 return new ULongConstant ((ulong) v);
1526 if (target_type == TypeManager.float_type)
1527 return new FloatConstant ((float) v);
1528 if (target_type == TypeManager.double_type)
1529 return new DoubleConstant ((double) v);
1530 if (target_type == TypeManager.char_type) {
1531 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1533 return new CharConstant ((char) v);
1535 if (target_type == TypeManager.decimal_type)
1536 return new DecimalConstant ((decimal) v);
1538 if (real_expr is IntConstant){
1539 int v = ((IntConstant) real_expr).Value;
1541 if (target_type == TypeManager.byte_type) {
1542 if (!CheckRange (ec, v, target_type, Byte.MinValue, Byte.MaxValue))
1544 return new ByteConstant ((byte) v);
1546 if (target_type == TypeManager.sbyte_type) {
1547 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1549 return new SByteConstant ((sbyte) v);
1551 if (target_type == TypeManager.short_type) {
1552 if (!CheckRange (ec, v, target_type, Int16.MinValue, Int16.MaxValue))
1554 return new ShortConstant ((short) v);
1556 if (target_type == TypeManager.ushort_type) {
1557 if (!CheckRange (ec, v, target_type, UInt16.MinValue, UInt16.MaxValue))
1559 return new UShortConstant ((ushort) v);
1561 if (target_type == TypeManager.uint32_type) {
1562 if (!CheckRange (ec, v, target_type, Int32.MinValue, Int32.MaxValue))
1564 return new UIntConstant ((uint) v);
1566 if (target_type == TypeManager.int64_type)
1567 return new LongConstant ((long) v);
1568 if (target_type == TypeManager.uint64_type) {
1569 if (!CheckUnsigned (ec, v, target_type))
1571 return new ULongConstant ((ulong) v);
1573 if (target_type == TypeManager.float_type)
1574 return new FloatConstant ((float) v);
1575 if (target_type == TypeManager.double_type)
1576 return new DoubleConstant ((double) v);
1577 if (target_type == TypeManager.char_type) {
1578 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1580 return new CharConstant ((char) v);
1582 if (target_type == TypeManager.decimal_type)
1583 return new DecimalConstant ((decimal) v);
1585 if (real_expr is UIntConstant){
1586 uint v = ((UIntConstant) real_expr).Value;
1588 if (target_type == TypeManager.byte_type) {
1589 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1591 return new ByteConstant ((byte) v);
1593 if (target_type == TypeManager.sbyte_type) {
1594 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1596 return new SByteConstant ((sbyte) v);
1598 if (target_type == TypeManager.short_type) {
1599 if (!CheckRange (ec, v, target_type, Int16.MinValue, Int16.MaxValue))
1601 return new ShortConstant ((short) v);
1603 if (target_type == TypeManager.ushort_type) {
1604 if (!CheckRange (ec, v, target_type, UInt16.MinValue, UInt16.MaxValue))
1606 return new UShortConstant ((ushort) v);
1608 if (target_type == TypeManager.int32_type) {
1609 if (!CheckRange (ec, v, target_type, Int32.MinValue, Int32.MaxValue))
1611 return new IntConstant ((int) v);
1613 if (target_type == TypeManager.int64_type)
1614 return new LongConstant ((long) v);
1615 if (target_type == TypeManager.uint64_type)
1616 return new ULongConstant ((ulong) v);
1617 if (target_type == TypeManager.float_type)
1618 return new FloatConstant ((float) v);
1619 if (target_type == TypeManager.double_type)
1620 return new DoubleConstant ((double) v);
1621 if (target_type == TypeManager.char_type) {
1622 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1624 return new CharConstant ((char) v);
1626 if (target_type == TypeManager.decimal_type)
1627 return new DecimalConstant ((decimal) v);
1629 if (real_expr is LongConstant){
1630 long v = ((LongConstant) real_expr).Value;
1632 if (target_type == TypeManager.byte_type) {
1633 if (!CheckRange (ec, v, target_type, Byte.MinValue, Byte.MaxValue))
1635 return new ByteConstant ((byte) v);
1637 if (target_type == TypeManager.sbyte_type) {
1638 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1640 return new SByteConstant ((sbyte) v);
1642 if (target_type == TypeManager.short_type) {
1643 if (!CheckRange (ec, v, target_type, Int16.MinValue, Int16.MaxValue))
1645 return new ShortConstant ((short) v);
1647 if (target_type == TypeManager.ushort_type) {
1648 if (!CheckRange (ec, v, target_type, UInt16.MinValue, UInt16.MaxValue))
1650 return new UShortConstant ((ushort) v);
1652 if (target_type == TypeManager.int32_type) {
1653 if (!CheckRange (ec, v, target_type, Int32.MinValue, Int32.MaxValue))
1655 return new IntConstant ((int) v);
1657 if (target_type == TypeManager.uint32_type) {
1658 if (!CheckRange (ec, v, target_type, UInt32.MinValue, UInt32.MaxValue))
1660 return new UIntConstant ((uint) v);
1662 if (target_type == TypeManager.uint64_type) {
1663 if (!CheckUnsigned (ec, v, target_type))
1665 return new ULongConstant ((ulong) v);
1667 if (target_type == TypeManager.float_type)
1668 return new FloatConstant ((float) v);
1669 if (target_type == TypeManager.double_type)
1670 return new DoubleConstant ((double) v);
1671 if (target_type == TypeManager.char_type) {
1672 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1674 return new CharConstant ((char) v);
1676 if (target_type == TypeManager.decimal_type)
1677 return new DecimalConstant ((decimal) v);
1679 if (real_expr is ULongConstant){
1680 ulong v = ((ULongConstant) real_expr).Value;
1682 if (target_type == TypeManager.byte_type) {
1683 if (!CheckRange (ec, v, target_type, Byte.MaxValue))
1685 return new ByteConstant ((byte) v);
1687 if (target_type == TypeManager.sbyte_type) {
1688 if (!CheckRange (ec, v, target_type, (ulong) SByte.MaxValue))
1690 return new SByteConstant ((sbyte) v);
1692 if (target_type == TypeManager.short_type) {
1693 if (!CheckRange (ec, v, target_type, (ulong) Int16.MaxValue))
1695 return new ShortConstant ((short) v);
1697 if (target_type == TypeManager.ushort_type) {
1698 if (!CheckRange (ec, v, target_type, UInt16.MaxValue))
1700 return new UShortConstant ((ushort) v);
1702 if (target_type == TypeManager.int32_type) {
1703 if (!CheckRange (ec, v, target_type, Int32.MaxValue))
1705 return new IntConstant ((int) v);
1707 if (target_type == TypeManager.uint32_type) {
1708 if (!CheckRange (ec, v, target_type, UInt32.MaxValue))
1710 return new UIntConstant ((uint) v);
1712 if (target_type == TypeManager.int64_type) {
1713 if (!CheckRange (ec, v, target_type, (ulong) Int64.MaxValue))
1715 return new LongConstant ((long) v);
1717 if (target_type == TypeManager.float_type)
1718 return new FloatConstant ((float) v);
1719 if (target_type == TypeManager.double_type)
1720 return new DoubleConstant ((double) v);
1721 if (target_type == TypeManager.char_type) {
1722 if (!CheckRange (ec, v, target_type, Char.MaxValue))
1724 return new CharConstant ((char) v);
1726 if (target_type == TypeManager.decimal_type)
1727 return new DecimalConstant ((decimal) v);
1729 if (real_expr is FloatConstant){
1730 float v = ((FloatConstant) real_expr).Value;
1732 if (target_type == TypeManager.byte_type)
1733 return new ByteConstant ((byte) v);
1734 if (target_type == TypeManager.sbyte_type)
1735 return new SByteConstant ((sbyte) v);
1736 if (target_type == TypeManager.short_type)
1737 return new ShortConstant ((short) v);
1738 if (target_type == TypeManager.ushort_type)
1739 return new UShortConstant ((ushort) v);
1740 if (target_type == TypeManager.int32_type)
1741 return new IntConstant ((int) v);
1742 if (target_type == TypeManager.uint32_type)
1743 return new UIntConstant ((uint) v);
1744 if (target_type == TypeManager.int64_type)
1745 return new LongConstant ((long) v);
1746 if (target_type == TypeManager.uint64_type)
1747 return new ULongConstant ((ulong) v);
1748 if (target_type == TypeManager.double_type)
1749 return new DoubleConstant ((double) v);
1750 if (target_type == TypeManager.char_type)
1751 return new CharConstant ((char) v);
1752 if (target_type == TypeManager.decimal_type)
1753 return new DecimalConstant ((decimal) v);
1755 if (real_expr is DoubleConstant){
1756 double v = ((DoubleConstant) real_expr).Value;
1758 if (target_type == TypeManager.byte_type){
1759 return new ByteConstant ((byte) v);
1760 } if (target_type == TypeManager.sbyte_type)
1761 return new SByteConstant ((sbyte) v);
1762 if (target_type == TypeManager.short_type)
1763 return new ShortConstant ((short) v);
1764 if (target_type == TypeManager.ushort_type)
1765 return new UShortConstant ((ushort) v);
1766 if (target_type == TypeManager.int32_type)
1767 return new IntConstant ((int) v);
1768 if (target_type == TypeManager.uint32_type)
1769 return new UIntConstant ((uint) v);
1770 if (target_type == TypeManager.int64_type)
1771 return new LongConstant ((long) v);
1772 if (target_type == TypeManager.uint64_type)
1773 return new ULongConstant ((ulong) v);
1774 if (target_type == TypeManager.float_type)
1775 return new FloatConstant ((float) v);
1776 if (target_type == TypeManager.char_type)
1777 return new CharConstant ((char) v);
1778 if (target_type == TypeManager.decimal_type)
1779 return new DecimalConstant ((decimal) v);
1782 if (real_expr is CharConstant){
1783 char v = ((CharConstant) real_expr).Value;
1785 if (target_type == TypeManager.byte_type) {
1786 if (!CheckRange (ec, v, target_type, Byte.MinValue, Byte.MaxValue))
1788 return new ByteConstant ((byte) v);
1790 if (target_type == TypeManager.sbyte_type) {
1791 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1793 return new SByteConstant ((sbyte) v);
1795 if (target_type == TypeManager.short_type) {
1796 if (!CheckRange (ec, v, target_type, Int16.MinValue, Int16.MaxValue))
1798 return new ShortConstant ((short) v);
1800 if (target_type == TypeManager.int32_type)
1801 return new IntConstant ((int) v);
1802 if (target_type == TypeManager.uint32_type)
1803 return new UIntConstant ((uint) v);
1804 if (target_type == TypeManager.int64_type)
1805 return new LongConstant ((long) v);
1806 if (target_type == TypeManager.uint64_type)
1807 return new ULongConstant ((ulong) v);
1808 if (target_type == TypeManager.float_type)
1809 return new FloatConstant ((float) v);
1810 if (target_type == TypeManager.double_type)
1811 return new DoubleConstant ((double) v);
1812 if (target_type == TypeManager.char_type) {
1813 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1815 return new CharConstant ((char) v);
1817 if (target_type == TypeManager.decimal_type)
1818 return new DecimalConstant ((decimal) v);
1824 public override Expression DoResolve (EmitContext ec)
1826 expr = expr.Resolve (ec);
1830 type = ec.DeclSpace.ResolveType (target_type, false, Location);
1835 eclass = ExprClass.Value;
1837 if (expr is Constant){
1838 Expression e = TryReduce (ec, type);
1844 expr = Convert.ExplicitConversion (ec, expr, type, loc);
1848 public override void Emit (EmitContext ec)
1851 // This one will never happen
1853 throw new Exception ("Should not happen");
1858 /// Binary operators
1860 public class Binary : Expression {
1861 public enum Operator : byte {
1862 Multiply, Division, Modulus,
1863 Addition, Subtraction,
1864 LeftShift, RightShift,
1865 LessThan, GreaterThan, LessThanOrEqual, GreaterThanOrEqual,
1866 Equality, Inequality,
1876 Expression left, right;
1878 // This must be kept in sync with Operator!!!
1879 public static readonly string [] oper_names;
1883 oper_names = new string [(int) Operator.TOP];
1885 oper_names [(int) Operator.Multiply] = "op_Multiply";
1886 oper_names [(int) Operator.Division] = "op_Division";
1887 oper_names [(int) Operator.Modulus] = "op_Modulus";
1888 oper_names [(int) Operator.Addition] = "op_Addition";
1889 oper_names [(int) Operator.Subtraction] = "op_Subtraction";
1890 oper_names [(int) Operator.LeftShift] = "op_LeftShift";
1891 oper_names [(int) Operator.RightShift] = "op_RightShift";
1892 oper_names [(int) Operator.LessThan] = "op_LessThan";
1893 oper_names [(int) Operator.GreaterThan] = "op_GreaterThan";
1894 oper_names [(int) Operator.LessThanOrEqual] = "op_LessThanOrEqual";
1895 oper_names [(int) Operator.GreaterThanOrEqual] = "op_GreaterThanOrEqual";
1896 oper_names [(int) Operator.Equality] = "op_Equality";
1897 oper_names [(int) Operator.Inequality] = "op_Inequality";
1898 oper_names [(int) Operator.BitwiseAnd] = "op_BitwiseAnd";
1899 oper_names [(int) Operator.BitwiseOr] = "op_BitwiseOr";
1900 oper_names [(int) Operator.ExclusiveOr] = "op_ExclusiveOr";
1901 oper_names [(int) Operator.LogicalOr] = "op_LogicalOr";
1902 oper_names [(int) Operator.LogicalAnd] = "op_LogicalAnd";
1905 public Binary (Operator oper, Expression left, Expression right, Location loc)
1913 public Operator Oper {
1922 public Expression Left {
1931 public Expression Right {
1942 /// Returns a stringified representation of the Operator
1944 static string OperName (Operator oper)
1947 case Operator.Multiply:
1949 case Operator.Division:
1951 case Operator.Modulus:
1953 case Operator.Addition:
1955 case Operator.Subtraction:
1957 case Operator.LeftShift:
1959 case Operator.RightShift:
1961 case Operator.LessThan:
1963 case Operator.GreaterThan:
1965 case Operator.LessThanOrEqual:
1967 case Operator.GreaterThanOrEqual:
1969 case Operator.Equality:
1971 case Operator.Inequality:
1973 case Operator.BitwiseAnd:
1975 case Operator.BitwiseOr:
1977 case Operator.ExclusiveOr:
1979 case Operator.LogicalOr:
1981 case Operator.LogicalAnd:
1985 return oper.ToString ();
1988 public override string ToString ()
1990 return "operator " + OperName (oper) + "(" + left.ToString () + ", " +
1991 right.ToString () + ")";
1994 Expression ForceConversion (EmitContext ec, Expression expr, Type target_type)
1996 if (expr.Type == target_type)
1999 return Convert.ImplicitConversion (ec, expr, target_type, loc);
2002 public static void Error_OperatorAmbiguous (Location loc, Operator oper, Type l, Type r)
2005 34, loc, "Operator `" + OperName (oper)
2006 + "' is ambiguous on operands of type `"
2007 + TypeManager.CSharpName (l) + "' "
2008 + "and `" + TypeManager.CSharpName (r)
2012 bool IsOfType (EmitContext ec, Type l, Type r, Type t, bool check_user_conversions)
2014 if ((l == t) || (r == t))
2017 if (!check_user_conversions)
2020 if (Convert.ImplicitUserConversionExists (ec, l, t))
2022 else if (Convert.ImplicitUserConversionExists (ec, r, t))
2029 // Note that handling the case l == Decimal || r == Decimal
2030 // is taken care of by the Step 1 Operator Overload resolution.
2032 // If `check_user_conv' is true, we also check whether a user-defined conversion
2033 // exists. Note that we only need to do this if both arguments are of a user-defined
2034 // type, otherwise ConvertImplict() already finds the user-defined conversion for us,
2035 // so we don't explicitly check for performance reasons.
2037 bool DoNumericPromotions (EmitContext ec, Type l, Type r, bool check_user_conv)
2039 if (IsOfType (ec, l, r, TypeManager.double_type, check_user_conv)){
2041 // If either operand is of type double, the other operand is
2042 // conveted to type double.
2044 if (r != TypeManager.double_type)
2045 right = Convert.ImplicitConversion (ec, right, TypeManager.double_type, loc);
2046 if (l != TypeManager.double_type)
2047 left = Convert.ImplicitConversion (ec, left, TypeManager.double_type, loc);
2049 type = TypeManager.double_type;
2050 } else if (IsOfType (ec, l, r, TypeManager.float_type, check_user_conv)){
2052 // if either operand is of type float, the other operand is
2053 // converted to type float.
2055 if (r != TypeManager.double_type)
2056 right = Convert.ImplicitConversion (ec, right, TypeManager.float_type, loc);
2057 if (l != TypeManager.double_type)
2058 left = Convert.ImplicitConversion (ec, left, TypeManager.float_type, loc);
2059 type = TypeManager.float_type;
2060 } else if (IsOfType (ec, l, r, TypeManager.uint64_type, check_user_conv)){
2064 // If either operand is of type ulong, the other operand is
2065 // converted to type ulong. or an error ocurrs if the other
2066 // operand is of type sbyte, short, int or long
2068 if (l == TypeManager.uint64_type){
2069 if (r != TypeManager.uint64_type){
2070 if (right is IntConstant){
2071 IntConstant ic = (IntConstant) right;
2073 e = Convert.TryImplicitIntConversion (l, ic);
2076 } else if (right is LongConstant){
2077 long ll = ((LongConstant) right).Value;
2080 right = new ULongConstant ((ulong) ll);
2082 e = Convert.ImplicitNumericConversion (ec, right, l, loc);
2089 if (left is IntConstant){
2090 e = Convert.TryImplicitIntConversion (r, (IntConstant) left);
2093 } else if (left is LongConstant){
2094 long ll = ((LongConstant) left).Value;
2097 left = new ULongConstant ((ulong) ll);
2099 e = Convert.ImplicitNumericConversion (ec, left, r, loc);
2106 if ((other == TypeManager.sbyte_type) ||
2107 (other == TypeManager.short_type) ||
2108 (other == TypeManager.int32_type) ||
2109 (other == TypeManager.int64_type))
2110 Error_OperatorAmbiguous (loc, oper, l, r);
2111 type = TypeManager.uint64_type;
2112 } else if (IsOfType (ec, l, r, TypeManager.int64_type, check_user_conv)){
2114 // If either operand is of type long, the other operand is converted
2117 if (l != TypeManager.int64_type)
2118 left = Convert.ImplicitConversion (ec, left, TypeManager.int64_type, loc);
2119 if (r != TypeManager.int64_type)
2120 right = Convert.ImplicitConversion (ec, right, TypeManager.int64_type, loc);
2122 type = TypeManager.int64_type;
2123 } else if (IsOfType (ec, l, r, TypeManager.uint32_type, check_user_conv)){
2125 // If either operand is of type uint, and the other
2126 // operand is of type sbyte, short or int, othe operands are
2127 // converted to type long (unless we have an int constant).
2131 if (l == TypeManager.uint32_type){
2132 if (right is IntConstant){
2133 IntConstant ic = (IntConstant) right;
2137 right = new UIntConstant ((uint) val);
2144 } else if (r == TypeManager.uint32_type){
2145 if (left is IntConstant){
2146 IntConstant ic = (IntConstant) left;
2150 left = new UIntConstant ((uint) val);
2159 if ((other == TypeManager.sbyte_type) ||
2160 (other == TypeManager.short_type) ||
2161 (other == TypeManager.int32_type)){
2162 left = ForceConversion (ec, left, TypeManager.int64_type);
2163 right = ForceConversion (ec, right, TypeManager.int64_type);
2164 type = TypeManager.int64_type;
2167 // if either operand is of type uint, the other
2168 // operand is converd to type uint
2170 left = ForceConversion (ec, left, TypeManager.uint32_type);
2171 right = ForceConversion (ec, right, TypeManager.uint32_type);
2172 type = TypeManager.uint32_type;
2174 } else if (l == TypeManager.decimal_type || r == TypeManager.decimal_type){
2175 if (l != TypeManager.decimal_type)
2176 left = Convert.ImplicitConversion (ec, left, TypeManager.decimal_type, loc);
2178 if (r != TypeManager.decimal_type)
2179 right = Convert.ImplicitConversion (ec, right, TypeManager.decimal_type, loc);
2180 type = TypeManager.decimal_type;
2182 left = ForceConversion (ec, left, TypeManager.int32_type);
2183 right = ForceConversion (ec, right, TypeManager.int32_type);
2185 type = TypeManager.int32_type;
2188 return (left != null) && (right != null);
2191 static public void Error_OperatorCannotBeApplied (Location loc, string name, Type l, Type r)
2193 Report.Error (19, loc,
2194 "Operator " + name + " cannot be applied to operands of type `" +
2195 TypeManager.CSharpName (l) + "' and `" +
2196 TypeManager.CSharpName (r) + "'");
2199 void Error_OperatorCannotBeApplied ()
2201 Error_OperatorCannotBeApplied (loc, OperName (oper), left.Type, right.Type);
2204 static bool is_unsigned (Type t)
2206 return (t == TypeManager.uint32_type || t == TypeManager.uint64_type ||
2207 t == TypeManager.short_type || t == TypeManager.byte_type);
2210 static bool is_user_defined (Type t)
2212 if (t.IsSubclassOf (TypeManager.value_type) &&
2213 (!TypeManager.IsBuiltinType (t) || t == TypeManager.decimal_type))
2219 Expression Make32or64 (EmitContext ec, Expression e)
2223 if (t == TypeManager.int32_type || t == TypeManager.uint32_type ||
2224 t == TypeManager.int64_type || t == TypeManager.uint64_type)
2226 Expression ee = Convert.ImplicitConversion (ec, e, TypeManager.int32_type, loc);
2229 ee = Convert.ImplicitConversion (ec, e, TypeManager.uint32_type, loc);
2232 ee = Convert.ImplicitConversion (ec, e, TypeManager.int64_type, loc);
2235 ee = Convert.ImplicitConversion (ec, e, TypeManager.uint64_type, loc);
2241 Expression CheckShiftArguments (EmitContext ec)
2245 e = ForceConversion (ec, right, TypeManager.int32_type);
2247 Error_OperatorCannotBeApplied ();
2252 if (((e = Convert.ImplicitConversion (ec, left, TypeManager.int32_type, loc)) != null) ||
2253 ((e = Convert.ImplicitConversion (ec, left, TypeManager.uint32_type, loc)) != null) ||
2254 ((e = Convert.ImplicitConversion (ec, left, TypeManager.int64_type, loc)) != null) ||
2255 ((e = Convert.ImplicitConversion (ec, left, TypeManager.uint64_type, loc)) != null)){
2259 if (type == TypeManager.int32_type || type == TypeManager.uint32_type){
2260 right = new Binary (Binary.Operator.BitwiseAnd, right, new IntLiteral (31), loc);
2261 right = right.DoResolve (ec);
2263 right = new Binary (Binary.Operator.BitwiseAnd, right, new IntLiteral (63), loc);
2264 right = right.DoResolve (ec);
2269 Error_OperatorCannotBeApplied ();
2273 Expression ResolveOperator (EmitContext ec)
2276 Type r = right.Type;
2278 bool overload_failed = false;
2281 // Special cases: string comapred to null
2283 if (oper == Operator.Equality || oper == Operator.Inequality){
2284 if ((l == TypeManager.string_type && (right is NullLiteral)) ||
2285 (r == TypeManager.string_type && (left is NullLiteral))){
2286 Type = TypeManager.bool_type;
2293 // Do not perform operator overload resolution when both sides are
2296 if (!(TypeManager.IsCLRType (l) && TypeManager.IsCLRType (r))){
2298 // Step 1: Perform Operator Overload location
2300 Expression left_expr, right_expr;
2302 string op = oper_names [(int) oper];
2304 MethodGroupExpr union;
2305 left_expr = MemberLookup (ec, l, op, MemberTypes.Method, AllBindingFlags, loc);
2307 right_expr = MemberLookup (
2308 ec, r, op, MemberTypes.Method, AllBindingFlags, loc);
2309 union = Invocation.MakeUnionSet (left_expr, right_expr, loc);
2311 union = (MethodGroupExpr) left_expr;
2313 if (union != null) {
2314 ArrayList args = new ArrayList (2);
2315 args.Add (new Argument (left, Argument.AType.Expression));
2316 args.Add (new Argument (right, Argument.AType.Expression));
2318 MethodBase method = Invocation.OverloadResolve (ec, union, args, Location.Null);
2319 if (method != null) {
2320 MethodInfo mi = (MethodInfo) method;
2322 return new BinaryMethod (mi.ReturnType, method, args);
2324 overload_failed = true;
2330 // Step 0: String concatenation (because overloading will get this wrong)
2332 if (oper == Operator.Addition){
2334 // If any of the arguments is a string, cast to string
2337 if (l == TypeManager.string_type){
2340 if (r == TypeManager.void_type) {
2341 Error_OperatorCannotBeApplied ();
2345 if (r == TypeManager.string_type){
2346 if (left is Constant && right is Constant){
2347 StringConstant ls = (StringConstant) left;
2348 StringConstant rs = (StringConstant) right;
2350 return new StringConstant (
2351 ls.Value + rs.Value);
2354 if (left is BinaryMethod){
2355 BinaryMethod b = (BinaryMethod) left;
2358 // Call String.Concat (string, string, string) or
2359 // String.Concat (string, string, string, string)
2362 if (b.method == TypeManager.string_concat_string_string ||
2363 b.method == TypeManager.string_concat_string_string_string){
2364 int count = b.Arguments.Count;
2367 ArrayList bargs = new ArrayList (3);
2368 bargs.AddRange (b.Arguments);
2369 bargs.Add (new Argument (right, Argument.AType.Expression));
2370 return new BinaryMethod (
2371 TypeManager.string_type,
2372 TypeManager.string_concat_string_string_string, bargs);
2373 } else if (count == 3){
2374 ArrayList bargs = new ArrayList (4);
2375 bargs.AddRange (b.Arguments);
2376 bargs.Add (new Argument (right, Argument.AType.Expression));
2377 return new BinaryMethod (
2378 TypeManager.string_type,
2379 TypeManager.string_concat_string_string_string_string, bargs);
2385 method = TypeManager.string_concat_string_string;
2388 method = TypeManager.string_concat_object_object;
2389 right = Convert.ImplicitConversion (
2390 ec, right, TypeManager.object_type, loc);
2392 Error_OperatorCannotBeApplied (loc, OperName (oper), l, r);
2398 // Cascading concats will hold up to 2 arguments, any extras will be
2399 // reallocated above.
2401 ArrayList args = new ArrayList (2);
2402 args.Add (new Argument (left, Argument.AType.Expression));
2403 args.Add (new Argument (right, Argument.AType.Expression));
2405 return new BinaryMethod (TypeManager.string_type, method, args);
2406 } else if (r == TypeManager.string_type){
2409 if (l == TypeManager.void_type) {
2410 Error_OperatorCannotBeApplied ();
2414 left = Convert.ImplicitConversion (ec, left, TypeManager.object_type, loc);
2416 Error_OperatorCannotBeApplied (loc, OperName (oper), l, r);
2419 ArrayList args = new ArrayList (2);
2420 args.Add (new Argument (left, Argument.AType.Expression));
2421 args.Add (new Argument (right, Argument.AType.Expression));
2423 return new BinaryMethod (TypeManager.string_type, TypeManager.string_concat_object_object, args);
2427 // Transform a + ( - b) into a - b
2429 if (right is Unary){
2430 Unary right_unary = (Unary) right;
2432 if (right_unary.Oper == Unary.Operator.UnaryNegation){
2433 oper = Operator.Subtraction;
2434 right = right_unary.Expr;
2440 if (oper == Operator.Equality || oper == Operator.Inequality){
2441 if (l == TypeManager.bool_type || r == TypeManager.bool_type){
2442 if (r != TypeManager.bool_type || l != TypeManager.bool_type){
2443 Error_OperatorCannotBeApplied ();
2447 type = TypeManager.bool_type;
2452 // operator != (object a, object b)
2453 // operator == (object a, object b)
2455 // For this to be used, both arguments have to be reference-types.
2456 // Read the rationale on the spec (14.9.6)
2458 // Also, if at compile time we know that the classes do not inherit
2459 // one from the other, then we catch the error there.
2461 if (!(l.IsValueType || r.IsValueType)){
2462 type = TypeManager.bool_type;
2467 if (l.IsSubclassOf (r) || r.IsSubclassOf (l))
2471 // Also, a standard conversion must exist from either one
2473 if (!(Convert.ImplicitStandardConversionExists (left, r) ||
2474 Convert.ImplicitStandardConversionExists (right, l))){
2475 Error_OperatorCannotBeApplied ();
2479 // We are going to have to convert to an object to compare
2481 if (l != TypeManager.object_type)
2482 left = new EmptyCast (left, TypeManager.object_type);
2483 if (r != TypeManager.object_type)
2484 right = new EmptyCast (right, TypeManager.object_type);
2487 // FIXME: CSC here catches errors cs254 and cs252
2493 // One of them is a valuetype, but the other one is not.
2495 if (!l.IsValueType || !r.IsValueType) {
2496 Error_OperatorCannotBeApplied ();
2501 // Only perform numeric promotions on:
2502 // +, -, *, /, %, &, |, ^, ==, !=, <, >, <=, >=
2504 if (oper == Operator.Addition || oper == Operator.Subtraction) {
2505 if (l.IsSubclassOf (TypeManager.delegate_type)){
2506 if (right.eclass == ExprClass.MethodGroup && RootContext.V2){
2507 Expression tmp = Convert.ImplicitConversionRequired (ec, right, l, loc);
2514 if (r.IsSubclassOf (TypeManager.delegate_type)){
2516 ArrayList args = new ArrayList (2);
2518 args = new ArrayList (2);
2519 args.Add (new Argument (left, Argument.AType.Expression));
2520 args.Add (new Argument (right, Argument.AType.Expression));
2522 if (oper == Operator.Addition)
2523 method = TypeManager.delegate_combine_delegate_delegate;
2525 method = TypeManager.delegate_remove_delegate_delegate;
2528 Error_OperatorCannotBeApplied ();
2532 return new BinaryDelegate (l, method, args);
2537 // Pointer arithmetic:
2539 // T* operator + (T* x, int y);
2540 // T* operator + (T* x, uint y);
2541 // T* operator + (T* x, long y);
2542 // T* operator + (T* x, ulong y);
2544 // T* operator + (int y, T* x);
2545 // T* operator + (uint y, T *x);
2546 // T* operator + (long y, T *x);
2547 // T* operator + (ulong y, T *x);
2549 // T* operator - (T* x, int y);
2550 // T* operator - (T* x, uint y);
2551 // T* operator - (T* x, long y);
2552 // T* operator - (T* x, ulong y);
2554 // long operator - (T* x, T *y)
2557 if (r.IsPointer && oper == Operator.Subtraction){
2559 return new PointerArithmetic (
2560 false, left, right, TypeManager.int64_type,
2563 Expression t = Make32or64 (ec, right);
2565 return new PointerArithmetic (oper == Operator.Addition, left, t, l, loc);
2567 } else if (r.IsPointer && oper == Operator.Addition){
2568 Expression t = Make32or64 (ec, left);
2570 return new PointerArithmetic (true, right, t, r, loc);
2575 // Enumeration operators
2577 bool lie = TypeManager.IsEnumType (l);
2578 bool rie = TypeManager.IsEnumType (r);
2582 // U operator - (E e, E f)
2584 if (oper == Operator.Subtraction){
2586 type = TypeManager.EnumToUnderlying (l);
2589 Error_OperatorCannotBeApplied ();
2595 // operator + (E e, U x)
2596 // operator - (E e, U x)
2598 if (oper == Operator.Addition || oper == Operator.Subtraction){
2599 Type enum_type = lie ? l : r;
2600 Type other_type = lie ? r : l;
2601 Type underlying_type = TypeManager.EnumToUnderlying (enum_type);
2603 if (underlying_type != other_type){
2604 temp = Convert.ImplicitConversion (ec, lie ? right : left, underlying_type, loc);
2614 Error_OperatorCannotBeApplied ();
2623 temp = Convert.ImplicitConversion (ec, right, l, loc);
2627 Error_OperatorCannotBeApplied ();
2631 temp = Convert.ImplicitConversion (ec, left, r, loc);
2636 Error_OperatorCannotBeApplied ();
2641 if (oper == Operator.Equality || oper == Operator.Inequality ||
2642 oper == Operator.LessThanOrEqual || oper == Operator.LessThan ||
2643 oper == Operator.GreaterThanOrEqual || oper == Operator.GreaterThan){
2644 if (left.Type != right.Type){
2645 Error_OperatorCannotBeApplied ();
2648 type = TypeManager.bool_type;
2652 if (oper == Operator.BitwiseAnd ||
2653 oper == Operator.BitwiseOr ||
2654 oper == Operator.ExclusiveOr){
2658 Error_OperatorCannotBeApplied ();
2662 if (oper == Operator.LeftShift || oper == Operator.RightShift)
2663 return CheckShiftArguments (ec);
2665 if (oper == Operator.LogicalOr || oper == Operator.LogicalAnd){
2666 if (l == TypeManager.bool_type && r == TypeManager.bool_type) {
2667 type = TypeManager.bool_type;
2672 Error_OperatorCannotBeApplied ();
2676 Expression e = new ConditionalLogicalOperator (
2677 oper == Operator.LogicalAnd, left, right, l, loc);
2678 return e.Resolve (ec);
2682 // operator & (bool x, bool y)
2683 // operator | (bool x, bool y)
2684 // operator ^ (bool x, bool y)
2686 if (l == TypeManager.bool_type && r == TypeManager.bool_type){
2687 if (oper == Operator.BitwiseAnd ||
2688 oper == Operator.BitwiseOr ||
2689 oper == Operator.ExclusiveOr){
2696 // Pointer comparison
2698 if (l.IsPointer && r.IsPointer){
2699 if (oper == Operator.Equality || oper == Operator.Inequality ||
2700 oper == Operator.LessThan || oper == Operator.LessThanOrEqual ||
2701 oper == Operator.GreaterThan || oper == Operator.GreaterThanOrEqual){
2702 type = TypeManager.bool_type;
2708 // We are dealing with numbers
2710 if (overload_failed){
2711 Error_OperatorCannotBeApplied ();
2716 // This will leave left or right set to null if there is an error
2718 bool check_user_conv = is_user_defined (l) && is_user_defined (r);
2719 DoNumericPromotions (ec, l, r, check_user_conv);
2720 if (left == null || right == null){
2721 Error_OperatorCannotBeApplied (loc, OperName (oper), l, r);
2726 // reload our cached types if required
2731 if (oper == Operator.BitwiseAnd ||
2732 oper == Operator.BitwiseOr ||
2733 oper == Operator.ExclusiveOr){
2735 if (!((l == TypeManager.int32_type) ||
2736 (l == TypeManager.uint32_type) ||
2737 (l == TypeManager.short_type) ||
2738 (l == TypeManager.ushort_type) ||
2739 (l == TypeManager.int64_type) ||
2740 (l == TypeManager.uint64_type))){
2744 Error_OperatorCannotBeApplied ();
2749 if (oper == Operator.Equality ||
2750 oper == Operator.Inequality ||
2751 oper == Operator.LessThanOrEqual ||
2752 oper == Operator.LessThan ||
2753 oper == Operator.GreaterThanOrEqual ||
2754 oper == Operator.GreaterThan){
2755 type = TypeManager.bool_type;
2761 public override Expression DoResolve (EmitContext ec)
2763 if ((oper == Operator.Subtraction) && (left is ParenthesizedExpression)) {
2764 left = ((ParenthesizedExpression) left).Expr;
2765 left = left.Resolve (ec, ResolveFlags.VariableOrValue | ResolveFlags.Type);
2769 if (left.eclass == ExprClass.Type) {
2770 Error (75, "Casting a negative value needs to have the value in parentheses.");
2774 left = left.Resolve (ec);
2775 right = right.Resolve (ec);
2777 if (left == null || right == null)
2780 eclass = ExprClass.Value;
2782 Constant rc = right as Constant;
2783 Constant lc = left as Constant;
2785 if (rc != null & lc != null){
2786 Expression e = ConstantFold.BinaryFold (
2787 ec, oper, lc, rc, loc);
2792 return ResolveOperator (ec);
2796 /// EmitBranchable is called from Statement.EmitBoolExpression in the
2797 /// context of a conditional bool expression. This function will return
2798 /// false if it is was possible to use EmitBranchable, or true if it was.
2800 /// The expression's code is generated, and we will generate a branch to `target'
2801 /// if the resulting expression value is equal to isTrue
2803 public override void EmitBranchable (EmitContext ec, Label target, bool onTrue)
2805 ILGenerator ig = ec.ig;
2808 // This is more complicated than it looks, but its just to avoid
2809 // duplicated tests: basically, we allow ==, !=, >, <, >= and <=
2810 // but on top of that we want for == and != to use a special path
2811 // if we are comparing against null
2813 if (oper == Operator.Equality || oper == Operator.Inequality) {
2814 bool my_on_true = oper == Operator.Inequality ? onTrue : !onTrue;
2816 if (left is NullLiteral || left is IntConstant && ((IntConstant) left).Value == 0) {
2819 ig.Emit (OpCodes.Brtrue, target);
2821 ig.Emit (OpCodes.Brfalse, target);
2824 } else if (right is NullLiteral || right is IntConstant && ((IntConstant) right).Value == 0){
2827 ig.Emit (OpCodes.Brtrue, target);
2829 ig.Emit (OpCodes.Brfalse, target);
2832 } else if (left is BoolConstant){
2834 if (my_on_true != ((BoolConstant) left).Value)
2835 ig.Emit (OpCodes.Brtrue, target);
2837 ig.Emit (OpCodes.Brfalse, target);
2840 } else if (right is BoolConstant){
2842 if (my_on_true != ((BoolConstant) right).Value)
2843 ig.Emit (OpCodes.Brtrue, target);
2845 ig.Emit (OpCodes.Brfalse, target);
2850 } else if (oper == Operator.LogicalAnd) {
2853 Label tests_end = ig.DefineLabel ();
2855 left.EmitBranchable (ec, tests_end, false);
2856 right.EmitBranchable (ec, target, true);
2857 ig.MarkLabel (tests_end);
2859 left.EmitBranchable (ec, target, false);
2860 right.EmitBranchable (ec, target, false);
2865 } else if (oper == Operator.LogicalOr){
2867 left.EmitBranchable (ec, target, true);
2868 right.EmitBranchable (ec, target, true);
2871 Label tests_end = ig.DefineLabel ();
2872 left.EmitBranchable (ec, tests_end, true);
2873 right.EmitBranchable (ec, target, false);
2874 ig.MarkLabel (tests_end);
2879 } else if (!(oper == Operator.LessThan || oper == Operator.GreaterThan ||
2880 oper == Operator.LessThanOrEqual || oper == Operator.GreaterThanOrEqual ||
2881 oper == Operator.Equality || oper == Operator.Inequality)) {
2882 base.EmitBranchable (ec, target, onTrue);
2890 bool isUnsigned = is_unsigned (t);
2893 case Operator.Equality:
2895 ig.Emit (OpCodes.Beq, target);
2897 ig.Emit (OpCodes.Bne_Un, target);
2900 case Operator.Inequality:
2902 ig.Emit (OpCodes.Bne_Un, target);
2904 ig.Emit (OpCodes.Beq, target);
2907 case Operator.LessThan:
2910 ig.Emit (OpCodes.Blt_Un, target);
2912 ig.Emit (OpCodes.Blt, target);
2915 ig.Emit (OpCodes.Bge_Un, target);
2917 ig.Emit (OpCodes.Bge, target);
2920 case Operator.GreaterThan:
2923 ig.Emit (OpCodes.Bgt_Un, target);
2925 ig.Emit (OpCodes.Bgt, target);
2928 ig.Emit (OpCodes.Ble_Un, target);
2930 ig.Emit (OpCodes.Ble, target);
2933 case Operator.LessThanOrEqual:
2934 if (t == TypeManager.double_type || t == TypeManager.float_type)
2939 ig.Emit (OpCodes.Ble_Un, target);
2941 ig.Emit (OpCodes.Ble, target);
2944 ig.Emit (OpCodes.Bgt_Un, target);
2946 ig.Emit (OpCodes.Bgt, target);
2950 case Operator.GreaterThanOrEqual:
2951 if (t == TypeManager.double_type || t == TypeManager.float_type)
2955 ig.Emit (OpCodes.Bge_Un, target);
2957 ig.Emit (OpCodes.Bge, target);
2960 ig.Emit (OpCodes.Blt_Un, target);
2962 ig.Emit (OpCodes.Blt, target);
2965 Console.WriteLine (oper);
2966 throw new Exception ("what is THAT");
2970 public override void Emit (EmitContext ec)
2972 ILGenerator ig = ec.ig;
2977 // Handle short-circuit operators differently
2980 if (oper == Operator.LogicalAnd) {
2981 Label load_zero = ig.DefineLabel ();
2982 Label end = ig.DefineLabel ();
2984 left.EmitBranchable (ec, load_zero, false);
2986 ig.Emit (OpCodes.Br, end);
2988 ig.MarkLabel (load_zero);
2989 ig.Emit (OpCodes.Ldc_I4_0);
2992 } else if (oper == Operator.LogicalOr) {
2993 Label load_one = ig.DefineLabel ();
2994 Label end = ig.DefineLabel ();
2996 left.EmitBranchable (ec, load_one, true);
2998 ig.Emit (OpCodes.Br, end);
3000 ig.MarkLabel (load_one);
3001 ig.Emit (OpCodes.Ldc_I4_1);
3009 bool isUnsigned = is_unsigned (left.Type);
3012 case Operator.Multiply:
3014 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
3015 opcode = OpCodes.Mul_Ovf;
3016 else if (isUnsigned)
3017 opcode = OpCodes.Mul_Ovf_Un;
3019 opcode = OpCodes.Mul;
3021 opcode = OpCodes.Mul;
3025 case Operator.Division:
3027 opcode = OpCodes.Div_Un;
3029 opcode = OpCodes.Div;
3032 case Operator.Modulus:
3034 opcode = OpCodes.Rem_Un;
3036 opcode = OpCodes.Rem;
3039 case Operator.Addition:
3041 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
3042 opcode = OpCodes.Add_Ovf;
3043 else if (isUnsigned)
3044 opcode = OpCodes.Add_Ovf_Un;
3046 opcode = OpCodes.Add;
3048 opcode = OpCodes.Add;
3051 case Operator.Subtraction:
3053 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
3054 opcode = OpCodes.Sub_Ovf;
3055 else if (isUnsigned)
3056 opcode = OpCodes.Sub_Ovf_Un;
3058 opcode = OpCodes.Sub;
3060 opcode = OpCodes.Sub;
3063 case Operator.RightShift:
3065 opcode = OpCodes.Shr_Un;
3067 opcode = OpCodes.Shr;
3070 case Operator.LeftShift:
3071 opcode = OpCodes.Shl;
3074 case Operator.Equality:
3075 opcode = OpCodes.Ceq;
3078 case Operator.Inequality:
3079 ig.Emit (OpCodes.Ceq);
3080 ig.Emit (OpCodes.Ldc_I4_0);
3082 opcode = OpCodes.Ceq;
3085 case Operator.LessThan:
3087 opcode = OpCodes.Clt_Un;
3089 opcode = OpCodes.Clt;
3092 case Operator.GreaterThan:
3094 opcode = OpCodes.Cgt_Un;
3096 opcode = OpCodes.Cgt;
3099 case Operator.LessThanOrEqual:
3100 Type lt = left.Type;
3102 if (isUnsigned || (lt == TypeManager.double_type || lt == TypeManager.float_type))
3103 ig.Emit (OpCodes.Cgt_Un);
3105 ig.Emit (OpCodes.Cgt);
3106 ig.Emit (OpCodes.Ldc_I4_0);
3108 opcode = OpCodes.Ceq;
3111 case Operator.GreaterThanOrEqual:
3112 Type le = left.Type;
3114 if (isUnsigned || (le == TypeManager.double_type || le == TypeManager.float_type))
3115 ig.Emit (OpCodes.Clt_Un);
3117 ig.Emit (OpCodes.Clt);
3119 ig.Emit (OpCodes.Ldc_I4_0);
3121 opcode = OpCodes.Ceq;
3124 case Operator.BitwiseOr:
3125 opcode = OpCodes.Or;
3128 case Operator.BitwiseAnd:
3129 opcode = OpCodes.And;
3132 case Operator.ExclusiveOr:
3133 opcode = OpCodes.Xor;
3137 throw new Exception ("This should not happen: Operator = "
3138 + oper.ToString ());
3146 // Object created by Binary when the binary operator uses an method instead of being
3147 // a binary operation that maps to a CIL binary operation.
3149 public class BinaryMethod : Expression {
3150 public MethodBase method;
3151 public ArrayList Arguments;
3153 public BinaryMethod (Type t, MethodBase m, ArrayList args)
3158 eclass = ExprClass.Value;
3161 public override Expression DoResolve (EmitContext ec)
3166 public override void Emit (EmitContext ec)
3168 ILGenerator ig = ec.ig;
3170 if (Arguments != null)
3171 Invocation.EmitArguments (ec, method, Arguments);
3173 if (method is MethodInfo)
3174 ig.Emit (OpCodes.Call, (MethodInfo) method);
3176 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
3181 // Object created with +/= on delegates
3183 public class BinaryDelegate : Expression {
3187 public BinaryDelegate (Type t, MethodInfo mi, ArrayList args)
3192 eclass = ExprClass.Value;
3195 public override Expression DoResolve (EmitContext ec)
3200 public override void Emit (EmitContext ec)
3202 ILGenerator ig = ec.ig;
3204 Invocation.EmitArguments (ec, method, args);
3206 ig.Emit (OpCodes.Call, (MethodInfo) method);
3207 ig.Emit (OpCodes.Castclass, type);
3210 public Expression Right {
3212 Argument arg = (Argument) args [1];
3217 public bool IsAddition {
3219 return method == TypeManager.delegate_combine_delegate_delegate;
3225 // User-defined conditional logical operator
3226 public class ConditionalLogicalOperator : Expression {
3227 Expression left, right;
3230 public ConditionalLogicalOperator (bool is_and, Expression left, Expression right, Type t, Location loc)
3233 eclass = ExprClass.Value;
3237 this.is_and = is_and;
3240 protected void Error19 ()
3242 Binary.Error_OperatorCannotBeApplied (loc, is_and ? "&&" : "||", type, type);
3245 protected void Error218 ()
3247 Error (218, "The type ('" + TypeManager.CSharpName (type) + "') must contain " +
3248 "declarations of operator true and operator false");
3251 Expression op_true, op_false, op;
3253 public override Expression DoResolve (EmitContext ec)
3256 Expression operator_group;
3258 operator_group = MethodLookup (ec, type, is_and ? "op_BitwiseAnd" : "op_BitwiseOr", loc);
3259 if (operator_group == null) {
3264 ArrayList arguments = new ArrayList ();
3265 arguments.Add (new Argument (left, Argument.AType.Expression));
3266 arguments.Add (new Argument (right, Argument.AType.Expression));
3267 method = Invocation.OverloadResolve (ec, (MethodGroupExpr) operator_group, arguments, loc) as MethodInfo;
3268 if ((method == null) || (method.ReturnType != type)) {
3273 op = new StaticCallExpr (method, arguments, loc);
3275 op_true = GetOperatorTrue (ec, left, loc);
3276 op_false = GetOperatorFalse (ec, left, loc);
3277 if ((op_true == null) || (op_false == null)) {
3285 public override void Emit (EmitContext ec)
3287 ILGenerator ig = ec.ig;
3288 Label false_target = ig.DefineLabel ();
3289 Label end_target = ig.DefineLabel ();
3291 ig.Emit (OpCodes.Nop);
3293 (is_and ? op_false : op_true).EmitBranchable (ec, false_target, false);
3295 ig.Emit (OpCodes.Br, end_target);
3296 ig.MarkLabel (false_target);
3298 ig.MarkLabel (end_target);
3300 ig.Emit (OpCodes.Nop);
3304 public class PointerArithmetic : Expression {
3305 Expression left, right;
3309 // We assume that `l' is always a pointer
3311 public PointerArithmetic (bool is_addition, Expression l, Expression r, Type t, Location loc)
3314 eclass = ExprClass.Variable;
3318 is_add = is_addition;
3321 public override Expression DoResolve (EmitContext ec)
3324 // We are born fully resolved
3329 public override void Emit (EmitContext ec)
3331 Type op_type = left.Type;
3332 ILGenerator ig = ec.ig;
3333 int size = GetTypeSize (TypeManager.GetElementType (op_type));
3334 Type rtype = right.Type;
3336 if (rtype.IsPointer){
3338 // handle (pointer - pointer)
3342 ig.Emit (OpCodes.Sub);
3346 ig.Emit (OpCodes.Sizeof, op_type);
3348 IntLiteral.EmitInt (ig, size);
3349 ig.Emit (OpCodes.Div);
3351 ig.Emit (OpCodes.Conv_I8);
3354 // handle + and - on (pointer op int)
3357 ig.Emit (OpCodes.Conv_I);
3361 ig.Emit (OpCodes.Sizeof, op_type);
3363 IntLiteral.EmitInt (ig, size);
3364 if (rtype == TypeManager.int64_type)
3365 ig.Emit (OpCodes.Conv_I8);
3366 else if (rtype == TypeManager.uint64_type)
3367 ig.Emit (OpCodes.Conv_U8);
3368 ig.Emit (OpCodes.Mul);
3369 ig.Emit (OpCodes.Conv_I);
3372 ig.Emit (OpCodes.Add);
3374 ig.Emit (OpCodes.Sub);
3380 /// Implements the ternary conditional operator (?:)
3382 public class Conditional : Expression {
3383 Expression expr, trueExpr, falseExpr;
3385 public Conditional (Expression expr, Expression trueExpr, Expression falseExpr, Location l)
3388 this.trueExpr = trueExpr;
3389 this.falseExpr = falseExpr;
3393 public Expression Expr {
3399 public Expression TrueExpr {
3405 public Expression FalseExpr {
3411 public override Expression DoResolve (EmitContext ec)
3413 expr = expr.Resolve (ec);
3418 if (expr.Type != TypeManager.bool_type){
3419 expr = Expression.ResolveBoolean (
3426 trueExpr = trueExpr.Resolve (ec);
3427 falseExpr = falseExpr.Resolve (ec);
3429 if (trueExpr == null || falseExpr == null)
3432 eclass = ExprClass.Value;
3433 if (trueExpr.Type == falseExpr.Type)
3434 type = trueExpr.Type;
3437 Type true_type = trueExpr.Type;
3438 Type false_type = falseExpr.Type;
3440 if (trueExpr is NullLiteral){
3443 } else if (falseExpr is NullLiteral){
3449 // First, if an implicit conversion exists from trueExpr
3450 // to falseExpr, then the result type is of type falseExpr.Type
3452 conv = Convert.ImplicitConversion (ec, trueExpr, false_type, loc);
3455 // Check if both can convert implicitl to each other's type
3457 if (Convert.ImplicitConversion (ec, falseExpr, true_type, loc) != null){
3459 "Can not compute type of conditional expression " +
3460 "as `" + TypeManager.CSharpName (trueExpr.Type) +
3461 "' and `" + TypeManager.CSharpName (falseExpr.Type) +
3462 "' convert implicitly to each other");
3467 } else if ((conv = Convert.ImplicitConversion(ec, falseExpr, true_type,loc))!= null){
3471 Error (173, "The type of the conditional expression can " +
3472 "not be computed because there is no implicit conversion" +
3473 " from `" + TypeManager.CSharpName (trueExpr.Type) + "'" +
3474 " and `" + TypeManager.CSharpName (falseExpr.Type) + "'");
3479 if (expr is BoolConstant){
3480 BoolConstant bc = (BoolConstant) expr;
3491 public override void Emit (EmitContext ec)
3493 ILGenerator ig = ec.ig;
3494 Label false_target = ig.DefineLabel ();
3495 Label end_target = ig.DefineLabel ();
3497 expr.EmitBranchable (ec, false_target, false);
3499 ig.Emit (OpCodes.Br, end_target);
3500 ig.MarkLabel (false_target);
3501 falseExpr.Emit (ec);
3502 ig.MarkLabel (end_target);
3510 public class LocalVariableReference : Expression, IAssignMethod, IMemoryLocation, IVariable {
3511 public readonly string Name;
3512 public readonly Block Block;
3513 LocalInfo local_info;
3516 public LocalVariableReference (Block block, string name, Location l)
3521 eclass = ExprClass.Variable;
3524 // Setting `is_readonly' to false will allow you to create a writable
3525 // reference to a read-only variable. This is used by foreach and using.
3526 public LocalVariableReference (Block block, string name, Location l,
3527 LocalInfo local_info, bool is_readonly)
3528 : this (block, name, l)
3530 this.local_info = local_info;
3531 this.is_readonly = is_readonly;
3534 public VariableInfo VariableInfo {
3535 get { return local_info.VariableInfo; }
3538 public bool IsReadOnly {
3544 protected void DoResolveBase (EmitContext ec)
3546 if (local_info == null) {
3547 local_info = Block.GetLocalInfo (Name);
3548 is_readonly = local_info.ReadOnly;
3551 type = local_info.VariableType;
3553 if (ec.InAnonymousMethod)
3554 Block.LiftVariable (local_info);
3558 protected Expression DoResolve (EmitContext ec, bool is_lvalue)
3560 Expression e = Block.GetConstantExpression (Name);
3562 local_info.Used = true;
3563 eclass = ExprClass.Value;
3567 VariableInfo variable_info = local_info.VariableInfo;
3568 if ((variable_info != null) && !variable_info.IsAssigned (ec, loc))
3572 local_info.Used = true;
3574 if (local_info.LocalBuilder == null)
3575 return ec.RemapLocal (local_info);
3580 public override Expression DoResolve (EmitContext ec)
3584 return DoResolve (ec, false);
3587 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
3591 VariableInfo variable_info = local_info.VariableInfo;
3592 if (variable_info != null)
3593 variable_info.SetAssigned (ec);
3595 Expression e = DoResolve (ec, true);
3601 Error (1604, "cannot assign to `" + Name + "' because it is readonly");
3605 if (local_info.LocalBuilder == null)
3606 return ec.RemapLocalLValue (local_info, right_side);
3611 public bool VerifyFixed (bool is_expression)
3613 return !is_expression || local_info.IsFixed;
3616 public override void Emit (EmitContext ec)
3618 ILGenerator ig = ec.ig;
3620 ig.Emit (OpCodes.Ldloc, local_info.LocalBuilder);
3623 public void EmitAssign (EmitContext ec, Expression source)
3625 ILGenerator ig = ec.ig;
3628 ig.Emit (OpCodes.Stloc, local_info.LocalBuilder);
3631 public void AddressOf (EmitContext ec, AddressOp mode)
3633 ILGenerator ig = ec.ig;
3635 ig.Emit (OpCodes.Ldloca, local_info.LocalBuilder);
3638 public override string ToString ()
3640 return String.Format ("{0} ({1}:{2})", GetType (), Name, loc);
3645 /// This represents a reference to a parameter in the intermediate
3648 public class ParameterReference : Expression, IAssignMethod, IMemoryLocation, IVariable {
3654 public Parameter.Modifier mod;
3655 public bool is_ref, is_out;
3657 public ParameterReference (Parameters pars, Block block, int idx, string name, Location loc)
3664 eclass = ExprClass.Variable;
3667 public VariableInfo VariableInfo {
3671 public bool VerifyFixed (bool is_expression)
3673 return !is_expression || TypeManager.IsValueType (type);
3676 public bool IsAssigned (EmitContext ec, Location loc)
3678 if (!ec.DoFlowAnalysis || !is_out ||
3679 ec.CurrentBranching.IsAssigned (vi))
3682 Report.Error (165, loc,
3683 "Use of unassigned parameter `" + name + "'");
3687 public bool IsFieldAssigned (EmitContext ec, string field_name, Location loc)
3689 if (!ec.DoFlowAnalysis || !is_out ||
3690 ec.CurrentBranching.IsFieldAssigned (vi, field_name))
3693 Report.Error (170, loc,
3694 "Use of possibly unassigned field `" + field_name + "'");
3698 public void SetAssigned (EmitContext ec)
3700 if (is_out && ec.DoFlowAnalysis)
3701 ec.CurrentBranching.SetAssigned (vi);
3704 public void SetFieldAssigned (EmitContext ec, string field_name)
3706 if (is_out && ec.DoFlowAnalysis)
3707 ec.CurrentBranching.SetFieldAssigned (vi, field_name);
3710 protected void DoResolveBase (EmitContext ec)
3712 type = pars.GetParameterInfo (ec.DeclSpace, idx, out mod);
3713 is_ref = (mod & Parameter.Modifier.ISBYREF) != 0;
3714 is_out = (mod & Parameter.Modifier.OUT) != 0;
3715 eclass = ExprClass.Variable;
3718 vi = block.ParameterMap [idx];
3722 // Notice that for ref/out parameters, the type exposed is not the
3723 // same type exposed externally.
3726 // externally we expose "int&"
3727 // here we expose "int".
3729 // We record this in "is_ref". This means that the type system can treat
3730 // the type as it is expected, but when we generate the code, we generate
3731 // the alternate kind of code.
3733 public override Expression DoResolve (EmitContext ec)
3737 if (is_out && ec.DoFlowAnalysis && !IsAssigned (ec, loc))
3740 if (ec.RemapToProxy)
3741 return ec.RemapParameter (idx);
3746 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
3752 if (ec.RemapToProxy)
3753 return ec.RemapParameterLValue (idx, right_side);
3758 static public void EmitLdArg (ILGenerator ig, int x)
3762 case 0: ig.Emit (OpCodes.Ldarg_0); break;
3763 case 1: ig.Emit (OpCodes.Ldarg_1); break;
3764 case 2: ig.Emit (OpCodes.Ldarg_2); break;
3765 case 3: ig.Emit (OpCodes.Ldarg_3); break;
3766 default: ig.Emit (OpCodes.Ldarg_S, (byte) x); break;
3769 ig.Emit (OpCodes.Ldarg, x);
3773 // This method is used by parameters that are references, that are
3774 // being passed as references: we only want to pass the pointer (that
3775 // is already stored in the parameter, not the address of the pointer,
3776 // and not the value of the variable).
3778 public void EmitLoad (EmitContext ec)
3780 ILGenerator ig = ec.ig;
3786 EmitLdArg (ig, arg_idx);
3789 public override void Emit (EmitContext ec)
3791 ILGenerator ig = ec.ig;
3798 EmitLdArg (ig, arg_idx);
3804 // If we are a reference, we loaded on the stack a pointer
3805 // Now lets load the real value
3807 LoadFromPtr (ig, type);
3810 public void EmitAssign (EmitContext ec, Expression source)
3812 ILGenerator ig = ec.ig;
3820 EmitLdArg (ig, arg_idx);
3825 StoreFromPtr (ig, type);
3828 ig.Emit (OpCodes.Starg_S, (byte) arg_idx);
3830 ig.Emit (OpCodes.Starg, arg_idx);
3834 public void AddressOf (EmitContext ec, AddressOp mode)
3843 ec.ig.Emit (OpCodes.Ldarg_S, (byte) arg_idx);
3845 ec.ig.Emit (OpCodes.Ldarg, arg_idx);
3848 ec.ig.Emit (OpCodes.Ldarga_S, (byte) arg_idx);
3850 ec.ig.Emit (OpCodes.Ldarga, arg_idx);
3857 /// Used for arguments to New(), Invocation()
3859 public class Argument {
3860 public enum AType : byte {
3866 public readonly AType ArgType;
3867 public Expression Expr;
3869 public Argument (Expression expr, AType type)
3872 this.ArgType = type;
3877 if (ArgType == AType.Ref || ArgType == AType.Out)
3878 return TypeManager.GetReferenceType (Expr.Type);
3884 public Parameter.Modifier GetParameterModifier ()
3888 return Parameter.Modifier.OUT | Parameter.Modifier.ISBYREF;
3891 return Parameter.Modifier.REF | Parameter.Modifier.ISBYREF;
3894 return Parameter.Modifier.NONE;
3898 public static string FullDesc (Argument a)
3900 return (a.ArgType == AType.Ref ? "ref " :
3901 (a.ArgType == AType.Out ? "out " : "")) +
3902 TypeManager.CSharpName (a.Expr.Type);
3905 public bool ResolveMethodGroup (EmitContext ec, Location loc)
3907 // FIXME: csc doesn't report any error if you try to use `ref' or
3908 // `out' in a delegate creation expression.
3909 Expr = Expr.Resolve (ec, ResolveFlags.VariableOrValue | ResolveFlags.MethodGroup);
3916 public bool Resolve (EmitContext ec, Location loc)
3918 if (ArgType == AType.Ref) {
3919 Expr = Expr.Resolve (ec);
3923 Expr = Expr.ResolveLValue (ec, Expr);
3924 } else if (ArgType == AType.Out)
3925 Expr = Expr.ResolveLValue (ec, new EmptyExpression ());
3927 Expr = Expr.Resolve (ec);
3932 if (ArgType == AType.Expression)
3935 if (Expr.eclass != ExprClass.Variable){
3937 // We just probe to match the CSC output
3939 if (Expr.eclass == ExprClass.PropertyAccess ||
3940 Expr.eclass == ExprClass.IndexerAccess){
3943 "A property or indexer can not be passed as an out or ref " +
3948 "An lvalue is required as an argument to out or ref");
3956 public void Emit (EmitContext ec)
3959 // Ref and Out parameters need to have their addresses taken.
3961 // ParameterReferences might already be references, so we want
3962 // to pass just the value
3964 if (ArgType == AType.Ref || ArgType == AType.Out){
3965 AddressOp mode = AddressOp.Store;
3967 if (ArgType == AType.Ref)
3968 mode |= AddressOp.Load;
3970 if (Expr is ParameterReference){
3971 ParameterReference pr = (ParameterReference) Expr;
3977 pr.AddressOf (ec, mode);
3980 ((IMemoryLocation)Expr).AddressOf (ec, mode);
3987 /// Invocation of methods or delegates.
3989 public class Invocation : ExpressionStatement {
3990 public readonly ArrayList Arguments;
3993 MethodBase method = null;
3996 static Hashtable method_parameter_cache;
3998 static Invocation ()
4000 method_parameter_cache = new PtrHashtable ();
4004 // arguments is an ArrayList, but we do not want to typecast,
4005 // as it might be null.
4007 // FIXME: only allow expr to be a method invocation or a
4008 // delegate invocation (7.5.5)
4010 public Invocation (Expression expr, ArrayList arguments, Location l)
4013 Arguments = arguments;
4017 public Expression Expr {
4024 /// Returns the Parameters (a ParameterData interface) for the
4027 public static ParameterData GetParameterData (MethodBase mb)
4029 object pd = method_parameter_cache [mb];
4033 return (ParameterData) pd;
4036 ip = TypeManager.LookupParametersByBuilder (mb);
4038 method_parameter_cache [mb] = ip;
4040 return (ParameterData) ip;
4042 ParameterInfo [] pi = mb.GetParameters ();
4043 ReflectionParameters rp = new ReflectionParameters (pi);
4044 method_parameter_cache [mb] = rp;
4046 return (ParameterData) rp;
4051 /// Determines "better conversion" as specified in 7.4.2.3
4053 /// Returns : 1 if a->p is better
4054 /// 0 if a->q or neither is better
4056 static int BetterConversion (EmitContext ec, Argument a, Type p, Type q, Location loc)
4058 Type argument_type = a.Type;
4059 Expression argument_expr = a.Expr;
4061 if (argument_type == null)
4062 throw new Exception ("Expression of type " + a.Expr +
4063 " does not resolve its type");
4066 // This is a special case since csc behaves this way. I can't find
4067 // it anywhere in the spec but oh well ...
4069 if (argument_expr is NullLiteral &&
4070 p == TypeManager.string_type &&
4071 q == TypeManager.object_type)
4073 else if (argument_expr is NullLiteral &&
4074 p == TypeManager.object_type &&
4075 q == TypeManager.string_type)
4081 if (argument_type == p)
4084 if (argument_type == q)
4088 // Now probe whether an implicit constant expression conversion
4091 // An implicit constant expression conversion permits the following
4094 // * A constant-expression of type `int' can be converted to type
4095 // sbyte, byute, short, ushort, uint, ulong provided the value of
4096 // of the expression is withing the range of the destination type.
4098 // * A constant-expression of type long can be converted to type
4099 // ulong, provided the value of the constant expression is not negative
4101 // FIXME: Note that this assumes that constant folding has
4102 // taken place. We dont do constant folding yet.
4105 if (argument_expr is IntConstant){
4106 IntConstant ei = (IntConstant) argument_expr;
4107 int value = ei.Value;
4109 if (p == TypeManager.sbyte_type){
4110 if (value >= SByte.MinValue && value <= SByte.MaxValue)
4112 } else if (p == TypeManager.byte_type){
4113 if (q == TypeManager.sbyte_type &&
4114 value >= SByte.MinValue && value <= SByte.MaxValue)
4116 else if (Byte.MinValue >= 0 && value <= Byte.MaxValue)
4118 } else if (p == TypeManager.short_type){
4119 if (value >= Int16.MinValue && value <= Int16.MaxValue)
4121 } else if (p == TypeManager.ushort_type){
4122 if (q == TypeManager.short_type &&
4123 value >= Int16.MinValue && value <= Int16.MaxValue)
4125 else if (value >= UInt16.MinValue && value <= UInt16.MaxValue)
4127 } else if (p == TypeManager.int32_type){
4128 if (value >= Int32.MinValue && value <= Int32.MaxValue)
4130 } else if (p == TypeManager.uint32_type){
4132 // we can optimize this case: a positive int32
4133 // always fits on a uint32
4137 } else if (p == TypeManager.uint64_type){
4139 // we can optimize this case: a positive int32
4140 // always fits on a uint64
4144 // This special case is needed because csc behaves like this.
4145 // int -> uint is better than int -> ulong!
4147 if (q == TypeManager.uint32_type)
4150 if (q == TypeManager.int64_type)
4152 else if (value >= 0)
4154 } else if (p == TypeManager.int64_type){
4157 } else if (argument_type == TypeManager.int64_type && argument_expr is LongConstant){
4158 LongConstant lc = (LongConstant) argument_expr;
4160 if (p == TypeManager.uint64_type){
4167 Expression tmp = Convert.ImplicitConversion (ec, argument_expr, p, loc);
4175 Expression p_tmp = new EmptyExpression (p);
4176 Expression q_tmp = new EmptyExpression (q);
4178 if (Convert.ImplicitConversionExists (ec, p_tmp, q) == true &&
4179 Convert.ImplicitConversionExists (ec, q_tmp, p) == false)
4182 if (p == TypeManager.sbyte_type)
4183 if (q == TypeManager.byte_type || q == TypeManager.ushort_type ||
4184 q == TypeManager.uint32_type || q == TypeManager.uint64_type)
4187 if (p == TypeManager.short_type)
4188 if (q == TypeManager.ushort_type || q == TypeManager.uint32_type ||
4189 q == TypeManager.uint64_type)
4192 if (p == TypeManager.int32_type)
4193 if (q == TypeManager.uint32_type || q == TypeManager.uint64_type)
4196 if (p == TypeManager.int64_type)
4197 if (q == TypeManager.uint64_type)
4204 /// Determines "Better function" between candidate
4205 /// and the current best match
4208 /// Returns an integer indicating :
4209 /// 0 if candidate ain't better
4210 /// 1 if candidate is better than the current best match
4212 static int BetterFunction (EmitContext ec, ArrayList args,
4213 MethodBase candidate, bool candidate_params,
4214 MethodBase best, bool best_params,
4217 ParameterData candidate_pd = GetParameterData (candidate);
4218 ParameterData best_pd;
4224 argument_count = args.Count;
4226 int cand_count = candidate_pd.Count;
4229 // If there is no best method, than this one
4230 // is better, however, if we already found a
4231 // best method, we cant tell. This happens
4243 // interface IFooBar : IFoo, IBar {}
4245 // We cant tell if IFoo.DoIt is better than IBar.DoIt
4247 // However, we have to consider that
4248 // Trim (); is better than Trim (params char[] chars);
4249 if (cand_count == 0 && argument_count == 0)
4250 return best == null || best_params ? 1 : 0;
4252 if (candidate_pd.ParameterModifier (cand_count - 1) != Parameter.Modifier.PARAMS)
4253 if (cand_count != argument_count)
4259 if (argument_count == 0 && cand_count == 1 &&
4260 candidate_pd.ParameterModifier (cand_count - 1) == Parameter.Modifier.PARAMS)
4263 for (int j = 0; j < argument_count; ++j) {
4265 Argument a = (Argument) args [j];
4266 Type t = candidate_pd.ParameterType (j);
4268 if (candidate_pd.ParameterModifier (j) == Parameter.Modifier.PARAMS)
4269 if (candidate_params)
4270 t = TypeManager.GetElementType (t);
4272 x = BetterConversion (ec, a, t, null, loc);
4284 best_pd = GetParameterData (best);
4286 int rating1 = 0, rating2 = 0;
4288 for (int j = 0; j < argument_count; ++j) {
4291 Argument a = (Argument) args [j];
4293 Type ct = candidate_pd.ParameterType (j);
4294 Type bt = best_pd.ParameterType (j);
4296 if (candidate_pd.ParameterModifier (j) == Parameter.Modifier.PARAMS)
4297 if (candidate_params)
4298 ct = TypeManager.GetElementType (ct);
4300 if (best_pd.ParameterModifier (j) == Parameter.Modifier.PARAMS)
4302 bt = TypeManager.GetElementType (bt);
4304 x = BetterConversion (ec, a, ct, bt, loc);
4305 y = BetterConversion (ec, a, bt, ct, loc);
4315 // If a method (in the normal form) with the
4316 // same signature as the expanded form of the
4317 // current best params method already exists,
4318 // the expanded form is not applicable so we
4319 // force it to select the candidate
4321 if (!candidate_params && best_params && cand_count == argument_count)
4324 if (rating1 > rating2)
4330 public static string FullMethodDesc (MethodBase mb)
4332 string ret_type = "";
4334 if (mb is MethodInfo)
4335 ret_type = TypeManager.CSharpName (((MethodInfo) mb).ReturnType);
4337 StringBuilder sb = new StringBuilder (ret_type);
4339 sb.Append (mb.ReflectedType.ToString ());
4341 sb.Append (mb.Name);
4343 ParameterData pd = GetParameterData (mb);
4345 int count = pd.Count;
4348 for (int i = count; i > 0; ) {
4351 sb.Append (pd.ParameterDesc (count - i - 1));
4357 return sb.ToString ();
4360 public static MethodGroupExpr MakeUnionSet (Expression mg1, Expression mg2, Location loc)
4362 MemberInfo [] miset;
4363 MethodGroupExpr union;
4368 return (MethodGroupExpr) mg2;
4371 return (MethodGroupExpr) mg1;
4374 MethodGroupExpr left_set = null, right_set = null;
4375 int length1 = 0, length2 = 0;
4377 left_set = (MethodGroupExpr) mg1;
4378 length1 = left_set.Methods.Length;
4380 right_set = (MethodGroupExpr) mg2;
4381 length2 = right_set.Methods.Length;
4383 ArrayList common = new ArrayList ();
4385 foreach (MethodBase r in right_set.Methods){
4386 if (TypeManager.ArrayContainsMethod (left_set.Methods, r))
4390 miset = new MemberInfo [length1 + length2 - common.Count];
4391 left_set.Methods.CopyTo (miset, 0);
4395 foreach (MethodBase r in right_set.Methods) {
4396 if (!common.Contains (r))
4400 union = new MethodGroupExpr (miset, loc);
4406 /// Determines if the candidate method, if a params method, is applicable
4407 /// in its expanded form to the given set of arguments
4409 static bool IsParamsMethodApplicable (EmitContext ec, ArrayList arguments, MethodBase candidate)
4413 if (arguments == null)
4416 arg_count = arguments.Count;
4418 ParameterData pd = GetParameterData (candidate);
4420 int pd_count = pd.Count;
4425 if (pd.ParameterModifier (pd_count - 1) != Parameter.Modifier.PARAMS)
4428 if (pd_count - 1 > arg_count)
4431 if (pd_count == 1 && arg_count == 0)
4435 // If we have come this far, the case which
4436 // remains is when the number of parameters is
4437 // less than or equal to the argument count.
4439 for (int i = 0; i < pd_count - 1; ++i) {
4441 Argument a = (Argument) arguments [i];
4443 Parameter.Modifier a_mod = a.GetParameterModifier () &
4444 ~(Parameter.Modifier.OUT | Parameter.Modifier.REF);
4445 Parameter.Modifier p_mod = pd.ParameterModifier (i) &
4446 ~(Parameter.Modifier.OUT | Parameter.Modifier.REF);
4448 if (a_mod == p_mod) {
4450 if (a_mod == Parameter.Modifier.NONE)
4451 if (!Convert.ImplicitConversionExists (ec,
4453 pd.ParameterType (i)))
4456 if ((a_mod & Parameter.Modifier.ISBYREF) != 0) {
4457 Type pt = pd.ParameterType (i);
4460 pt = TypeManager.GetReferenceType (pt);
4470 Type element_type = TypeManager.GetElementType (pd.ParameterType (pd_count - 1));
4472 for (int i = pd_count - 1; i < arg_count; i++) {
4473 Argument a = (Argument) arguments [i];
4475 if (!Convert.ImplicitConversionExists (ec, a.Expr, element_type))
4483 /// Determines if the candidate method is applicable (section 14.4.2.1)
4484 /// to the given set of arguments
4486 static bool IsApplicable (EmitContext ec, ArrayList arguments, MethodBase candidate)
4490 if (arguments == null)
4493 arg_count = arguments.Count;
4496 ParameterData pd = GetParameterData (candidate);
4498 if (arg_count != pd.Count)
4501 for (int i = arg_count; i > 0; ) {
4504 Argument a = (Argument) arguments [i];
4506 Parameter.Modifier a_mod = a.GetParameterModifier () &
4507 ~(Parameter.Modifier.OUT | Parameter.Modifier.REF);
4508 Parameter.Modifier p_mod = pd.ParameterModifier (i) &
4509 ~(Parameter.Modifier.OUT | Parameter.Modifier.REF);
4512 if (a_mod == p_mod ||
4513 (a_mod == Parameter.Modifier.NONE && p_mod == Parameter.Modifier.PARAMS)) {
4514 if (a_mod == Parameter.Modifier.NONE) {
4515 if (!Convert.ImplicitConversionExists (ec,
4517 pd.ParameterType (i)))
4521 if ((a_mod & Parameter.Modifier.ISBYREF) != 0) {
4522 Type pt = pd.ParameterType (i);
4525 pt = TypeManager.GetReferenceType (pt);
4540 /// Find the Applicable Function Members (7.4.2.1)
4542 /// me: Method Group expression with the members to select.
4543 /// it might contain constructors or methods (or anything
4544 /// that maps to a method).
4546 /// Arguments: ArrayList containing resolved Argument objects.
4548 /// loc: The location if we want an error to be reported, or a Null
4549 /// location for "probing" purposes.
4551 /// Returns: The MethodBase (either a ConstructorInfo or a MethodInfo)
4552 /// that is the best match of me on Arguments.
4555 public static MethodBase OverloadResolve (EmitContext ec, MethodGroupExpr me,
4556 ArrayList Arguments, Location loc)
4558 MethodBase method = null;
4559 Type applicable_type = null;
4561 ArrayList candidates = new ArrayList ();
4564 // Used to keep a map between the candidate
4565 // and whether it is being considered in its
4566 // normal or expanded form
4568 Hashtable candidate_to_form = new PtrHashtable ();
4572 // First we construct the set of applicable methods
4574 // We start at the top of the type hierarchy and
4575 // go down to find applicable methods
4577 applicable_type = me.DeclaringType;
4579 if (me.Name == "Invoke" && TypeManager.IsDelegateType (applicable_type)) {
4580 Error_InvokeOnDelegate (loc);
4584 bool found_applicable = false;
4586 foreach (MethodBase candidate in me.Methods){
4587 Type decl_type = candidate.DeclaringType;
4590 // If we have already found an applicable method
4591 // we eliminate all base types (Section 14.5.5.1)
4593 if (decl_type != applicable_type &&
4594 (applicable_type.IsSubclassOf (decl_type) ||
4595 TypeManager.ImplementsInterface (applicable_type, decl_type)) &&
4600 // Check if candidate is applicable (section 14.4.2.1)
4601 if (IsApplicable (ec, Arguments, candidate)) {
4602 // Candidate is applicable in normal form
4603 candidates.Add (candidate);
4604 applicable_type = candidate.DeclaringType;
4605 found_applicable = true;
4606 candidate_to_form [candidate] = false;
4608 if (IsParamsMethodApplicable (ec, Arguments, candidate)) {
4609 // Candidate is applicable in expanded form
4610 candidates.Add (candidate);
4611 applicable_type = candidate.DeclaringType;
4612 found_applicable = true;
4613 candidate_to_form [candidate] = true;
4619 // Now we actually find the best method
4621 int candidate_top = candidates.Count;
4622 for (int ix = 0; ix < candidate_top; ix++){
4623 MethodBase candidate = (MethodBase) candidates [ix];
4625 bool cand_params = (bool) candidate_to_form [candidate];
4626 bool method_params = false;
4629 method_params = (bool) candidate_to_form [method];
4631 int x = BetterFunction (ec, Arguments,
4632 candidate, cand_params,
4633 method, method_params,
4641 if (Arguments == null)
4644 argument_count = Arguments.Count;
4647 if (method == null) {
4649 // Okay so we have failed to find anything so we
4650 // return by providing info about the closest match
4652 for (int i = 0; i < me.Methods.Length; ++i) {
4654 MethodBase c = (MethodBase) me.Methods [i];
4655 ParameterData pd = GetParameterData (c);
4657 if (pd.Count != argument_count)
4660 VerifyArgumentsCompat (ec, Arguments, argument_count, c, false,
4665 if (!Location.IsNull (loc)) {
4666 string report_name = me.Name;
4667 if (report_name == ".ctor")
4668 report_name = me.DeclaringType.ToString ();
4670 Error_WrongNumArguments (loc, report_name, argument_count);
4677 // Now check that there are no ambiguities i.e the selected method
4678 // should be better than all the others
4680 bool best_params = (bool) candidate_to_form [method];
4682 for (int ix = 0; ix < candidate_top; ix++){
4683 MethodBase candidate = (MethodBase) candidates [ix];
4685 if (candidate == method)
4689 // If a normal method is applicable in
4690 // the sense that it has the same
4691 // number of arguments, then the
4692 // expanded params method is never
4693 // applicable so we debar the params
4696 if ((IsParamsMethodApplicable (ec, Arguments, candidate) &&
4697 IsApplicable (ec, Arguments, method)))
4700 bool cand_params = (bool) candidate_to_form [candidate];
4701 int x = BetterFunction (ec, Arguments,
4702 method, best_params,
4703 candidate, cand_params,
4709 "Ambiguous call when selecting function due to implicit casts");
4715 // And now check if the arguments are all
4716 // compatible, perform conversions if
4717 // necessary etc. and return if everything is
4720 if (!VerifyArgumentsCompat (ec, Arguments, argument_count, method,
4721 best_params, null, loc))
4727 static void Error_WrongNumArguments (Location loc, String name, int arg_count)
4729 Report.Error (1501, loc,
4730 "No overload for method `" + name + "' takes `" +
4731 arg_count + "' arguments");
4734 static void Error_InvokeOnDelegate (Location loc)
4736 Report.Error (1533, loc,
4737 "Invoke cannot be called directly on a delegate");
4740 static void Error_InvalidArguments (Location loc, int idx, MethodBase method,
4741 Type delegate_type, string arg_sig, string par_desc)
4743 if (delegate_type == null)
4744 Report.Error (1502, loc,
4745 "The best overloaded match for method '" +
4746 FullMethodDesc (method) +
4747 "' has some invalid arguments");
4749 Report.Error (1594, loc,
4750 "Delegate '" + delegate_type.ToString () +
4751 "' has some invalid arguments.");
4752 Report.Error (1503, loc,
4753 String.Format ("Argument {0}: Cannot convert from '{1}' to '{2}'",
4754 idx, arg_sig, par_desc));
4757 public static bool VerifyArgumentsCompat (EmitContext ec, ArrayList Arguments,
4760 bool chose_params_expanded,
4764 ParameterData pd = GetParameterData (method);
4765 int pd_count = pd.Count;
4767 for (int j = 0; j < argument_count; j++) {
4768 Argument a = (Argument) Arguments [j];
4769 Expression a_expr = a.Expr;
4770 Type parameter_type = pd.ParameterType (j);
4771 Parameter.Modifier pm = pd.ParameterModifier (j);
4773 if (pm == Parameter.Modifier.PARAMS){
4774 if ((pm & ~Parameter.Modifier.PARAMS) != a.GetParameterModifier ()) {
4775 if (!Location.IsNull (loc))
4776 Error_InvalidArguments (
4777 loc, j, method, delegate_type,
4778 Argument.FullDesc (a), pd.ParameterDesc (j));
4782 if (chose_params_expanded)
4783 parameter_type = TypeManager.GetElementType (parameter_type);
4788 if (pd.ParameterModifier (j) != a.GetParameterModifier ()){
4789 if (!Location.IsNull (loc))
4790 Error_InvalidArguments (
4791 loc, j, method, delegate_type,
4792 Argument.FullDesc (a), pd.ParameterDesc (j));
4800 if (a.Type != parameter_type){
4803 conv = Convert.ImplicitConversion (ec, a_expr, parameter_type, loc);
4806 if (!Location.IsNull (loc))
4807 Error_InvalidArguments (
4808 loc, j, method, delegate_type,
4809 Argument.FullDesc (a), pd.ParameterDesc (j));
4814 // Update the argument with the implicit conversion
4820 Parameter.Modifier a_mod = a.GetParameterModifier () &
4821 ~(Parameter.Modifier.OUT | Parameter.Modifier.REF);
4822 Parameter.Modifier p_mod = pd.ParameterModifier (j) &
4823 ~(Parameter.Modifier.OUT | Parameter.Modifier.REF);
4825 if (a_mod != p_mod &&
4826 pd.ParameterModifier (pd_count - 1) != Parameter.Modifier.PARAMS) {
4827 if (!Location.IsNull (loc)) {
4828 Report.Error (1502, loc,
4829 "The best overloaded match for method '" + FullMethodDesc (method)+
4830 "' has some invalid arguments");
4831 Report.Error (1503, loc,
4832 "Argument " + (j+1) +
4833 ": Cannot convert from '" + Argument.FullDesc (a)
4834 + "' to '" + pd.ParameterDesc (j) + "'");
4844 public override Expression DoResolve (EmitContext ec)
4847 // First, resolve the expression that is used to
4848 // trigger the invocation
4850 if (expr is BaseAccess)
4853 if (expr is ConstructedType)
4854 expr = ((ConstructedType) expr).GetMemberAccess (ec.TypeContainer.CurrentType);
4856 expr = expr.Resolve (ec, ResolveFlags.VariableOrValue | ResolveFlags.MethodGroup);
4860 if (!(expr is MethodGroupExpr)) {
4861 Type expr_type = expr.Type;
4863 if (expr_type != null){
4864 bool IsDelegate = TypeManager.IsDelegateType (expr_type);
4866 return (new DelegateInvocation (
4867 this.expr, Arguments, loc)).Resolve (ec);
4871 if (!(expr is MethodGroupExpr)){
4872 expr.Error_UnexpectedKind (ResolveFlags.MethodGroup);
4877 // Next, evaluate all the expressions in the argument list
4879 if (Arguments != null){
4880 foreach (Argument a in Arguments){
4881 if (!a.Resolve (ec, loc))
4886 MethodGroupExpr mg = (MethodGroupExpr) expr;
4887 method = OverloadResolve (ec, mg, Arguments, loc);
4889 if (method == null){
4891 "Could not find any applicable function for this argument list");
4895 MethodInfo mi = method as MethodInfo;
4897 type = TypeManager.TypeToCoreType (mi.ReturnType);
4898 if (!mi.IsStatic && !mg.IsExplicitImpl && (mg.InstanceExpression == null))
4899 SimpleName.Error_ObjectRefRequired (ec, loc, mi.Name);
4902 if (type.IsPointer){
4910 // Only base will allow this invocation to happen.
4912 if (is_base && method.IsAbstract){
4913 Report.Error (205, loc, "Cannot call an abstract base member: " +
4914 FullMethodDesc (method));
4918 if ((method.Attributes & MethodAttributes.SpecialName) != 0){
4919 if (TypeManager.IsSpecialMethod (method))
4920 Report.Error (571, loc, method.Name + ": can not call operator or accessor");
4923 eclass = ExprClass.Value;
4928 // Emits the list of arguments as an array
4930 static void EmitParams (EmitContext ec, int idx, ArrayList arguments)
4932 ILGenerator ig = ec.ig;
4933 int count = arguments.Count - idx;
4934 Argument a = (Argument) arguments [idx];
4935 Type t = a.Expr.Type;
4936 string array_type = t.FullName + "[]";
4939 array = ig.DeclareLocal (TypeManager.LookupType (array_type));
4940 IntConstant.EmitInt (ig, count);
4941 ig.Emit (OpCodes.Newarr, TypeManager.TypeToCoreType (t));
4942 ig.Emit (OpCodes.Stloc, array);
4944 int top = arguments.Count;
4945 for (int j = idx; j < top; j++){
4946 a = (Argument) arguments [j];
4948 ig.Emit (OpCodes.Ldloc, array);
4949 IntConstant.EmitInt (ig, j - idx);
4951 bool is_stobj, has_type_arg;
4952 OpCode op = ArrayAccess.GetStoreOpcode (t, out is_stobj, out has_type_arg);
4954 ig.Emit (OpCodes.Ldelema, t);
4963 ig.Emit (OpCodes.Ldloc, array);
4967 /// Emits a list of resolved Arguments that are in the arguments
4970 /// The MethodBase argument might be null if the
4971 /// emission of the arguments is known not to contain
4972 /// a `params' field (for example in constructors or other routines
4973 /// that keep their arguments in this structure)
4975 public static void EmitArguments (EmitContext ec, MethodBase mb, ArrayList arguments)
4979 pd = GetParameterData (mb);
4984 // If we are calling a params method with no arguments, special case it
4986 if (arguments == null){
4987 if (pd != null && pd.Count > 0 &&
4988 pd.ParameterModifier (0) == Parameter.Modifier.PARAMS){
4989 ILGenerator ig = ec.ig;
4991 IntConstant.EmitInt (ig, 0);
4992 ig.Emit (OpCodes.Newarr, TypeManager.GetElementType (pd.ParameterType (0)));
4998 int top = arguments.Count;
5000 for (int i = 0; i < top; i++){
5001 Argument a = (Argument) arguments [i];
5004 if (pd.ParameterModifier (i) == Parameter.Modifier.PARAMS){
5006 // Special case if we are passing the same data as the
5007 // params argument, do not put it in an array.
5009 if (pd.ParameterType (i) == a.Type)
5012 EmitParams (ec, i, arguments);
5020 if (pd != null && pd.Count > top &&
5021 pd.ParameterModifier (top) == Parameter.Modifier.PARAMS){
5022 ILGenerator ig = ec.ig;
5024 IntConstant.EmitInt (ig, 0);
5025 ig.Emit (OpCodes.Newarr, TypeManager.GetElementType (pd.ParameterType (top)));
5030 /// is_base tells whether we want to force the use of the `call'
5031 /// opcode instead of using callvirt. Call is required to call
5032 /// a specific method, while callvirt will always use the most
5033 /// recent method in the vtable.
5035 /// is_static tells whether this is an invocation on a static method
5037 /// instance_expr is an expression that represents the instance
5038 /// it must be non-null if is_static is false.
5040 /// method is the method to invoke.
5042 /// Arguments is the list of arguments to pass to the method or constructor.
5044 public static void EmitCall (EmitContext ec, bool is_base,
5045 bool is_static, Expression instance_expr,
5046 MethodBase method, ArrayList Arguments, Location loc)
5048 ILGenerator ig = ec.ig;
5049 bool struct_call = false;
5051 Type decl_type = method.DeclaringType;
5053 if (!RootContext.StdLib) {
5054 // Replace any calls to the system's System.Array type with calls to
5055 // the newly created one.
5056 if (method == TypeManager.system_int_array_get_length)
5057 method = TypeManager.int_array_get_length;
5058 else if (method == TypeManager.system_int_array_get_rank)
5059 method = TypeManager.int_array_get_rank;
5060 else if (method == TypeManager.system_object_array_clone)
5061 method = TypeManager.object_array_clone;
5062 else if (method == TypeManager.system_int_array_get_length_int)
5063 method = TypeManager.int_array_get_length_int;
5064 else if (method == TypeManager.system_int_array_get_lower_bound_int)
5065 method = TypeManager.int_array_get_lower_bound_int;
5066 else if (method == TypeManager.system_int_array_get_upper_bound_int)
5067 method = TypeManager.int_array_get_upper_bound_int;
5068 else if (method == TypeManager.system_void_array_copyto_array_int)
5069 method = TypeManager.void_array_copyto_array_int;
5073 // This checks the `ConditionalAttribute' on the method, and the
5074 // ObsoleteAttribute
5076 TypeManager.MethodFlags flags = TypeManager.GetMethodFlags (method, loc);
5077 if ((flags & TypeManager.MethodFlags.IsObsoleteError) != 0)
5079 if ((flags & TypeManager.MethodFlags.ShouldIgnore) != 0)
5083 if (TypeManager.IsValueType (decl_type))
5086 // If this is ourselves, push "this"
5088 if (instance_expr == null){
5089 ig.Emit (OpCodes.Ldarg_0);
5092 // Push the instance expression
5094 if (TypeManager.IsValueType (instance_expr.Type)){
5096 // Special case: calls to a function declared in a
5097 // reference-type with a value-type argument need
5098 // to have their value boxed.
5100 if (!instance_expr.Type.IsGenericParameter)
5102 if (TypeManager.IsValueType (decl_type)){
5104 // If the expression implements IMemoryLocation, then
5105 // we can optimize and use AddressOf on the
5108 // If not we have to use some temporary storage for
5110 if (instance_expr is IMemoryLocation){
5111 ((IMemoryLocation)instance_expr).
5112 AddressOf (ec, AddressOp.LoadStore);
5115 Type t = instance_expr.Type;
5117 instance_expr.Emit (ec);
5118 LocalBuilder temp = ig.DeclareLocal (t);
5119 ig.Emit (OpCodes.Stloc, temp);
5120 ig.Emit (OpCodes.Ldloca, temp);
5123 instance_expr.Emit (ec);
5124 ig.Emit (OpCodes.Box, instance_expr.Type);
5127 instance_expr.Emit (ec);
5131 EmitArguments (ec, method, Arguments);
5133 if (is_static || struct_call || is_base){
5134 if (method is MethodInfo) {
5135 ig.Emit (OpCodes.Call, (MethodInfo) method);
5137 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
5139 if (method is MethodInfo)
5140 ig.Emit (OpCodes.Callvirt, (MethodInfo) method);
5142 ig.Emit (OpCodes.Callvirt, (ConstructorInfo) method);
5146 public override void Emit (EmitContext ec)
5148 MethodGroupExpr mg = (MethodGroupExpr) this.expr;
5150 EmitCall (ec, is_base, method.IsStatic, mg.InstanceExpression, method, Arguments, loc);
5153 public override void EmitStatement (EmitContext ec)
5158 // Pop the return value if there is one
5160 if (method is MethodInfo){
5161 Type ret = ((MethodInfo)method).ReturnType;
5162 if (TypeManager.TypeToCoreType (ret) != TypeManager.void_type)
5163 ec.ig.Emit (OpCodes.Pop);
5168 public class InvocationOrCast : ExpressionStatement
5171 Expression argument;
5173 public InvocationOrCast (Expression expr, Expression argument, Location loc)
5176 this.argument = argument;
5180 public override Expression DoResolve (EmitContext ec)
5183 // First try to resolve it as a cast.
5185 type = ec.DeclSpace.ResolveType (expr, true, loc);
5187 Cast cast = new Cast (new TypeExpression (type, loc), argument, loc);
5188 return cast.Resolve (ec);
5192 // This can either be a type or a delegate invocation.
5193 // Let's just resolve it and see what we'll get.
5195 expr = expr.Resolve (ec, ResolveFlags.Type | ResolveFlags.VariableOrValue);
5200 // Ok, so it's a Cast.
5202 if (expr.eclass == ExprClass.Type) {
5203 Cast cast = new Cast (new TypeExpression (expr.Type, loc), argument, loc);
5204 return cast.Resolve (ec);
5208 // It's a delegate invocation.
5210 if (!TypeManager.IsDelegateType (expr.Type)) {
5211 Error (149, "Method name expected");
5215 ArrayList args = new ArrayList ();
5216 args.Add (new Argument (argument, Argument.AType.Expression));
5217 DelegateInvocation invocation = new DelegateInvocation (expr, args, loc);
5218 return invocation.Resolve (ec);
5223 Error (201, "Only assignment, call, increment, decrement and new object " +
5224 "expressions can be used as a statement");
5227 public override ExpressionStatement ResolveStatement (EmitContext ec)
5230 // First try to resolve it as a cast.
5232 type = ec.DeclSpace.ResolveType (expr, true, loc);
5239 // This can either be a type or a delegate invocation.
5240 // Let's just resolve it and see what we'll get.
5242 expr = expr.Resolve (ec, ResolveFlags.Type | ResolveFlags.VariableOrValue);
5243 if ((expr == null) || (expr.eclass == ExprClass.Type)) {
5249 // It's a delegate invocation.
5251 if (!TypeManager.IsDelegateType (expr.Type)) {
5252 Error (149, "Method name expected");
5256 ArrayList args = new ArrayList ();
5257 args.Add (new Argument (argument, Argument.AType.Expression));
5258 DelegateInvocation invocation = new DelegateInvocation (expr, args, loc);
5259 return invocation.ResolveStatement (ec);
5262 public override void Emit (EmitContext ec)
5264 throw new Exception ("Cannot happen");
5267 public override void EmitStatement (EmitContext ec)
5269 throw new Exception ("Cannot happen");
5274 // This class is used to "disable" the code generation for the
5275 // temporary variable when initializing value types.
5277 class EmptyAddressOf : EmptyExpression, IMemoryLocation {
5278 public void AddressOf (EmitContext ec, AddressOp Mode)
5285 /// Implements the new expression
5287 public class New : ExpressionStatement, IMemoryLocation {
5288 public readonly ArrayList Arguments;
5291 // During bootstrap, it contains the RequestedType,
5292 // but if `type' is not null, it *might* contain a NewDelegate
5293 // (because of field multi-initialization)
5295 public Expression RequestedType;
5297 MethodBase method = null;
5300 // If set, the new expression is for a value_target, and
5301 // we will not leave anything on the stack.
5303 Expression value_target;
5304 bool value_target_set = false;
5306 public New (Expression requested_type, ArrayList arguments, Location l)
5308 RequestedType = requested_type;
5309 Arguments = arguments;
5313 public bool SetValueTypeVariable (Expression value)
5315 value_target = value;
5316 value_target_set = true;
5317 if (!(value_target is IMemoryLocation)){
5318 Error_UnexpectedKind ("variable");
5325 // This function is used to disable the following code sequence for
5326 // value type initialization:
5328 // AddressOf (temporary)
5332 // Instead the provide will have provided us with the address on the
5333 // stack to store the results.
5335 static Expression MyEmptyExpression;
5337 public void DisableTemporaryValueType ()
5339 if (MyEmptyExpression == null)
5340 MyEmptyExpression = new EmptyAddressOf ();
5343 // To enable this, look into:
5344 // test-34 and test-89 and self bootstrapping.
5346 // For instance, we can avoid a copy by using `newobj'
5347 // instead of Call + Push-temp on value types.
5348 // value_target = MyEmptyExpression;
5351 public override Expression DoResolve (EmitContext ec)
5354 // The New DoResolve might be called twice when initializing field
5355 // expressions (see EmitFieldInitializers, the call to
5356 // GetInitializerExpression will perform a resolve on the expression,
5357 // and later the assign will trigger another resolution
5359 // This leads to bugs (#37014)
5362 if (RequestedType is NewDelegate)
5363 return RequestedType;
5367 type = ec.DeclSpace.ResolveType (RequestedType, false, loc);
5372 bool IsDelegate = TypeManager.IsDelegateType (type);
5375 RequestedType = (new NewDelegate (type, Arguments, loc)).Resolve (ec);
5376 if (RequestedType != null)
5377 if (!(RequestedType is NewDelegate))
5378 throw new Exception ("NewDelegate.Resolve returned a non NewDelegate: " + RequestedType.GetType ());
5379 return RequestedType;
5382 if (type.IsInterface || type.IsAbstract){
5383 Error (144, "It is not possible to create instances of interfaces or abstract classes");
5387 bool is_struct = type.IsValueType;
5388 eclass = ExprClass.Value;
5391 // SRE returns a match for .ctor () on structs (the object constructor),
5392 // so we have to manually ignore it.
5394 if (is_struct && Arguments == null)
5398 ml = MemberLookupFinal (ec, null, type, ".ctor",
5399 MemberTypes.Constructor,
5400 AllBindingFlags | BindingFlags.DeclaredOnly, loc);
5405 if (! (ml is MethodGroupExpr)){
5407 ml.Error_UnexpectedKind ("method group");
5413 if (Arguments != null){
5414 foreach (Argument a in Arguments){
5415 if (!a.Resolve (ec, loc))
5420 method = Invocation.OverloadResolve (ec, (MethodGroupExpr) ml, Arguments, loc);
5424 if (method == null) {
5425 if (!is_struct || Arguments.Count > 0) {
5426 Error (1501, String.Format (
5427 "New invocation: Can not find a constructor in `{0}' for this argument list",
5428 TypeManager.CSharpName (type)));
5437 // This DoEmit can be invoked in two contexts:
5438 // * As a mechanism that will leave a value on the stack (new object)
5439 // * As one that wont (init struct)
5441 // You can control whether a value is required on the stack by passing
5442 // need_value_on_stack. The code *might* leave a value on the stack
5443 // so it must be popped manually
5445 // If we are dealing with a ValueType, we have a few
5446 // situations to deal with:
5448 // * The target is a ValueType, and we have been provided
5449 // the instance (this is easy, we are being assigned).
5451 // * The target of New is being passed as an argument,
5452 // to a boxing operation or a function that takes a
5455 // In this case, we need to create a temporary variable
5456 // that is the argument of New.
5458 // Returns whether a value is left on the stack
5460 bool DoEmit (EmitContext ec, bool need_value_on_stack)
5462 bool is_value_type = type.IsValueType;
5463 ILGenerator ig = ec.ig;
5468 // Allow DoEmit() to be called multiple times.
5469 // We need to create a new LocalTemporary each time since
5470 // you can't share LocalBuilders among ILGeneators.
5471 if (!value_target_set)
5472 value_target = new LocalTemporary (ec, type);
5474 ml = (IMemoryLocation) value_target;
5475 ml.AddressOf (ec, AddressOp.Store);
5479 Invocation.EmitArguments (ec, method, Arguments);
5483 ig.Emit (OpCodes.Initobj, type);
5485 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
5486 if (need_value_on_stack){
5487 value_target.Emit (ec);
5492 ig.Emit (OpCodes.Newobj, (ConstructorInfo) method);
5497 public override void Emit (EmitContext ec)
5502 public override void EmitStatement (EmitContext ec)
5504 if (DoEmit (ec, false))
5505 ec.ig.Emit (OpCodes.Pop);
5508 public void AddressOf (EmitContext ec, AddressOp Mode)
5510 if (!type.IsValueType){
5512 // We throw an exception. So far, I believe we only need to support
5514 // foreach (int j in new StructType ())
5517 throw new Exception ("AddressOf should not be used for classes");
5520 if (!value_target_set)
5521 value_target = new LocalTemporary (ec, type);
5523 IMemoryLocation ml = (IMemoryLocation) value_target;
5524 ml.AddressOf (ec, AddressOp.Store);
5526 Invocation.EmitArguments (ec, method, Arguments);
5529 ec.ig.Emit (OpCodes.Initobj, type);
5531 ec.ig.Emit (OpCodes.Call, (ConstructorInfo) method);
5533 ((IMemoryLocation) value_target).AddressOf (ec, Mode);
5538 /// 14.5.10.2: Represents an array creation expression.
5542 /// There are two possible scenarios here: one is an array creation
5543 /// expression that specifies the dimensions and optionally the
5544 /// initialization data and the other which does not need dimensions
5545 /// specified but where initialization data is mandatory.
5547 public class ArrayCreation : ExpressionStatement {
5548 Expression requested_base_type;
5549 ArrayList initializers;
5552 // The list of Argument types.
5553 // This is used to construct the `newarray' or constructor signature
5555 ArrayList arguments;
5558 // Method used to create the array object.
5560 MethodBase new_method = null;
5562 Type array_element_type;
5563 Type underlying_type;
5564 bool is_one_dimensional = false;
5565 bool is_builtin_type = false;
5566 bool expect_initializers = false;
5567 int num_arguments = 0;
5571 ArrayList array_data;
5576 // The number of array initializers that we can handle
5577 // via the InitializeArray method - through EmitStaticInitializers
5579 int num_automatic_initializers;
5581 const int max_automatic_initializers = 6;
5583 public ArrayCreation (Expression requested_base_type, ArrayList exprs, string rank, ArrayList initializers, Location l)
5585 this.requested_base_type = requested_base_type;
5586 this.initializers = initializers;
5590 arguments = new ArrayList ();
5592 foreach (Expression e in exprs) {
5593 arguments.Add (new Argument (e, Argument.AType.Expression));
5598 public ArrayCreation (Expression requested_base_type, string rank, ArrayList initializers, Location l)
5600 this.requested_base_type = requested_base_type;
5601 this.initializers = initializers;
5605 //this.rank = rank.Substring (0, rank.LastIndexOf ('['));
5607 //string tmp = rank.Substring (rank.LastIndexOf ('['));
5609 //dimensions = tmp.Length - 1;
5610 expect_initializers = true;
5613 public Expression FormArrayType (Expression base_type, int idx_count, string rank)
5615 StringBuilder sb = new StringBuilder (rank);
5618 for (int i = 1; i < idx_count; i++)
5623 return new ComposedCast (base_type, sb.ToString (), loc);
5626 void Error_IncorrectArrayInitializer ()
5628 Error (178, "Incorrectly structured array initializer");
5631 public bool CheckIndices (EmitContext ec, ArrayList probe, int idx, bool specified_dims)
5633 if (specified_dims) {
5634 Argument a = (Argument) arguments [idx];
5636 if (!a.Resolve (ec, loc))
5639 if (!(a.Expr is Constant)) {
5640 Error (150, "A constant value is expected");
5644 int value = (int) ((Constant) a.Expr).GetValue ();
5646 if (value != probe.Count) {
5647 Error_IncorrectArrayInitializer ();
5651 bounds [idx] = value;
5654 int child_bounds = -1;
5655 foreach (object o in probe) {
5656 if (o is ArrayList) {
5657 int current_bounds = ((ArrayList) o).Count;
5659 if (child_bounds == -1)
5660 child_bounds = current_bounds;
5662 else if (child_bounds != current_bounds){
5663 Error_IncorrectArrayInitializer ();
5666 if (specified_dims && (idx + 1 >= arguments.Count)){
5667 Error (623, "Array initializers can only be used in a variable or field initializer, try using the new expression");
5671 bool ret = CheckIndices (ec, (ArrayList) o, idx + 1, specified_dims);
5675 if (child_bounds != -1){
5676 Error_IncorrectArrayInitializer ();
5680 Expression tmp = (Expression) o;
5681 tmp = tmp.Resolve (ec);
5685 // Console.WriteLine ("I got: " + tmp);
5686 // Handle initialization from vars, fields etc.
5688 Expression conv = Convert.ImplicitConversionRequired (
5689 ec, tmp, underlying_type, loc);
5694 if (conv is StringConstant)
5695 array_data.Add (conv);
5696 else if (conv is Constant) {
5697 array_data.Add (conv);
5698 num_automatic_initializers++;
5700 array_data.Add (conv);
5707 public void UpdateIndices (EmitContext ec)
5710 for (ArrayList probe = initializers; probe != null;) {
5711 if (probe.Count > 0 && probe [0] is ArrayList) {
5712 Expression e = new IntConstant (probe.Count);
5713 arguments.Add (new Argument (e, Argument.AType.Expression));
5715 bounds [i++] = probe.Count;
5717 probe = (ArrayList) probe [0];
5720 Expression e = new IntConstant (probe.Count);
5721 arguments.Add (new Argument (e, Argument.AType.Expression));
5723 bounds [i++] = probe.Count;
5730 public bool ValidateInitializers (EmitContext ec, Type array_type)
5732 if (initializers == null) {
5733 if (expect_initializers)
5739 if (underlying_type == null)
5743 // We use this to store all the date values in the order in which we
5744 // will need to store them in the byte blob later
5746 array_data = new ArrayList ();
5747 bounds = new Hashtable ();
5751 if (arguments != null) {
5752 ret = CheckIndices (ec, initializers, 0, true);
5755 arguments = new ArrayList ();
5757 ret = CheckIndices (ec, initializers, 0, false);
5764 if (arguments.Count != dimensions) {
5765 Error_IncorrectArrayInitializer ();
5773 void Error_NegativeArrayIndex ()
5775 Error (284, "Can not create array with a negative size");
5779 // Converts `source' to an int, uint, long or ulong.
5781 Expression ExpressionToArrayArgument (EmitContext ec, Expression source)
5785 bool old_checked = ec.CheckState;
5786 ec.CheckState = true;
5788 target = Convert.ImplicitConversion (ec, source, TypeManager.int32_type, loc);
5789 if (target == null){
5790 target = Convert.ImplicitConversion (ec, source, TypeManager.uint32_type, loc);
5791 if (target == null){
5792 target = Convert.ImplicitConversion (ec, source, TypeManager.int64_type, loc);
5793 if (target == null){
5794 target = Convert.ImplicitConversion (ec, source, TypeManager.uint64_type, loc);
5796 Convert.Error_CannotImplicitConversion (loc, source.Type, TypeManager.int32_type);
5800 ec.CheckState = old_checked;
5803 // Only positive constants are allowed at compile time
5805 if (target is Constant){
5806 if (target is IntConstant){
5807 if (((IntConstant) target).Value < 0){
5808 Error_NegativeArrayIndex ();
5813 if (target is LongConstant){
5814 if (((LongConstant) target).Value < 0){
5815 Error_NegativeArrayIndex ();
5826 // Creates the type of the array
5828 bool LookupType (EmitContext ec)
5830 StringBuilder array_qualifier = new StringBuilder (rank);
5833 // `In the first form allocates an array instace of the type that results
5834 // from deleting each of the individual expression from the expression list'
5836 if (num_arguments > 0) {
5837 array_qualifier.Append ("[");
5838 for (int i = num_arguments-1; i > 0; i--)
5839 array_qualifier.Append (",");
5840 array_qualifier.Append ("]");
5846 Expression array_type_expr;
5847 array_type_expr = new ComposedCast (requested_base_type, array_qualifier.ToString (), loc);
5848 type = ec.DeclSpace.ResolveType (array_type_expr, false, loc);
5853 underlying_type = type;
5854 if (underlying_type.IsArray)
5855 underlying_type = TypeManager.GetElementType (underlying_type);
5856 dimensions = type.GetArrayRank ();
5861 public override Expression DoResolve (EmitContext ec)
5865 if (!LookupType (ec))
5869 // First step is to validate the initializers and fill
5870 // in any missing bits
5872 if (!ValidateInitializers (ec, type))
5875 if (arguments == null)
5878 arg_count = arguments.Count;
5879 foreach (Argument a in arguments){
5880 if (!a.Resolve (ec, loc))
5883 Expression real_arg = ExpressionToArrayArgument (ec, a.Expr, loc);
5884 if (real_arg == null)
5891 array_element_type = TypeManager.GetElementType (type);
5893 if (arg_count == 1) {
5894 is_one_dimensional = true;
5895 eclass = ExprClass.Value;
5899 is_builtin_type = TypeManager.IsBuiltinType (type);
5901 if (is_builtin_type) {
5904 ml = MemberLookup (ec, type, ".ctor", MemberTypes.Constructor,
5905 AllBindingFlags, loc);
5907 if (!(ml is MethodGroupExpr)) {
5908 ml.Error_UnexpectedKind ("method group");
5913 Error (-6, "New invocation: Can not find a constructor for " +
5914 "this argument list");
5918 new_method = Invocation.OverloadResolve (ec, (MethodGroupExpr) ml, arguments, loc);
5920 if (new_method == null) {
5921 Error (-6, "New invocation: Can not find a constructor for " +
5922 "this argument list");
5926 eclass = ExprClass.Value;
5929 ModuleBuilder mb = CodeGen.Module.Builder;
5930 ArrayList args = new ArrayList ();
5932 if (arguments != null) {
5933 for (int i = 0; i < arg_count; i++)
5934 args.Add (TypeManager.int32_type);
5937 Type [] arg_types = null;
5940 arg_types = new Type [args.Count];
5942 args.CopyTo (arg_types, 0);
5944 new_method = mb.GetArrayMethod (type, ".ctor", CallingConventions.HasThis, null,
5947 if (new_method == null) {
5948 Error (-6, "New invocation: Can not find a constructor for " +
5949 "this argument list");
5953 eclass = ExprClass.Value;
5958 public static byte [] MakeByteBlob (ArrayList array_data, Type underlying_type, Location loc)
5963 int count = array_data.Count;
5965 if (underlying_type.IsEnum)
5966 underlying_type = TypeManager.EnumToUnderlying (underlying_type);
5968 factor = GetTypeSize (underlying_type);
5970 throw new Exception ("unrecognized type in MakeByteBlob: " + underlying_type);
5972 data = new byte [(count * factor + 4) & ~3];
5975 for (int i = 0; i < count; ++i) {
5976 object v = array_data [i];
5978 if (v is EnumConstant)
5979 v = ((EnumConstant) v).Child;
5981 if (v is Constant && !(v is StringConstant))
5982 v = ((Constant) v).GetValue ();
5988 if (underlying_type == TypeManager.int64_type){
5989 if (!(v is Expression)){
5990 long val = (long) v;
5992 for (int j = 0; j < factor; ++j) {
5993 data [idx + j] = (byte) (val & 0xFF);
5997 } else if (underlying_type == TypeManager.uint64_type){
5998 if (!(v is Expression)){
5999 ulong val = (ulong) v;
6001 for (int j = 0; j < factor; ++j) {
6002 data [idx + j] = (byte) (val & 0xFF);
6006 } else if (underlying_type == TypeManager.float_type) {
6007 if (!(v is Expression)){
6008 element = BitConverter.GetBytes ((float) v);
6010 for (int j = 0; j < factor; ++j)
6011 data [idx + j] = element [j];
6013 } else if (underlying_type == TypeManager.double_type) {
6014 if (!(v is Expression)){
6015 element = BitConverter.GetBytes ((double) v);
6017 for (int j = 0; j < factor; ++j)
6018 data [idx + j] = element [j];
6020 } else if (underlying_type == TypeManager.char_type){
6021 if (!(v is Expression)){
6022 int val = (int) ((char) v);
6024 data [idx] = (byte) (val & 0xff);
6025 data [idx+1] = (byte) (val >> 8);
6027 } else if (underlying_type == TypeManager.short_type){
6028 if (!(v is Expression)){
6029 int val = (int) ((short) v);
6031 data [idx] = (byte) (val & 0xff);
6032 data [idx+1] = (byte) (val >> 8);
6034 } else if (underlying_type == TypeManager.ushort_type){
6035 if (!(v is Expression)){
6036 int val = (int) ((ushort) v);
6038 data [idx] = (byte) (val & 0xff);
6039 data [idx+1] = (byte) (val >> 8);
6041 } else if (underlying_type == TypeManager.int32_type) {
6042 if (!(v is Expression)){
6045 data [idx] = (byte) (val & 0xff);
6046 data [idx+1] = (byte) ((val >> 8) & 0xff);
6047 data [idx+2] = (byte) ((val >> 16) & 0xff);
6048 data [idx+3] = (byte) (val >> 24);
6050 } else if (underlying_type == TypeManager.uint32_type) {
6051 if (!(v is Expression)){
6052 uint val = (uint) v;
6054 data [idx] = (byte) (val & 0xff);
6055 data [idx+1] = (byte) ((val >> 8) & 0xff);
6056 data [idx+2] = (byte) ((val >> 16) & 0xff);
6057 data [idx+3] = (byte) (val >> 24);
6059 } else if (underlying_type == TypeManager.sbyte_type) {
6060 if (!(v is Expression)){
6061 sbyte val = (sbyte) v;
6062 data [idx] = (byte) val;
6064 } else if (underlying_type == TypeManager.byte_type) {
6065 if (!(v is Expression)){
6066 byte val = (byte) v;
6067 data [idx] = (byte) val;
6069 } else if (underlying_type == TypeManager.bool_type) {
6070 if (!(v is Expression)){
6071 bool val = (bool) v;
6072 data [idx] = (byte) (val ? 1 : 0);
6074 } else if (underlying_type == TypeManager.decimal_type){
6075 if (!(v is Expression)){
6076 int [] bits = Decimal.GetBits ((decimal) v);
6079 // FIXME: For some reason, this doesn't work on the MS runtime.
6080 int [] nbits = new int [4];
6081 nbits [0] = bits [3];
6082 nbits [1] = bits [2];
6083 nbits [2] = bits [0];
6084 nbits [3] = bits [1];
6086 for (int j = 0; j < 4; j++){
6087 data [p++] = (byte) (nbits [j] & 0xff);
6088 data [p++] = (byte) ((nbits [j] >> 8) & 0xff);
6089 data [p++] = (byte) ((nbits [j] >> 16) & 0xff);
6090 data [p++] = (byte) (nbits [j] >> 24);
6094 throw new Exception ("Unrecognized type in MakeByteBlob: " + underlying_type);
6103 // Emits the initializers for the array
6105 void EmitStaticInitializers (EmitContext ec, bool is_expression)
6108 // First, the static data
6111 ILGenerator ig = ec.ig;
6113 byte [] data = MakeByteBlob (array_data, underlying_type, loc);
6115 fb = RootContext.MakeStaticData (data);
6118 ig.Emit (OpCodes.Dup);
6119 ig.Emit (OpCodes.Ldtoken, fb);
6120 ig.Emit (OpCodes.Call,
6121 TypeManager.void_initializearray_array_fieldhandle);
6125 // Emits pieces of the array that can not be computed at compile
6126 // time (variables and string locations).
6128 // This always expect the top value on the stack to be the array
6130 void EmitDynamicInitializers (EmitContext ec, bool is_expression)
6132 ILGenerator ig = ec.ig;
6133 int dims = bounds.Count;
6134 int [] current_pos = new int [dims];
6135 int top = array_data.Count;
6136 LocalBuilder temp = ig.DeclareLocal (type);
6138 ig.Emit (OpCodes.Stloc, temp);
6140 MethodInfo set = null;
6144 ModuleBuilder mb = null;
6145 mb = CodeGen.Module.Builder;
6146 args = new Type [dims + 1];
6149 for (j = 0; j < dims; j++)
6150 args [j] = TypeManager.int32_type;
6152 args [j] = array_element_type;
6154 set = mb.GetArrayMethod (
6156 CallingConventions.HasThis | CallingConventions.Standard,
6157 TypeManager.void_type, args);
6160 for (int i = 0; i < top; i++){
6162 Expression e = null;
6164 if (array_data [i] is Expression)
6165 e = (Expression) array_data [i];
6169 // Basically we do this for string literals and
6170 // other non-literal expressions
6172 if (e is EnumConstant){
6173 e = ((EnumConstant) e).Child;
6176 if (e is StringConstant || e is DecimalConstant || !(e is Constant) ||
6177 num_automatic_initializers <= max_automatic_initializers) {
6178 Type etype = e.Type;
6180 ig.Emit (OpCodes.Ldloc, temp);
6182 for (int idx = 0; idx < dims; idx++)
6183 IntConstant.EmitInt (ig, current_pos [idx]);
6186 // If we are dealing with a struct, get the
6187 // address of it, so we can store it.
6190 etype.IsSubclassOf (TypeManager.value_type) &&
6191 (!TypeManager.IsBuiltinOrEnum (etype) ||
6192 etype == TypeManager.decimal_type)) {
6197 // Let new know that we are providing
6198 // the address where to store the results
6200 n.DisableTemporaryValueType ();
6203 ig.Emit (OpCodes.Ldelema, etype);
6209 ArrayAccess.EmitStoreOpcode (ig, array_element_type);
6211 ig.Emit (OpCodes.Call, set);
6219 for (int j = dims - 1; j >= 0; j--){
6221 if (current_pos [j] < (int) bounds [j])
6223 current_pos [j] = 0;
6228 ig.Emit (OpCodes.Ldloc, temp);
6231 void EmitArrayArguments (EmitContext ec)
6233 ILGenerator ig = ec.ig;
6235 foreach (Argument a in arguments) {
6236 Type atype = a.Type;
6239 if (atype == TypeManager.uint64_type)
6240 ig.Emit (OpCodes.Conv_Ovf_U4);
6241 else if (atype == TypeManager.int64_type)
6242 ig.Emit (OpCodes.Conv_Ovf_I4);
6246 void DoEmit (EmitContext ec, bool is_statement)
6248 ILGenerator ig = ec.ig;
6250 EmitArrayArguments (ec);
6251 if (is_one_dimensional)
6252 ig.Emit (OpCodes.Newarr, array_element_type);
6254 if (is_builtin_type)
6255 ig.Emit (OpCodes.Newobj, (ConstructorInfo) new_method);
6257 ig.Emit (OpCodes.Newobj, (MethodInfo) new_method);
6260 if (initializers != null){
6262 // FIXME: Set this variable correctly.
6264 bool dynamic_initializers = true;
6266 if (underlying_type != TypeManager.string_type &&
6267 underlying_type != TypeManager.decimal_type &&
6268 underlying_type != TypeManager.object_type) {
6269 if (num_automatic_initializers > max_automatic_initializers)
6270 EmitStaticInitializers (ec, dynamic_initializers || !is_statement);
6273 if (dynamic_initializers)
6274 EmitDynamicInitializers (ec, !is_statement);
6278 public override void Emit (EmitContext ec)
6283 public override void EmitStatement (EmitContext ec)
6288 public object EncodeAsAttribute ()
6290 if (!is_one_dimensional){
6291 Report.Error (-211, Location, "attribute can not encode multi-dimensional arrays");
6295 if (array_data == null){
6296 Report.Error (-212, Location, "array should be initialized when passing it to an attribute");
6300 object [] ret = new object [array_data.Count];
6302 foreach (Expression e in array_data){
6305 if (e is NullLiteral)
6308 if (!Attribute.GetAttributeArgumentExpression (e, Location, out v))
6318 /// Represents the `this' construct
6320 public class This : Expression, IAssignMethod, IMemoryLocation, IVariable {
6323 VariableInfo variable_info;
6325 public This (Block block, Location loc)
6331 public This (Location loc)
6336 public VariableInfo VariableInfo {
6337 get { return variable_info; }
6340 public bool VerifyFixed (bool is_expression)
6342 if ((variable_info == null) || (variable_info.LocalInfo == null))
6345 return variable_info.LocalInfo.IsFixed;
6348 public bool ResolveBase (EmitContext ec)
6350 eclass = ExprClass.Variable;
6352 if (ec.TypeContainer.CurrentType != null)
6353 type = ec.TypeContainer.CurrentType.ResolveType (ec);
6355 type = ec.ContainerType;
6358 Error (26, "Keyword this not valid in static code");
6362 if ((block != null) && (block.ThisVariable != null))
6363 variable_info = block.ThisVariable.VariableInfo;
6368 public override Expression DoResolve (EmitContext ec)
6370 if (!ResolveBase (ec))
6373 if ((variable_info != null) && !variable_info.IsAssigned (ec)) {
6374 Error (188, "The this object cannot be used before all " +
6375 "of its fields are assigned to");
6376 variable_info.SetAssigned (ec);
6380 if (ec.IsFieldInitializer) {
6381 Error (27, "Keyword `this' can't be used outside a constructor, " +
6382 "a method or a property.");
6389 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
6391 if (!ResolveBase (ec))
6394 if (variable_info != null)
6395 variable_info.SetAssigned (ec);
6397 if (ec.TypeContainer is Class){
6398 Error (1604, "Cannot assign to `this'");
6405 public override void Emit (EmitContext ec)
6407 ILGenerator ig = ec.ig;
6409 ig.Emit (OpCodes.Ldarg_0);
6410 if (ec.TypeContainer is Struct)
6411 ig.Emit (OpCodes.Ldobj, type);
6414 public void EmitAssign (EmitContext ec, Expression source)
6416 ILGenerator ig = ec.ig;
6418 if (ec.TypeContainer is Struct){
6419 ig.Emit (OpCodes.Ldarg_0);
6421 ig.Emit (OpCodes.Stobj, type);
6424 ig.Emit (OpCodes.Starg, 0);
6428 public void AddressOf (EmitContext ec, AddressOp mode)
6430 ec.ig.Emit (OpCodes.Ldarg_0);
6433 // FIGURE OUT WHY LDARG_S does not work
6435 // consider: struct X { int val; int P { set { val = value; }}}
6437 // Yes, this looks very bad. Look at `NOTAS' for
6439 // ec.ig.Emit (OpCodes.Ldarga_S, (byte) 0);
6444 // This produces the value that renders an instance, used by the iterators code
6446 public class ProxyInstance : Expression, IMemoryLocation {
6447 public override Expression DoResolve (EmitContext ec)
6449 eclass = ExprClass.Variable;
6450 type = ec.ContainerType;
6454 public override void Emit (EmitContext ec)
6456 ec.ig.Emit (OpCodes.Ldarg_0);
6460 public void AddressOf (EmitContext ec, AddressOp mode)
6462 ec.ig.Emit (OpCodes.Ldarg_0);
6467 /// Implements the typeof operator
6469 public class TypeOf : Expression {
6470 public readonly Expression QueriedType;
6471 protected Type typearg;
6473 public TypeOf (Expression queried_type, Location l)
6475 QueriedType = queried_type;
6479 public override Expression DoResolve (EmitContext ec)
6481 typearg = ec.DeclSpace.ResolveType (QueriedType, false, loc);
6483 if (typearg == null)
6486 if (typearg == TypeManager.void_type) {
6487 Error (673, "System.Void cannot be used from C# - " +
6488 "use typeof (void) to get the void type object");
6492 type = TypeManager.type_type;
6493 eclass = ExprClass.Type;
6497 public override void Emit (EmitContext ec)
6499 ec.ig.Emit (OpCodes.Ldtoken, typearg);
6500 ec.ig.Emit (OpCodes.Call, TypeManager.system_type_get_type_from_handle);
6503 public Type TypeArg {
6504 get { return typearg; }
6509 /// Implements the `typeof (void)' operator
6511 public class TypeOfVoid : TypeOf {
6512 public TypeOfVoid (Location l) : base (null, l)
6517 public override Expression DoResolve (EmitContext ec)
6519 type = TypeManager.type_type;
6520 typearg = TypeManager.void_type;
6521 eclass = ExprClass.Type;
6527 /// Implements the sizeof expression
6529 public class SizeOf : Expression {
6530 public Expression QueriedType;
6533 public SizeOf (Expression queried_type, Location l)
6535 this.QueriedType = queried_type;
6539 public override Expression DoResolve (EmitContext ec)
6543 233, loc, "Sizeof may only be used in an unsafe context " +
6544 "(consider using System.Runtime.InteropServices.Marshal.Sizeof");
6548 QueriedType = ec.DeclSpace.ResolveTypeExpr (QueriedType, false, loc);
6549 if (QueriedType == null || QueriedType.Type == null)
6552 if (QueriedType is TypeParameterExpr){
6553 ((TypeParameterExpr)QueriedType).Error_CannotUseAsUnmanagedType (loc);
6557 type_queried = QueriedType.Type;
6558 if (!TypeManager.IsUnmanagedType (type_queried)){
6559 Report.Error (208, loc, "Cannot take the size of an unmanaged type (" + TypeManager.CSharpName (type_queried) + ")");
6563 type = TypeManager.int32_type;
6564 eclass = ExprClass.Value;
6568 public override void Emit (EmitContext ec)
6570 int size = GetTypeSize (type_queried);
6573 ec.ig.Emit (OpCodes.Sizeof, type_queried);
6575 IntConstant.EmitInt (ec.ig, size);
6580 /// Implements the member access expression
6582 public class MemberAccess : Expression {
6583 public readonly string Identifier;
6584 protected Expression expr;
6586 public MemberAccess (Expression expr, string id, Location l)
6593 public Expression Expr {
6599 static void error176 (Location loc, string name)
6601 Report.Error (176, loc, "Static member `" +
6602 name + "' cannot be accessed " +
6603 "with an instance reference, qualify with a " +
6604 "type name instead");
6607 static bool IdenticalNameAndTypeName (EmitContext ec, Expression left_original, Location loc)
6609 if (left_original == null)
6612 if (!(left_original is SimpleName))
6615 SimpleName sn = (SimpleName) left_original;
6617 Type t = RootContext.LookupType (ec.DeclSpace, sn.Name, true, loc);
6624 public static Expression ResolveMemberAccess (EmitContext ec, Expression member_lookup,
6625 Expression left, Location loc,
6626 Expression left_original)
6628 bool left_is_type, left_is_explicit;
6630 // If `left' is null, then we're called from SimpleNameResolve and this is
6631 // a member in the currently defining class.
6633 left_is_type = ec.IsStatic || ec.IsFieldInitializer;
6634 left_is_explicit = false;
6636 // Implicitly default to `this' unless we're static.
6637 if (!ec.IsStatic && !ec.IsFieldInitializer && !ec.InEnumContext)
6638 left = ec.GetThis (loc);
6640 left_is_type = left is TypeExpr;
6641 left_is_explicit = true;
6644 if (member_lookup is FieldExpr){
6645 FieldExpr fe = (FieldExpr) member_lookup;
6646 FieldInfo fi = fe.FieldInfo;
6647 Type decl_type = fi.DeclaringType;
6649 if (fi is FieldBuilder) {
6650 Const c = TypeManager.LookupConstant ((FieldBuilder) fi);
6653 object o = c.LookupConstantValue ();
6657 object real_value = ((Constant) c.Expr).GetValue ();
6659 return Constantify (real_value, fi.FieldType);
6664 Type t = fi.FieldType;
6668 if (fi is FieldBuilder)
6669 o = TypeManager.GetValue ((FieldBuilder) fi);
6671 o = fi.GetValue (fi);
6673 if (decl_type.IsSubclassOf (TypeManager.enum_type)) {
6674 if (left_is_explicit && !left_is_type &&
6675 !IdenticalNameAndTypeName (ec, left_original, loc)) {
6676 error176 (loc, fe.FieldInfo.Name);
6680 Expression enum_member = MemberLookup (
6681 ec, decl_type, "value__", MemberTypes.Field,
6682 AllBindingFlags, loc);
6684 Enum en = TypeManager.LookupEnum (decl_type);
6688 c = Constantify (o, en.UnderlyingType);
6690 c = Constantify (o, enum_member.Type);
6692 return new EnumConstant (c, decl_type);
6695 Expression exp = Constantify (o, t);
6697 if (left_is_explicit && !left_is_type) {
6698 error176 (loc, fe.FieldInfo.Name);
6705 if (fi.FieldType.IsPointer && !ec.InUnsafe){
6711 if (member_lookup is EventExpr) {
6712 EventExpr ee = (EventExpr) member_lookup;
6715 // If the event is local to this class, we transform ourselves into
6719 if (ee.EventInfo.DeclaringType == ec.ContainerType ||
6720 TypeManager.IsNestedChildOf(ec.ContainerType, ee.EventInfo.DeclaringType)) {
6721 MemberInfo mi = GetFieldFromEvent (ee);
6725 // If this happens, then we have an event with its own
6726 // accessors and private field etc so there's no need
6727 // to transform ourselves.
6732 Expression ml = ExprClassFromMemberInfo (ec, mi, loc);
6735 Report.Error (-200, loc, "Internal error!!");
6739 if (!left_is_explicit)
6742 return ResolveMemberAccess (ec, ml, left, loc, left_original);
6746 if (member_lookup is IMemberExpr) {
6747 IMemberExpr me = (IMemberExpr) member_lookup;
6750 MethodGroupExpr mg = me as MethodGroupExpr;
6751 if ((mg != null) && left_is_explicit && left.Type.IsInterface)
6752 mg.IsExplicitImpl = left_is_explicit;
6755 if ((ec.IsFieldInitializer || ec.IsStatic) &&
6756 IdenticalNameAndTypeName (ec, left_original, loc))
6757 return member_lookup;
6759 SimpleName.Error_ObjectRefRequired (ec, loc, me.Name);
6764 if (!me.IsInstance){
6765 if (IdenticalNameAndTypeName (ec, left_original, loc))
6766 return member_lookup;
6768 if (left_is_explicit) {
6769 error176 (loc, me.Name);
6775 // Since we can not check for instance objects in SimpleName,
6776 // becaue of the rule that allows types and variables to share
6777 // the name (as long as they can be de-ambiguated later, see
6778 // IdenticalNameAndTypeName), we have to check whether left
6779 // is an instance variable in a static context
6781 // However, if the left-hand value is explicitly given, then
6782 // it is already our instance expression, so we aren't in
6786 if (ec.IsStatic && !left_is_explicit && left is IMemberExpr){
6787 IMemberExpr mexp = (IMemberExpr) left;
6789 if (!mexp.IsStatic){
6790 SimpleName.Error_ObjectRefRequired (ec, loc, mexp.Name);
6795 me.InstanceExpression = left;
6798 return member_lookup;
6801 Console.WriteLine ("Left is: " + left);
6802 Report.Error (-100, loc, "Support for [" + member_lookup + "] is not present yet");
6803 Environment.Exit (0);
6807 public virtual Expression DoResolve (EmitContext ec, Expression right_side,
6811 throw new Exception ();
6814 // Resolve the expression with flow analysis turned off, we'll do the definite
6815 // assignment checks later. This is because we don't know yet what the expression
6816 // will resolve to - it may resolve to a FieldExpr and in this case we must do the
6817 // definite assignment check on the actual field and not on the whole struct.
6820 Expression original = expr;
6821 expr = expr.Resolve (ec, flags | ResolveFlags.DisableFlowAnalysis);
6825 if (expr is SimpleName){
6826 SimpleName child_expr = (SimpleName) expr;
6828 Expression new_expr = new SimpleName (child_expr.Name, Identifier, loc);
6830 return new_expr.Resolve (ec, flags);
6834 // TODO: I mailed Ravi about this, and apparently we can get rid
6835 // of this and put it in the right place.
6837 // Handle enums here when they are in transit.
6838 // Note that we cannot afford to hit MemberLookup in this case because
6839 // it will fail to find any members at all
6842 Type expr_type = expr.Type;
6843 if (expr is TypeExpr){
6844 if (!ec.DeclSpace.CheckAccessLevel (expr_type)){
6845 Error (122, "`" + expr_type + "' " +
6846 "is inaccessible because of its protection level");
6850 if (expr_type == TypeManager.enum_type || expr_type.IsSubclassOf (TypeManager.enum_type)){
6851 Enum en = TypeManager.LookupEnum (expr_type);
6854 object value = en.LookupEnumValue (ec, Identifier, loc);
6857 Constant c = Constantify (value, en.UnderlyingType);
6858 return new EnumConstant (c, expr_type);
6864 if (expr_type.IsPointer){
6865 Error (23, "The `.' operator can not be applied to pointer operands (" +
6866 TypeManager.CSharpName (expr_type) + ")");
6870 Expression member_lookup;
6871 member_lookup = MemberLookupFinal (ec, expr_type, expr_type, Identifier, loc);
6872 if (member_lookup == null)
6875 if (member_lookup is TypeExpr) {
6876 if (!(expr is TypeExpr) && !(expr is SimpleName)) {
6877 Error (572, "Can't reference type `" + Identifier + "' through an expression; try `" +
6878 member_lookup.Type + "' instead");
6882 return member_lookup;
6885 member_lookup = ResolveMemberAccess (ec, member_lookup, expr, loc, original);
6886 if (member_lookup == null)
6889 // The following DoResolve/DoResolveLValue will do the definite assignment
6892 if (right_side != null)
6893 member_lookup = member_lookup.DoResolveLValue (ec, right_side);
6895 member_lookup = member_lookup.DoResolve (ec);
6897 return member_lookup;
6900 public override Expression DoResolve (EmitContext ec)
6902 return DoResolve (ec, null, ResolveFlags.VariableOrValue |
6903 ResolveFlags.SimpleName | ResolveFlags.Type);
6906 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
6908 return DoResolve (ec, right_side, ResolveFlags.VariableOrValue |
6909 ResolveFlags.SimpleName | ResolveFlags.Type);
6912 public override Expression ResolveAsTypeStep (EmitContext ec)
6914 string fname = null;
6915 MemberAccess full_expr = this;
6916 while (full_expr != null) {
6918 fname = String.Concat (full_expr.Identifier, ".", fname);
6920 fname = full_expr.Identifier;
6922 if (full_expr.Expr is SimpleName) {
6923 string full_name = String.Concat (((SimpleName) full_expr.Expr).Name, ".", fname);
6924 Type fully_qualified = ec.DeclSpace.FindType (loc, full_name);
6925 if (fully_qualified != null)
6926 return new TypeExpression (fully_qualified, loc);
6929 full_expr = full_expr.Expr as MemberAccess;
6932 Expression new_expr = expr.ResolveAsTypeStep (ec);
6934 if (new_expr == null)
6937 if (new_expr is SimpleName){
6938 SimpleName child_expr = (SimpleName) new_expr;
6940 new_expr = new SimpleName (child_expr.Name, Identifier, loc);
6942 return new_expr.ResolveAsTypeStep (ec);
6945 Type expr_type = ((TypeExpr) new_expr).ResolveType (ec);
6947 if (expr_type.IsPointer){
6948 Error (23, "The `.' operator can not be applied to pointer operands (" +
6949 TypeManager.CSharpName (expr_type) + ")");
6953 Expression member_lookup;
6954 member_lookup = MemberLookupFinal (ec, expr_type, expr_type, Identifier, loc);
6955 if (member_lookup == null)
6958 if (member_lookup is TypeExpr){
6959 member_lookup.Resolve (ec, ResolveFlags.Type);
6960 return member_lookup;
6966 public override void Emit (EmitContext ec)
6968 throw new Exception ("Should not happen");
6971 public override string ToString ()
6973 return expr + "." + Identifier;
6978 /// Implements checked expressions
6980 public class CheckedExpr : Expression {
6982 public Expression Expr;
6984 public CheckedExpr (Expression e, Location l)
6990 public override Expression DoResolve (EmitContext ec)
6992 bool last_check = ec.CheckState;
6993 bool last_const_check = ec.ConstantCheckState;
6995 ec.CheckState = true;
6996 ec.ConstantCheckState = true;
6997 Expr = Expr.Resolve (ec);
6998 ec.CheckState = last_check;
6999 ec.ConstantCheckState = last_const_check;
7004 if (Expr is Constant)
7007 eclass = Expr.eclass;
7012 public override void Emit (EmitContext ec)
7014 bool last_check = ec.CheckState;
7015 bool last_const_check = ec.ConstantCheckState;
7017 ec.CheckState = true;
7018 ec.ConstantCheckState = true;
7020 ec.CheckState = last_check;
7021 ec.ConstantCheckState = last_const_check;
7027 /// Implements the unchecked expression
7029 public class UnCheckedExpr : Expression {
7031 public Expression Expr;
7033 public UnCheckedExpr (Expression e, Location l)
7039 public override Expression DoResolve (EmitContext ec)
7041 bool last_check = ec.CheckState;
7042 bool last_const_check = ec.ConstantCheckState;
7044 ec.CheckState = false;
7045 ec.ConstantCheckState = false;
7046 Expr = Expr.Resolve (ec);
7047 ec.CheckState = last_check;
7048 ec.ConstantCheckState = last_const_check;
7053 if (Expr is Constant)
7056 eclass = Expr.eclass;
7061 public override void Emit (EmitContext ec)
7063 bool last_check = ec.CheckState;
7064 bool last_const_check = ec.ConstantCheckState;
7066 ec.CheckState = false;
7067 ec.ConstantCheckState = false;
7069 ec.CheckState = last_check;
7070 ec.ConstantCheckState = last_const_check;
7076 /// An Element Access expression.
7078 /// During semantic analysis these are transformed into
7079 /// IndexerAccess, ArrayAccess or a PointerArithmetic.
7081 public class ElementAccess : Expression {
7082 public ArrayList Arguments;
7083 public Expression Expr;
7085 public ElementAccess (Expression e, ArrayList e_list, Location l)
7094 Arguments = new ArrayList ();
7095 foreach (Expression tmp in e_list)
7096 Arguments.Add (new Argument (tmp, Argument.AType.Expression));
7100 bool CommonResolve (EmitContext ec)
7102 Expr = Expr.Resolve (ec);
7107 if (Arguments == null)
7110 foreach (Argument a in Arguments){
7111 if (!a.Resolve (ec, loc))
7118 Expression MakePointerAccess ()
7122 if (t == TypeManager.void_ptr_type){
7123 Error (242, "The array index operation is not valid for void pointers");
7126 if (Arguments.Count != 1){
7127 Error (196, "A pointer must be indexed by a single value");
7132 p = new PointerArithmetic (true, Expr, ((Argument)Arguments [0]).Expr, t, loc);
7133 return new Indirection (p, loc);
7136 public override Expression DoResolve (EmitContext ec)
7138 if (!CommonResolve (ec))
7142 // We perform some simple tests, and then to "split" the emit and store
7143 // code we create an instance of a different class, and return that.
7145 // I am experimenting with this pattern.
7149 if (t == TypeManager.array_type){
7150 Report.Error (21, loc, "Cannot use indexer on System.Array");
7155 return (new ArrayAccess (this, loc)).Resolve (ec);
7156 else if (t.IsPointer)
7157 return MakePointerAccess ();
7159 return (new IndexerAccess (this, loc)).Resolve (ec);
7162 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
7164 if (!CommonResolve (ec))
7169 return (new ArrayAccess (this, loc)).ResolveLValue (ec, right_side);
7170 else if (t.IsPointer)
7171 return MakePointerAccess ();
7173 return (new IndexerAccess (this, loc)).ResolveLValue (ec, right_side);
7176 public override void Emit (EmitContext ec)
7178 throw new Exception ("Should never be reached");
7183 /// Implements array access
7185 public class ArrayAccess : Expression, IAssignMethod, IMemoryLocation {
7187 // Points to our "data" repository
7191 LocalTemporary [] cached_locations;
7193 public ArrayAccess (ElementAccess ea_data, Location l)
7196 eclass = ExprClass.Variable;
7200 public override Expression DoResolve (EmitContext ec)
7203 ExprClass eclass = ea.Expr.eclass;
7205 // As long as the type is valid
7206 if (!(eclass == ExprClass.Variable || eclass == ExprClass.PropertyAccess ||
7207 eclass == ExprClass.Value)) {
7208 ea.Expr.Error_UnexpectedKind ("variable or value");
7213 Type t = ea.Expr.Type;
7214 if (t.GetArrayRank () != ea.Arguments.Count){
7216 "Incorrect number of indexes for array " +
7217 " expected: " + t.GetArrayRank () + " got: " +
7218 ea.Arguments.Count);
7222 type = TypeManager.GetElementType (t);
7223 if (type.IsPointer && !ec.InUnsafe){
7224 UnsafeError (ea.Location);
7228 foreach (Argument a in ea.Arguments){
7229 Type argtype = a.Type;
7231 if (argtype == TypeManager.int32_type ||
7232 argtype == TypeManager.uint32_type ||
7233 argtype == TypeManager.int64_type ||
7234 argtype == TypeManager.uint64_type)
7238 // Mhm. This is strage, because the Argument.Type is not the same as
7239 // Argument.Expr.Type: the value changes depending on the ref/out setting.
7241 // Wonder if I will run into trouble for this.
7243 a.Expr = ExpressionToArrayArgument (ec, a.Expr, ea.Location);
7248 eclass = ExprClass.Variable;
7254 /// Emits the right opcode to load an object of Type `t'
7255 /// from an array of T
7257 static public void EmitLoadOpcode (ILGenerator ig, Type type)
7259 if (type == TypeManager.byte_type || type == TypeManager.bool_type)
7260 ig.Emit (OpCodes.Ldelem_U1);
7261 else if (type == TypeManager.sbyte_type)
7262 ig.Emit (OpCodes.Ldelem_I1);
7263 else if (type == TypeManager.short_type)
7264 ig.Emit (OpCodes.Ldelem_I2);
7265 else if (type == TypeManager.ushort_type || type == TypeManager.char_type)
7266 ig.Emit (OpCodes.Ldelem_U2);
7267 else if (type == TypeManager.int32_type)
7268 ig.Emit (OpCodes.Ldelem_I4);
7269 else if (type == TypeManager.uint32_type)
7270 ig.Emit (OpCodes.Ldelem_U4);
7271 else if (type == TypeManager.uint64_type)
7272 ig.Emit (OpCodes.Ldelem_I8);
7273 else if (type == TypeManager.int64_type)
7274 ig.Emit (OpCodes.Ldelem_I8);
7275 else if (type == TypeManager.float_type)
7276 ig.Emit (OpCodes.Ldelem_R4);
7277 else if (type == TypeManager.double_type)
7278 ig.Emit (OpCodes.Ldelem_R8);
7279 else if (type == TypeManager.intptr_type)
7280 ig.Emit (OpCodes.Ldelem_I);
7281 else if (type.IsValueType){
7282 ig.Emit (OpCodes.Ldelema, type);
7283 ig.Emit (OpCodes.Ldobj, type);
7284 } else if (type.IsGenericParameter)
7285 ig.Emit (OpCodes.Ldelem_Any, type);
7287 ig.Emit (OpCodes.Ldelem_Ref);
7291 /// Emits the right opcode to store an object of Type `t'
7292 /// from an array of T.
7294 static public void EmitStoreOpcode (ILGenerator ig, Type t)
7296 bool is_stobj, has_type_arg;
7297 OpCode op = GetStoreOpcode (t, out is_stobj, out has_type_arg);
7305 /// Returns the right opcode to store an object of Type `t'
7306 /// from an array of T.
7308 static public OpCode GetStoreOpcode (Type t, out bool is_stobj, out bool has_type_arg)
7310 //Console.WriteLine (new System.Diagnostics.StackTrace ());
7311 has_type_arg = false; is_stobj = false;
7312 t = TypeManager.TypeToCoreType (t);
7313 if (TypeManager.IsEnumType (t) && t != TypeManager.enum_type)
7314 t = TypeManager.EnumToUnderlying (t);
7315 if (t == TypeManager.byte_type || t == TypeManager.sbyte_type ||
7316 t == TypeManager.bool_type)
7317 return OpCodes.Stelem_I1;
7318 else if (t == TypeManager.short_type || t == TypeManager.ushort_type ||
7319 t == TypeManager.char_type)
7320 return OpCodes.Stelem_I2;
7321 else if (t == TypeManager.int32_type || t == TypeManager.uint32_type)
7322 return OpCodes.Stelem_I4;
7323 else if (t == TypeManager.int64_type || t == TypeManager.uint64_type)
7324 return OpCodes.Stelem_I8;
7325 else if (t == TypeManager.float_type)
7326 return OpCodes.Stelem_R4;
7327 else if (t == TypeManager.double_type)
7328 return OpCodes.Stelem_R8;
7329 else if (t == TypeManager.intptr_type) {
7330 has_type_arg = true;
7332 return OpCodes.Stobj;
7333 } else if (t.IsValueType) {
7334 has_type_arg = true;
7336 return OpCodes.Stobj;
7337 } else if (t.IsGenericParameter) {
7338 has_type_arg = true;
7339 return OpCodes.Stelem_Any;
7341 return OpCodes.Stelem_Ref;
7344 MethodInfo FetchGetMethod ()
7346 ModuleBuilder mb = CodeGen.Module.Builder;
7347 int arg_count = ea.Arguments.Count;
7348 Type [] args = new Type [arg_count];
7351 for (int i = 0; i < arg_count; i++){
7352 //args [i++] = a.Type;
7353 args [i] = TypeManager.int32_type;
7356 get = mb.GetArrayMethod (
7357 ea.Expr.Type, "Get",
7358 CallingConventions.HasThis |
7359 CallingConventions.Standard,
7365 MethodInfo FetchAddressMethod ()
7367 ModuleBuilder mb = CodeGen.Module.Builder;
7368 int arg_count = ea.Arguments.Count;
7369 Type [] args = new Type [arg_count];
7373 ret_type = TypeManager.GetReferenceType (type);
7375 for (int i = 0; i < arg_count; i++){
7376 //args [i++] = a.Type;
7377 args [i] = TypeManager.int32_type;
7380 address = mb.GetArrayMethod (
7381 ea.Expr.Type, "Address",
7382 CallingConventions.HasThis |
7383 CallingConventions.Standard,
7390 // Load the array arguments into the stack.
7392 // If we have been requested to cache the values (cached_locations array
7393 // initialized), then load the arguments the first time and store them
7394 // in locals. otherwise load from local variables.
7396 void LoadArrayAndArguments (EmitContext ec)
7398 ILGenerator ig = ec.ig;
7400 if (cached_locations == null){
7402 foreach (Argument a in ea.Arguments){
7403 Type argtype = a.Expr.Type;
7407 if (argtype == TypeManager.int64_type)
7408 ig.Emit (OpCodes.Conv_Ovf_I);
7409 else if (argtype == TypeManager.uint64_type)
7410 ig.Emit (OpCodes.Conv_Ovf_I_Un);
7415 if (cached_locations [0] == null){
7416 cached_locations [0] = new LocalTemporary (ec, ea.Expr.Type);
7418 ig.Emit (OpCodes.Dup);
7419 cached_locations [0].Store (ec);
7423 foreach (Argument a in ea.Arguments){
7424 Type argtype = a.Expr.Type;
7426 cached_locations [j] = new LocalTemporary (ec, TypeManager.intptr_type /* a.Expr.Type */);
7428 if (argtype == TypeManager.int64_type)
7429 ig.Emit (OpCodes.Conv_Ovf_I);
7430 else if (argtype == TypeManager.uint64_type)
7431 ig.Emit (OpCodes.Conv_Ovf_I_Un);
7433 ig.Emit (OpCodes.Dup);
7434 cached_locations [j].Store (ec);
7440 foreach (LocalTemporary lt in cached_locations)
7444 public new void CacheTemporaries (EmitContext ec)
7446 cached_locations = new LocalTemporary [ea.Arguments.Count + 1];
7449 public override void Emit (EmitContext ec)
7451 int rank = ea.Expr.Type.GetArrayRank ();
7452 ILGenerator ig = ec.ig;
7454 LoadArrayAndArguments (ec);
7457 EmitLoadOpcode (ig, type);
7461 method = FetchGetMethod ();
7462 ig.Emit (OpCodes.Call, method);
7466 public void EmitAssign (EmitContext ec, Expression source)
7468 int rank = ea.Expr.Type.GetArrayRank ();
7469 ILGenerator ig = ec.ig;
7470 Type t = source.Type;
7472 LoadArrayAndArguments (ec);
7475 // The stobj opcode used by value types will need
7476 // an address on the stack, not really an array/array
7480 if (t == TypeManager.enum_type || t == TypeManager.decimal_type ||
7481 (t.IsSubclassOf (TypeManager.value_type) && !TypeManager.IsEnumType (t) && !TypeManager.IsBuiltinType (t)))
7482 ig.Emit (OpCodes.Ldelema, t);
7488 EmitStoreOpcode (ig, t);
7490 ModuleBuilder mb = CodeGen.Module.Builder;
7491 int arg_count = ea.Arguments.Count;
7492 Type [] args = new Type [arg_count + 1];
7495 for (int i = 0; i < arg_count; i++){
7496 //args [i++] = a.Type;
7497 args [i] = TypeManager.int32_type;
7500 args [arg_count] = type;
7502 set = mb.GetArrayMethod (
7503 ea.Expr.Type, "Set",
7504 CallingConventions.HasThis |
7505 CallingConventions.Standard,
7506 TypeManager.void_type, args);
7508 ig.Emit (OpCodes.Call, set);
7512 public void AddressOf (EmitContext ec, AddressOp mode)
7514 int rank = ea.Expr.Type.GetArrayRank ();
7515 ILGenerator ig = ec.ig;
7517 LoadArrayAndArguments (ec);
7520 ig.Emit (OpCodes.Ldelema, type);
7522 MethodInfo address = FetchAddressMethod ();
7523 ig.Emit (OpCodes.Call, address);
7530 public ArrayList Properties;
7531 static Hashtable map;
7533 public struct Indexer {
7534 public readonly Type Type;
7535 public readonly MethodInfo Getter, Setter;
7537 public Indexer (Type type, MethodInfo get, MethodInfo set)
7547 map = new Hashtable ();
7552 Properties = new ArrayList ();
7555 void Append (MemberInfo [] mi)
7557 foreach (PropertyInfo property in mi){
7558 MethodInfo get, set;
7560 get = property.GetGetMethod (true);
7561 set = property.GetSetMethod (true);
7562 Properties.Add (new Indexer (property.PropertyType, get, set));
7566 static private MemberInfo [] GetIndexersForTypeOrInterface (Type caller_type, Type lookup_type)
7568 string p_name = TypeManager.IndexerPropertyName (lookup_type);
7570 MemberInfo [] mi = TypeManager.MemberLookup (
7571 caller_type, caller_type, lookup_type, MemberTypes.Property,
7572 BindingFlags.Public | BindingFlags.Instance |
7573 BindingFlags.DeclaredOnly, p_name);
7575 if (mi == null || mi.Length == 0)
7581 static public Indexers GetIndexersForType (Type caller_type, Type lookup_type, Location loc)
7583 Indexers ix = (Indexers) map [lookup_type];
7588 Type copy = lookup_type;
7589 while (copy != TypeManager.object_type && copy != null){
7590 MemberInfo [] mi = GetIndexersForTypeOrInterface (caller_type, copy);
7594 ix = new Indexers ();
7599 copy = copy.BaseType;
7602 if (!lookup_type.IsInterface)
7605 TypeExpr [] ifaces = TypeManager.GetInterfaces (lookup_type);
7606 if (ifaces != null) {
7607 foreach (TypeExpr iface in ifaces) {
7608 Type itype = iface.Type;
7609 MemberInfo [] mi = GetIndexersForTypeOrInterface (caller_type, itype);
7612 ix = new Indexers ();
7624 /// Expressions that represent an indexer call.
7626 public class IndexerAccess : Expression, IAssignMethod {
7628 // Points to our "data" repository
7630 MethodInfo get, set;
7631 ArrayList set_arguments;
7632 bool is_base_indexer;
7634 protected Type indexer_type;
7635 protected Type current_type;
7636 protected Expression instance_expr;
7637 protected ArrayList arguments;
7639 public IndexerAccess (ElementAccess ea, Location loc)
7640 : this (ea.Expr, false, loc)
7642 this.arguments = ea.Arguments;
7645 protected IndexerAccess (Expression instance_expr, bool is_base_indexer,
7648 this.instance_expr = instance_expr;
7649 this.is_base_indexer = is_base_indexer;
7650 this.eclass = ExprClass.Value;
7654 protected virtual bool CommonResolve (EmitContext ec)
7656 indexer_type = instance_expr.Type;
7657 current_type = ec.ContainerType;
7662 public override Expression DoResolve (EmitContext ec)
7664 ArrayList AllGetters = new ArrayList();
7665 if (!CommonResolve (ec))
7669 // Step 1: Query for all `Item' *properties*. Notice
7670 // that the actual methods are pointed from here.
7672 // This is a group of properties, piles of them.
7674 bool found_any = false, found_any_getters = false;
7675 Type lookup_type = indexer_type;
7678 ilist = Indexers.GetIndexersForType (current_type, lookup_type, loc);
7679 if (ilist != null) {
7681 if (ilist.Properties != null) {
7682 foreach (Indexers.Indexer ix in ilist.Properties) {
7683 if (ix.Getter != null)
7684 AllGetters.Add(ix.Getter);
7689 if (AllGetters.Count > 0) {
7690 found_any_getters = true;
7691 get = (MethodInfo) Invocation.OverloadResolve (
7692 ec, new MethodGroupExpr (AllGetters, loc), arguments, loc);
7696 Report.Error (21, loc,
7697 "Type `" + TypeManager.CSharpName (indexer_type) +
7698 "' does not have any indexers defined");
7702 if (!found_any_getters) {
7703 Error (154, "indexer can not be used in this context, because " +
7704 "it lacks a `get' accessor");
7709 Error (1501, "No Overload for method `this' takes `" +
7710 arguments.Count + "' arguments");
7715 // Only base will allow this invocation to happen.
7717 if (get.IsAbstract && this is BaseIndexerAccess){
7718 Report.Error (205, loc, "Cannot call an abstract base indexer: " + Invocation.FullMethodDesc (get));
7722 type = get.ReturnType;
7723 if (type.IsPointer && !ec.InUnsafe){
7728 eclass = ExprClass.IndexerAccess;
7732 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
7734 ArrayList AllSetters = new ArrayList();
7735 if (!CommonResolve (ec))
7738 bool found_any = false, found_any_setters = false;
7740 Indexers ilist = Indexers.GetIndexersForType (current_type, indexer_type, loc);
7741 if (ilist != null) {
7743 if (ilist.Properties != null) {
7744 foreach (Indexers.Indexer ix in ilist.Properties) {
7745 if (ix.Setter != null)
7746 AllSetters.Add(ix.Setter);
7750 if (AllSetters.Count > 0) {
7751 found_any_setters = true;
7752 set_arguments = (ArrayList) arguments.Clone ();
7753 set_arguments.Add (new Argument (right_side, Argument.AType.Expression));
7754 set = (MethodInfo) Invocation.OverloadResolve (
7755 ec, new MethodGroupExpr (AllSetters, loc),
7756 set_arguments, loc);
7760 Report.Error (21, loc,
7761 "Type `" + TypeManager.CSharpName (indexer_type) +
7762 "' does not have any indexers defined");
7766 if (!found_any_setters) {
7767 Error (154, "indexer can not be used in this context, because " +
7768 "it lacks a `set' accessor");
7773 Error (1501, "No Overload for method `this' takes `" +
7774 arguments.Count + "' arguments");
7779 // Only base will allow this invocation to happen.
7781 if (set.IsAbstract && this is BaseIndexerAccess){
7782 Report.Error (205, loc, "Cannot call an abstract base indexer: " + Invocation.FullMethodDesc (set));
7787 // Now look for the actual match in the list of indexers to set our "return" type
7789 type = TypeManager.void_type; // default value
7790 foreach (Indexers.Indexer ix in ilist.Properties){
7791 if (ix.Setter == set){
7797 eclass = ExprClass.IndexerAccess;
7801 public override void Emit (EmitContext ec)
7803 Invocation.EmitCall (ec, is_base_indexer, false, instance_expr, get, arguments, loc);
7807 // source is ignored, because we already have a copy of it from the
7808 // LValue resolution and we have already constructed a pre-cached
7809 // version of the arguments (ea.set_arguments);
7811 public void EmitAssign (EmitContext ec, Expression source)
7813 Invocation.EmitCall (ec, is_base_indexer, false, instance_expr, set, set_arguments, loc);
7818 /// The base operator for method names
7820 public class BaseAccess : Expression {
7823 public BaseAccess (string member, Location l)
7825 this.member = member;
7829 public override Expression DoResolve (EmitContext ec)
7831 Expression c = CommonResolve (ec);
7837 // MethodGroups use this opportunity to flag an error on lacking ()
7839 if (!(c is MethodGroupExpr))
7840 return c.Resolve (ec);
7844 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
7846 Expression c = CommonResolve (ec);
7852 // MethodGroups use this opportunity to flag an error on lacking ()
7854 if (! (c is MethodGroupExpr))
7855 return c.DoResolveLValue (ec, right_side);
7860 Expression CommonResolve (EmitContext ec)
7862 Expression member_lookup;
7863 Type current_type = ec.ContainerType;
7864 Type base_type = current_type.BaseType;
7868 Error (1511, "Keyword base is not allowed in static method");
7872 member_lookup = MemberLookup (ec, ec.ContainerType, null, base_type, member,
7873 AllMemberTypes, AllBindingFlags, loc);
7874 if (member_lookup == null) {
7875 MemberLookupFailed (ec, base_type, base_type, member, null, loc);
7882 left = new TypeExpression (base_type, loc);
7884 left = ec.GetThis (loc);
7886 e = MemberAccess.ResolveMemberAccess (ec, member_lookup, left, loc, null);
7888 if (e is PropertyExpr){
7889 PropertyExpr pe = (PropertyExpr) e;
7897 public override void Emit (EmitContext ec)
7899 throw new Exception ("Should never be called");
7904 /// The base indexer operator
7906 public class BaseIndexerAccess : IndexerAccess {
7907 public BaseIndexerAccess (ArrayList args, Location loc)
7908 : base (null, true, loc)
7910 arguments = new ArrayList ();
7911 foreach (Expression tmp in args)
7912 arguments.Add (new Argument (tmp, Argument.AType.Expression));
7915 protected override bool CommonResolve (EmitContext ec)
7917 instance_expr = ec.GetThis (loc);
7919 current_type = ec.ContainerType.BaseType;
7920 indexer_type = current_type;
7922 foreach (Argument a in arguments){
7923 if (!a.Resolve (ec, loc))
7932 /// This class exists solely to pass the Type around and to be a dummy
7933 /// that can be passed to the conversion functions (this is used by
7934 /// foreach implementation to typecast the object return value from
7935 /// get_Current into the proper type. All code has been generated and
7936 /// we only care about the side effect conversions to be performed
7938 /// This is also now used as a placeholder where a no-action expression
7939 /// is needed (the `New' class).
7941 public class EmptyExpression : Expression {
7942 public EmptyExpression ()
7944 type = TypeManager.object_type;
7945 eclass = ExprClass.Value;
7946 loc = Location.Null;
7949 public EmptyExpression (Type t)
7952 eclass = ExprClass.Value;
7953 loc = Location.Null;
7956 public override Expression DoResolve (EmitContext ec)
7961 public override void Emit (EmitContext ec)
7963 // nothing, as we only exist to not do anything.
7967 // This is just because we might want to reuse this bad boy
7968 // instead of creating gazillions of EmptyExpressions.
7969 // (CanImplicitConversion uses it)
7971 public void SetType (Type t)
7977 public class UserCast : Expression {
7981 public UserCast (MethodInfo method, Expression source, Location l)
7983 this.method = method;
7984 this.source = source;
7985 type = method.ReturnType;
7986 eclass = ExprClass.Value;
7990 public override Expression DoResolve (EmitContext ec)
7993 // We are born fully resolved
7998 public override void Emit (EmitContext ec)
8000 ILGenerator ig = ec.ig;
8004 if (method is MethodInfo)
8005 ig.Emit (OpCodes.Call, (MethodInfo) method);
8007 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
8013 // This class is used to "construct" the type during a typecast
8014 // operation. Since the Type.GetType class in .NET can parse
8015 // the type specification, we just use this to construct the type
8016 // one bit at a time.
8018 public class ComposedCast : TypeExpr {
8022 public ComposedCast (Expression left, string dim, Location l)
8029 public override TypeExpr DoResolveAsTypeStep (EmitContext ec)
8031 Type ltype = ec.DeclSpace.ResolveType (left, false, loc);
8036 while ((pos < dim.Length) && (dim [pos] == '[')) {
8038 if (dim [pos] == ']') {
8039 ltype = ltype.MakeArrayType ();
8042 if (pos < dim.Length)
8046 eclass = ExprClass.Type;
8051 while (dim [pos++] == ',')
8054 if ((dim [pos] != ']') || (pos != dim.Length-1))
8057 type = ltype.MakeArrayType (rank + 1);
8058 eclass = ExprClass.Type;
8063 // ltype.Fullname is already fully qualified, so we can skip
8064 // a lot of probes, and go directly to TypeManager.LookupType
8066 string cname = ltype.FullName + dim;
8067 type = TypeManager.LookupTypeDirect (cname);
8070 // For arrays of enumerations we are having a problem
8071 // with the direct lookup. Need to investigate.
8073 // For now, fall back to the full lookup in that case.
8075 type = RootContext.LookupType (
8076 ec.DeclSpace, cname, false, loc);
8082 if (!ec.ResolvingTypeTree){
8084 // If the above flag is set, this is being invoked from the ResolveType function.
8085 // Upper layers take care of the type validity in this context.
8087 if (!ec.InUnsafe && type.IsPointer){
8093 eclass = ExprClass.Type;
8097 public override string Name {
8105 // This class is used to represent the address of an array, used
8106 // only by the Fixed statement, this is like the C "&a [0]" construct.
8108 public class ArrayPtr : Expression {
8111 public ArrayPtr (Expression array, Location l)
8113 Type array_type = TypeManager.GetElementType (array.Type);
8117 type = TypeManager.GetPointerType (array_type);
8118 eclass = ExprClass.Value;
8122 public override void Emit (EmitContext ec)
8124 ILGenerator ig = ec.ig;
8127 IntLiteral.EmitInt (ig, 0);
8128 ig.Emit (OpCodes.Ldelema, TypeManager.GetElementType (array.Type));
8131 public override Expression DoResolve (EmitContext ec)
8134 // We are born fully resolved
8141 // Used by the fixed statement
8143 public class StringPtr : Expression {
8146 public StringPtr (LocalBuilder b, Location l)
8149 eclass = ExprClass.Value;
8150 type = TypeManager.char_ptr_type;
8154 public override Expression DoResolve (EmitContext ec)
8156 // This should never be invoked, we are born in fully
8157 // initialized state.
8162 public override void Emit (EmitContext ec)
8164 ILGenerator ig = ec.ig;
8166 ig.Emit (OpCodes.Ldloc, b);
8167 ig.Emit (OpCodes.Conv_I);
8168 ig.Emit (OpCodes.Call, TypeManager.int_get_offset_to_string_data);
8169 ig.Emit (OpCodes.Add);
8174 // Implements the `stackalloc' keyword
8176 public class StackAlloc : Expression {
8181 public StackAlloc (Expression type, Expression count, Location l)
8188 public override Expression DoResolve (EmitContext ec)
8190 count = count.Resolve (ec);
8194 if (count.Type != TypeManager.int32_type){
8195 count = Convert.ImplicitConversionRequired (ec, count, TypeManager.int32_type, loc);
8200 if (ec.CurrentBranching.InCatch () ||
8201 ec.CurrentBranching.InFinally (true)) {
8203 "stackalloc can not be used in a catch or finally block");
8207 otype = ec.DeclSpace.ResolveType (t, false, loc);
8212 if (!TypeManager.VerifyUnManaged (otype, loc))
8215 type = TypeManager.GetPointerType (otype);
8216 eclass = ExprClass.Value;
8221 public override void Emit (EmitContext ec)
8223 int size = GetTypeSize (otype);
8224 ILGenerator ig = ec.ig;
8227 ig.Emit (OpCodes.Sizeof, otype);
8229 IntConstant.EmitInt (ig, size);
8231 ig.Emit (OpCodes.Mul);
8232 ig.Emit (OpCodes.Localloc);