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 (
70 ec, (MethodGroupExpr) mg, args, false, loc);
75 return new StaticCallExpr ((MethodInfo) method, args, loc);
78 public override void EmitStatement (EmitContext ec)
81 if (TypeManager.TypeToCoreType (type) != TypeManager.void_type)
82 ec.ig.Emit (OpCodes.Pop);
86 public class ParenthesizedExpression : Expression
88 public Expression Expr;
90 public ParenthesizedExpression (Expression expr, Location loc)
96 public override Expression DoResolve (EmitContext ec)
98 Expr = Expr.Resolve (ec);
102 public override void Emit (EmitContext ec)
104 throw new Exception ("Should not happen");
109 /// Unary expressions.
113 /// Unary implements unary expressions. It derives from
114 /// ExpressionStatement becuase the pre/post increment/decrement
115 /// operators can be used in a statement context.
117 public class Unary : Expression {
118 public enum Operator : byte {
119 UnaryPlus, UnaryNegation, LogicalNot, OnesComplement,
120 Indirection, AddressOf, TOP
123 public Operator Oper;
124 public Expression Expr;
126 public Unary (Operator op, Expression expr, Location loc)
134 /// Returns a stringified representation of the Operator
136 static public string OperName (Operator oper)
139 case Operator.UnaryPlus:
141 case Operator.UnaryNegation:
143 case Operator.LogicalNot:
145 case Operator.OnesComplement:
147 case Operator.AddressOf:
149 case Operator.Indirection:
153 return oper.ToString ();
156 public static readonly string [] oper_names;
160 oper_names = new string [(int)Operator.TOP];
162 oper_names [(int) Operator.UnaryPlus] = "op_UnaryPlus";
163 oper_names [(int) Operator.UnaryNegation] = "op_UnaryNegation";
164 oper_names [(int) Operator.LogicalNot] = "op_LogicalNot";
165 oper_names [(int) Operator.OnesComplement] = "op_OnesComplement";
166 oper_names [(int) Operator.Indirection] = "op_Indirection";
167 oper_names [(int) Operator.AddressOf] = "op_AddressOf";
170 void Error23 (Type t)
173 23, "Operator " + OperName (Oper) +
174 " cannot be applied to operand of type `" +
175 TypeManager.CSharpName (t) + "'");
179 /// The result has been already resolved:
181 /// FIXME: a minus constant -128 sbyte cant be turned into a
184 static Expression TryReduceNegative (Constant expr)
188 if (expr is IntConstant)
189 e = new IntConstant (-((IntConstant) expr).Value);
190 else if (expr is UIntConstant){
191 uint value = ((UIntConstant) expr).Value;
193 if (value < 2147483649)
194 return new IntConstant (-(int)value);
196 e = new LongConstant (-value);
198 else if (expr is LongConstant)
199 e = new LongConstant (-((LongConstant) expr).Value);
200 else if (expr is ULongConstant){
201 ulong value = ((ULongConstant) expr).Value;
203 if (value < 9223372036854775809)
204 return new LongConstant(-(long)value);
206 else if (expr is FloatConstant)
207 e = new FloatConstant (-((FloatConstant) expr).Value);
208 else if (expr is DoubleConstant)
209 e = new DoubleConstant (-((DoubleConstant) expr).Value);
210 else if (expr is DecimalConstant)
211 e = new DecimalConstant (-((DecimalConstant) expr).Value);
212 else if (expr is ShortConstant)
213 e = new IntConstant (-((ShortConstant) expr).Value);
214 else if (expr is UShortConstant)
215 e = new IntConstant (-((UShortConstant) expr).Value);
220 // This routine will attempt to simplify the unary expression when the
221 // argument is a constant. The result is returned in `result' and the
222 // function returns true or false depending on whether a reduction
223 // was performed or not
225 bool Reduce (EmitContext ec, Constant e, out Expression result)
227 Type expr_type = e.Type;
230 case Operator.UnaryPlus:
234 case Operator.UnaryNegation:
235 result = TryReduceNegative (e);
238 case Operator.LogicalNot:
239 if (expr_type != TypeManager.bool_type) {
245 BoolConstant b = (BoolConstant) e;
246 result = new BoolConstant (!(b.Value));
249 case Operator.OnesComplement:
250 if (!((expr_type == TypeManager.int32_type) ||
251 (expr_type == TypeManager.uint32_type) ||
252 (expr_type == TypeManager.int64_type) ||
253 (expr_type == TypeManager.uint64_type) ||
254 (expr_type.IsSubclassOf (TypeManager.enum_type)))){
257 if (Convert.ImplicitConversionExists (ec, e, TypeManager.int32_type)){
258 result = new Cast (new TypeExpression (TypeManager.int32_type, loc), e, loc);
259 result = result.Resolve (ec);
260 } else if (Convert.ImplicitConversionExists (ec, e, TypeManager.uint32_type)){
261 result = new Cast (new TypeExpression (TypeManager.uint32_type, loc), e, loc);
262 result = result.Resolve (ec);
263 } else if (Convert.ImplicitConversionExists (ec, e, TypeManager.int64_type)){
264 result = new Cast (new TypeExpression (TypeManager.int64_type, loc), e, loc);
265 result = result.Resolve (ec);
266 } else if (Convert.ImplicitConversionExists (ec, e, TypeManager.uint64_type)){
267 result = new Cast (new TypeExpression (TypeManager.uint64_type, loc), e, loc);
268 result = result.Resolve (ec);
271 if (result == null || !(result is Constant)){
277 expr_type = result.Type;
278 e = (Constant) result;
281 if (e is EnumConstant){
282 EnumConstant enum_constant = (EnumConstant) e;
285 if (Reduce (ec, enum_constant.Child, out reduced)){
286 result = new EnumConstant ((Constant) reduced, enum_constant.Type);
294 if (expr_type == TypeManager.int32_type){
295 result = new IntConstant (~ ((IntConstant) e).Value);
296 } else if (expr_type == TypeManager.uint32_type){
297 result = new UIntConstant (~ ((UIntConstant) e).Value);
298 } else if (expr_type == TypeManager.int64_type){
299 result = new LongConstant (~ ((LongConstant) e).Value);
300 } else if (expr_type == TypeManager.uint64_type){
301 result = new ULongConstant (~ ((ULongConstant) e).Value);
309 case Operator.AddressOf:
313 case Operator.Indirection:
317 throw new Exception ("Can not constant fold: " + Oper.ToString());
320 Expression ResolveOperator (EmitContext ec)
322 Type expr_type = Expr.Type;
325 // Step 1: Perform Operator Overload location
330 op_name = oper_names [(int) Oper];
332 mg = MemberLookup (ec, expr_type, op_name, MemberTypes.Method, AllBindingFlags, loc);
335 Expression e = StaticCallExpr.MakeSimpleCall (
336 ec, (MethodGroupExpr) mg, Expr, loc);
346 // Only perform numeric promotions on:
349 if (expr_type == null)
353 // Step 2: Default operations on CLI native types.
356 // Attempt to use a constant folding operation.
357 if (Expr is Constant){
360 if (Reduce (ec, (Constant) Expr, out result))
365 case Operator.LogicalNot:
366 if (expr_type != TypeManager.bool_type) {
367 Expr = ResolveBoolean (ec, Expr, loc);
374 type = TypeManager.bool_type;
377 case Operator.OnesComplement:
378 if (!((expr_type == TypeManager.int32_type) ||
379 (expr_type == TypeManager.uint32_type) ||
380 (expr_type == TypeManager.int64_type) ||
381 (expr_type == TypeManager.uint64_type) ||
382 (expr_type.IsSubclassOf (TypeManager.enum_type)))){
385 e = Convert.ImplicitConversion (ec, Expr, TypeManager.int32_type, loc);
387 type = TypeManager.int32_type;
390 e = Convert.ImplicitConversion (ec, Expr, TypeManager.uint32_type, loc);
392 type = TypeManager.uint32_type;
395 e = Convert.ImplicitConversion (ec, Expr, TypeManager.int64_type, loc);
397 type = TypeManager.int64_type;
400 e = Convert.ImplicitConversion (ec, Expr, TypeManager.uint64_type, loc);
402 type = TypeManager.uint64_type;
411 case Operator.AddressOf:
412 if (Expr.eclass != ExprClass.Variable){
413 Error (211, "Cannot take the address of non-variables");
422 if (!TypeManager.VerifyUnManaged (Expr.Type, loc)){
426 IVariable variable = Expr as IVariable;
427 if (!ec.InFixedInitializer && ((variable == null) || !variable.VerifyFixed (false))) {
428 Error (212, "You can only take the address of an unfixed expression inside " +
429 "of a fixed statement initializer");
433 if (ec.InFixedInitializer && ((variable != null) && variable.VerifyFixed (false))) {
434 Error (213, "You can not fix an already fixed expression");
438 // According to the specs, a variable is considered definitely assigned if you take
440 if ((variable != null) && (variable.VariableInfo != null))
441 variable.VariableInfo.SetAssigned (ec);
443 type = TypeManager.GetPointerType (Expr.Type);
446 case Operator.Indirection:
452 if (!expr_type.IsPointer){
453 Error (193, "The * or -> operator can only be applied to pointers");
458 // We create an Indirection expression, because
459 // it can implement the IMemoryLocation.
461 return new Indirection (Expr, loc);
463 case Operator.UnaryPlus:
465 // A plus in front of something is just a no-op, so return the child.
469 case Operator.UnaryNegation:
471 // Deals with -literals
472 // int operator- (int x)
473 // long operator- (long x)
474 // float operator- (float f)
475 // double operator- (double d)
476 // decimal operator- (decimal d)
478 Expression expr = null;
481 // transform - - expr into expr
484 Unary unary = (Unary) Expr;
486 if (unary.Oper == Operator.UnaryNegation)
491 // perform numeric promotions to int,
495 // The following is inneficient, because we call
496 // ImplicitConversion too many times.
498 // It is also not clear if we should convert to Float
499 // or Double initially.
501 if (expr_type == TypeManager.uint32_type){
503 // FIXME: handle exception to this rule that
504 // permits the int value -2147483648 (-2^31) to
505 // bt wrote as a decimal interger literal
507 type = TypeManager.int64_type;
508 Expr = Convert.ImplicitConversion (ec, Expr, type, loc);
512 if (expr_type == TypeManager.uint64_type){
514 // FIXME: Handle exception of `long value'
515 // -92233720368547758087 (-2^63) to be wrote as
516 // decimal integer literal.
522 if (expr_type == TypeManager.float_type){
527 expr = Convert.ImplicitConversion (ec, Expr, TypeManager.int32_type, loc);
534 expr = Convert.ImplicitConversion (ec, Expr, TypeManager.int64_type, loc);
541 expr = Convert.ImplicitConversion (ec, Expr, TypeManager.double_type, loc);
552 Error (187, "No such operator '" + OperName (Oper) + "' defined for type '" +
553 TypeManager.CSharpName (expr_type) + "'");
557 public override Expression DoResolve (EmitContext ec)
559 if (Oper == Operator.AddressOf)
560 Expr = Expr.ResolveLValue (ec, new EmptyExpression ());
562 Expr = Expr.Resolve (ec);
567 eclass = ExprClass.Value;
568 return ResolveOperator (ec);
571 public override Expression DoResolveLValue (EmitContext ec, Expression right)
573 if (Oper == Operator.Indirection)
574 return base.DoResolveLValue (ec, right);
576 Error (131, "The left-hand side of an assignment must be a " +
577 "variable, property or indexer");
581 public override void Emit (EmitContext ec)
583 ILGenerator ig = ec.ig;
586 case Operator.UnaryPlus:
587 throw new Exception ("This should be caught by Resolve");
589 case Operator.UnaryNegation:
591 ig.Emit (OpCodes.Ldc_I4_0);
592 if (type == TypeManager.int64_type)
593 ig.Emit (OpCodes.Conv_U8);
595 ig.Emit (OpCodes.Sub_Ovf);
598 ig.Emit (OpCodes.Neg);
603 case Operator.LogicalNot:
605 ig.Emit (OpCodes.Ldc_I4_0);
606 ig.Emit (OpCodes.Ceq);
609 case Operator.OnesComplement:
611 ig.Emit (OpCodes.Not);
614 case Operator.AddressOf:
615 ((IMemoryLocation)Expr).AddressOf (ec, AddressOp.LoadStore);
619 throw new Exception ("This should not happen: Operator = "
624 public override void EmitBranchable (EmitContext ec, Label target, bool onTrue)
626 if (Oper == Operator.LogicalNot)
627 Expr.EmitBranchable (ec, target, !onTrue);
629 base.EmitBranchable (ec, target, onTrue);
632 public override string ToString ()
634 return "Unary (" + Oper + ", " + Expr + ")";
640 // Unary operators are turned into Indirection expressions
641 // after semantic analysis (this is so we can take the address
642 // of an indirection).
644 public class Indirection : Expression, IMemoryLocation, IAssignMethod {
646 LocalTemporary temporary;
649 public Indirection (Expression expr, Location l)
652 this.type = TypeManager.GetElementType (expr.Type);
653 eclass = ExprClass.Variable;
657 void LoadExprValue (EmitContext ec)
661 public override void Emit (EmitContext ec)
663 ILGenerator ig = ec.ig;
665 if (temporary != null){
666 if (have_temporary) {
670 ec.ig.Emit (OpCodes.Dup);
671 temporary.Store (ec);
672 have_temporary = true;
677 LoadFromPtr (ig, Type);
680 public void EmitAssign (EmitContext ec, Expression source)
682 if (temporary != null){
687 ec.ig.Emit (OpCodes.Dup);
688 temporary.Store (ec);
689 have_temporary = true;
695 StoreFromPtr (ec.ig, type);
698 public void AddressOf (EmitContext ec, AddressOp Mode)
700 if (temporary != null){
706 ec.ig.Emit (OpCodes.Dup);
707 temporary.Store (ec);
708 have_temporary = true;
713 public override Expression DoResolve (EmitContext ec)
716 // Born fully resolved
721 public new void CacheTemporaries (EmitContext ec)
723 temporary = new LocalTemporary (ec, expr.Type);
726 public override string ToString ()
728 return "*(" + expr + ")";
733 /// Unary Mutator expressions (pre and post ++ and --)
737 /// UnaryMutator implements ++ and -- expressions. It derives from
738 /// ExpressionStatement becuase the pre/post increment/decrement
739 /// operators can be used in a statement context.
741 /// FIXME: Idea, we could split this up in two classes, one simpler
742 /// for the common case, and one with the extra fields for more complex
743 /// classes (indexers require temporary access; overloaded require method)
746 public class UnaryMutator : ExpressionStatement {
748 public enum Mode : byte {
755 PreDecrement = IsDecrement,
756 PostIncrement = IsPost,
757 PostDecrement = IsPost | IsDecrement
762 LocalTemporary temp_storage;
765 // This is expensive for the simplest case.
769 public UnaryMutator (Mode m, Expression e, Location l)
776 static string OperName (Mode mode)
778 return (mode == Mode.PreIncrement || mode == Mode.PostIncrement) ?
782 void Error23 (Type t)
785 23, "Operator " + OperName (mode) +
786 " cannot be applied to operand of type `" +
787 TypeManager.CSharpName (t) + "'");
791 /// Returns whether an object of type `t' can be incremented
792 /// or decremented with add/sub (ie, basically whether we can
793 /// use pre-post incr-decr operations on it, but it is not a
794 /// System.Decimal, which we require operator overloading to catch)
796 static bool IsIncrementableNumber (Type t)
798 return (t == TypeManager.sbyte_type) ||
799 (t == TypeManager.byte_type) ||
800 (t == TypeManager.short_type) ||
801 (t == TypeManager.ushort_type) ||
802 (t == TypeManager.int32_type) ||
803 (t == TypeManager.uint32_type) ||
804 (t == TypeManager.int64_type) ||
805 (t == TypeManager.uint64_type) ||
806 (t == TypeManager.char_type) ||
807 (t.IsSubclassOf (TypeManager.enum_type)) ||
808 (t == TypeManager.float_type) ||
809 (t == TypeManager.double_type) ||
810 (t.IsPointer && t != TypeManager.void_ptr_type);
813 Expression ResolveOperator (EmitContext ec)
815 Type expr_type = expr.Type;
818 // Step 1: Perform Operator Overload location
823 if (mode == Mode.PreIncrement || mode == Mode.PostIncrement)
824 op_name = "op_Increment";
826 op_name = "op_Decrement";
828 mg = MemberLookup (ec, expr_type, op_name, MemberTypes.Method, AllBindingFlags, loc);
830 if (mg == null && expr_type.BaseType != null)
831 mg = MemberLookup (ec, expr_type.BaseType, op_name,
832 MemberTypes.Method, AllBindingFlags, loc);
835 method = StaticCallExpr.MakeSimpleCall (
836 ec, (MethodGroupExpr) mg, expr, loc);
843 // The operand of the prefix/postfix increment decrement operators
844 // should be an expression that is classified as a variable,
845 // a property access or an indexer access
848 if (expr.eclass == ExprClass.Variable){
849 LocalVariableReference var = expr as LocalVariableReference;
850 if ((var != null) && var.IsReadOnly)
851 Error (1604, "cannot assign to `" + var.Name + "' because it is readonly");
852 if (IsIncrementableNumber (expr_type) ||
853 expr_type == TypeManager.decimal_type){
856 } else if (expr.eclass == ExprClass.IndexerAccess){
857 IndexerAccess ia = (IndexerAccess) expr;
859 temp_storage = new LocalTemporary (ec, expr.Type);
861 expr = ia.ResolveLValue (ec, temp_storage);
866 } else if (expr.eclass == ExprClass.PropertyAccess){
867 PropertyExpr pe = (PropertyExpr) expr;
869 if (pe.VerifyAssignable ())
874 expr.Error_UnexpectedKind ("variable, indexer or property access");
878 Error (187, "No such operator '" + OperName (mode) + "' defined for type '" +
879 TypeManager.CSharpName (expr_type) + "'");
883 public override Expression DoResolve (EmitContext ec)
885 expr = expr.Resolve (ec);
890 eclass = ExprClass.Value;
891 return ResolveOperator (ec);
894 static int PtrTypeSize (Type t)
896 return GetTypeSize (TypeManager.GetElementType (t));
900 // Loads the proper "1" into the stack based on the type, then it emits the
901 // opcode for the operation requested
903 void LoadOneAndEmitOp (EmitContext ec, Type t)
906 // Measure if getting the typecode and using that is more/less efficient
907 // that comparing types. t.GetTypeCode() is an internal call.
909 ILGenerator ig = ec.ig;
911 if (t == TypeManager.uint64_type || t == TypeManager.int64_type)
912 LongConstant.EmitLong (ig, 1);
913 else if (t == TypeManager.double_type)
914 ig.Emit (OpCodes.Ldc_R8, 1.0);
915 else if (t == TypeManager.float_type)
916 ig.Emit (OpCodes.Ldc_R4, 1.0F);
917 else if (t.IsPointer){
918 int n = PtrTypeSize (t);
921 ig.Emit (OpCodes.Sizeof, t);
923 IntConstant.EmitInt (ig, n);
925 ig.Emit (OpCodes.Ldc_I4_1);
928 // Now emit the operation
931 if (t == TypeManager.int32_type ||
932 t == TypeManager.int64_type){
933 if ((mode & Mode.IsDecrement) != 0)
934 ig.Emit (OpCodes.Sub_Ovf);
936 ig.Emit (OpCodes.Add_Ovf);
937 } else if (t == TypeManager.uint32_type ||
938 t == TypeManager.uint64_type){
939 if ((mode & Mode.IsDecrement) != 0)
940 ig.Emit (OpCodes.Sub_Ovf_Un);
942 ig.Emit (OpCodes.Add_Ovf_Un);
944 if ((mode & Mode.IsDecrement) != 0)
945 ig.Emit (OpCodes.Sub_Ovf);
947 ig.Emit (OpCodes.Add_Ovf);
950 if ((mode & Mode.IsDecrement) != 0)
951 ig.Emit (OpCodes.Sub);
953 ig.Emit (OpCodes.Add);
956 if (t == TypeManager.sbyte_type){
958 ig.Emit (OpCodes.Conv_Ovf_I1);
960 ig.Emit (OpCodes.Conv_I1);
961 } else if (t == TypeManager.byte_type){
963 ig.Emit (OpCodes.Conv_Ovf_U1);
965 ig.Emit (OpCodes.Conv_U1);
966 } else if (t == TypeManager.short_type){
968 ig.Emit (OpCodes.Conv_Ovf_I2);
970 ig.Emit (OpCodes.Conv_I2);
971 } else if (t == TypeManager.ushort_type || t == TypeManager.char_type){
973 ig.Emit (OpCodes.Conv_Ovf_U2);
975 ig.Emit (OpCodes.Conv_U2);
980 static EmptyExpression empty_expr;
982 void EmitCode (EmitContext ec, bool is_expr)
984 ILGenerator ig = ec.ig;
985 IAssignMethod ia = (IAssignMethod) expr;
986 Type expr_type = expr.Type;
988 ia.CacheTemporaries (ec);
991 // NOTE: We should probably handle three cases:
993 // * method invocation required.
994 // * direct stack manipulation possible
995 // * the object requires an "instance" field
997 if (temp_storage == null){
999 // Temporary improvement: if we are dealing with something that does
1000 // not require complicated instance setup, avoid using a temporary
1002 // For now: only localvariables when not remapped
1005 if (method == null &&
1006 ((expr is LocalVariableReference) ||(expr is FieldExpr && ((FieldExpr) expr).FieldInfo.IsStatic))){
1007 if (empty_expr == null)
1008 empty_expr = new EmptyExpression ();
1011 case Mode.PreIncrement:
1012 case Mode.PreDecrement:
1015 LoadOneAndEmitOp (ec, expr_type);
1017 ig.Emit (OpCodes.Dup);
1018 ia.EmitAssign (ec, empty_expr);
1021 case Mode.PostIncrement:
1022 case Mode.PostDecrement:
1025 ig.Emit (OpCodes.Dup);
1027 LoadOneAndEmitOp (ec, expr_type);
1028 ia.EmitAssign (ec, empty_expr);
1033 temp_storage = new LocalTemporary (ec, expr_type);
1037 case Mode.PreIncrement:
1038 case Mode.PreDecrement:
1039 if (method == null){
1042 LoadOneAndEmitOp (ec, expr_type);
1046 temp_storage.Store (ec);
1047 ia.EmitAssign (ec, temp_storage);
1049 temp_storage.Emit (ec);
1052 case Mode.PostIncrement:
1053 case Mode.PostDecrement:
1057 if (method == null){
1061 ig.Emit (OpCodes.Dup);
1063 LoadOneAndEmitOp (ec, expr_type);
1068 temp_storage.Store (ec);
1069 ia.EmitAssign (ec, temp_storage);
1073 temp_storage.Release (ec);
1076 public override void Emit (EmitContext ec)
1078 EmitCode (ec, true);
1082 public override void EmitStatement (EmitContext ec)
1084 EmitCode (ec, false);
1090 /// Base class for the `Is' and `As' classes.
1094 /// FIXME: Split this in two, and we get to save the `Operator' Oper
1097 public abstract class Probe : Expression {
1098 public readonly Expression ProbeType;
1099 protected Expression expr;
1100 protected Type probe_type;
1102 public Probe (Expression expr, Expression probe_type, Location l)
1104 ProbeType = probe_type;
1109 public Expression Expr {
1115 public override Expression DoResolve (EmitContext ec)
1117 probe_type = ec.DeclSpace.ResolveType (ProbeType, false, loc);
1119 if (probe_type == null)
1122 CheckObsoleteAttribute (probe_type);
1124 expr = expr.Resolve (ec);
1133 /// Implementation of the `is' operator.
1135 public class Is : Probe {
1136 public Is (Expression expr, Expression probe_type, Location l)
1137 : base (expr, probe_type, l)
1142 AlwaysTrue, AlwaysNull, AlwaysFalse, LeaveOnStack, Probe
1147 public override void Emit (EmitContext ec)
1149 ILGenerator ig = ec.ig;
1154 case Action.AlwaysFalse:
1155 ig.Emit (OpCodes.Pop);
1156 IntConstant.EmitInt (ig, 0);
1158 case Action.AlwaysTrue:
1159 ig.Emit (OpCodes.Pop);
1160 IntConstant.EmitInt (ig, 1);
1162 case Action.LeaveOnStack:
1163 // the `e != null' rule.
1164 ig.Emit (OpCodes.Ldnull);
1165 ig.Emit (OpCodes.Ceq);
1166 ig.Emit (OpCodes.Ldc_I4_0);
1167 ig.Emit (OpCodes.Ceq);
1170 ig.Emit (OpCodes.Isinst, probe_type);
1171 ig.Emit (OpCodes.Ldnull);
1172 ig.Emit (OpCodes.Cgt_Un);
1175 throw new Exception ("never reached");
1178 public override void EmitBranchable (EmitContext ec, Label target, bool onTrue)
1180 ILGenerator ig = ec.ig;
1183 case Action.AlwaysFalse:
1185 ig.Emit (OpCodes.Br, target);
1188 case Action.AlwaysTrue:
1190 ig.Emit (OpCodes.Br, target);
1193 case Action.LeaveOnStack:
1194 // the `e != null' rule.
1196 ig.Emit (onTrue ? OpCodes.Brtrue : OpCodes.Brfalse, target);
1200 ig.Emit (OpCodes.Isinst, probe_type);
1201 ig.Emit (onTrue ? OpCodes.Brtrue : OpCodes.Brfalse, target);
1204 throw new Exception ("never reached");
1207 public override Expression DoResolve (EmitContext ec)
1209 Expression e = base.DoResolve (ec);
1211 if ((e == null) || (expr == null))
1214 Type etype = expr.Type;
1215 bool warning_always_matches = false;
1216 bool warning_never_matches = false;
1218 type = TypeManager.bool_type;
1219 eclass = ExprClass.Value;
1222 // First case, if at compile time, there is an implicit conversion
1223 // then e != null (objects) or true (value types)
1225 e = Convert.ImplicitConversionStandard (ec, expr, probe_type, loc);
1228 if (etype.IsValueType)
1229 action = Action.AlwaysTrue;
1231 action = Action.LeaveOnStack;
1233 warning_always_matches = true;
1234 } else if (Convert.ExplicitReferenceConversionExists (etype, probe_type)){
1236 // Second case: explicit reference convresion
1238 if (expr is NullLiteral)
1239 action = Action.AlwaysFalse;
1241 action = Action.Probe;
1243 action = Action.AlwaysFalse;
1244 warning_never_matches = true;
1247 if (RootContext.WarningLevel >= 1){
1248 if (warning_always_matches)
1249 Warning (183, "The expression is always of type `" +
1250 TypeManager.CSharpName (probe_type) + "'");
1251 else if (warning_never_matches){
1252 if (!(probe_type.IsInterface || expr.Type.IsInterface))
1254 "The expression is never of type `" +
1255 TypeManager.CSharpName (probe_type) + "'");
1264 /// Implementation of the `as' operator.
1266 public class As : Probe {
1267 public As (Expression expr, Expression probe_type, Location l)
1268 : base (expr, probe_type, l)
1272 bool do_isinst = false;
1274 public override void Emit (EmitContext ec)
1276 ILGenerator ig = ec.ig;
1281 ig.Emit (OpCodes.Isinst, probe_type);
1284 static void Error_CannotConvertType (Type source, Type target, Location loc)
1287 39, loc, "as operator can not convert from `" +
1288 TypeManager.CSharpName (source) + "' to `" +
1289 TypeManager.CSharpName (target) + "'");
1292 public override Expression DoResolve (EmitContext ec)
1294 Expression e = base.DoResolve (ec);
1300 eclass = ExprClass.Value;
1301 Type etype = expr.Type;
1303 if (TypeManager.IsValueType (probe_type)){
1304 Report.Error (77, loc, "The as operator should be used with a reference type only (" +
1305 TypeManager.CSharpName (probe_type) + " is a value type)");
1310 e = Convert.ImplicitConversion (ec, expr, probe_type, loc);
1317 if (Convert.ExplicitReferenceConversionExists (etype, probe_type)){
1322 Error_CannotConvertType (etype, probe_type, loc);
1328 /// This represents a typecast in the source language.
1330 /// FIXME: Cast expressions have an unusual set of parsing
1331 /// rules, we need to figure those out.
1333 public class Cast : Expression {
1334 Expression target_type;
1337 public Cast (Expression cast_type, Expression expr, Location loc)
1339 this.target_type = cast_type;
1344 public Expression TargetType {
1350 public Expression Expr {
1359 bool CheckRange (EmitContext ec, long value, Type type, long min, long max)
1361 if (!ec.ConstantCheckState)
1364 if ((value < min) || (value > max)) {
1365 Error (221, "Constant value `" + value + "' cannot be converted " +
1366 "to a `" + TypeManager.CSharpName (type) + "' (use `unchecked' " +
1367 "syntax to override)");
1374 bool CheckRange (EmitContext ec, ulong value, Type type, ulong max)
1376 if (!ec.ConstantCheckState)
1380 Error (221, "Constant value `" + value + "' cannot be converted " +
1381 "to a `" + TypeManager.CSharpName (type) + "' (use `unchecked' " +
1382 "syntax to override)");
1389 bool CheckUnsigned (EmitContext ec, long value, Type type)
1391 if (!ec.ConstantCheckState)
1395 Error (221, "Constant value `" + value + "' cannot be converted " +
1396 "to a `" + TypeManager.CSharpName (type) + "' (use `unchecked' " +
1397 "syntax to override)");
1405 /// Attempts to do a compile-time folding of a constant cast.
1407 Expression TryReduce (EmitContext ec, Type target_type)
1409 Expression real_expr = expr;
1410 if (real_expr is EnumConstant)
1411 real_expr = ((EnumConstant) real_expr).Child;
1413 if (real_expr is ByteConstant){
1414 byte v = ((ByteConstant) real_expr).Value;
1416 if (target_type == TypeManager.sbyte_type) {
1417 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1419 return new SByteConstant ((sbyte) v);
1421 if (target_type == TypeManager.short_type)
1422 return new ShortConstant ((short) v);
1423 if (target_type == TypeManager.ushort_type)
1424 return new UShortConstant ((ushort) v);
1425 if (target_type == TypeManager.int32_type)
1426 return new IntConstant ((int) v);
1427 if (target_type == TypeManager.uint32_type)
1428 return new UIntConstant ((uint) v);
1429 if (target_type == TypeManager.int64_type)
1430 return new LongConstant ((long) v);
1431 if (target_type == TypeManager.uint64_type)
1432 return new ULongConstant ((ulong) v);
1433 if (target_type == TypeManager.float_type)
1434 return new FloatConstant ((float) v);
1435 if (target_type == TypeManager.double_type)
1436 return new DoubleConstant ((double) v);
1437 if (target_type == TypeManager.char_type)
1438 return new CharConstant ((char) v);
1439 if (target_type == TypeManager.decimal_type)
1440 return new DecimalConstant ((decimal) v);
1442 if (real_expr is SByteConstant){
1443 sbyte v = ((SByteConstant) real_expr).Value;
1445 if (target_type == TypeManager.byte_type) {
1446 if (!CheckUnsigned (ec, v, target_type))
1448 return new ByteConstant ((byte) v);
1450 if (target_type == TypeManager.short_type)
1451 return new ShortConstant ((short) v);
1452 if (target_type == TypeManager.ushort_type) {
1453 if (!CheckUnsigned (ec, v, target_type))
1455 return new UShortConstant ((ushort) v);
1456 } if (target_type == TypeManager.int32_type)
1457 return new IntConstant ((int) v);
1458 if (target_type == TypeManager.uint32_type) {
1459 if (!CheckUnsigned (ec, v, target_type))
1461 return new UIntConstant ((uint) v);
1462 } if (target_type == TypeManager.int64_type)
1463 return new LongConstant ((long) v);
1464 if (target_type == TypeManager.uint64_type) {
1465 if (!CheckUnsigned (ec, v, target_type))
1467 return new ULongConstant ((ulong) v);
1469 if (target_type == TypeManager.float_type)
1470 return new FloatConstant ((float) v);
1471 if (target_type == TypeManager.double_type)
1472 return new DoubleConstant ((double) v);
1473 if (target_type == TypeManager.char_type) {
1474 if (!CheckUnsigned (ec, v, target_type))
1476 return new CharConstant ((char) v);
1478 if (target_type == TypeManager.decimal_type)
1479 return new DecimalConstant ((decimal) v);
1481 if (real_expr is ShortConstant){
1482 short v = ((ShortConstant) real_expr).Value;
1484 if (target_type == TypeManager.byte_type) {
1485 if (!CheckRange (ec, v, target_type, Byte.MinValue, Byte.MaxValue))
1487 return new ByteConstant ((byte) v);
1489 if (target_type == TypeManager.sbyte_type) {
1490 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1492 return new SByteConstant ((sbyte) v);
1494 if (target_type == TypeManager.ushort_type) {
1495 if (!CheckUnsigned (ec, v, target_type))
1497 return new UShortConstant ((ushort) v);
1499 if (target_type == TypeManager.int32_type)
1500 return new IntConstant ((int) v);
1501 if (target_type == TypeManager.uint32_type) {
1502 if (!CheckUnsigned (ec, v, target_type))
1504 return new UIntConstant ((uint) v);
1506 if (target_type == TypeManager.int64_type)
1507 return new LongConstant ((long) v);
1508 if (target_type == TypeManager.uint64_type) {
1509 if (!CheckUnsigned (ec, v, target_type))
1511 return new ULongConstant ((ulong) v);
1513 if (target_type == TypeManager.float_type)
1514 return new FloatConstant ((float) v);
1515 if (target_type == TypeManager.double_type)
1516 return new DoubleConstant ((double) v);
1517 if (target_type == TypeManager.char_type) {
1518 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1520 return new CharConstant ((char) v);
1522 if (target_type == TypeManager.decimal_type)
1523 return new DecimalConstant ((decimal) v);
1525 if (real_expr is UShortConstant){
1526 ushort v = ((UShortConstant) real_expr).Value;
1528 if (target_type == TypeManager.byte_type) {
1529 if (!CheckRange (ec, v, target_type, Byte.MinValue, Byte.MaxValue))
1531 return new ByteConstant ((byte) v);
1533 if (target_type == TypeManager.sbyte_type) {
1534 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1536 return new SByteConstant ((sbyte) v);
1538 if (target_type == TypeManager.short_type) {
1539 if (!CheckRange (ec, v, target_type, Int16.MinValue, Int16.MaxValue))
1541 return new ShortConstant ((short) v);
1543 if (target_type == TypeManager.int32_type)
1544 return new IntConstant ((int) v);
1545 if (target_type == TypeManager.uint32_type)
1546 return new UIntConstant ((uint) v);
1547 if (target_type == TypeManager.int64_type)
1548 return new LongConstant ((long) v);
1549 if (target_type == TypeManager.uint64_type)
1550 return new ULongConstant ((ulong) v);
1551 if (target_type == TypeManager.float_type)
1552 return new FloatConstant ((float) v);
1553 if (target_type == TypeManager.double_type)
1554 return new DoubleConstant ((double) v);
1555 if (target_type == TypeManager.char_type) {
1556 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1558 return new CharConstant ((char) v);
1560 if (target_type == TypeManager.decimal_type)
1561 return new DecimalConstant ((decimal) v);
1563 if (real_expr is IntConstant){
1564 int v = ((IntConstant) real_expr).Value;
1566 if (target_type == TypeManager.byte_type) {
1567 if (!CheckRange (ec, v, target_type, Byte.MinValue, Byte.MaxValue))
1569 return new ByteConstant ((byte) v);
1571 if (target_type == TypeManager.sbyte_type) {
1572 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1574 return new SByteConstant ((sbyte) v);
1576 if (target_type == TypeManager.short_type) {
1577 if (!CheckRange (ec, v, target_type, Int16.MinValue, Int16.MaxValue))
1579 return new ShortConstant ((short) v);
1581 if (target_type == TypeManager.ushort_type) {
1582 if (!CheckRange (ec, v, target_type, UInt16.MinValue, UInt16.MaxValue))
1584 return new UShortConstant ((ushort) v);
1586 if (target_type == TypeManager.uint32_type) {
1587 if (!CheckRange (ec, v, target_type, Int32.MinValue, Int32.MaxValue))
1589 return new UIntConstant ((uint) v);
1591 if (target_type == TypeManager.int64_type)
1592 return new LongConstant ((long) v);
1593 if (target_type == TypeManager.uint64_type) {
1594 if (!CheckUnsigned (ec, v, target_type))
1596 return new ULongConstant ((ulong) v);
1598 if (target_type == TypeManager.float_type)
1599 return new FloatConstant ((float) v);
1600 if (target_type == TypeManager.double_type)
1601 return new DoubleConstant ((double) v);
1602 if (target_type == TypeManager.char_type) {
1603 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1605 return new CharConstant ((char) v);
1607 if (target_type == TypeManager.decimal_type)
1608 return new DecimalConstant ((decimal) v);
1610 if (real_expr is UIntConstant){
1611 uint v = ((UIntConstant) real_expr).Value;
1613 if (target_type == TypeManager.byte_type) {
1614 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1616 return new ByteConstant ((byte) v);
1618 if (target_type == TypeManager.sbyte_type) {
1619 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1621 return new SByteConstant ((sbyte) v);
1623 if (target_type == TypeManager.short_type) {
1624 if (!CheckRange (ec, v, target_type, Int16.MinValue, Int16.MaxValue))
1626 return new ShortConstant ((short) v);
1628 if (target_type == TypeManager.ushort_type) {
1629 if (!CheckRange (ec, v, target_type, UInt16.MinValue, UInt16.MaxValue))
1631 return new UShortConstant ((ushort) v);
1633 if (target_type == TypeManager.int32_type) {
1634 if (!CheckRange (ec, v, target_type, Int32.MinValue, Int32.MaxValue))
1636 return new IntConstant ((int) v);
1638 if (target_type == TypeManager.int64_type)
1639 return new LongConstant ((long) v);
1640 if (target_type == TypeManager.uint64_type)
1641 return new ULongConstant ((ulong) v);
1642 if (target_type == TypeManager.float_type)
1643 return new FloatConstant ((float) v);
1644 if (target_type == TypeManager.double_type)
1645 return new DoubleConstant ((double) v);
1646 if (target_type == TypeManager.char_type) {
1647 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1649 return new CharConstant ((char) v);
1651 if (target_type == TypeManager.decimal_type)
1652 return new DecimalConstant ((decimal) v);
1654 if (real_expr is LongConstant){
1655 long v = ((LongConstant) real_expr).Value;
1657 if (target_type == TypeManager.byte_type) {
1658 if (!CheckRange (ec, v, target_type, Byte.MinValue, Byte.MaxValue))
1660 return new ByteConstant ((byte) v);
1662 if (target_type == TypeManager.sbyte_type) {
1663 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1665 return new SByteConstant ((sbyte) v);
1667 if (target_type == TypeManager.short_type) {
1668 if (!CheckRange (ec, v, target_type, Int16.MinValue, Int16.MaxValue))
1670 return new ShortConstant ((short) v);
1672 if (target_type == TypeManager.ushort_type) {
1673 if (!CheckRange (ec, v, target_type, UInt16.MinValue, UInt16.MaxValue))
1675 return new UShortConstant ((ushort) v);
1677 if (target_type == TypeManager.int32_type) {
1678 if (!CheckRange (ec, v, target_type, Int32.MinValue, Int32.MaxValue))
1680 return new IntConstant ((int) v);
1682 if (target_type == TypeManager.uint32_type) {
1683 if (!CheckRange (ec, v, target_type, UInt32.MinValue, UInt32.MaxValue))
1685 return new UIntConstant ((uint) v);
1687 if (target_type == TypeManager.uint64_type) {
1688 if (!CheckUnsigned (ec, v, target_type))
1690 return new ULongConstant ((ulong) v);
1692 if (target_type == TypeManager.float_type)
1693 return new FloatConstant ((float) v);
1694 if (target_type == TypeManager.double_type)
1695 return new DoubleConstant ((double) v);
1696 if (target_type == TypeManager.char_type) {
1697 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1699 return new CharConstant ((char) v);
1701 if (target_type == TypeManager.decimal_type)
1702 return new DecimalConstant ((decimal) v);
1704 if (real_expr is ULongConstant){
1705 ulong v = ((ULongConstant) real_expr).Value;
1707 if (target_type == TypeManager.byte_type) {
1708 if (!CheckRange (ec, v, target_type, Byte.MaxValue))
1710 return new ByteConstant ((byte) v);
1712 if (target_type == TypeManager.sbyte_type) {
1713 if (!CheckRange (ec, v, target_type, (ulong) SByte.MaxValue))
1715 return new SByteConstant ((sbyte) v);
1717 if (target_type == TypeManager.short_type) {
1718 if (!CheckRange (ec, v, target_type, (ulong) Int16.MaxValue))
1720 return new ShortConstant ((short) v);
1722 if (target_type == TypeManager.ushort_type) {
1723 if (!CheckRange (ec, v, target_type, UInt16.MaxValue))
1725 return new UShortConstant ((ushort) v);
1727 if (target_type == TypeManager.int32_type) {
1728 if (!CheckRange (ec, v, target_type, Int32.MaxValue))
1730 return new IntConstant ((int) v);
1732 if (target_type == TypeManager.uint32_type) {
1733 if (!CheckRange (ec, v, target_type, UInt32.MaxValue))
1735 return new UIntConstant ((uint) v);
1737 if (target_type == TypeManager.int64_type) {
1738 if (!CheckRange (ec, v, target_type, (ulong) Int64.MaxValue))
1740 return new LongConstant ((long) v);
1742 if (target_type == TypeManager.float_type)
1743 return new FloatConstant ((float) v);
1744 if (target_type == TypeManager.double_type)
1745 return new DoubleConstant ((double) v);
1746 if (target_type == TypeManager.char_type) {
1747 if (!CheckRange (ec, v, target_type, Char.MaxValue))
1749 return new CharConstant ((char) v);
1751 if (target_type == TypeManager.decimal_type)
1752 return new DecimalConstant ((decimal) v);
1754 if (real_expr is FloatConstant){
1755 float v = ((FloatConstant) real_expr).Value;
1757 if (target_type == TypeManager.byte_type)
1758 return new ByteConstant ((byte) v);
1759 if (target_type == TypeManager.sbyte_type)
1760 return new SByteConstant ((sbyte) v);
1761 if (target_type == TypeManager.short_type)
1762 return new ShortConstant ((short) v);
1763 if (target_type == TypeManager.ushort_type)
1764 return new UShortConstant ((ushort) v);
1765 if (target_type == TypeManager.int32_type)
1766 return new IntConstant ((int) v);
1767 if (target_type == TypeManager.uint32_type)
1768 return new UIntConstant ((uint) v);
1769 if (target_type == TypeManager.int64_type)
1770 return new LongConstant ((long) v);
1771 if (target_type == TypeManager.uint64_type)
1772 return new ULongConstant ((ulong) v);
1773 if (target_type == TypeManager.double_type)
1774 return new DoubleConstant ((double) v);
1775 if (target_type == TypeManager.char_type)
1776 return new CharConstant ((char) v);
1777 if (target_type == TypeManager.decimal_type)
1778 return new DecimalConstant ((decimal) v);
1780 if (real_expr is DoubleConstant){
1781 double v = ((DoubleConstant) real_expr).Value;
1783 if (target_type == TypeManager.byte_type){
1784 return new ByteConstant ((byte) v);
1785 } if (target_type == TypeManager.sbyte_type)
1786 return new SByteConstant ((sbyte) v);
1787 if (target_type == TypeManager.short_type)
1788 return new ShortConstant ((short) v);
1789 if (target_type == TypeManager.ushort_type)
1790 return new UShortConstant ((ushort) v);
1791 if (target_type == TypeManager.int32_type)
1792 return new IntConstant ((int) v);
1793 if (target_type == TypeManager.uint32_type)
1794 return new UIntConstant ((uint) v);
1795 if (target_type == TypeManager.int64_type)
1796 return new LongConstant ((long) v);
1797 if (target_type == TypeManager.uint64_type)
1798 return new ULongConstant ((ulong) v);
1799 if (target_type == TypeManager.float_type)
1800 return new FloatConstant ((float) v);
1801 if (target_type == TypeManager.char_type)
1802 return new CharConstant ((char) v);
1803 if (target_type == TypeManager.decimal_type)
1804 return new DecimalConstant ((decimal) v);
1807 if (real_expr is CharConstant){
1808 char v = ((CharConstant) real_expr).Value;
1810 if (target_type == TypeManager.byte_type) {
1811 if (!CheckRange (ec, v, target_type, Byte.MinValue, Byte.MaxValue))
1813 return new ByteConstant ((byte) v);
1815 if (target_type == TypeManager.sbyte_type) {
1816 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1818 return new SByteConstant ((sbyte) v);
1820 if (target_type == TypeManager.short_type) {
1821 if (!CheckRange (ec, v, target_type, Int16.MinValue, Int16.MaxValue))
1823 return new ShortConstant ((short) v);
1825 if (target_type == TypeManager.int32_type)
1826 return new IntConstant ((int) v);
1827 if (target_type == TypeManager.uint32_type)
1828 return new UIntConstant ((uint) v);
1829 if (target_type == TypeManager.int64_type)
1830 return new LongConstant ((long) v);
1831 if (target_type == TypeManager.uint64_type)
1832 return new ULongConstant ((ulong) v);
1833 if (target_type == TypeManager.float_type)
1834 return new FloatConstant ((float) v);
1835 if (target_type == TypeManager.double_type)
1836 return new DoubleConstant ((double) v);
1837 if (target_type == TypeManager.char_type) {
1838 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1840 return new CharConstant ((char) v);
1842 if (target_type == TypeManager.decimal_type)
1843 return new DecimalConstant ((decimal) v);
1849 public override Expression DoResolve (EmitContext ec)
1851 expr = expr.Resolve (ec);
1855 type = ec.DeclSpace.ResolveType (target_type, false, Location);
1860 CheckObsoleteAttribute (type);
1862 eclass = ExprClass.Value;
1864 if (expr is Constant){
1865 Expression e = TryReduce (ec, type);
1871 if (type.IsPointer && !ec.InUnsafe) {
1875 expr = Convert.ExplicitConversion (ec, expr, type, loc);
1879 public override void Emit (EmitContext ec)
1882 // This one will never happen
1884 throw new Exception ("Should not happen");
1889 /// Binary operators
1891 public class Binary : Expression {
1892 public enum Operator : byte {
1893 Multiply, Division, Modulus,
1894 Addition, Subtraction,
1895 LeftShift, RightShift,
1896 LessThan, GreaterThan, LessThanOrEqual, GreaterThanOrEqual,
1897 Equality, Inequality,
1907 Expression left, right;
1909 // This must be kept in sync with Operator!!!
1910 public static readonly string [] oper_names;
1914 oper_names = new string [(int) Operator.TOP];
1916 oper_names [(int) Operator.Multiply] = "op_Multiply";
1917 oper_names [(int) Operator.Division] = "op_Division";
1918 oper_names [(int) Operator.Modulus] = "op_Modulus";
1919 oper_names [(int) Operator.Addition] = "op_Addition";
1920 oper_names [(int) Operator.Subtraction] = "op_Subtraction";
1921 oper_names [(int) Operator.LeftShift] = "op_LeftShift";
1922 oper_names [(int) Operator.RightShift] = "op_RightShift";
1923 oper_names [(int) Operator.LessThan] = "op_LessThan";
1924 oper_names [(int) Operator.GreaterThan] = "op_GreaterThan";
1925 oper_names [(int) Operator.LessThanOrEqual] = "op_LessThanOrEqual";
1926 oper_names [(int) Operator.GreaterThanOrEqual] = "op_GreaterThanOrEqual";
1927 oper_names [(int) Operator.Equality] = "op_Equality";
1928 oper_names [(int) Operator.Inequality] = "op_Inequality";
1929 oper_names [(int) Operator.BitwiseAnd] = "op_BitwiseAnd";
1930 oper_names [(int) Operator.BitwiseOr] = "op_BitwiseOr";
1931 oper_names [(int) Operator.ExclusiveOr] = "op_ExclusiveOr";
1932 oper_names [(int) Operator.LogicalOr] = "op_LogicalOr";
1933 oper_names [(int) Operator.LogicalAnd] = "op_LogicalAnd";
1936 public Binary (Operator oper, Expression left, Expression right, Location loc)
1944 public Operator Oper {
1953 public Expression Left {
1962 public Expression Right {
1973 /// Returns a stringified representation of the Operator
1975 static string OperName (Operator oper)
1978 case Operator.Multiply:
1980 case Operator.Division:
1982 case Operator.Modulus:
1984 case Operator.Addition:
1986 case Operator.Subtraction:
1988 case Operator.LeftShift:
1990 case Operator.RightShift:
1992 case Operator.LessThan:
1994 case Operator.GreaterThan:
1996 case Operator.LessThanOrEqual:
1998 case Operator.GreaterThanOrEqual:
2000 case Operator.Equality:
2002 case Operator.Inequality:
2004 case Operator.BitwiseAnd:
2006 case Operator.BitwiseOr:
2008 case Operator.ExclusiveOr:
2010 case Operator.LogicalOr:
2012 case Operator.LogicalAnd:
2016 return oper.ToString ();
2019 public override string ToString ()
2021 return "operator " + OperName (oper) + "(" + left.ToString () + ", " +
2022 right.ToString () + ")";
2025 Expression ForceConversion (EmitContext ec, Expression expr, Type target_type)
2027 if (expr.Type == target_type)
2030 return Convert.ImplicitConversion (ec, expr, target_type, loc);
2033 public static void Error_OperatorAmbiguous (Location loc, Operator oper, Type l, Type r)
2036 34, loc, "Operator `" + OperName (oper)
2037 + "' is ambiguous on operands of type `"
2038 + TypeManager.CSharpName (l) + "' "
2039 + "and `" + TypeManager.CSharpName (r)
2043 bool IsOfType (EmitContext ec, Type l, Type r, Type t, bool check_user_conversions)
2045 if ((l == t) || (r == t))
2048 if (!check_user_conversions)
2051 if (Convert.ImplicitUserConversionExists (ec, l, t))
2053 else if (Convert.ImplicitUserConversionExists (ec, r, t))
2060 // Note that handling the case l == Decimal || r == Decimal
2061 // is taken care of by the Step 1 Operator Overload resolution.
2063 // If `check_user_conv' is true, we also check whether a user-defined conversion
2064 // exists. Note that we only need to do this if both arguments are of a user-defined
2065 // type, otherwise ConvertImplict() already finds the user-defined conversion for us,
2066 // so we don't explicitly check for performance reasons.
2068 bool DoNumericPromotions (EmitContext ec, Type l, Type r, bool check_user_conv)
2070 if (IsOfType (ec, l, r, TypeManager.double_type, check_user_conv)){
2072 // If either operand is of type double, the other operand is
2073 // conveted to type double.
2075 if (r != TypeManager.double_type)
2076 right = Convert.ImplicitConversion (ec, right, TypeManager.double_type, loc);
2077 if (l != TypeManager.double_type)
2078 left = Convert.ImplicitConversion (ec, left, TypeManager.double_type, loc);
2080 type = TypeManager.double_type;
2081 } else if (IsOfType (ec, l, r, TypeManager.float_type, check_user_conv)){
2083 // if either operand is of type float, the other operand is
2084 // converted to type float.
2086 if (r != TypeManager.double_type)
2087 right = Convert.ImplicitConversion (ec, right, TypeManager.float_type, loc);
2088 if (l != TypeManager.double_type)
2089 left = Convert.ImplicitConversion (ec, left, TypeManager.float_type, loc);
2090 type = TypeManager.float_type;
2091 } else if (IsOfType (ec, l, r, TypeManager.uint64_type, check_user_conv)){
2095 // If either operand is of type ulong, the other operand is
2096 // converted to type ulong. or an error ocurrs if the other
2097 // operand is of type sbyte, short, int or long
2099 if (l == TypeManager.uint64_type){
2100 if (r != TypeManager.uint64_type){
2101 if (right is IntConstant){
2102 IntConstant ic = (IntConstant) right;
2104 e = Convert.TryImplicitIntConversion (l, ic);
2107 } else if (right is LongConstant){
2108 long ll = ((LongConstant) right).Value;
2111 right = new ULongConstant ((ulong) ll);
2113 e = Convert.ImplicitNumericConversion (ec, right, l, loc);
2120 if (left is IntConstant){
2121 e = Convert.TryImplicitIntConversion (r, (IntConstant) left);
2124 } else if (left is LongConstant){
2125 long ll = ((LongConstant) left).Value;
2128 left = new ULongConstant ((ulong) ll);
2130 e = Convert.ImplicitNumericConversion (ec, left, r, loc);
2137 if ((other == TypeManager.sbyte_type) ||
2138 (other == TypeManager.short_type) ||
2139 (other == TypeManager.int32_type) ||
2140 (other == TypeManager.int64_type))
2141 Error_OperatorAmbiguous (loc, oper, l, r);
2143 left = ForceConversion (ec, left, TypeManager.uint64_type);
2144 right = ForceConversion (ec, right, TypeManager.uint64_type);
2146 type = TypeManager.uint64_type;
2147 } else if (IsOfType (ec, l, r, TypeManager.int64_type, check_user_conv)){
2149 // If either operand is of type long, the other operand is converted
2152 if (l != TypeManager.int64_type)
2153 left = Convert.ImplicitConversion (ec, left, TypeManager.int64_type, loc);
2154 if (r != TypeManager.int64_type)
2155 right = Convert.ImplicitConversion (ec, right, TypeManager.int64_type, loc);
2157 type = TypeManager.int64_type;
2158 } else if (IsOfType (ec, l, r, TypeManager.uint32_type, check_user_conv)){
2160 // If either operand is of type uint, and the other
2161 // operand is of type sbyte, short or int, othe operands are
2162 // converted to type long (unless we have an int constant).
2166 if (l == TypeManager.uint32_type){
2167 if (right is IntConstant){
2168 IntConstant ic = (IntConstant) right;
2172 right = new UIntConstant ((uint) val);
2179 } else if (r == TypeManager.uint32_type){
2180 if (left is IntConstant){
2181 IntConstant ic = (IntConstant) left;
2185 left = new UIntConstant ((uint) val);
2194 if ((other == TypeManager.sbyte_type) ||
2195 (other == TypeManager.short_type) ||
2196 (other == TypeManager.int32_type)){
2197 left = ForceConversion (ec, left, TypeManager.int64_type);
2198 right = ForceConversion (ec, right, TypeManager.int64_type);
2199 type = TypeManager.int64_type;
2202 // if either operand is of type uint, the other
2203 // operand is converd to type uint
2205 left = ForceConversion (ec, left, TypeManager.uint32_type);
2206 right = ForceConversion (ec, right, TypeManager.uint32_type);
2207 type = TypeManager.uint32_type;
2209 } else if (l == TypeManager.decimal_type || r == TypeManager.decimal_type){
2210 if (l != TypeManager.decimal_type)
2211 left = Convert.ImplicitConversion (ec, left, TypeManager.decimal_type, loc);
2213 if (r != TypeManager.decimal_type)
2214 right = Convert.ImplicitConversion (ec, right, TypeManager.decimal_type, loc);
2215 type = TypeManager.decimal_type;
2217 left = ForceConversion (ec, left, TypeManager.int32_type);
2218 right = ForceConversion (ec, right, TypeManager.int32_type);
2220 type = TypeManager.int32_type;
2223 return (left != null) && (right != null);
2226 static public void Error_OperatorCannotBeApplied (Location loc, string name, Type l, Type r)
2228 Report.Error (19, loc,
2229 "Operator " + name + " cannot be applied to operands of type `" +
2230 TypeManager.CSharpName (l) + "' and `" +
2231 TypeManager.CSharpName (r) + "'");
2234 void Error_OperatorCannotBeApplied ()
2236 Error_OperatorCannotBeApplied (loc, OperName (oper), left.Type, right.Type);
2239 static bool is_unsigned (Type t)
2241 return (t == TypeManager.uint32_type || t == TypeManager.uint64_type ||
2242 t == TypeManager.short_type || t == TypeManager.byte_type);
2245 static bool is_user_defined (Type t)
2247 if (t.IsSubclassOf (TypeManager.value_type) &&
2248 (!TypeManager.IsBuiltinType (t) || t == TypeManager.decimal_type))
2254 Expression Make32or64 (EmitContext ec, Expression e)
2258 if (t == TypeManager.int32_type || t == TypeManager.uint32_type ||
2259 t == TypeManager.int64_type || t == TypeManager.uint64_type)
2261 Expression ee = Convert.ImplicitConversion (ec, e, TypeManager.int32_type, loc);
2264 ee = Convert.ImplicitConversion (ec, e, TypeManager.uint32_type, loc);
2267 ee = Convert.ImplicitConversion (ec, e, TypeManager.int64_type, loc);
2270 ee = Convert.ImplicitConversion (ec, e, TypeManager.uint64_type, loc);
2276 Expression CheckShiftArguments (EmitContext ec)
2280 e = ForceConversion (ec, right, TypeManager.int32_type);
2282 Error_OperatorCannotBeApplied ();
2287 if (((e = Convert.ImplicitConversion (ec, left, TypeManager.int32_type, loc)) != null) ||
2288 ((e = Convert.ImplicitConversion (ec, left, TypeManager.uint32_type, loc)) != null) ||
2289 ((e = Convert.ImplicitConversion (ec, left, TypeManager.int64_type, loc)) != null) ||
2290 ((e = Convert.ImplicitConversion (ec, left, TypeManager.uint64_type, loc)) != null)){
2294 if (type == TypeManager.int32_type || type == TypeManager.uint32_type){
2295 right = new Binary (Binary.Operator.BitwiseAnd, right, new IntLiteral (31), loc);
2296 right = right.DoResolve (ec);
2298 right = new Binary (Binary.Operator.BitwiseAnd, right, new IntLiteral (63), loc);
2299 right = right.DoResolve (ec);
2304 Error_OperatorCannotBeApplied ();
2308 Expression ResolveOperator (EmitContext ec)
2311 Type r = right.Type;
2313 bool overload_failed = false;
2316 // Special cases: string or type parameter comapred to null
2318 if (oper == Operator.Equality || oper == Operator.Inequality){
2319 if ((l == TypeManager.string_type && (right is NullLiteral)) ||
2320 (r == TypeManager.string_type && (left is NullLiteral))){
2321 Type = TypeManager.bool_type;
2326 if (l.IsGenericParameter && (right is NullLiteral)) {
2327 if (l.BaseType == TypeManager.value_type) {
2328 Error_OperatorCannotBeApplied ();
2332 left = new BoxedCast (left);
2333 Type = TypeManager.bool_type;
2337 if (r.IsGenericParameter && (left is NullLiteral)) {
2338 if (r.BaseType == TypeManager.value_type) {
2339 Error_OperatorCannotBeApplied ();
2343 right = new BoxedCast (right);
2344 Type = TypeManager.bool_type;
2349 if (l == TypeManager.intptr_type && r == TypeManager.intptr_type) {
2350 Type = TypeManager.bool_type;
2357 // Do not perform operator overload resolution when both sides are
2360 if (!(TypeManager.IsCLRType (l) && TypeManager.IsCLRType (r))){
2362 // Step 1: Perform Operator Overload location
2364 Expression left_expr, right_expr;
2366 string op = oper_names [(int) oper];
2368 MethodGroupExpr union;
2369 left_expr = MemberLookup (ec, l, op, MemberTypes.Method, AllBindingFlags, loc);
2371 right_expr = MemberLookup (
2372 ec, r, op, MemberTypes.Method, AllBindingFlags, loc);
2373 union = Invocation.MakeUnionSet (left_expr, right_expr, loc);
2375 union = (MethodGroupExpr) left_expr;
2377 if (union != null) {
2378 ArrayList args = new ArrayList (2);
2379 args.Add (new Argument (left, Argument.AType.Expression));
2380 args.Add (new Argument (right, Argument.AType.Expression));
2382 MethodBase method = Invocation.OverloadResolve (
2383 ec, union, args, true, Location.Null);
2385 if (method != null) {
2386 MethodInfo mi = (MethodInfo) method;
2388 return new BinaryMethod (mi.ReturnType, method, args);
2390 overload_failed = true;
2396 // Step 0: String concatenation (because overloading will get this wrong)
2398 if (oper == Operator.Addition){
2400 // If any of the arguments is a string, cast to string
2403 // Simple constant folding
2404 if (left is StringConstant && right is StringConstant)
2405 return new StringConstant (((StringConstant) left).Value + ((StringConstant) right).Value);
2407 if (l == TypeManager.string_type || r == TypeManager.string_type) {
2409 if (r == TypeManager.void_type || l == TypeManager.void_type) {
2410 Error_OperatorCannotBeApplied ();
2414 // try to fold it in on the left
2415 if (left is StringConcat) {
2418 // We have to test here for not-null, since we can be doubly-resolved
2419 // take care of not appending twice
2422 type = TypeManager.string_type;
2423 ((StringConcat) left).Append (ec, right);
2424 return left.Resolve (ec);
2430 // Otherwise, start a new concat expression
2431 return new StringConcat (ec, loc, left, right).Resolve (ec);
2435 // Transform a + ( - b) into a - b
2437 if (right is Unary){
2438 Unary right_unary = (Unary) right;
2440 if (right_unary.Oper == Unary.Operator.UnaryNegation){
2441 oper = Operator.Subtraction;
2442 right = right_unary.Expr;
2448 if (oper == Operator.Equality || oper == Operator.Inequality){
2449 if (l == TypeManager.bool_type || r == TypeManager.bool_type){
2450 if (r != TypeManager.bool_type || l != TypeManager.bool_type){
2451 Error_OperatorCannotBeApplied ();
2455 type = TypeManager.bool_type;
2460 // operator != (object a, object b)
2461 // operator == (object a, object b)
2463 // For this to be used, both arguments have to be reference-types.
2464 // Read the rationale on the spec (14.9.6)
2466 // Also, if at compile time we know that the classes do not inherit
2467 // one from the other, then we catch the error there.
2469 if (!(l.IsValueType || r.IsValueType)){
2470 type = TypeManager.bool_type;
2475 if (l.IsSubclassOf (r) || r.IsSubclassOf (l))
2479 // Also, a standard conversion must exist from either one
2481 if (!(Convert.ImplicitStandardConversionExists (left, r) ||
2482 Convert.ImplicitStandardConversionExists (right, l))){
2483 Error_OperatorCannotBeApplied ();
2487 // We are going to have to convert to an object to compare
2489 if (l != TypeManager.object_type)
2490 left = new EmptyCast (left, TypeManager.object_type);
2491 if (r != TypeManager.object_type)
2492 right = new EmptyCast (right, TypeManager.object_type);
2495 // FIXME: CSC here catches errors cs254 and cs252
2501 // One of them is a valuetype, but the other one is not.
2503 if (!l.IsValueType || !r.IsValueType) {
2504 Error_OperatorCannotBeApplied ();
2509 // Only perform numeric promotions on:
2510 // +, -, *, /, %, &, |, ^, ==, !=, <, >, <=, >=
2512 if (oper == Operator.Addition || oper == Operator.Subtraction) {
2513 if (TypeManager.IsDelegateType (l)){
2514 if (right.eclass == ExprClass.MethodGroup && RootContext.V2){
2515 Expression tmp = Convert.ImplicitConversionRequired (ec, right, l, loc);
2522 if (TypeManager.IsDelegateType (r)){
2524 ArrayList args = new ArrayList (2);
2526 args = new ArrayList (2);
2527 args.Add (new Argument (left, Argument.AType.Expression));
2528 args.Add (new Argument (right, Argument.AType.Expression));
2530 if (oper == Operator.Addition)
2531 method = TypeManager.delegate_combine_delegate_delegate;
2533 method = TypeManager.delegate_remove_delegate_delegate;
2536 Error_OperatorCannotBeApplied ();
2540 return new BinaryDelegate (l, method, args);
2545 // Pointer arithmetic:
2547 // T* operator + (T* x, int y);
2548 // T* operator + (T* x, uint y);
2549 // T* operator + (T* x, long y);
2550 // T* operator + (T* x, ulong y);
2552 // T* operator + (int y, T* x);
2553 // T* operator + (uint y, T *x);
2554 // T* operator + (long y, T *x);
2555 // T* operator + (ulong y, T *x);
2557 // T* operator - (T* x, int y);
2558 // T* operator - (T* x, uint y);
2559 // T* operator - (T* x, long y);
2560 // T* operator - (T* x, ulong y);
2562 // long operator - (T* x, T *y)
2565 if (r.IsPointer && oper == Operator.Subtraction){
2567 return new PointerArithmetic (
2568 false, left, right, TypeManager.int64_type,
2571 Expression t = Make32or64 (ec, right);
2573 return new PointerArithmetic (oper == Operator.Addition, left, t, l, loc);
2575 } else if (r.IsPointer && oper == Operator.Addition){
2576 Expression t = Make32or64 (ec, left);
2578 return new PointerArithmetic (true, right, t, r, loc);
2583 // Enumeration operators
2585 bool lie = TypeManager.IsEnumType (l);
2586 bool rie = TypeManager.IsEnumType (r);
2590 // U operator - (E e, E f)
2592 if (oper == Operator.Subtraction){
2594 type = TypeManager.EnumToUnderlying (l);
2597 Error_OperatorCannotBeApplied ();
2603 // operator + (E e, U x)
2604 // operator - (E e, U x)
2606 if (oper == Operator.Addition || oper == Operator.Subtraction){
2607 Type enum_type = lie ? l : r;
2608 Type other_type = lie ? r : l;
2609 Type underlying_type = TypeManager.EnumToUnderlying (enum_type);
2611 if (underlying_type != other_type){
2612 temp = Convert.ImplicitConversion (ec, lie ? right : left, underlying_type, loc);
2622 Error_OperatorCannotBeApplied ();
2631 temp = Convert.ImplicitConversion (ec, right, l, loc);
2635 Error_OperatorCannotBeApplied ();
2639 temp = Convert.ImplicitConversion (ec, left, r, loc);
2644 Error_OperatorCannotBeApplied ();
2649 if (oper == Operator.Equality || oper == Operator.Inequality ||
2650 oper == Operator.LessThanOrEqual || oper == Operator.LessThan ||
2651 oper == Operator.GreaterThanOrEqual || oper == Operator.GreaterThan){
2652 if (left.Type != right.Type){
2653 Error_OperatorCannotBeApplied ();
2656 type = TypeManager.bool_type;
2660 if (oper == Operator.BitwiseAnd ||
2661 oper == Operator.BitwiseOr ||
2662 oper == Operator.ExclusiveOr){
2666 Error_OperatorCannotBeApplied ();
2670 if (oper == Operator.LeftShift || oper == Operator.RightShift)
2671 return CheckShiftArguments (ec);
2673 if (oper == Operator.LogicalOr || oper == Operator.LogicalAnd){
2674 if (l == TypeManager.bool_type && r == TypeManager.bool_type) {
2675 type = TypeManager.bool_type;
2680 Error_OperatorCannotBeApplied ();
2684 Expression e = new ConditionalLogicalOperator (
2685 oper == Operator.LogicalAnd, left, right, l, loc);
2686 return e.Resolve (ec);
2690 // operator & (bool x, bool y)
2691 // operator | (bool x, bool y)
2692 // operator ^ (bool x, bool y)
2694 if (l == TypeManager.bool_type && r == TypeManager.bool_type){
2695 if (oper == Operator.BitwiseAnd ||
2696 oper == Operator.BitwiseOr ||
2697 oper == Operator.ExclusiveOr){
2704 // Pointer comparison
2706 if (l.IsPointer && r.IsPointer){
2707 if (oper == Operator.Equality || oper == Operator.Inequality ||
2708 oper == Operator.LessThan || oper == Operator.LessThanOrEqual ||
2709 oper == Operator.GreaterThan || oper == Operator.GreaterThanOrEqual){
2710 type = TypeManager.bool_type;
2716 // We are dealing with numbers
2718 if (overload_failed){
2719 Error_OperatorCannotBeApplied ();
2724 // This will leave left or right set to null if there is an error
2726 bool check_user_conv = is_user_defined (l) && is_user_defined (r);
2727 DoNumericPromotions (ec, l, r, check_user_conv);
2728 if (left == null || right == null){
2729 Error_OperatorCannotBeApplied (loc, OperName (oper), l, r);
2734 // reload our cached types if required
2739 if (oper == Operator.BitwiseAnd ||
2740 oper == Operator.BitwiseOr ||
2741 oper == Operator.ExclusiveOr){
2743 if (((l == TypeManager.int32_type) ||
2744 (l == TypeManager.uint32_type) ||
2745 (l == TypeManager.short_type) ||
2746 (l == TypeManager.ushort_type) ||
2747 (l == TypeManager.int64_type) ||
2748 (l == TypeManager.uint64_type))){
2751 Error_OperatorCannotBeApplied ();
2755 Error_OperatorCannotBeApplied ();
2760 if (oper == Operator.Equality ||
2761 oper == Operator.Inequality ||
2762 oper == Operator.LessThanOrEqual ||
2763 oper == Operator.LessThan ||
2764 oper == Operator.GreaterThanOrEqual ||
2765 oper == Operator.GreaterThan){
2766 type = TypeManager.bool_type;
2772 public override Expression DoResolve (EmitContext ec)
2774 if ((oper == Operator.Subtraction) && (left is ParenthesizedExpression)) {
2775 left = ((ParenthesizedExpression) left).Expr;
2776 left = left.Resolve (ec, ResolveFlags.VariableOrValue | ResolveFlags.Type);
2780 if (left.eclass == ExprClass.Type) {
2781 Error (75, "Casting a negative value needs to have the value in parentheses.");
2785 left = left.Resolve (ec);
2786 right = right.Resolve (ec);
2788 if (left == null || right == null)
2791 eclass = ExprClass.Value;
2793 Constant rc = right as Constant;
2794 Constant lc = left as Constant;
2796 if (rc != null & lc != null){
2797 Expression e = ConstantFold.BinaryFold (
2798 ec, oper, lc, rc, loc);
2803 return ResolveOperator (ec);
2807 /// EmitBranchable is called from Statement.EmitBoolExpression in the
2808 /// context of a conditional bool expression. This function will return
2809 /// false if it is was possible to use EmitBranchable, or true if it was.
2811 /// The expression's code is generated, and we will generate a branch to `target'
2812 /// if the resulting expression value is equal to isTrue
2814 public override void EmitBranchable (EmitContext ec, Label target, bool onTrue)
2816 ILGenerator ig = ec.ig;
2819 // This is more complicated than it looks, but its just to avoid
2820 // duplicated tests: basically, we allow ==, !=, >, <, >= and <=
2821 // but on top of that we want for == and != to use a special path
2822 // if we are comparing against null
2824 if ((oper == Operator.Equality || oper == Operator.Inequality) && (left is Constant || right is Constant)) {
2825 bool my_on_true = oper == Operator.Inequality ? onTrue : !onTrue;
2828 // put the constant on the rhs, for simplicity
2830 if (left is Constant) {
2831 Expression swap = right;
2836 if (((Constant) right).IsZeroInteger) {
2839 ig.Emit (OpCodes.Brtrue, target);
2841 ig.Emit (OpCodes.Brfalse, target);
2844 } else if (right is BoolConstant){
2846 if (my_on_true != ((BoolConstant) right).Value)
2847 ig.Emit (OpCodes.Brtrue, target);
2849 ig.Emit (OpCodes.Brfalse, target);
2854 } else if (oper == Operator.LogicalAnd) {
2857 Label tests_end = ig.DefineLabel ();
2859 left.EmitBranchable (ec, tests_end, false);
2860 right.EmitBranchable (ec, target, true);
2861 ig.MarkLabel (tests_end);
2863 left.EmitBranchable (ec, target, false);
2864 right.EmitBranchable (ec, target, false);
2869 } else if (oper == Operator.LogicalOr){
2871 left.EmitBranchable (ec, target, true);
2872 right.EmitBranchable (ec, target, true);
2875 Label tests_end = ig.DefineLabel ();
2876 left.EmitBranchable (ec, tests_end, true);
2877 right.EmitBranchable (ec, target, false);
2878 ig.MarkLabel (tests_end);
2883 } else if (!(oper == Operator.LessThan || oper == Operator.GreaterThan ||
2884 oper == Operator.LessThanOrEqual || oper == Operator.GreaterThanOrEqual ||
2885 oper == Operator.Equality || oper == Operator.Inequality)) {
2886 base.EmitBranchable (ec, target, onTrue);
2894 bool isUnsigned = is_unsigned (t) || t == TypeManager.double_type || t == TypeManager.float_type;
2897 case Operator.Equality:
2899 ig.Emit (OpCodes.Beq, target);
2901 ig.Emit (OpCodes.Bne_Un, target);
2904 case Operator.Inequality:
2906 ig.Emit (OpCodes.Bne_Un, target);
2908 ig.Emit (OpCodes.Beq, target);
2911 case Operator.LessThan:
2914 ig.Emit (OpCodes.Blt_Un, target);
2916 ig.Emit (OpCodes.Blt, target);
2919 ig.Emit (OpCodes.Bge_Un, target);
2921 ig.Emit (OpCodes.Bge, target);
2924 case Operator.GreaterThan:
2927 ig.Emit (OpCodes.Bgt_Un, target);
2929 ig.Emit (OpCodes.Bgt, target);
2932 ig.Emit (OpCodes.Ble_Un, target);
2934 ig.Emit (OpCodes.Ble, target);
2937 case Operator.LessThanOrEqual:
2940 ig.Emit (OpCodes.Ble_Un, target);
2942 ig.Emit (OpCodes.Ble, target);
2945 ig.Emit (OpCodes.Bgt_Un, target);
2947 ig.Emit (OpCodes.Bgt, target);
2951 case Operator.GreaterThanOrEqual:
2954 ig.Emit (OpCodes.Bge_Un, target);
2956 ig.Emit (OpCodes.Bge, target);
2959 ig.Emit (OpCodes.Blt_Un, target);
2961 ig.Emit (OpCodes.Blt, target);
2964 Console.WriteLine (oper);
2965 throw new Exception ("what is THAT");
2969 public override void Emit (EmitContext ec)
2971 ILGenerator ig = ec.ig;
2976 // Handle short-circuit operators differently
2979 if (oper == Operator.LogicalAnd) {
2980 Label load_zero = ig.DefineLabel ();
2981 Label end = ig.DefineLabel ();
2983 left.EmitBranchable (ec, load_zero, false);
2985 ig.Emit (OpCodes.Br, end);
2987 ig.MarkLabel (load_zero);
2988 ig.Emit (OpCodes.Ldc_I4_0);
2991 } else if (oper == Operator.LogicalOr) {
2992 Label load_one = ig.DefineLabel ();
2993 Label end = ig.DefineLabel ();
2995 left.EmitBranchable (ec, load_one, true);
2997 ig.Emit (OpCodes.Br, end);
2999 ig.MarkLabel (load_one);
3000 ig.Emit (OpCodes.Ldc_I4_1);
3008 bool isUnsigned = is_unsigned (left.Type);
3011 case Operator.Multiply:
3013 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
3014 opcode = OpCodes.Mul_Ovf;
3015 else if (isUnsigned)
3016 opcode = OpCodes.Mul_Ovf_Un;
3018 opcode = OpCodes.Mul;
3020 opcode = OpCodes.Mul;
3024 case Operator.Division:
3026 opcode = OpCodes.Div_Un;
3028 opcode = OpCodes.Div;
3031 case Operator.Modulus:
3033 opcode = OpCodes.Rem_Un;
3035 opcode = OpCodes.Rem;
3038 case Operator.Addition:
3040 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
3041 opcode = OpCodes.Add_Ovf;
3042 else if (isUnsigned)
3043 opcode = OpCodes.Add_Ovf_Un;
3045 opcode = OpCodes.Add;
3047 opcode = OpCodes.Add;
3050 case Operator.Subtraction:
3052 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
3053 opcode = OpCodes.Sub_Ovf;
3054 else if (isUnsigned)
3055 opcode = OpCodes.Sub_Ovf_Un;
3057 opcode = OpCodes.Sub;
3059 opcode = OpCodes.Sub;
3062 case Operator.RightShift:
3064 opcode = OpCodes.Shr_Un;
3066 opcode = OpCodes.Shr;
3069 case Operator.LeftShift:
3070 opcode = OpCodes.Shl;
3073 case Operator.Equality:
3074 opcode = OpCodes.Ceq;
3077 case Operator.Inequality:
3078 ig.Emit (OpCodes.Ceq);
3079 ig.Emit (OpCodes.Ldc_I4_0);
3081 opcode = OpCodes.Ceq;
3084 case Operator.LessThan:
3086 opcode = OpCodes.Clt_Un;
3088 opcode = OpCodes.Clt;
3091 case Operator.GreaterThan:
3093 opcode = OpCodes.Cgt_Un;
3095 opcode = OpCodes.Cgt;
3098 case Operator.LessThanOrEqual:
3099 Type lt = left.Type;
3101 if (isUnsigned || (lt == TypeManager.double_type || lt == TypeManager.float_type))
3102 ig.Emit (OpCodes.Cgt_Un);
3104 ig.Emit (OpCodes.Cgt);
3105 ig.Emit (OpCodes.Ldc_I4_0);
3107 opcode = OpCodes.Ceq;
3110 case Operator.GreaterThanOrEqual:
3111 Type le = left.Type;
3113 if (isUnsigned || (le == TypeManager.double_type || le == TypeManager.float_type))
3114 ig.Emit (OpCodes.Clt_Un);
3116 ig.Emit (OpCodes.Clt);
3118 ig.Emit (OpCodes.Ldc_I4_0);
3120 opcode = OpCodes.Ceq;
3123 case Operator.BitwiseOr:
3124 opcode = OpCodes.Or;
3127 case Operator.BitwiseAnd:
3128 opcode = OpCodes.And;
3131 case Operator.ExclusiveOr:
3132 opcode = OpCodes.Xor;
3136 throw new Exception ("This should not happen: Operator = "
3137 + oper.ToString ());
3145 // Object created by Binary when the binary operator uses an method instead of being
3146 // a binary operation that maps to a CIL binary operation.
3148 public class BinaryMethod : Expression {
3149 public MethodBase method;
3150 public ArrayList Arguments;
3152 public BinaryMethod (Type t, MethodBase m, ArrayList args)
3157 eclass = ExprClass.Value;
3160 public override Expression DoResolve (EmitContext ec)
3165 public override void Emit (EmitContext ec)
3167 ILGenerator ig = ec.ig;
3169 if (Arguments != null)
3170 Invocation.EmitArguments (ec, method, Arguments);
3172 if (method is MethodInfo)
3173 ig.Emit (OpCodes.Call, (MethodInfo) method);
3175 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
3180 // Represents the operation a + b [+ c [+ d [+ ...]]], where a is a string
3181 // b, c, d... may be strings or objects.
3183 public class StringConcat : Expression {
3185 bool invalid = false;
3188 public StringConcat (EmitContext ec, Location loc, Expression left, Expression right)
3191 type = TypeManager.string_type;
3192 eclass = ExprClass.Value;
3194 operands = new ArrayList (2);
3199 public override Expression DoResolve (EmitContext ec)
3207 public void Append (EmitContext ec, Expression operand)
3212 if (operand is StringConstant && operands.Count != 0) {
3213 StringConstant last_operand = operands [operands.Count - 1] as StringConstant;
3214 if (last_operand != null) {
3215 operands [operands.Count - 1] = new StringConstant (last_operand.Value + ((StringConstant) operand).Value);
3221 // Conversion to object
3223 if (operand.Type != TypeManager.string_type) {
3224 Expression no = Convert.ImplicitConversion (ec, operand, TypeManager.object_type, loc);
3227 Binary.Error_OperatorCannotBeApplied (loc, "+", TypeManager.string_type, operand.Type);
3233 operands.Add (operand);
3236 public override void Emit (EmitContext ec)
3238 MethodInfo concat_method = null;
3241 // Are we also concating objects?
3243 bool is_strings_only = true;
3246 // Do conversion to arguments; check for strings only
3248 for (int i = 0; i < operands.Count; i ++) {
3249 Expression e = (Expression) operands [i];
3250 is_strings_only &= e.Type == TypeManager.string_type;
3253 for (int i = 0; i < operands.Count; i ++) {
3254 Expression e = (Expression) operands [i];
3256 if (! is_strings_only && e.Type == TypeManager.string_type) {
3257 // need to make sure this is an object, because the EmitParams
3258 // method might look at the type of this expression, see it is a
3259 // string and emit a string [] when we want an object [];
3261 e = Convert.ImplicitConversion (ec, e, TypeManager.object_type, loc);
3263 operands [i] = new Argument (e, Argument.AType.Expression);
3267 // Find the right method
3269 switch (operands.Count) {
3272 // This should not be possible, because simple constant folding
3273 // is taken care of in the Binary code.
3275 throw new Exception ("how did you get here?");
3278 concat_method = is_strings_only ?
3279 TypeManager.string_concat_string_string :
3280 TypeManager.string_concat_object_object ;
3283 concat_method = is_strings_only ?
3284 TypeManager.string_concat_string_string_string :
3285 TypeManager.string_concat_object_object_object ;
3289 // There is not a 4 param overlaod for object (the one that there is
3290 // is actually a varargs methods, and is only in corlib because it was
3291 // introduced there before.).
3293 if (!is_strings_only)
3296 concat_method = TypeManager.string_concat_string_string_string_string;
3299 concat_method = is_strings_only ?
3300 TypeManager.string_concat_string_dot_dot_dot :
3301 TypeManager.string_concat_object_dot_dot_dot ;
3305 Invocation.EmitArguments (ec, concat_method, operands);
3306 ec.ig.Emit (OpCodes.Call, concat_method);
3311 // Object created with +/= on delegates
3313 public class BinaryDelegate : Expression {
3317 public BinaryDelegate (Type t, MethodInfo mi, ArrayList args)
3322 eclass = ExprClass.Value;
3325 public override Expression DoResolve (EmitContext ec)
3330 public override void Emit (EmitContext ec)
3332 ILGenerator ig = ec.ig;
3334 Invocation.EmitArguments (ec, method, args);
3336 ig.Emit (OpCodes.Call, (MethodInfo) method);
3337 ig.Emit (OpCodes.Castclass, type);
3340 public Expression Right {
3342 Argument arg = (Argument) args [1];
3347 public bool IsAddition {
3349 return method == TypeManager.delegate_combine_delegate_delegate;
3355 // User-defined conditional logical operator
3356 public class ConditionalLogicalOperator : Expression {
3357 Expression left, right;
3360 public ConditionalLogicalOperator (bool is_and, Expression left, Expression right, Type t, Location loc)
3363 eclass = ExprClass.Value;
3367 this.is_and = is_and;
3370 protected void Error19 ()
3372 Binary.Error_OperatorCannotBeApplied (loc, is_and ? "&&" : "||", type, type);
3375 protected void Error218 ()
3377 Error (218, "The type ('" + TypeManager.CSharpName (type) + "') must contain " +
3378 "declarations of operator true and operator false");
3381 Expression op_true, op_false, op;
3382 LocalTemporary left_temp;
3384 public override Expression DoResolve (EmitContext ec)
3387 Expression operator_group;
3389 operator_group = MethodLookup (ec, type, is_and ? "op_BitwiseAnd" : "op_BitwiseOr", loc);
3390 if (operator_group == null) {
3395 left_temp = new LocalTemporary (ec, type);
3397 ArrayList arguments = new ArrayList ();
3398 arguments.Add (new Argument (left_temp, Argument.AType.Expression));
3399 arguments.Add (new Argument (right, Argument.AType.Expression));
3400 method = Invocation.OverloadResolve (
3401 ec, (MethodGroupExpr) operator_group, arguments, false, loc)
3403 if ((method == null) || (method.ReturnType != type)) {
3408 op = new StaticCallExpr (method, arguments, loc);
3410 op_true = GetOperatorTrue (ec, left_temp, loc);
3411 op_false = GetOperatorFalse (ec, left_temp, loc);
3412 if ((op_true == null) || (op_false == null)) {
3420 public override void Emit (EmitContext ec)
3422 ILGenerator ig = ec.ig;
3423 Label false_target = ig.DefineLabel ();
3424 Label end_target = ig.DefineLabel ();
3426 ig.Emit (OpCodes.Nop);
3429 left_temp.Store (ec);
3431 (is_and ? op_false : op_true).EmitBranchable (ec, false_target, false);
3432 left_temp.Emit (ec);
3433 ig.Emit (OpCodes.Br, end_target);
3434 ig.MarkLabel (false_target);
3436 ig.MarkLabel (end_target);
3438 ig.Emit (OpCodes.Nop);
3442 public class PointerArithmetic : Expression {
3443 Expression left, right;
3447 // We assume that `l' is always a pointer
3449 public PointerArithmetic (bool is_addition, Expression l, Expression r, Type t, Location loc)
3452 eclass = ExprClass.Variable;
3456 is_add = is_addition;
3459 public override Expression DoResolve (EmitContext ec)
3462 // We are born fully resolved
3467 public override void Emit (EmitContext ec)
3469 Type op_type = left.Type;
3470 ILGenerator ig = ec.ig;
3471 int size = GetTypeSize (TypeManager.GetElementType (op_type));
3472 Type rtype = right.Type;
3474 if (rtype.IsPointer){
3476 // handle (pointer - pointer)
3480 ig.Emit (OpCodes.Sub);
3484 ig.Emit (OpCodes.Sizeof, op_type);
3486 IntLiteral.EmitInt (ig, size);
3487 ig.Emit (OpCodes.Div);
3489 ig.Emit (OpCodes.Conv_I8);
3492 // handle + and - on (pointer op int)
3495 ig.Emit (OpCodes.Conv_I);
3499 ig.Emit (OpCodes.Sizeof, op_type);
3501 IntLiteral.EmitInt (ig, size);
3502 if (rtype == TypeManager.int64_type)
3503 ig.Emit (OpCodes.Conv_I8);
3504 else if (rtype == TypeManager.uint64_type)
3505 ig.Emit (OpCodes.Conv_U8);
3506 ig.Emit (OpCodes.Mul);
3507 ig.Emit (OpCodes.Conv_I);
3510 ig.Emit (OpCodes.Add);
3512 ig.Emit (OpCodes.Sub);
3518 /// Implements the ternary conditional operator (?:)
3520 public class Conditional : Expression {
3521 Expression expr, trueExpr, falseExpr;
3523 public Conditional (Expression expr, Expression trueExpr, Expression falseExpr, Location l)
3526 this.trueExpr = trueExpr;
3527 this.falseExpr = falseExpr;
3531 public Expression Expr {
3537 public Expression TrueExpr {
3543 public Expression FalseExpr {
3549 public override Expression DoResolve (EmitContext ec)
3551 expr = expr.Resolve (ec);
3556 if (expr.Type != TypeManager.bool_type){
3557 expr = Expression.ResolveBoolean (
3564 trueExpr = trueExpr.Resolve (ec);
3565 falseExpr = falseExpr.Resolve (ec);
3567 if (trueExpr == null || falseExpr == null)
3570 eclass = ExprClass.Value;
3571 if (trueExpr.Type == falseExpr.Type)
3572 type = trueExpr.Type;
3575 Type true_type = trueExpr.Type;
3576 Type false_type = falseExpr.Type;
3578 if (trueExpr is NullLiteral){
3581 } else if (falseExpr is NullLiteral){
3587 // First, if an implicit conversion exists from trueExpr
3588 // to falseExpr, then the result type is of type falseExpr.Type
3590 conv = Convert.ImplicitConversion (ec, trueExpr, false_type, loc);
3593 // Check if both can convert implicitl to each other's type
3595 if (Convert.ImplicitConversion (ec, falseExpr, true_type, loc) != null){
3597 "Can not compute type of conditional expression " +
3598 "as `" + TypeManager.CSharpName (trueExpr.Type) +
3599 "' and `" + TypeManager.CSharpName (falseExpr.Type) +
3600 "' convert implicitly to each other");
3605 } else if ((conv = Convert.ImplicitConversion(ec, falseExpr, true_type,loc))!= null){
3609 Error (173, "The type of the conditional expression can " +
3610 "not be computed because there is no implicit conversion" +
3611 " from `" + TypeManager.CSharpName (trueExpr.Type) + "'" +
3612 " and `" + TypeManager.CSharpName (falseExpr.Type) + "'");
3617 if (expr is BoolConstant){
3618 BoolConstant bc = (BoolConstant) expr;
3629 public override void Emit (EmitContext ec)
3631 ILGenerator ig = ec.ig;
3632 Label false_target = ig.DefineLabel ();
3633 Label end_target = ig.DefineLabel ();
3635 expr.EmitBranchable (ec, false_target, false);
3637 ig.Emit (OpCodes.Br, end_target);
3638 ig.MarkLabel (false_target);
3639 falseExpr.Emit (ec);
3640 ig.MarkLabel (end_target);
3648 public class LocalVariableReference : Expression, IAssignMethod, IMemoryLocation, IVariable {
3649 public readonly string Name;
3650 public readonly Block Block;
3651 LocalInfo local_info;
3654 public LocalVariableReference (Block block, string name, Location l)
3659 eclass = ExprClass.Variable;
3662 // Setting `is_readonly' to false will allow you to create a writable
3663 // reference to a read-only variable. This is used by foreach and using.
3664 public LocalVariableReference (Block block, string name, Location l,
3665 LocalInfo local_info, bool is_readonly)
3666 : this (block, name, l)
3668 this.local_info = local_info;
3669 this.is_readonly = is_readonly;
3672 public VariableInfo VariableInfo {
3673 get { return local_info.VariableInfo; }
3676 public bool IsReadOnly {
3682 protected void DoResolveBase (EmitContext ec)
3684 if (local_info == null) {
3685 local_info = Block.GetLocalInfo (Name);
3686 is_readonly = local_info.ReadOnly;
3689 type = local_info.VariableType;
3691 if (ec.InAnonymousMethod)
3692 Block.LiftVariable (local_info);
3696 protected Expression DoResolve (EmitContext ec, bool is_lvalue)
3698 Expression e = Block.GetConstantExpression (Name);
3700 local_info.Used = true;
3701 eclass = ExprClass.Value;
3705 VariableInfo variable_info = local_info.VariableInfo;
3706 if ((variable_info != null) && !variable_info.IsAssigned (ec, loc))
3710 local_info.Used = true;
3712 if (local_info.LocalBuilder == null)
3713 return ec.RemapLocal (local_info);
3718 public override Expression DoResolve (EmitContext ec)
3722 return DoResolve (ec, false);
3725 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
3729 VariableInfo variable_info = local_info.VariableInfo;
3730 if (variable_info != null)
3731 variable_info.SetAssigned (ec);
3733 Expression e = DoResolve (ec, true);
3739 Error (1604, "cannot assign to `" + Name + "' because it is readonly");
3743 CheckObsoleteAttribute (e.Type);
3745 if (local_info.LocalBuilder == null)
3746 return ec.RemapLocalLValue (local_info, right_side);
3751 public bool VerifyFixed (bool is_expression)
3753 return !is_expression || local_info.IsFixed;
3756 public override void Emit (EmitContext ec)
3758 ILGenerator ig = ec.ig;
3760 ig.Emit (OpCodes.Ldloc, local_info.LocalBuilder);
3763 public void EmitAssign (EmitContext ec, Expression source)
3765 ILGenerator ig = ec.ig;
3768 ig.Emit (OpCodes.Stloc, local_info.LocalBuilder);
3771 public void AddressOf (EmitContext ec, AddressOp mode)
3773 ILGenerator ig = ec.ig;
3775 ig.Emit (OpCodes.Ldloca, local_info.LocalBuilder);
3778 public override string ToString ()
3780 return String.Format ("{0} ({1}:{2})", GetType (), Name, loc);
3785 /// This represents a reference to a parameter in the intermediate
3788 public class ParameterReference : Expression, IAssignMethod, IMemoryLocation, IVariable {
3794 public Parameter.Modifier mod;
3795 public bool is_ref, is_out;
3797 public ParameterReference (Parameters pars, Block block, int idx, string name, Location loc)
3804 eclass = ExprClass.Variable;
3807 public VariableInfo VariableInfo {
3811 public bool VerifyFixed (bool is_expression)
3813 return !is_expression || TypeManager.IsValueType (type);
3816 public bool IsAssigned (EmitContext ec, Location loc)
3818 if (!ec.DoFlowAnalysis || !is_out ||
3819 ec.CurrentBranching.IsAssigned (vi))
3822 Report.Error (165, loc,
3823 "Use of unassigned parameter `" + name + "'");
3827 public bool IsFieldAssigned (EmitContext ec, string field_name, Location loc)
3829 if (!ec.DoFlowAnalysis || !is_out ||
3830 ec.CurrentBranching.IsFieldAssigned (vi, field_name))
3833 Report.Error (170, loc,
3834 "Use of possibly unassigned field `" + field_name + "'");
3838 public void SetAssigned (EmitContext ec)
3840 if (is_out && ec.DoFlowAnalysis)
3841 ec.CurrentBranching.SetAssigned (vi);
3844 public void SetFieldAssigned (EmitContext ec, string field_name)
3846 if (is_out && ec.DoFlowAnalysis)
3847 ec.CurrentBranching.SetFieldAssigned (vi, field_name);
3850 protected void DoResolveBase (EmitContext ec)
3852 type = pars.GetParameterInfo (ec.DeclSpace, idx, out mod);
3853 is_ref = (mod & Parameter.Modifier.ISBYREF) != 0;
3854 is_out = (mod & Parameter.Modifier.OUT) != 0;
3855 eclass = ExprClass.Variable;
3858 vi = block.ParameterMap [idx];
3862 // Notice that for ref/out parameters, the type exposed is not the
3863 // same type exposed externally.
3866 // externally we expose "int&"
3867 // here we expose "int".
3869 // We record this in "is_ref". This means that the type system can treat
3870 // the type as it is expected, but when we generate the code, we generate
3871 // the alternate kind of code.
3873 public override Expression DoResolve (EmitContext ec)
3877 if (is_out && ec.DoFlowAnalysis && !IsAssigned (ec, loc))
3880 if (ec.RemapToProxy)
3881 return ec.RemapParameter (idx);
3886 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
3892 if (ec.RemapToProxy)
3893 return ec.RemapParameterLValue (idx, right_side);
3898 static public void EmitLdArg (ILGenerator ig, int x)
3902 case 0: ig.Emit (OpCodes.Ldarg_0); break;
3903 case 1: ig.Emit (OpCodes.Ldarg_1); break;
3904 case 2: ig.Emit (OpCodes.Ldarg_2); break;
3905 case 3: ig.Emit (OpCodes.Ldarg_3); break;
3906 default: ig.Emit (OpCodes.Ldarg_S, (byte) x); break;
3909 ig.Emit (OpCodes.Ldarg, x);
3913 // This method is used by parameters that are references, that are
3914 // being passed as references: we only want to pass the pointer (that
3915 // is already stored in the parameter, not the address of the pointer,
3916 // and not the value of the variable).
3918 public void EmitLoad (EmitContext ec)
3920 ILGenerator ig = ec.ig;
3926 EmitLdArg (ig, arg_idx);
3929 public override void Emit (EmitContext ec)
3931 ILGenerator ig = ec.ig;
3938 EmitLdArg (ig, arg_idx);
3944 // If we are a reference, we loaded on the stack a pointer
3945 // Now lets load the real value
3947 LoadFromPtr (ig, type);
3950 public void EmitAssign (EmitContext ec, Expression source)
3952 ILGenerator ig = ec.ig;
3960 EmitLdArg (ig, arg_idx);
3965 StoreFromPtr (ig, type);
3968 ig.Emit (OpCodes.Starg_S, (byte) arg_idx);
3970 ig.Emit (OpCodes.Starg, arg_idx);
3974 public void AddressOf (EmitContext ec, AddressOp mode)
3983 ec.ig.Emit (OpCodes.Ldarg_S, (byte) arg_idx);
3985 ec.ig.Emit (OpCodes.Ldarg, arg_idx);
3988 ec.ig.Emit (OpCodes.Ldarga_S, (byte) arg_idx);
3990 ec.ig.Emit (OpCodes.Ldarga, arg_idx);
3997 /// Used for arguments to New(), Invocation()
3999 public class Argument {
4000 public enum AType : byte {
4007 public readonly AType ArgType;
4008 public Expression Expr;
4010 public Argument (Expression expr, AType type)
4013 this.ArgType = type;
4018 if (ArgType == AType.Ref || ArgType == AType.Out)
4019 return TypeManager.GetReferenceType (Expr.Type);
4025 public Parameter.Modifier GetParameterModifier ()
4029 return Parameter.Modifier.OUT | Parameter.Modifier.ISBYREF;
4032 return Parameter.Modifier.REF | Parameter.Modifier.ISBYREF;
4035 return Parameter.Modifier.NONE;
4039 public static string FullDesc (Argument a)
4041 if (a.ArgType == AType.ArgList)
4044 return (a.ArgType == AType.Ref ? "ref " :
4045 (a.ArgType == AType.Out ? "out " : "")) +
4046 TypeManager.CSharpName (a.Expr.Type);
4049 public bool ResolveMethodGroup (EmitContext ec, Location loc)
4051 ConstructedType ctype = Expr as ConstructedType;
4053 Expr = ctype.GetSimpleName (ec);
4055 // FIXME: csc doesn't report any error if you try to use `ref' or
4056 // `out' in a delegate creation expression.
4057 Expr = Expr.Resolve (ec, ResolveFlags.VariableOrValue | ResolveFlags.MethodGroup);
4064 public bool Resolve (EmitContext ec, Location loc)
4066 if (ArgType == AType.Ref) {
4067 Expr = Expr.Resolve (ec);
4071 Expr = Expr.ResolveLValue (ec, Expr);
4072 } else if (ArgType == AType.Out)
4073 Expr = Expr.ResolveLValue (ec, new EmptyExpression ());
4075 Expr = Expr.Resolve (ec);
4080 if (ArgType == AType.Expression)
4084 // Catch errors where fields of a MarshalByRefObject are passed as ref or out
4085 // This is only allowed for `this'
4087 FieldExpr fe = Expr as FieldExpr;
4088 if (fe != null && !fe.IsStatic){
4089 Expression instance = fe.InstanceExpression;
4091 if (instance.GetType () != typeof (This)){
4092 if (fe.InstanceExpression.Type.IsSubclassOf (TypeManager.mbr_type)){
4093 Report.Error (197, loc,
4094 "Can not pass a type that derives from MarshalByRefObject with out or ref");
4101 if (Expr.eclass != ExprClass.Variable){
4103 // We just probe to match the CSC output
4105 if (Expr.eclass == ExprClass.PropertyAccess ||
4106 Expr.eclass == ExprClass.IndexerAccess){
4109 "A property or indexer can not be passed as an out or ref " +
4114 "An lvalue is required as an argument to out or ref");
4122 public void Emit (EmitContext ec)
4125 // Ref and Out parameters need to have their addresses taken.
4127 // ParameterReferences might already be references, so we want
4128 // to pass just the value
4130 if (ArgType == AType.Ref || ArgType == AType.Out){
4131 AddressOp mode = AddressOp.Store;
4133 if (ArgType == AType.Ref)
4134 mode |= AddressOp.Load;
4136 if (Expr is ParameterReference){
4137 ParameterReference pr = (ParameterReference) Expr;
4143 pr.AddressOf (ec, mode);
4146 ((IMemoryLocation)Expr).AddressOf (ec, mode);
4154 /// Invocation of methods or delegates.
4156 public class Invocation : ExpressionStatement {
4157 public readonly ArrayList Arguments;
4160 MethodBase method = null;
4163 static Hashtable method_parameter_cache;
4165 static Invocation ()
4167 method_parameter_cache = new PtrHashtable ();
4171 // arguments is an ArrayList, but we do not want to typecast,
4172 // as it might be null.
4174 // FIXME: only allow expr to be a method invocation or a
4175 // delegate invocation (7.5.5)
4177 public Invocation (Expression expr, ArrayList arguments, Location l)
4180 Arguments = arguments;
4184 public Expression Expr {
4191 /// Returns the Parameters (a ParameterData interface) for the
4194 public static ParameterData GetParameterData (MethodBase mb)
4196 object pd = method_parameter_cache [mb];
4200 return (ParameterData) pd;
4202 ip = TypeManager.LookupParametersByBuilder (mb);
4204 method_parameter_cache [mb] = ip;
4206 return (ParameterData) ip;
4208 ReflectionParameters rp = new ReflectionParameters (mb);
4209 method_parameter_cache [mb] = rp;
4211 return (ParameterData) rp;
4216 /// Determines "better conversion" as specified in 7.4.2.3
4218 /// Returns : 1 if a->p is better
4219 /// 0 if a->q or neither is better
4221 static int BetterConversion (EmitContext ec, Argument a, Type p, Type q, Location loc)
4223 Type argument_type = a.Type;
4224 Expression argument_expr = a.Expr;
4226 if (argument_type == null)
4227 throw new Exception ("Expression of type " + a.Expr +
4228 " does not resolve its type");
4231 // This is a special case since csc behaves this way.
4233 if (argument_expr is NullLiteral &&
4234 p == TypeManager.string_type &&
4235 q == TypeManager.object_type)
4237 else if (argument_expr is NullLiteral &&
4238 p == TypeManager.object_type &&
4239 q == TypeManager.string_type)
4243 // csc behaves this way so we emulate it. Basically, if the argument
4244 // is null and one of the types to compare is 'object' and the other
4245 // is a reference type, we prefer the other.
4247 // I can't find this anywhere in the spec but we can interpret this
4248 // to mean that null can be of any type you wish in such a context
4250 if (p != null && q != null) {
4251 if (argument_expr is NullLiteral &&
4253 q == TypeManager.object_type)
4255 else if (argument_expr is NullLiteral &&
4257 p == TypeManager.object_type)
4264 if (argument_type == p)
4267 if (argument_type == q)
4271 Expression tmp = Convert.ImplicitConversion (ec, argument_expr, p, loc);
4279 Expression p_tmp = new EmptyExpression (p);
4280 Expression q_tmp = new EmptyExpression (q);
4282 if (Convert.ImplicitConversionExists (ec, p_tmp, q) == true &&
4283 Convert.ImplicitConversionExists (ec, q_tmp, p) == false)
4286 if (p == TypeManager.sbyte_type)
4287 if (q == TypeManager.byte_type || q == TypeManager.ushort_type ||
4288 q == TypeManager.uint32_type || q == TypeManager.uint64_type)
4291 if (p == TypeManager.short_type)
4292 if (q == TypeManager.ushort_type || q == TypeManager.uint32_type ||
4293 q == TypeManager.uint64_type)
4296 if (p == TypeManager.int32_type)
4297 if (q == TypeManager.uint32_type || q == TypeManager.uint64_type)
4300 if (p == TypeManager.int64_type)
4301 if (q == TypeManager.uint64_type)
4308 /// Determines "Better function" between candidate
4309 /// and the current best match
4312 /// Returns an integer indicating :
4313 /// 0 if candidate ain't better
4314 /// 1 if candidate is better than the current best match
4316 static int BetterFunction (EmitContext ec, ArrayList args,
4317 MethodBase candidate, bool candidate_params,
4318 MethodBase best, bool best_params,
4321 ParameterData candidate_pd = GetParameterData (candidate);
4322 ParameterData best_pd;
4328 argument_count = args.Count;
4330 int cand_count = candidate_pd.Count;
4333 // If there is no best method, than this one
4334 // is better, however, if we already found a
4335 // best method, we cant tell. This happens
4346 // interface IFooBar : IFoo, IBar {}
4348 // We cant tell if IFoo.DoIt is better than IBar.DoIt
4350 // However, we have to consider that
4351 // Trim (); is better than Trim (params char[] chars);
4353 if (cand_count == 0 && argument_count == 0)
4354 return best == null || best_params ? 1 : 0;
4356 if ((candidate_pd.ParameterModifier (cand_count - 1) != Parameter.Modifier.PARAMS) &&
4357 (candidate_pd.ParameterModifier (cand_count - 1) != Parameter.Modifier.ARGLIST))
4358 if (cand_count != argument_count)
4364 if (argument_count == 0 && cand_count == 1 &&
4365 candidate_pd.ParameterModifier (cand_count - 1) == Parameter.Modifier.PARAMS)
4368 for (int j = 0; j < argument_count; ++j) {
4370 Argument a = (Argument) args [j];
4371 Type t = candidate_pd.ParameterType (j);
4373 if (candidate_pd.ParameterModifier (j) == Parameter.Modifier.PARAMS)
4374 if (candidate_params)
4375 t = TypeManager.GetElementType (t);
4377 x = BetterConversion (ec, a, t, null, loc);
4389 best_pd = GetParameterData (best);
4391 int rating1 = 0, rating2 = 0;
4393 for (int j = 0; j < argument_count; ++j) {
4396 Argument a = (Argument) args [j];
4398 Type ct = candidate_pd.ParameterType (j);
4399 Type bt = best_pd.ParameterType (j);
4401 if (candidate_pd.ParameterModifier (j) == Parameter.Modifier.PARAMS)
4402 if (candidate_params)
4403 ct = TypeManager.GetElementType (ct);
4405 if (best_pd.ParameterModifier (j) == Parameter.Modifier.PARAMS)
4407 bt = TypeManager.GetElementType (bt);
4409 x = BetterConversion (ec, a, ct, bt, loc);
4410 y = BetterConversion (ec, a, bt, ct, loc);
4420 // If a method (in the normal form) with the
4421 // same signature as the expanded form of the
4422 // current best params method already exists,
4423 // the expanded form is not applicable so we
4424 // force it to select the candidate
4426 if (!candidate_params && best_params && cand_count == argument_count)
4429 if (rating1 > rating2)
4435 public static string FullMethodDesc (MethodBase mb)
4437 string ret_type = "";
4442 if (mb is MethodInfo)
4443 ret_type = TypeManager.CSharpName (((MethodInfo) mb).ReturnType);
4445 StringBuilder sb = new StringBuilder (ret_type);
4447 sb.Append (mb.ReflectedType.ToString ());
4449 sb.Append (mb.Name);
4451 ParameterData pd = GetParameterData (mb);
4453 int count = pd.Count;
4456 for (int i = count; i > 0; ) {
4459 sb.Append (pd.ParameterDesc (count - i - 1));
4465 return sb.ToString ();
4468 public static MethodGroupExpr MakeUnionSet (Expression mg1, Expression mg2, Location loc)
4470 MemberInfo [] miset;
4471 MethodGroupExpr union;
4476 return (MethodGroupExpr) mg2;
4479 return (MethodGroupExpr) mg1;
4482 MethodGroupExpr left_set = null, right_set = null;
4483 int length1 = 0, length2 = 0;
4485 left_set = (MethodGroupExpr) mg1;
4486 length1 = left_set.Methods.Length;
4488 right_set = (MethodGroupExpr) mg2;
4489 length2 = right_set.Methods.Length;
4491 ArrayList common = new ArrayList ();
4493 foreach (MethodBase r in right_set.Methods){
4494 if (TypeManager.ArrayContainsMethod (left_set.Methods, r))
4498 miset = new MemberInfo [length1 + length2 - common.Count];
4499 left_set.Methods.CopyTo (miset, 0);
4503 foreach (MethodBase r in right_set.Methods) {
4504 if (!common.Contains (r))
4508 union = new MethodGroupExpr (miset, loc);
4513 static bool IsParamsMethodApplicable (EmitContext ec, MethodGroupExpr me,
4514 ArrayList arguments, bool do_varargs,
4515 ref MethodBase candidate)
4517 if (!me.HasTypeArguments &&
4518 !InferParamsTypeArguments (ec, arguments, ref candidate))
4521 return IsParamsMethodApplicable (ec, arguments, candidate, do_varargs);
4525 /// Determines if the candidate method, if a params method, is applicable
4526 /// in its expanded form to the given set of arguments
4528 static bool IsParamsMethodApplicable (EmitContext ec, ArrayList arguments,
4529 MethodBase candidate, bool do_varargs)
4533 if (arguments == null)
4536 arg_count = arguments.Count;
4538 ParameterData pd = GetParameterData (candidate);
4540 int pd_count = pd.Count;
4545 int count = pd_count - 1;
4547 if (pd.ParameterModifier (count) != Parameter.Modifier.ARGLIST)
4549 if (pd_count != arg_count)
4552 if (pd.ParameterModifier (count) != Parameter.Modifier.PARAMS)
4556 if (count > arg_count)
4559 if (pd_count == 1 && arg_count == 0)
4563 // If we have come this far, the case which
4564 // remains is when the number of parameters is
4565 // less than or equal to the argument count.
4567 for (int i = 0; i < count; ++i) {
4569 Argument a = (Argument) arguments [i];
4571 Parameter.Modifier a_mod = a.GetParameterModifier () &
4572 ~(Parameter.Modifier.OUT | Parameter.Modifier.REF);
4573 Parameter.Modifier p_mod = pd.ParameterModifier (i) &
4574 ~(Parameter.Modifier.OUT | Parameter.Modifier.REF);
4576 if (a_mod == p_mod) {
4578 if (a_mod == Parameter.Modifier.NONE)
4579 if (!Convert.ImplicitConversionExists (ec,
4581 pd.ParameterType (i)))
4584 if ((a_mod & Parameter.Modifier.ISBYREF) != 0) {
4585 Type pt = pd.ParameterType (i);
4588 pt = TypeManager.GetReferenceType (pt);
4599 Argument a = (Argument) arguments [count];
4600 if (!(a.Expr is Arglist))
4606 Type element_type = TypeManager.GetElementType (pd.ParameterType (pd_count - 1));
4608 for (int i = pd_count - 1; i < arg_count; i++) {
4609 Argument a = (Argument) arguments [i];
4611 if (!Convert.ImplicitConversionExists (ec, a.Expr, element_type))
4618 static bool IsApplicable (EmitContext ec, MethodGroupExpr me,
4619 ArrayList arguments, ref MethodBase candidate)
4621 if (!me.HasTypeArguments &&
4622 !InferTypeArguments (ec, arguments, ref candidate))
4625 return IsApplicable (ec, arguments, candidate);
4629 /// Determines if the candidate method is applicable (section 14.4.2.1)
4630 /// to the given set of arguments
4632 static bool IsApplicable (EmitContext ec, ArrayList arguments, MethodBase candidate)
4636 if (arguments == null)
4639 arg_count = arguments.Count;
4642 ParameterData pd = GetParameterData (candidate);
4644 if (arg_count != pd.Count)
4647 for (int i = arg_count; i > 0; ) {
4650 Argument a = (Argument) arguments [i];
4652 Parameter.Modifier a_mod = a.GetParameterModifier () &
4653 ~(Parameter.Modifier.OUT | Parameter.Modifier.REF);
4654 Parameter.Modifier p_mod = pd.ParameterModifier (i) &
4655 ~(Parameter.Modifier.OUT | Parameter.Modifier.REF);
4658 if (a_mod == p_mod ||
4659 (a_mod == Parameter.Modifier.NONE && p_mod == Parameter.Modifier.PARAMS)) {
4660 if (a_mod == Parameter.Modifier.NONE) {
4661 if (!Convert.ImplicitConversionExists (ec,
4663 pd.ParameterType (i)))
4667 if ((a_mod & Parameter.Modifier.ISBYREF) != 0) {
4668 Type pt = pd.ParameterType (i);
4671 pt = TypeManager.GetReferenceType (pt);
4684 /// Find the Applicable Function Members (7.4.2.1)
4686 /// me: Method Group expression with the members to select.
4687 /// it might contain constructors or methods (or anything
4688 /// that maps to a method).
4690 /// Arguments: ArrayList containing resolved Argument objects.
4692 /// loc: The location if we want an error to be reported, or a Null
4693 /// location for "probing" purposes.
4695 /// Returns: The MethodBase (either a ConstructorInfo or a MethodInfo)
4696 /// that is the best match of me on Arguments.
4699 public static MethodBase OverloadResolve (EmitContext ec, MethodGroupExpr me,
4700 ArrayList Arguments, bool may_fail,
4703 MethodBase method = null;
4704 Type applicable_type = null;
4706 ArrayList candidates = new ArrayList ();
4709 // Used to keep a map between the candidate
4710 // and whether it is being considered in its
4711 // normal or expanded form
4713 // false is normal form, true is expanded form
4715 Hashtable candidate_to_form = new PtrHashtable ();
4719 // First we construct the set of applicable methods
4721 // We start at the top of the type hierarchy and
4722 // go down to find applicable methods
4724 applicable_type = me.DeclaringType;
4726 if (me.Name == "Invoke" && TypeManager.IsDelegateType (applicable_type)) {
4727 Error_InvokeOnDelegate (loc);
4731 bool found_applicable = false;
4733 MethodBase[] methods = me.Methods;
4735 for (int i = 0; i < methods.Length; i++) {
4736 Type decl_type = methods [i].DeclaringType;
4739 // If we have already found an applicable method
4740 // we eliminate all base types (Section 14.5.5.1)
4742 if (decl_type != applicable_type &&
4743 (applicable_type.IsSubclassOf (decl_type) ||
4744 TypeManager.ImplementsInterface (applicable_type, decl_type)) &&
4748 // Check if candidate is applicable (section 14.4.2.1)
4749 if (IsApplicable (ec, me, Arguments, ref methods [i])) {
4750 // Candidate is applicable in normal form
4751 MethodBase candidate = methods [i];
4752 candidates.Add (candidate);
4753 applicable_type = candidate.DeclaringType;
4754 found_applicable = true;
4755 candidate_to_form [candidate] = false;
4756 } else if (IsParamsMethodApplicable (
4757 ec, me, Arguments,false, ref methods [i])) {
4758 // Candidate is applicable in expanded form
4759 MethodBase candidate = methods [i];
4760 candidates.Add (candidate);
4761 applicable_type = candidate.DeclaringType;
4762 found_applicable = true;
4763 candidate_to_form [candidate] = true;
4764 } else if (IsParamsMethodApplicable (
4765 ec, me, Arguments,true, ref methods [i])) {
4766 // Candidate is applicable in expanded form
4767 MethodBase candidate = methods [i];
4768 candidates.Add (candidate);
4769 applicable_type = candidate.DeclaringType;
4770 found_applicable = true;
4771 candidate_to_form [candidate] = true;
4775 if (Arguments == null)
4778 argument_count = Arguments.Count;
4781 // Now we actually find the best method
4783 int candidate_top = candidates.Count;
4784 for (int ix = 0; ix < candidate_top; ix++){
4785 MethodBase candidate = (MethodBase) candidates [ix];
4787 bool cand_params = (bool) candidate_to_form [candidate];
4788 bool method_params = false;
4791 method_params = (bool) candidate_to_form [method];
4793 int x = BetterFunction (ec, Arguments,
4794 candidate, cand_params,
4795 method, method_params,
4803 if (method == null) {
4804 int errors = Report.Errors;
4807 // Okay so we have failed to find anything so we
4808 // return by providing info about the closest match
4810 for (int i = 0; i < methods.Length; ++i) {
4812 MethodBase c = methods [i];
4816 ParameterData pd = GetParameterData (c);
4817 if (pd.Count != argument_count)
4820 if (!InferTypeArguments (ec, Arguments, ref c))
4823 VerifyArgumentsCompat (ec, Arguments, argument_count,
4824 c, false, null, loc);
4828 if (Report.Errors > errors)
4831 string report_name = me.Name;
4832 if (report_name == ".ctor")
4833 report_name = me.DeclaringType.ToString ();
4835 for (int i = 0; i < methods.Length; ++i) {
4837 MethodBase c = methods [i];
4841 ParameterData pd = GetParameterData (c);
4842 if (pd.Count != argument_count)
4845 if (InferTypeArguments (ec, Arguments, ref c))
4848 Report.Error (411, loc, "The type arguments for " +
4849 "method `{0}' cannot be infered from " +
4850 "the usage. Try specifying the type " +
4851 "arguments explicitly.", report_name);
4855 if (!may_fail && (errors == Report.Errors))
4856 Error_WrongNumArguments (loc, report_name,
4863 // Now check that there are no ambiguities i.e the selected method
4864 // should be better than all the others
4866 bool best_params = (bool) candidate_to_form [method];
4868 for (int ix = 0; ix < candidate_top; ix++){
4869 MethodBase candidate = (MethodBase) candidates [ix];
4871 if (candidate == method)
4875 // If a normal method is applicable in
4876 // the sense that it has the same
4877 // number of arguments, then the
4878 // expanded params method is never
4879 // applicable so we debar the params
4882 // if ((IsParamsMethodApplicable (ec, Arguments, candidate) &&
4883 // IsApplicable (ec, Arguments, method)))
4886 bool cand_params = (bool) candidate_to_form [candidate];
4887 int x = BetterFunction (ec, Arguments,
4888 method, best_params,
4889 candidate, cand_params,
4895 "Ambiguous call when selecting function due to implicit casts");
4901 // And now check if the arguments are all
4902 // compatible, perform conversions if
4903 // necessary etc. and return if everything is
4906 if (!VerifyArgumentsCompat (ec, Arguments, argument_count, method,
4907 best_params, null, loc))
4913 static void Error_WrongNumArguments (Location loc, String name, int arg_count)
4915 Report.Error (1501, loc,
4916 "No overload for method `" + name + "' takes `" +
4917 arg_count + "' arguments");
4920 static void Error_InvokeOnDelegate (Location loc)
4922 Report.Error (1533, loc,
4923 "Invoke cannot be called directly on a delegate");
4926 static void Error_InvalidArguments (Location loc, int idx, MethodBase method,
4927 Type delegate_type, string arg_sig, string par_desc)
4929 if (delegate_type == null)
4930 Report.Error (1502, loc,
4931 "The best overloaded match for method '" +
4932 FullMethodDesc (method) +
4933 "' has some invalid arguments");
4935 Report.Error (1594, loc,
4936 "Delegate '" + delegate_type.ToString () +
4937 "' has some invalid arguments.");
4938 Report.Error (1503, loc,
4939 String.Format ("Argument {0}: Cannot convert from '{1}' to '{2}'",
4940 idx, arg_sig, par_desc));
4943 public static bool VerifyArgumentsCompat (EmitContext ec, ArrayList Arguments,
4946 bool chose_params_expanded,
4950 ParameterData pd = GetParameterData (method);
4951 int pd_count = pd.Count;
4953 for (int j = 0; j < argument_count; j++) {
4954 Argument a = (Argument) Arguments [j];
4955 Expression a_expr = a.Expr;
4956 Type parameter_type = pd.ParameterType (j);
4957 Parameter.Modifier pm = pd.ParameterModifier (j);
4959 if (pm == Parameter.Modifier.PARAMS){
4960 if ((pm & ~Parameter.Modifier.PARAMS) != a.GetParameterModifier ()) {
4961 if (!Location.IsNull (loc))
4962 Error_InvalidArguments (
4963 loc, j, method, delegate_type,
4964 Argument.FullDesc (a), pd.ParameterDesc (j));
4968 if (chose_params_expanded)
4969 parameter_type = TypeManager.GetElementType (parameter_type);
4970 } else if (pm == Parameter.Modifier.ARGLIST){
4976 if (pd.ParameterModifier (j) != a.GetParameterModifier ()){
4977 if (!Location.IsNull (loc))
4978 Error_InvalidArguments (
4979 loc, j, method, delegate_type,
4980 Argument.FullDesc (a), pd.ParameterDesc (j));
4988 if (a.Type != parameter_type){
4991 conv = Convert.ImplicitConversion (ec, a_expr, parameter_type, loc);
4994 if (!Location.IsNull (loc))
4995 Error_InvalidArguments (
4996 loc, j, method, delegate_type,
4997 Argument.FullDesc (a), pd.ParameterDesc (j));
5002 // Update the argument with the implicit conversion
5008 Parameter.Modifier a_mod = a.GetParameterModifier () &
5009 ~(Parameter.Modifier.OUT | Parameter.Modifier.REF);
5010 Parameter.Modifier p_mod = pd.ParameterModifier (j) &
5011 ~(Parameter.Modifier.OUT | Parameter.Modifier.REF);
5013 if (a_mod != p_mod &&
5014 pd.ParameterModifier (pd_count - 1) != Parameter.Modifier.PARAMS) {
5015 if (!Location.IsNull (loc)) {
5016 Report.Error (1502, loc,
5017 "The best overloaded match for method '" + FullMethodDesc (method)+
5018 "' has some invalid arguments");
5019 Report.Error (1503, loc,
5020 "Argument " + (j+1) +
5021 ": Cannot convert from '" + Argument.FullDesc (a)
5022 + "' to '" + pd.ParameterDesc (j) + "'");
5032 static bool InferType (Type pt, Type at, ref Type[] infered)
5034 if (pt.IsGenericParameter) {
5035 int pos = pt.GenericParameterPosition;
5037 if (infered [pos] == null) {
5039 while (check.IsArray)
5040 check = check.GetElementType ();
5042 if (pt.Equals (check))
5049 if (infered [pos] != at)
5055 if (!pt.ContainsGenericParameters)
5060 (at.GetArrayRank () != pt.GetArrayRank ()))
5063 return InferType (pt.GetElementType (), at.GetElementType (),
5069 (pt.GetArrayRank () != at.GetArrayRank ()))
5072 return InferType (pt.GetElementType (), at.GetElementType (),
5076 if (!at.IsGenericInstance)
5079 Type[] at_args = at.GetGenericArguments ();
5080 Type[] pt_args = pt.GetGenericArguments ();
5082 if (at_args.Length != pt_args.Length)
5085 Type[] infered_types = new Type [at_args.Length];
5087 for (int i = 0; i < at_args.Length; i++)
5088 if (!InferType (pt_args [i], at_args [i], ref infered_types))
5091 for (int i = 0; i < infered_types.Length; i++)
5092 if (infered_types [i] == null)
5095 for (int i = 0; i < infered_types.Length; i++) {
5096 if (infered [i] == null) {
5097 infered [i] = infered_types [i];
5101 if (infered [i] != infered_types [i])
5108 static bool InferParamsTypeArguments (EmitContext ec, ArrayList arguments,
5109 ref MethodBase method)
5111 if ((arguments == null) || !TypeManager.IsGenericMethod (method))
5116 if (arguments == null)
5119 arg_count = arguments.Count;
5121 ParameterData pd = GetParameterData (method);
5123 int pd_count = pd.Count;
5128 if (pd.ParameterModifier (pd_count - 1) != Parameter.Modifier.PARAMS)
5131 if (pd_count - 1 > arg_count)
5134 if (pd_count == 1 && arg_count == 0)
5137 Type[] method_args = method.GetGenericArguments ();
5138 Type[] infered_types = new Type [method_args.Length];
5141 // If we have come this far, the case which
5142 // remains is when the number of parameters is
5143 // less than or equal to the argument count.
5145 for (int i = 0; i < pd_count - 1; ++i) {
5146 Argument a = (Argument) arguments [i];
5148 if ((a.Expr is NullLiteral) || (a.Expr is MethodGroupExpr))
5151 Type pt = pd.ParameterType (i);
5154 if (!InferType (pt, at, ref infered_types))
5158 Type element_type = TypeManager.GetElementType (pd.ParameterType (pd_count - 1));
5160 for (int i = pd_count - 1; i < arg_count; i++) {
5161 Argument a = (Argument) arguments [i];
5163 if ((a.Expr is NullLiteral) || (a.Expr is MethodGroupExpr))
5166 if (!InferType (element_type, a.Type, ref infered_types))
5170 for (int i = 0; i < infered_types.Length; i++)
5171 if (infered_types [i] == null)
5174 method = method.BindGenericParameters (infered_types);
5178 public static bool InferTypeArguments (Type[] param_types, Type[] arg_types,
5179 ref Type[] infered_types)
5181 for (int i = 0; i < arg_types.Length; i++) {
5182 if (arg_types [i] == null)
5185 if (!InferType (param_types [i], arg_types [i],
5190 for (int i = 0; i < infered_types.Length; i++)
5191 if (infered_types [i] == null)
5197 static bool InferTypeArguments (EmitContext ec, ArrayList arguments,
5198 ref MethodBase method)
5200 if (!TypeManager.IsGenericMethod (method))
5204 if (arguments != null)
5205 arg_count = arguments.Count;
5209 ParameterData pd = GetParameterData (method);
5210 if (arg_count != pd.Count)
5213 Type[] method_args = method.GetGenericArguments ();
5214 Type[] infered_types = new Type [method_args.Length];
5216 Type[] param_types = new Type [pd.Count];
5217 Type[] arg_types = new Type [pd.Count];
5219 for (int i = 0; i < arg_count; i++) {
5220 param_types [i] = pd.ParameterType (i);
5222 Argument a = (Argument) arguments [i];
5223 if ((a.Expr is NullLiteral) || (a.Expr is MethodGroupExpr))
5226 arg_types [i] = a.Type;
5229 if (!InferTypeArguments (param_types, arg_types, ref infered_types))
5232 method = method.BindGenericParameters (infered_types);
5236 public static bool InferTypeArguments (EmitContext ec, ParameterData apd,
5237 ref MethodBase method)
5239 if (!TypeManager.IsGenericMethod (method))
5242 ParameterData pd = GetParameterData (method);
5243 if (apd.Count != pd.Count)
5246 Type[] method_args = method.GetGenericArguments ();
5247 Type[] infered_types = new Type [method_args.Length];
5249 Type[] param_types = new Type [pd.Count];
5250 Type[] arg_types = new Type [pd.Count];
5252 for (int i = 0; i < apd.Count; i++) {
5253 param_types [i] = pd.ParameterType (i);
5254 arg_types [i] = apd.ParameterType (i);
5257 if (!InferTypeArguments (param_types, arg_types, ref infered_types))
5260 method = method.BindGenericParameters (infered_types);
5264 public override Expression DoResolve (EmitContext ec)
5267 // First, resolve the expression that is used to
5268 // trigger the invocation
5270 if (expr is BaseAccess)
5273 if (expr is ConstructedType)
5274 expr = ((ConstructedType) expr).GetSimpleName (ec);
5276 expr = expr.Resolve (ec, ResolveFlags.VariableOrValue | ResolveFlags.MethodGroup);
5280 if (!(expr is MethodGroupExpr)) {
5281 Type expr_type = expr.Type;
5283 if (expr_type != null){
5284 bool IsDelegate = TypeManager.IsDelegateType (expr_type);
5286 return (new DelegateInvocation (
5287 this.expr, Arguments, loc)).Resolve (ec);
5291 if (!(expr is MethodGroupExpr)){
5292 expr.Error_UnexpectedKind (ResolveFlags.MethodGroup);
5297 // Next, evaluate all the expressions in the argument list
5299 if (Arguments != null){
5300 foreach (Argument a in Arguments){
5301 if (!a.Resolve (ec, loc))
5306 MethodGroupExpr mg = (MethodGroupExpr) expr;
5307 method = OverloadResolve (ec, mg, Arguments, false, loc);
5312 MethodInfo mi = method as MethodInfo;
5314 type = TypeManager.TypeToCoreType (mi.ReturnType);
5315 if (!mi.IsStatic && !mg.IsExplicitImpl && (mg.InstanceExpression == null)) {
5316 SimpleName.Error_ObjectRefRequired (ec, loc, mi.Name);
5320 Expression iexpr = mg.InstanceExpression;
5321 if (mi.IsStatic && (iexpr != null) && !(iexpr is This)) {
5322 if (mg.IdenticalTypeName)
5323 mg.InstanceExpression = null;
5325 MemberAccess.error176 (loc, mi.Name);
5331 if (type.IsPointer){
5339 // Only base will allow this invocation to happen.
5341 if (is_base && method.IsAbstract){
5342 Report.Error (205, loc, "Cannot call an abstract base member: " +
5343 FullMethodDesc (method));
5347 if ((method.Attributes & MethodAttributes.SpecialName) != 0){
5348 if (TypeManager.IsSpecialMethod (method))
5349 Report.Error (571, loc, method.Name + ": can not call operator or accessor");
5352 eclass = ExprClass.Value;
5357 // Emits the list of arguments as an array
5359 static void EmitParams (EmitContext ec, int idx, ArrayList arguments)
5361 ILGenerator ig = ec.ig;
5362 int count = arguments.Count - idx;
5363 Argument a = (Argument) arguments [idx];
5364 Type t = a.Expr.Type;
5366 IntConstant.EmitInt (ig, count);
5367 ig.Emit (OpCodes.Newarr, TypeManager.TypeToCoreType (t));
5369 int top = arguments.Count;
5370 for (int j = idx; j < top; j++){
5371 a = (Argument) arguments [j];
5373 ig.Emit (OpCodes.Dup);
5374 IntConstant.EmitInt (ig, j - idx);
5376 bool is_stobj, has_type_arg;
5377 OpCode op = ArrayAccess.GetStoreOpcode (t, out is_stobj, out has_type_arg);
5379 ig.Emit (OpCodes.Ldelema, t);
5391 /// Emits a list of resolved Arguments that are in the arguments
5394 /// The MethodBase argument might be null if the
5395 /// emission of the arguments is known not to contain
5396 /// a `params' field (for example in constructors or other routines
5397 /// that keep their arguments in this structure)
5399 public static void EmitArguments (EmitContext ec, MethodBase mb, ArrayList arguments)
5403 pd = GetParameterData (mb);
5408 // If we are calling a params method with no arguments, special case it
5410 if (arguments == null){
5411 if (pd != null && pd.Count > 0 &&
5412 pd.ParameterModifier (0) == Parameter.Modifier.PARAMS){
5413 ILGenerator ig = ec.ig;
5415 IntConstant.EmitInt (ig, 0);
5416 ig.Emit (OpCodes.Newarr, TypeManager.GetElementType (pd.ParameterType (0)));
5422 int top = arguments.Count;
5424 for (int i = 0; i < top; i++){
5425 Argument a = (Argument) arguments [i];
5428 if (pd.ParameterModifier (i) == Parameter.Modifier.PARAMS){
5430 // Special case if we are passing the same data as the
5431 // params argument, do not put it in an array.
5433 if (pd.ParameterType (i) == a.Type)
5436 EmitParams (ec, i, arguments);
5444 if (pd != null && pd.Count > top &&
5445 pd.ParameterModifier (top) == Parameter.Modifier.PARAMS){
5446 ILGenerator ig = ec.ig;
5448 IntConstant.EmitInt (ig, 0);
5449 ig.Emit (OpCodes.Newarr, TypeManager.GetElementType (pd.ParameterType (top)));
5453 static Type[] GetVarargsTypes (EmitContext ec, MethodBase mb,
5454 ArrayList arguments)
5456 ParameterData pd = GetParameterData (mb);
5458 if (arguments == null)
5459 return new Type [0];
5461 Argument a = (Argument) arguments [pd.Count - 1];
5462 Arglist list = (Arglist) a.Expr;
5464 return list.ArgumentTypes;
5468 /// This checks the ConditionalAttribute on the method
5470 static bool IsMethodExcluded (MethodBase method, EmitContext ec)
5472 if (method.IsConstructor)
5475 IMethodData md = TypeManager.GetMethod (method);
5477 return md.IsExcluded (ec);
5479 // For some methods (generated by delegate class) GetMethod returns null
5480 // because they are not included in builder_to_method table
5481 if (method.DeclaringType is TypeBuilder)
5484 return AttributeTester.IsConditionalMethodExcluded (method);
5488 /// is_base tells whether we want to force the use of the `call'
5489 /// opcode instead of using callvirt. Call is required to call
5490 /// a specific method, while callvirt will always use the most
5491 /// recent method in the vtable.
5493 /// is_static tells whether this is an invocation on a static method
5495 /// instance_expr is an expression that represents the instance
5496 /// it must be non-null if is_static is false.
5498 /// method is the method to invoke.
5500 /// Arguments is the list of arguments to pass to the method or constructor.
5502 public static void EmitCall (EmitContext ec, bool is_base,
5503 bool is_static, Expression instance_expr,
5504 MethodBase method, ArrayList Arguments, Location loc)
5506 ILGenerator ig = ec.ig;
5507 bool struct_call = false;
5508 bool this_call = false;
5510 Type decl_type = method.DeclaringType;
5512 if (!RootContext.StdLib) {
5513 // Replace any calls to the system's System.Array type with calls to
5514 // the newly created one.
5515 if (method == TypeManager.system_int_array_get_length)
5516 method = TypeManager.int_array_get_length;
5517 else if (method == TypeManager.system_int_array_get_rank)
5518 method = TypeManager.int_array_get_rank;
5519 else if (method == TypeManager.system_object_array_clone)
5520 method = TypeManager.object_array_clone;
5521 else if (method == TypeManager.system_int_array_get_length_int)
5522 method = TypeManager.int_array_get_length_int;
5523 else if (method == TypeManager.system_int_array_get_lower_bound_int)
5524 method = TypeManager.int_array_get_lower_bound_int;
5525 else if (method == TypeManager.system_int_array_get_upper_bound_int)
5526 method = TypeManager.int_array_get_upper_bound_int;
5527 else if (method == TypeManager.system_void_array_copyto_array_int)
5528 method = TypeManager.void_array_copyto_array_int;
5532 // This checks ObsoleteAttribute on the method and on the declaring type
5534 ObsoleteAttribute oa = AttributeTester.GetMethodObsoleteAttribute (method);
5536 AttributeTester.Report_ObsoleteMessage (oa, TypeManager.CSharpSignature (method), loc);
5538 oa = AttributeTester.GetObsoleteAttribute (method.DeclaringType);
5540 AttributeTester.Report_ObsoleteMessage (oa, method.DeclaringType.FullName, loc);
5544 oa = AttributeTester.GetObsoleteAttribute (method.DeclaringType);
5546 AttributeTester.Report_ObsoleteMessage (oa, method.DeclaringType.FullName, loc);
5549 if (IsMethodExcluded (method, ec))
5553 if (TypeManager.IsValueType (decl_type))
5556 // If this is ourselves, push "this"
5558 if (instance_expr == null){
5560 ig.Emit (OpCodes.Ldarg_0);
5562 Type itype = instance_expr.Type;
5565 // Push the instance expression
5567 if (TypeManager.IsValueType (itype)){
5569 // Special case: calls to a function declared in a
5570 // reference-type with a value-type argument need
5571 // to have their value boxed.
5572 if (decl_type.IsValueType || itype.IsGenericParameter){
5574 // If the expression implements IMemoryLocation, then
5575 // we can optimize and use AddressOf on the
5578 // If not we have to use some temporary storage for
5580 if (instance_expr is IMemoryLocation){
5581 ((IMemoryLocation)instance_expr).
5582 AddressOf (ec, AddressOp.LoadStore);
5585 instance_expr.Emit (ec);
5586 LocalBuilder temp = ig.DeclareLocal (itype);
5587 ig.Emit (OpCodes.Stloc, temp);
5588 ig.Emit (OpCodes.Ldloca, temp);
5590 if (itype.IsGenericParameter)
5591 ig.Emit (OpCodes.Constrained, itype);
5595 instance_expr.Emit (ec);
5596 ig.Emit (OpCodes.Box, itype);
5599 instance_expr.Emit (ec);
5603 EmitArguments (ec, method, Arguments);
5606 if (is_static || struct_call || is_base || (this_call && !method.IsVirtual))
5607 call_op = OpCodes.Call;
5609 call_op = OpCodes.Callvirt;
5611 if ((method.CallingConvention & CallingConventions.VarArgs) != 0) {
5612 Type[] varargs_types = GetVarargsTypes (ec, method, Arguments);
5613 ig.EmitCall (call_op, (MethodInfo) method, varargs_types);
5620 // and DoFoo is not virtual, you can omit the callvirt,
5621 // because you don't need the null checking behavior.
5623 if (method is MethodInfo)
5624 ig.Emit (call_op, (MethodInfo) method);
5626 ig.Emit (call_op, (ConstructorInfo) method);
5629 public override void Emit (EmitContext ec)
5631 MethodGroupExpr mg = (MethodGroupExpr) this.expr;
5633 EmitCall (ec, is_base, method.IsStatic, mg.InstanceExpression, method, Arguments, loc);
5636 public override void EmitStatement (EmitContext ec)
5641 // Pop the return value if there is one
5643 if (method is MethodInfo){
5644 Type ret = ((MethodInfo)method).ReturnType;
5645 if (TypeManager.TypeToCoreType (ret) != TypeManager.void_type)
5646 ec.ig.Emit (OpCodes.Pop);
5651 public class InvocationOrCast : ExpressionStatement
5654 Expression argument;
5656 public InvocationOrCast (Expression expr, Expression argument, Location loc)
5659 this.argument = argument;
5663 public override Expression DoResolve (EmitContext ec)
5666 // First try to resolve it as a cast.
5668 type = ec.DeclSpace.ResolveType (expr, true, loc);
5670 Cast cast = new Cast (new TypeExpression (type, loc), argument, loc);
5671 return cast.Resolve (ec);
5675 // This can either be a type or a delegate invocation.
5676 // Let's just resolve it and see what we'll get.
5678 expr = expr.Resolve (ec, ResolveFlags.Type | ResolveFlags.VariableOrValue);
5683 // Ok, so it's a Cast.
5685 if (expr.eclass == ExprClass.Type) {
5686 Cast cast = new Cast (new TypeExpression (expr.Type, loc), argument, loc);
5687 return cast.Resolve (ec);
5691 // It's a delegate invocation.
5693 if (!TypeManager.IsDelegateType (expr.Type)) {
5694 Error (149, "Method name expected");
5698 ArrayList args = new ArrayList ();
5699 args.Add (new Argument (argument, Argument.AType.Expression));
5700 DelegateInvocation invocation = new DelegateInvocation (expr, args, loc);
5701 return invocation.Resolve (ec);
5706 Error (201, "Only assignment, call, increment, decrement and new object " +
5707 "expressions can be used as a statement");
5710 public override ExpressionStatement ResolveStatement (EmitContext ec)
5713 // First try to resolve it as a cast.
5715 type = ec.DeclSpace.ResolveType (expr, true, loc);
5722 // This can either be a type or a delegate invocation.
5723 // Let's just resolve it and see what we'll get.
5725 expr = expr.Resolve (ec, ResolveFlags.Type | ResolveFlags.VariableOrValue);
5726 if ((expr == null) || (expr.eclass == ExprClass.Type)) {
5732 // It's a delegate invocation.
5734 if (!TypeManager.IsDelegateType (expr.Type)) {
5735 Error (149, "Method name expected");
5739 ArrayList args = new ArrayList ();
5740 args.Add (new Argument (argument, Argument.AType.Expression));
5741 DelegateInvocation invocation = new DelegateInvocation (expr, args, loc);
5742 return invocation.ResolveStatement (ec);
5745 public override void Emit (EmitContext ec)
5747 throw new Exception ("Cannot happen");
5750 public override void EmitStatement (EmitContext ec)
5752 throw new Exception ("Cannot happen");
5757 // This class is used to "disable" the code generation for the
5758 // temporary variable when initializing value types.
5760 class EmptyAddressOf : EmptyExpression, IMemoryLocation {
5761 public void AddressOf (EmitContext ec, AddressOp Mode)
5768 /// Implements the new expression
5770 public class New : ExpressionStatement, IMemoryLocation {
5771 public readonly ArrayList Arguments;
5774 // During bootstrap, it contains the RequestedType,
5775 // but if `type' is not null, it *might* contain a NewDelegate
5776 // (because of field multi-initialization)
5778 public Expression RequestedType;
5780 MethodBase method = null;
5783 // If set, the new expression is for a value_target, and
5784 // we will not leave anything on the stack.
5786 Expression value_target;
5787 bool value_target_set = false;
5788 bool is_type_parameter = false;
5790 public New (Expression requested_type, ArrayList arguments, Location l)
5792 RequestedType = requested_type;
5793 Arguments = arguments;
5797 public bool SetValueTypeVariable (Expression value)
5799 value_target = value;
5800 value_target_set = true;
5801 if (!(value_target is IMemoryLocation)){
5802 Error_UnexpectedKind ("variable");
5809 // This function is used to disable the following code sequence for
5810 // value type initialization:
5812 // AddressOf (temporary)
5816 // Instead the provide will have provided us with the address on the
5817 // stack to store the results.
5819 static Expression MyEmptyExpression;
5821 public void DisableTemporaryValueType ()
5823 if (MyEmptyExpression == null)
5824 MyEmptyExpression = new EmptyAddressOf ();
5827 // To enable this, look into:
5828 // test-34 and test-89 and self bootstrapping.
5830 // For instance, we can avoid a copy by using `newobj'
5831 // instead of Call + Push-temp on value types.
5832 // value_target = MyEmptyExpression;
5835 public override Expression DoResolve (EmitContext ec)
5838 // The New DoResolve might be called twice when initializing field
5839 // expressions (see EmitFieldInitializers, the call to
5840 // GetInitializerExpression will perform a resolve on the expression,
5841 // and later the assign will trigger another resolution
5843 // This leads to bugs (#37014)
5846 if (RequestedType is NewDelegate)
5847 return RequestedType;
5851 type = ec.DeclSpace.ResolveType (RequestedType, false, loc);
5856 CheckObsoleteAttribute (type);
5858 bool IsDelegate = TypeManager.IsDelegateType (type);
5861 RequestedType = (new NewDelegate (type, Arguments, loc)).Resolve (ec);
5862 if (RequestedType != null)
5863 if (!(RequestedType is NewDelegate))
5864 throw new Exception ("NewDelegate.Resolve returned a non NewDelegate: " + RequestedType.GetType ());
5865 return RequestedType;
5868 if (type.IsGenericParameter) {
5869 if (!TypeManager.HasConstructorConstraint (type)) {
5870 Error (304, String.Format (
5871 "Cannot create an instance of the " +
5872 "variable type '{0}' because it " +
5873 "doesn't have the new() constraint",
5878 if ((Arguments != null) && (Arguments.Count != 0)) {
5879 Error (417, String.Format (
5880 "`{0}': cannot provide arguments " +
5881 "when creating an instance of a " +
5882 "variable type.", type));
5886 is_type_parameter = true;
5887 eclass = ExprClass.Value;
5889 } else if (type.IsInterface || type.IsAbstract){
5890 Error (144, "It is not possible to create instances of interfaces or abstract classes");
5894 bool is_struct = type.IsValueType;
5895 eclass = ExprClass.Value;
5898 // SRE returns a match for .ctor () on structs (the object constructor),
5899 // so we have to manually ignore it.
5901 if (is_struct && Arguments == null)
5905 ml = MemberLookupFinal (ec, type, type, ".ctor",
5906 // For member-lookup, treat 'new Foo (bar)' as call to 'foo.ctor (bar)', where 'foo' is of type 'Foo'.
5907 MemberTypes.Constructor,
5908 AllBindingFlags | BindingFlags.DeclaredOnly, loc);
5913 if (! (ml is MethodGroupExpr)){
5915 ml.Error_UnexpectedKind ("method group");
5921 if (Arguments != null){
5922 foreach (Argument a in Arguments){
5923 if (!a.Resolve (ec, loc))
5928 method = Invocation.OverloadResolve (
5929 ec, (MethodGroupExpr) ml, Arguments, false, loc);
5933 if (method == null) {
5934 if (!is_struct || Arguments.Count > 0) {
5935 Error (1501, String.Format (
5936 "New invocation: Can not find a constructor in `{0}' for this argument list",
5937 TypeManager.CSharpName (type)));
5945 bool DoEmitTypeParameter (EmitContext ec)
5947 ILGenerator ig = ec.ig;
5949 ig.Emit (OpCodes.Ldtoken, type);
5950 ig.Emit (OpCodes.Call, TypeManager.system_type_get_type_from_handle);
5951 ig.Emit (OpCodes.Call, TypeManager.activator_create_instance);
5952 ig.Emit (OpCodes.Unbox_Any, type);
5958 // This DoEmit can be invoked in two contexts:
5959 // * As a mechanism that will leave a value on the stack (new object)
5960 // * As one that wont (init struct)
5962 // You can control whether a value is required on the stack by passing
5963 // need_value_on_stack. The code *might* leave a value on the stack
5964 // so it must be popped manually
5966 // If we are dealing with a ValueType, we have a few
5967 // situations to deal with:
5969 // * The target is a ValueType, and we have been provided
5970 // the instance (this is easy, we are being assigned).
5972 // * The target of New is being passed as an argument,
5973 // to a boxing operation or a function that takes a
5976 // In this case, we need to create a temporary variable
5977 // that is the argument of New.
5979 // Returns whether a value is left on the stack
5981 bool DoEmit (EmitContext ec, bool need_value_on_stack)
5983 bool is_value_type = type.IsValueType;
5984 ILGenerator ig = ec.ig;
5989 // Allow DoEmit() to be called multiple times.
5990 // We need to create a new LocalTemporary each time since
5991 // you can't share LocalBuilders among ILGeneators.
5992 if (!value_target_set)
5993 value_target = new LocalTemporary (ec, type);
5995 ml = (IMemoryLocation) value_target;
5996 ml.AddressOf (ec, AddressOp.Store);
6000 Invocation.EmitArguments (ec, method, Arguments);
6004 ig.Emit (OpCodes.Initobj, type);
6006 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
6007 if (need_value_on_stack){
6008 value_target.Emit (ec);
6013 ig.Emit (OpCodes.Newobj, (ConstructorInfo) method);
6018 public override void Emit (EmitContext ec)
6020 if (is_type_parameter)
6021 DoEmitTypeParameter (ec);
6026 public override void EmitStatement (EmitContext ec)
6028 if (is_type_parameter)
6029 throw new InvalidOperationException ();
6031 if (DoEmit (ec, false))
6032 ec.ig.Emit (OpCodes.Pop);
6035 public void AddressOf (EmitContext ec, AddressOp Mode)
6037 if (is_type_parameter)
6038 throw new InvalidOperationException ();
6040 if (!type.IsValueType){
6042 // We throw an exception. So far, I believe we only need to support
6044 // foreach (int j in new StructType ())
6047 throw new Exception ("AddressOf should not be used for classes");
6050 if (!value_target_set)
6051 value_target = new LocalTemporary (ec, type);
6053 IMemoryLocation ml = (IMemoryLocation) value_target;
6054 ml.AddressOf (ec, AddressOp.Store);
6056 Invocation.EmitArguments (ec, method, Arguments);
6059 ec.ig.Emit (OpCodes.Initobj, type);
6061 ec.ig.Emit (OpCodes.Call, (ConstructorInfo) method);
6063 ((IMemoryLocation) value_target).AddressOf (ec, Mode);
6068 /// 14.5.10.2: Represents an array creation expression.
6072 /// There are two possible scenarios here: one is an array creation
6073 /// expression that specifies the dimensions and optionally the
6074 /// initialization data and the other which does not need dimensions
6075 /// specified but where initialization data is mandatory.
6077 public class ArrayCreation : Expression {
6078 Expression requested_base_type;
6079 ArrayList initializers;
6082 // The list of Argument types.
6083 // This is used to construct the `newarray' or constructor signature
6085 ArrayList arguments;
6088 // Method used to create the array object.
6090 MethodBase new_method = null;
6092 Type array_element_type;
6093 Type underlying_type;
6094 bool is_one_dimensional = false;
6095 bool is_builtin_type = false;
6096 bool expect_initializers = false;
6097 int num_arguments = 0;
6101 ArrayList array_data;
6106 // The number of array initializers that we can handle
6107 // via the InitializeArray method - through EmitStaticInitializers
6109 int num_automatic_initializers;
6111 const int max_automatic_initializers = 6;
6113 public ArrayCreation (Expression requested_base_type, ArrayList exprs, string rank, ArrayList initializers, Location l)
6115 this.requested_base_type = requested_base_type;
6116 this.initializers = initializers;
6120 arguments = new ArrayList ();
6122 foreach (Expression e in exprs) {
6123 arguments.Add (new Argument (e, Argument.AType.Expression));
6128 public ArrayCreation (Expression requested_base_type, string rank, ArrayList initializers, Location l)
6130 this.requested_base_type = requested_base_type;
6131 this.initializers = initializers;
6135 //this.rank = rank.Substring (0, rank.LastIndexOf ('['));
6137 //string tmp = rank.Substring (rank.LastIndexOf ('['));
6139 //dimensions = tmp.Length - 1;
6140 expect_initializers = true;
6143 public Expression FormArrayType (Expression base_type, int idx_count, string rank)
6145 StringBuilder sb = new StringBuilder (rank);
6148 for (int i = 1; i < idx_count; i++)
6153 return new ComposedCast (base_type, sb.ToString (), loc);
6156 void Error_IncorrectArrayInitializer ()
6158 Error (178, "Incorrectly structured array initializer");
6161 public bool CheckIndices (EmitContext ec, ArrayList probe, int idx, bool specified_dims)
6163 if (specified_dims) {
6164 Argument a = (Argument) arguments [idx];
6166 if (!a.Resolve (ec, loc))
6169 if (!(a.Expr is Constant)) {
6170 Error (150, "A constant value is expected");
6174 int value = (int) ((Constant) a.Expr).GetValue ();
6176 if (value != probe.Count) {
6177 Error_IncorrectArrayInitializer ();
6181 bounds [idx] = value;
6184 int child_bounds = -1;
6185 foreach (object o in probe) {
6186 if (o is ArrayList) {
6187 int current_bounds = ((ArrayList) o).Count;
6189 if (child_bounds == -1)
6190 child_bounds = current_bounds;
6192 else if (child_bounds != current_bounds){
6193 Error_IncorrectArrayInitializer ();
6196 if (specified_dims && (idx + 1 >= arguments.Count)){
6197 Error (623, "Array initializers can only be used in a variable or field initializer, try using the new expression");
6201 bool ret = CheckIndices (ec, (ArrayList) o, idx + 1, specified_dims);
6205 if (child_bounds != -1){
6206 Error_IncorrectArrayInitializer ();
6210 Expression tmp = (Expression) o;
6211 tmp = tmp.Resolve (ec);
6215 // Console.WriteLine ("I got: " + tmp);
6216 // Handle initialization from vars, fields etc.
6218 Expression conv = Convert.ImplicitConversionRequired (
6219 ec, tmp, underlying_type, loc);
6224 if (conv is StringConstant || conv is DecimalConstant || conv is NullCast) {
6225 // These are subclasses of Constant that can appear as elements of an
6226 // array that cannot be statically initialized (with num_automatic_initializers
6227 // > max_automatic_initializers), so num_automatic_initializers should be left as zero.
6228 array_data.Add (conv);
6229 } else if (conv is Constant) {
6230 // These are the types of Constant that can appear in arrays that can be
6231 // statically allocated.
6232 array_data.Add (conv);
6233 num_automatic_initializers++;
6235 array_data.Add (conv);
6242 public void UpdateIndices (EmitContext ec)
6245 for (ArrayList probe = initializers; probe != null;) {
6246 if (probe.Count > 0 && probe [0] is ArrayList) {
6247 Expression e = new IntConstant (probe.Count);
6248 arguments.Add (new Argument (e, Argument.AType.Expression));
6250 bounds [i++] = probe.Count;
6252 probe = (ArrayList) probe [0];
6255 Expression e = new IntConstant (probe.Count);
6256 arguments.Add (new Argument (e, Argument.AType.Expression));
6258 bounds [i++] = probe.Count;
6265 public bool ValidateInitializers (EmitContext ec, Type array_type)
6267 if (initializers == null) {
6268 if (expect_initializers)
6274 if (underlying_type == null)
6278 // We use this to store all the date values in the order in which we
6279 // will need to store them in the byte blob later
6281 array_data = new ArrayList ();
6282 bounds = new Hashtable ();
6286 if (arguments != null) {
6287 ret = CheckIndices (ec, initializers, 0, true);
6290 arguments = new ArrayList ();
6292 ret = CheckIndices (ec, initializers, 0, false);
6299 if (arguments.Count != dimensions) {
6300 Error_IncorrectArrayInitializer ();
6308 void Error_NegativeArrayIndex ()
6310 Error (284, "Can not create array with a negative size");
6314 // Converts `source' to an int, uint, long or ulong.
6316 Expression ExpressionToArrayArgument (EmitContext ec, Expression source)
6320 bool old_checked = ec.CheckState;
6321 ec.CheckState = true;
6323 target = Convert.ImplicitConversion (ec, source, TypeManager.int32_type, loc);
6324 if (target == null){
6325 target = Convert.ImplicitConversion (ec, source, TypeManager.uint32_type, loc);
6326 if (target == null){
6327 target = Convert.ImplicitConversion (ec, source, TypeManager.int64_type, loc);
6328 if (target == null){
6329 target = Convert.ImplicitConversion (ec, source, TypeManager.uint64_type, loc);
6331 Convert.Error_CannotImplicitConversion (loc, source.Type, TypeManager.int32_type);
6335 ec.CheckState = old_checked;
6338 // Only positive constants are allowed at compile time
6340 if (target is Constant){
6341 if (target is IntConstant){
6342 if (((IntConstant) target).Value < 0){
6343 Error_NegativeArrayIndex ();
6348 if (target is LongConstant){
6349 if (((LongConstant) target).Value < 0){
6350 Error_NegativeArrayIndex ();
6361 // Creates the type of the array
6363 bool LookupType (EmitContext ec)
6365 StringBuilder array_qualifier = new StringBuilder (rank);
6368 // `In the first form allocates an array instace of the type that results
6369 // from deleting each of the individual expression from the expression list'
6371 if (num_arguments > 0) {
6372 array_qualifier.Append ("[");
6373 for (int i = num_arguments-1; i > 0; i--)
6374 array_qualifier.Append (",");
6375 array_qualifier.Append ("]");
6381 Expression array_type_expr;
6382 array_type_expr = new ComposedCast (requested_base_type, array_qualifier.ToString (), loc);
6383 type = ec.DeclSpace.ResolveType (array_type_expr, false, loc);
6388 underlying_type = type;
6389 if (underlying_type.IsArray)
6390 underlying_type = TypeManager.GetElementType (underlying_type);
6391 dimensions = type.GetArrayRank ();
6396 public override Expression DoResolve (EmitContext ec)
6400 if (!LookupType (ec))
6404 // First step is to validate the initializers and fill
6405 // in any missing bits
6407 if (!ValidateInitializers (ec, type))
6410 if (arguments == null)
6413 arg_count = arguments.Count;
6414 foreach (Argument a in arguments){
6415 if (!a.Resolve (ec, loc))
6418 Expression real_arg = ExpressionToArrayArgument (ec, a.Expr, loc);
6419 if (real_arg == null)
6426 array_element_type = TypeManager.GetElementType (type);
6428 if (arg_count == 1) {
6429 is_one_dimensional = true;
6430 eclass = ExprClass.Value;
6434 is_builtin_type = TypeManager.IsBuiltinType (type);
6436 if (is_builtin_type) {
6439 ml = MemberLookup (ec, type, ".ctor", MemberTypes.Constructor,
6440 AllBindingFlags, loc);
6442 if (!(ml is MethodGroupExpr)) {
6443 ml.Error_UnexpectedKind ("method group");
6448 Error (-6, "New invocation: Can not find a constructor for " +
6449 "this argument list");
6453 new_method = Invocation.OverloadResolve (
6454 ec, (MethodGroupExpr) ml, arguments, false, loc);
6456 if (new_method == null) {
6457 Error (-6, "New invocation: Can not find a constructor for " +
6458 "this argument list");
6462 eclass = ExprClass.Value;
6465 ModuleBuilder mb = CodeGen.Module.Builder;
6466 ArrayList args = new ArrayList ();
6468 if (arguments != null) {
6469 for (int i = 0; i < arg_count; i++)
6470 args.Add (TypeManager.int32_type);
6473 Type [] arg_types = null;
6476 arg_types = new Type [args.Count];
6478 args.CopyTo (arg_types, 0);
6480 new_method = mb.GetArrayMethod (type, ".ctor", CallingConventions.HasThis, null,
6483 if (new_method == null) {
6484 Error (-6, "New invocation: Can not find a constructor for " +
6485 "this argument list");
6489 eclass = ExprClass.Value;
6494 public static byte [] MakeByteBlob (ArrayList array_data, Type underlying_type, Location loc)
6499 int count = array_data.Count;
6501 if (underlying_type.IsEnum)
6502 underlying_type = TypeManager.EnumToUnderlying (underlying_type);
6504 factor = GetTypeSize (underlying_type);
6506 throw new Exception ("unrecognized type in MakeByteBlob: " + underlying_type);
6508 data = new byte [(count * factor + 4) & ~3];
6511 for (int i = 0; i < count; ++i) {
6512 object v = array_data [i];
6514 if (v is EnumConstant)
6515 v = ((EnumConstant) v).Child;
6517 if (v is Constant && !(v is StringConstant))
6518 v = ((Constant) v).GetValue ();
6524 if (underlying_type == TypeManager.int64_type){
6525 if (!(v is Expression)){
6526 long val = (long) v;
6528 for (int j = 0; j < factor; ++j) {
6529 data [idx + j] = (byte) (val & 0xFF);
6533 } else if (underlying_type == TypeManager.uint64_type){
6534 if (!(v is Expression)){
6535 ulong val = (ulong) v;
6537 for (int j = 0; j < factor; ++j) {
6538 data [idx + j] = (byte) (val & 0xFF);
6542 } else if (underlying_type == TypeManager.float_type) {
6543 if (!(v is Expression)){
6544 element = BitConverter.GetBytes ((float) v);
6546 for (int j = 0; j < factor; ++j)
6547 data [idx + j] = element [j];
6549 } else if (underlying_type == TypeManager.double_type) {
6550 if (!(v is Expression)){
6551 element = BitConverter.GetBytes ((double) v);
6553 for (int j = 0; j < factor; ++j)
6554 data [idx + j] = element [j];
6556 } else if (underlying_type == TypeManager.char_type){
6557 if (!(v is Expression)){
6558 int val = (int) ((char) v);
6560 data [idx] = (byte) (val & 0xff);
6561 data [idx+1] = (byte) (val >> 8);
6563 } else if (underlying_type == TypeManager.short_type){
6564 if (!(v is Expression)){
6565 int val = (int) ((short) v);
6567 data [idx] = (byte) (val & 0xff);
6568 data [idx+1] = (byte) (val >> 8);
6570 } else if (underlying_type == TypeManager.ushort_type){
6571 if (!(v is Expression)){
6572 int val = (int) ((ushort) v);
6574 data [idx] = (byte) (val & 0xff);
6575 data [idx+1] = (byte) (val >> 8);
6577 } else if (underlying_type == TypeManager.int32_type) {
6578 if (!(v is Expression)){
6581 data [idx] = (byte) (val & 0xff);
6582 data [idx+1] = (byte) ((val >> 8) & 0xff);
6583 data [idx+2] = (byte) ((val >> 16) & 0xff);
6584 data [idx+3] = (byte) (val >> 24);
6586 } else if (underlying_type == TypeManager.uint32_type) {
6587 if (!(v is Expression)){
6588 uint val = (uint) v;
6590 data [idx] = (byte) (val & 0xff);
6591 data [idx+1] = (byte) ((val >> 8) & 0xff);
6592 data [idx+2] = (byte) ((val >> 16) & 0xff);
6593 data [idx+3] = (byte) (val >> 24);
6595 } else if (underlying_type == TypeManager.sbyte_type) {
6596 if (!(v is Expression)){
6597 sbyte val = (sbyte) v;
6598 data [idx] = (byte) val;
6600 } else if (underlying_type == TypeManager.byte_type) {
6601 if (!(v is Expression)){
6602 byte val = (byte) v;
6603 data [idx] = (byte) val;
6605 } else if (underlying_type == TypeManager.bool_type) {
6606 if (!(v is Expression)){
6607 bool val = (bool) v;
6608 data [idx] = (byte) (val ? 1 : 0);
6610 } else if (underlying_type == TypeManager.decimal_type){
6611 if (!(v is Expression)){
6612 int [] bits = Decimal.GetBits ((decimal) v);
6615 // FIXME: For some reason, this doesn't work on the MS runtime.
6616 int [] nbits = new int [4];
6617 nbits [0] = bits [3];
6618 nbits [1] = bits [2];
6619 nbits [2] = bits [0];
6620 nbits [3] = bits [1];
6622 for (int j = 0; j < 4; j++){
6623 data [p++] = (byte) (nbits [j] & 0xff);
6624 data [p++] = (byte) ((nbits [j] >> 8) & 0xff);
6625 data [p++] = (byte) ((nbits [j] >> 16) & 0xff);
6626 data [p++] = (byte) (nbits [j] >> 24);
6630 throw new Exception ("Unrecognized type in MakeByteBlob: " + underlying_type);
6639 // Emits the initializers for the array
6641 void EmitStaticInitializers (EmitContext ec)
6644 // First, the static data
6647 ILGenerator ig = ec.ig;
6649 byte [] data = MakeByteBlob (array_data, underlying_type, loc);
6651 fb = RootContext.MakeStaticData (data);
6653 ig.Emit (OpCodes.Dup);
6654 ig.Emit (OpCodes.Ldtoken, fb);
6655 ig.Emit (OpCodes.Call,
6656 TypeManager.void_initializearray_array_fieldhandle);
6660 // Emits pieces of the array that can not be computed at compile
6661 // time (variables and string locations).
6663 // This always expect the top value on the stack to be the array
6665 void EmitDynamicInitializers (EmitContext ec)
6667 ILGenerator ig = ec.ig;
6668 int dims = bounds.Count;
6669 int [] current_pos = new int [dims];
6670 int top = array_data.Count;
6672 MethodInfo set = null;
6676 ModuleBuilder mb = null;
6677 mb = CodeGen.Module.Builder;
6678 args = new Type [dims + 1];
6681 for (j = 0; j < dims; j++)
6682 args [j] = TypeManager.int32_type;
6684 args [j] = array_element_type;
6686 set = mb.GetArrayMethod (
6688 CallingConventions.HasThis | CallingConventions.Standard,
6689 TypeManager.void_type, args);
6692 for (int i = 0; i < top; i++){
6694 Expression e = null;
6696 if (array_data [i] is Expression)
6697 e = (Expression) array_data [i];
6701 // Basically we do this for string literals and
6702 // other non-literal expressions
6704 if (e is EnumConstant){
6705 e = ((EnumConstant) e).Child;
6708 if (e is StringConstant || e is DecimalConstant || !(e is Constant) ||
6709 num_automatic_initializers <= max_automatic_initializers) {
6710 Type etype = e.Type;
6712 ig.Emit (OpCodes.Dup);
6714 for (int idx = 0; idx < dims; idx++)
6715 IntConstant.EmitInt (ig, current_pos [idx]);
6718 // If we are dealing with a struct, get the
6719 // address of it, so we can store it.
6722 etype.IsSubclassOf (TypeManager.value_type) &&
6723 (!TypeManager.IsBuiltinOrEnum (etype) ||
6724 etype == TypeManager.decimal_type)) {
6729 // Let new know that we are providing
6730 // the address where to store the results
6732 n.DisableTemporaryValueType ();
6735 ig.Emit (OpCodes.Ldelema, etype);
6741 ArrayAccess.EmitStoreOpcode (ig, array_element_type);
6743 ig.Emit (OpCodes.Call, set);
6751 for (int j = dims - 1; j >= 0; j--){
6753 if (current_pos [j] < (int) bounds [j])
6755 current_pos [j] = 0;
6760 void EmitArrayArguments (EmitContext ec)
6762 ILGenerator ig = ec.ig;
6764 foreach (Argument a in arguments) {
6765 Type atype = a.Type;
6768 if (atype == TypeManager.uint64_type)
6769 ig.Emit (OpCodes.Conv_Ovf_U4);
6770 else if (atype == TypeManager.int64_type)
6771 ig.Emit (OpCodes.Conv_Ovf_I4);
6775 public override void Emit (EmitContext ec)
6777 ILGenerator ig = ec.ig;
6779 EmitArrayArguments (ec);
6780 if (is_one_dimensional)
6781 ig.Emit (OpCodes.Newarr, array_element_type);
6783 if (is_builtin_type)
6784 ig.Emit (OpCodes.Newobj, (ConstructorInfo) new_method);
6786 ig.Emit (OpCodes.Newobj, (MethodInfo) new_method);
6789 if (initializers != null){
6791 // FIXME: Set this variable correctly.
6793 bool dynamic_initializers = true;
6795 // This will never be true for array types that cannot be statically
6796 // initialized. num_automatic_initializers will always be zero. See
6798 if (num_automatic_initializers > max_automatic_initializers)
6799 EmitStaticInitializers (ec);
6801 if (dynamic_initializers)
6802 EmitDynamicInitializers (ec);
6806 public object EncodeAsAttribute ()
6808 if (!is_one_dimensional){
6809 Report.Error (-211, Location, "attribute can not encode multi-dimensional arrays");
6813 if (array_data == null){
6814 Report.Error (-212, Location, "array should be initialized when passing it to an attribute");
6818 object [] ret = new object [array_data.Count];
6820 foreach (Expression e in array_data){
6823 if (e is NullLiteral)
6826 if (!Attribute.GetAttributeArgumentExpression (e, Location, out v))
6834 public Expression TurnIntoConstant ()
6837 // Should use something like the above attribute thing.
6838 // It should return a subclass of Constant that just returns
6839 // the computed value of the array
6841 throw new Exception ("Does not support yet Turning array into a Constant");
6846 /// Represents the `this' construct
6848 public class This : Expression, IAssignMethod, IMemoryLocation, IVariable {
6851 VariableInfo variable_info;
6853 public This (Block block, Location loc)
6859 public This (Location loc)
6864 public VariableInfo VariableInfo {
6865 get { return variable_info; }
6868 public bool VerifyFixed (bool is_expression)
6870 if ((variable_info == null) || (variable_info.LocalInfo == null))
6873 return variable_info.LocalInfo.IsFixed;
6876 public bool ResolveBase (EmitContext ec)
6878 eclass = ExprClass.Variable;
6880 if (ec.TypeContainer.CurrentType != null)
6881 type = ec.TypeContainer.CurrentType.ResolveType (ec);
6883 type = ec.ContainerType;
6886 Error (26, "Keyword this not valid in static code");
6890 if ((block != null) && (block.ThisVariable != null))
6891 variable_info = block.ThisVariable.VariableInfo;
6896 public override Expression DoResolve (EmitContext ec)
6898 if (!ResolveBase (ec))
6901 if ((variable_info != null) && !variable_info.IsAssigned (ec)) {
6902 Error (188, "The this object cannot be used before all " +
6903 "of its fields are assigned to");
6904 variable_info.SetAssigned (ec);
6908 if (ec.IsFieldInitializer) {
6909 Error (27, "Keyword `this' can't be used outside a constructor, " +
6910 "a method or a property.");
6917 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
6919 if (!ResolveBase (ec))
6922 if (variable_info != null)
6923 variable_info.SetAssigned (ec);
6925 if (ec.TypeContainer is Class){
6926 Error (1604, "Cannot assign to `this'");
6933 public override void Emit (EmitContext ec)
6935 ILGenerator ig = ec.ig;
6938 if (ec.TypeContainer is Struct)
6939 ig.Emit (OpCodes.Ldobj, type);
6942 public void EmitAssign (EmitContext ec, Expression source)
6944 ILGenerator ig = ec.ig;
6946 if (ec.TypeContainer is Struct){
6949 ig.Emit (OpCodes.Stobj, type);
6952 ig.Emit (OpCodes.Starg, 0);
6956 public void AddressOf (EmitContext ec, AddressOp mode)
6961 // FIGURE OUT WHY LDARG_S does not work
6963 // consider: struct X { int val; int P { set { val = value; }}}
6965 // Yes, this looks very bad. Look at `NOTAS' for
6967 // ec.ig.Emit (OpCodes.Ldarga_S, (byte) 0);
6972 /// Represents the `__arglist' construct
6974 public class ArglistAccess : Expression
6976 public ArglistAccess (Location loc)
6981 public bool ResolveBase (EmitContext ec)
6983 eclass = ExprClass.Variable;
6984 type = TypeManager.runtime_argument_handle_type;
6988 public override Expression DoResolve (EmitContext ec)
6990 if (!ResolveBase (ec))
6993 if (ec.IsFieldInitializer || !ec.CurrentBlock.HasVarargs) {
6994 Error (190, "The __arglist construct is valid only within " +
6995 "a variable argument method.");
7002 public override void Emit (EmitContext ec)
7004 ec.ig.Emit (OpCodes.Arglist);
7009 /// Represents the `__arglist (....)' construct
7011 public class Arglist : Expression
7013 public readonly Argument[] Arguments;
7015 public Arglist (Argument[] args, Location l)
7021 public Type[] ArgumentTypes {
7023 Type[] retval = new Type [Arguments.Length];
7024 for (int i = 0; i < Arguments.Length; i++)
7025 retval [i] = Arguments [i].Type;
7030 public override Expression DoResolve (EmitContext ec)
7032 eclass = ExprClass.Variable;
7033 type = TypeManager.runtime_argument_handle_type;
7035 foreach (Argument arg in Arguments) {
7036 if (!arg.Resolve (ec, loc))
7043 public override void Emit (EmitContext ec)
7045 foreach (Argument arg in Arguments)
7051 // This produces the value that renders an instance, used by the iterators code
7053 public class ProxyInstance : Expression, IMemoryLocation {
7054 public override Expression DoResolve (EmitContext ec)
7056 eclass = ExprClass.Variable;
7057 type = ec.ContainerType;
7061 public override void Emit (EmitContext ec)
7063 ec.ig.Emit (OpCodes.Ldarg_0);
7067 public void AddressOf (EmitContext ec, AddressOp mode)
7069 ec.ig.Emit (OpCodes.Ldarg_0);
7074 /// Implements the typeof operator
7076 public class TypeOf : Expression {
7077 public readonly Expression QueriedType;
7078 protected Type typearg;
7080 public TypeOf (Expression queried_type, Location l)
7082 QueriedType = queried_type;
7086 public override Expression DoResolve (EmitContext ec)
7088 typearg = ec.DeclSpace.ResolveType (QueriedType, false, loc);
7090 if (typearg == null)
7093 if (typearg == TypeManager.void_type) {
7094 Error (673, "System.Void cannot be used from C# - " +
7095 "use typeof (void) to get the void type object");
7099 CheckObsoleteAttribute (typearg);
7101 type = TypeManager.type_type;
7102 eclass = ExprClass.Type;
7106 public override void Emit (EmitContext ec)
7108 ec.ig.Emit (OpCodes.Ldtoken, typearg);
7109 ec.ig.Emit (OpCodes.Call, TypeManager.system_type_get_type_from_handle);
7112 public Type TypeArg {
7113 get { return typearg; }
7118 /// Implements the `typeof (void)' operator
7120 public class TypeOfVoid : TypeOf {
7121 public TypeOfVoid (Location l) : base (null, l)
7126 public override Expression DoResolve (EmitContext ec)
7128 type = TypeManager.type_type;
7129 typearg = TypeManager.void_type;
7130 eclass = ExprClass.Type;
7136 /// Implements the sizeof expression
7138 public class SizeOf : Expression {
7139 public Expression QueriedType;
7142 public SizeOf (Expression queried_type, Location l)
7144 this.QueriedType = queried_type;
7148 public override Expression DoResolve (EmitContext ec)
7152 233, loc, "Sizeof may only be used in an unsafe context " +
7153 "(consider using System.Runtime.InteropServices.Marshal.Sizeof");
7157 QueriedType = ec.DeclSpace.ResolveTypeExpr (QueriedType, false, loc);
7158 if (QueriedType == null || QueriedType.Type == null)
7161 if (QueriedType is TypeParameterExpr){
7162 ((TypeParameterExpr)QueriedType).Error_CannotUseAsUnmanagedType (loc);
7166 type_queried = QueriedType.Type;
7167 if (type_queried == null)
7170 CheckObsoleteAttribute (type_queried);
7172 if (!TypeManager.IsUnmanagedType (type_queried)){
7173 Report.Error (208, loc, "Cannot take the size of an unmanaged type (" + TypeManager.CSharpName (type_queried) + ")");
7177 type = TypeManager.int32_type;
7178 eclass = ExprClass.Value;
7182 public override void Emit (EmitContext ec)
7184 int size = GetTypeSize (type_queried);
7187 ec.ig.Emit (OpCodes.Sizeof, type_queried);
7189 IntConstant.EmitInt (ec.ig, size);
7194 /// Implements the member access expression
7196 public class MemberAccess : Expression {
7197 public string Identifier;
7198 protected Expression expr;
7199 protected TypeArguments args;
7201 public MemberAccess (Expression expr, string id, Location l)
7208 public MemberAccess (Expression expr, string id, TypeArguments args,
7210 : this (expr, id, l)
7215 public Expression Expr {
7221 public static void error176 (Location loc, string name)
7223 Report.Error (176, loc, "Static member `" +
7224 name + "' cannot be accessed " +
7225 "with an instance reference, qualify with a " +
7226 "type name instead");
7229 public static bool IdenticalNameAndTypeName (EmitContext ec, Expression left_original, Expression left, Location loc)
7231 SimpleName sn = left_original as SimpleName;
7232 if (sn == null || left == null || left.Type.Name != sn.Name)
7235 return RootContext.LookupType (ec.DeclSpace, sn.Name, true, loc) != null;
7238 public static Expression ResolveMemberAccess (EmitContext ec, Expression member_lookup,
7239 Expression left, Location loc,
7240 Expression left_original)
7242 bool left_is_type, left_is_explicit;
7244 // If `left' is null, then we're called from SimpleNameResolve and this is
7245 // a member in the currently defining class.
7247 left_is_type = ec.IsStatic || ec.IsFieldInitializer;
7248 left_is_explicit = false;
7250 // Implicitly default to `this' unless we're static.
7251 if (!ec.IsStatic && !ec.IsFieldInitializer && !ec.InEnumContext)
7252 left = ec.GetThis (loc);
7254 left_is_type = left is TypeExpr;
7255 left_is_explicit = true;
7258 if (member_lookup is FieldExpr){
7259 FieldExpr fe = (FieldExpr) member_lookup;
7260 FieldInfo fi = fe.FieldInfo.Mono_GetGenericFieldDefinition ();
7261 Type decl_type = fi.DeclaringType;
7263 if (fi is FieldBuilder) {
7264 Const c = TypeManager.LookupConstant ((FieldBuilder) fi);
7268 if (!c.LookupConstantValue (out o))
7271 object real_value = ((Constant) c.Expr).GetValue ();
7273 return Constantify (real_value, fi.FieldType);
7278 Type t = fi.FieldType;
7282 if (fi is FieldBuilder)
7283 o = TypeManager.GetValue ((FieldBuilder) fi);
7285 o = fi.GetValue (fi);
7287 if (decl_type.IsSubclassOf (TypeManager.enum_type)) {
7288 if (left_is_explicit && !left_is_type &&
7289 !IdenticalNameAndTypeName (ec, left_original, member_lookup, loc)) {
7290 error176 (loc, fe.FieldInfo.Name);
7294 Expression enum_member = MemberLookup (
7295 ec, decl_type, "value__", MemberTypes.Field,
7296 AllBindingFlags, loc);
7298 Enum en = TypeManager.LookupEnum (decl_type);
7302 c = Constantify (o, en.UnderlyingType);
7304 c = Constantify (o, enum_member.Type);
7306 return new EnumConstant (c, decl_type);
7309 Expression exp = Constantify (o, t);
7311 if (left_is_explicit && !left_is_type) {
7312 error176 (loc, fe.FieldInfo.Name);
7319 if (fi.FieldType.IsPointer && !ec.InUnsafe){
7325 if (member_lookup is EventExpr) {
7326 EventExpr ee = (EventExpr) member_lookup;
7329 // If the event is local to this class, we transform ourselves into
7333 if (ee.EventInfo.DeclaringType == ec.ContainerType ||
7334 TypeManager.IsNestedChildOf(ec.ContainerType, ee.EventInfo.DeclaringType)) {
7335 MemberInfo mi = GetFieldFromEvent (ee);
7339 // If this happens, then we have an event with its own
7340 // accessors and private field etc so there's no need
7341 // to transform ourselves.
7343 ee.InstanceExpression = left;
7347 Expression ml = ExprClassFromMemberInfo (ec, mi, loc);
7350 Report.Error (-200, loc, "Internal error!!");
7354 if (!left_is_explicit)
7357 ee.InstanceExpression = left;
7359 return ResolveMemberAccess (ec, ml, left, loc, left_original);
7363 if (member_lookup is IMemberExpr) {
7364 IMemberExpr me = (IMemberExpr) member_lookup;
7365 MethodGroupExpr mg = me as MethodGroupExpr;
7368 if ((mg != null) && left_is_explicit && left.Type.IsInterface)
7369 mg.IsExplicitImpl = left_is_explicit;
7372 if ((ec.IsFieldInitializer || ec.IsStatic) &&
7373 IdenticalNameAndTypeName (ec, left_original, member_lookup, loc))
7374 return member_lookup;
7376 SimpleName.Error_ObjectRefRequired (ec, loc, me.Name);
7381 if (!me.IsInstance){
7382 if (IdenticalNameAndTypeName (ec, left_original, left, loc))
7383 return member_lookup;
7385 if (left_is_explicit) {
7386 error176 (loc, me.Name);
7392 // Since we can not check for instance objects in SimpleName,
7393 // becaue of the rule that allows types and variables to share
7394 // the name (as long as they can be de-ambiguated later, see
7395 // IdenticalNameAndTypeName), we have to check whether left
7396 // is an instance variable in a static context
7398 // However, if the left-hand value is explicitly given, then
7399 // it is already our instance expression, so we aren't in
7403 if (ec.IsStatic && !left_is_explicit && left is IMemberExpr){
7404 IMemberExpr mexp = (IMemberExpr) left;
7406 if (!mexp.IsStatic){
7407 SimpleName.Error_ObjectRefRequired (ec, loc, mexp.Name);
7412 if ((mg != null) && IdenticalNameAndTypeName (ec, left_original, left, loc))
7413 mg.IdenticalTypeName = true;
7415 me.InstanceExpression = left;
7418 return member_lookup;
7421 Console.WriteLine ("Left is: " + left);
7422 Report.Error (-100, loc, "Support for [" + member_lookup + "] is not present yet");
7423 Environment.Exit (1);
7427 public virtual Expression DoResolve (EmitContext ec, Expression right_side,
7431 throw new Exception ();
7434 // Resolve the expression with flow analysis turned off, we'll do the definite
7435 // assignment checks later. This is because we don't know yet what the expression
7436 // will resolve to - it may resolve to a FieldExpr and in this case we must do the
7437 // definite assignment check on the actual field and not on the whole struct.
7440 Expression original = expr;
7441 expr = expr.Resolve (ec, flags | ResolveFlags.Intermediate | ResolveFlags.DisableFlowAnalysis);
7445 if (expr is SimpleName){
7446 SimpleName child_expr = (SimpleName) expr;
7448 Expression new_expr = new SimpleName (child_expr.Name, Identifier, loc);
7450 return new_expr.Resolve (ec, flags);
7454 // TODO: I mailed Ravi about this, and apparently we can get rid
7455 // of this and put it in the right place.
7457 // Handle enums here when they are in transit.
7458 // Note that we cannot afford to hit MemberLookup in this case because
7459 // it will fail to find any members at all
7463 if (expr is TypeExpr){
7464 expr_type = ((TypeExpr) expr).ResolveType (ec);
7466 if (!ec.DeclSpace.CheckAccessLevel (expr_type)){
7467 Report.Error_T (122, loc, expr_type);
7471 if (expr_type == TypeManager.enum_type || expr_type.IsSubclassOf (TypeManager.enum_type)){
7472 Enum en = TypeManager.LookupEnum (expr_type);
7475 object value = en.LookupEnumValue (ec, Identifier, loc);
7478 ObsoleteAttribute oa = en.GetObsoleteAttribute (ec, Identifier);
7480 AttributeTester.Report_ObsoleteMessage (oa, en.GetSignatureForError (), Location);
7483 Constant c = Constantify (value, en.UnderlyingType);
7484 return new EnumConstant (c, expr_type);
7487 CheckObsoleteAttribute (expr_type);
7489 FieldInfo fi = expr_type.GetField (Identifier);
7491 ObsoleteAttribute oa = AttributeTester.GetMemberObsoleteAttribute (fi);
7493 AttributeTester.Report_ObsoleteMessage (oa, TypeManager.GetFullNameSignature (fi), Location);
7498 expr_type = expr.Type;
7500 if (expr_type.IsPointer){
7501 Error (23, "The `.' operator can not be applied to pointer operands (" +
7502 TypeManager.CSharpName (expr_type) + ")");
7506 int errors = Report.Errors;
7508 Expression member_lookup;
7509 member_lookup = MemberLookup (
7510 ec, expr_type, expr_type, Identifier, loc);
7511 if ((member_lookup == null) && (args != null)) {
7512 string lookup_id = MemberName.MakeName (Identifier, args);
7513 member_lookup = MemberLookup (
7514 ec, expr_type, expr_type, lookup_id, loc);
7516 if (member_lookup == null) {
7517 MemberLookupFailed (
7518 ec, expr_type, expr_type, Identifier, null, loc);
7522 if (member_lookup is TypeExpr) {
7523 if (!(expr is TypeExpr) && !(expr is SimpleName)) {
7524 Error (572, "Can't reference type `" + Identifier + "' through an expression; try `" +
7525 member_lookup.Type + "' instead");
7529 return member_lookup;
7533 string full_name = expr_type + "." + Identifier;
7535 if (member_lookup is FieldExpr) {
7536 Report.Error (307, loc, "The field `{0}' cannot " +
7537 "be used with type arguments", full_name);
7539 } else if (member_lookup is EventExpr) {
7540 Report.Error (307, loc, "The event `{0}' cannot " +
7541 "be used with type arguments", full_name);
7543 } else if (member_lookup is PropertyExpr) {
7544 Report.Error (307, loc, "The property `{0}' cannot " +
7545 "be used with type arguments", full_name);
7550 member_lookup = ResolveMemberAccess (ec, member_lookup, expr, loc, original);
7551 if (member_lookup == null)
7555 MethodGroupExpr mg = member_lookup as MethodGroupExpr;
7557 throw new InternalErrorException ();
7559 return mg.ResolveGeneric (ec, args);
7562 // The following DoResolve/DoResolveLValue will do the definite assignment
7565 if (right_side != null)
7566 member_lookup = member_lookup.DoResolveLValue (ec, right_side);
7568 member_lookup = member_lookup.DoResolve (ec);
7570 return member_lookup;
7573 public override Expression DoResolve (EmitContext ec)
7575 return DoResolve (ec, null, ResolveFlags.VariableOrValue |
7576 ResolveFlags.SimpleName | ResolveFlags.Type);
7579 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
7581 return DoResolve (ec, right_side, ResolveFlags.VariableOrValue |
7582 ResolveFlags.SimpleName | ResolveFlags.Type);
7585 public override Expression ResolveAsTypeStep (EmitContext ec)
7587 string fname = null;
7588 MemberAccess full_expr = this;
7589 while (full_expr != null) {
7591 fname = String.Concat (full_expr.Identifier, ".", fname);
7593 fname = full_expr.Identifier;
7595 fname = MemberName.MakeName (fname, args);
7597 if (full_expr.Expr is SimpleName) {
7598 string full_name = String.Concat (((SimpleName) full_expr.Expr).Name, ".", fname);
7599 Type fully_qualified = ec.DeclSpace.FindType (loc, full_name);
7600 if (fully_qualified != null)
7601 return new TypeExpression (fully_qualified, loc);
7604 full_expr = full_expr.Expr as MemberAccess;
7607 Expression new_expr = expr.ResolveAsTypeStep (ec);
7609 if (new_expr == null)
7612 if (new_expr is SimpleName){
7613 SimpleName child_expr = (SimpleName) new_expr;
7615 new_expr = new SimpleName (child_expr.Name, Identifier, loc);
7617 return new_expr.ResolveAsTypeStep (ec);
7620 Type expr_type = ((TypeExpr) new_expr).ResolveType (ec);
7622 if (expr_type.IsPointer){
7623 Error (23, "The `.' operator can not be applied to pointer operands (" +
7624 TypeManager.CSharpName (expr_type) + ")");
7628 Expression member_lookup;
7630 lookup_id = MemberName.MakeName (Identifier, args);
7631 member_lookup = MemberLookupFinal (
7632 ec, expr_type, expr_type, lookup_id, loc);
7633 if (member_lookup == null)
7636 TypeExpr texpr = member_lookup as TypeExpr;
7640 Type t = texpr.ResolveType (ec);
7644 if (TypeManager.HasGenericArguments (expr_type)) {
7645 Type[] decl_args = TypeManager.GetTypeArguments (expr_type);
7647 TypeArguments new_args = new TypeArguments (loc);
7648 foreach (Type decl in decl_args)
7649 new_args.Add (new TypeExpression (decl, loc));
7652 new_args.Add (args);
7658 ConstructedType ctype = new ConstructedType (t, args, loc);
7659 return ctype.ResolveAsTypeStep (ec);
7665 public override void Emit (EmitContext ec)
7667 throw new Exception ("Should not happen");
7670 public override string ToString ()
7672 return expr + "." + MemberName.MakeName (Identifier, args);
7677 /// Implements checked expressions
7679 public class CheckedExpr : Expression {
7681 public Expression Expr;
7683 public CheckedExpr (Expression e, Location l)
7689 public override Expression DoResolve (EmitContext ec)
7691 bool last_check = ec.CheckState;
7692 bool last_const_check = ec.ConstantCheckState;
7694 ec.CheckState = true;
7695 ec.ConstantCheckState = true;
7696 Expr = Expr.Resolve (ec);
7697 ec.CheckState = last_check;
7698 ec.ConstantCheckState = last_const_check;
7703 if (Expr is Constant)
7706 eclass = Expr.eclass;
7711 public override void Emit (EmitContext ec)
7713 bool last_check = ec.CheckState;
7714 bool last_const_check = ec.ConstantCheckState;
7716 ec.CheckState = true;
7717 ec.ConstantCheckState = true;
7719 ec.CheckState = last_check;
7720 ec.ConstantCheckState = last_const_check;
7726 /// Implements the unchecked expression
7728 public class UnCheckedExpr : Expression {
7730 public Expression Expr;
7732 public UnCheckedExpr (Expression e, Location l)
7738 public override Expression DoResolve (EmitContext ec)
7740 bool last_check = ec.CheckState;
7741 bool last_const_check = ec.ConstantCheckState;
7743 ec.CheckState = false;
7744 ec.ConstantCheckState = false;
7745 Expr = Expr.Resolve (ec);
7746 ec.CheckState = last_check;
7747 ec.ConstantCheckState = last_const_check;
7752 if (Expr is Constant)
7755 eclass = Expr.eclass;
7760 public override void Emit (EmitContext ec)
7762 bool last_check = ec.CheckState;
7763 bool last_const_check = ec.ConstantCheckState;
7765 ec.CheckState = false;
7766 ec.ConstantCheckState = false;
7768 ec.CheckState = last_check;
7769 ec.ConstantCheckState = last_const_check;
7775 /// An Element Access expression.
7777 /// During semantic analysis these are transformed into
7778 /// IndexerAccess, ArrayAccess or a PointerArithmetic.
7780 public class ElementAccess : Expression {
7781 public ArrayList Arguments;
7782 public Expression Expr;
7784 public ElementAccess (Expression e, ArrayList e_list, Location l)
7793 Arguments = new ArrayList ();
7794 foreach (Expression tmp in e_list)
7795 Arguments.Add (new Argument (tmp, Argument.AType.Expression));
7799 bool CommonResolve (EmitContext ec)
7801 Expr = Expr.Resolve (ec);
7806 if (Arguments == null)
7809 foreach (Argument a in Arguments){
7810 if (!a.Resolve (ec, loc))
7817 Expression MakePointerAccess ()
7821 if (t == TypeManager.void_ptr_type){
7822 Error (242, "The array index operation is not valid for void pointers");
7825 if (Arguments.Count != 1){
7826 Error (196, "A pointer must be indexed by a single value");
7831 p = new PointerArithmetic (true, Expr, ((Argument)Arguments [0]).Expr, t, loc);
7832 return new Indirection (p, loc);
7835 public override Expression DoResolve (EmitContext ec)
7837 if (!CommonResolve (ec))
7841 // We perform some simple tests, and then to "split" the emit and store
7842 // code we create an instance of a different class, and return that.
7844 // I am experimenting with this pattern.
7848 if (t == TypeManager.array_type){
7849 Report.Error (21, loc, "Cannot use indexer on System.Array");
7854 return (new ArrayAccess (this, loc)).Resolve (ec);
7855 else if (t.IsPointer)
7856 return MakePointerAccess ();
7858 return (new IndexerAccess (this, loc)).Resolve (ec);
7861 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
7863 if (!CommonResolve (ec))
7868 return (new ArrayAccess (this, loc)).ResolveLValue (ec, right_side);
7869 else if (t.IsPointer)
7870 return MakePointerAccess ();
7872 return (new IndexerAccess (this, loc)).ResolveLValue (ec, right_side);
7875 public override void Emit (EmitContext ec)
7877 throw new Exception ("Should never be reached");
7882 /// Implements array access
7884 public class ArrayAccess : Expression, IAssignMethod, IMemoryLocation {
7886 // Points to our "data" repository
7890 LocalTemporary [] cached_locations;
7892 public ArrayAccess (ElementAccess ea_data, Location l)
7895 eclass = ExprClass.Variable;
7899 public override Expression DoResolve (EmitContext ec)
7902 ExprClass eclass = ea.Expr.eclass;
7904 // As long as the type is valid
7905 if (!(eclass == ExprClass.Variable || eclass == ExprClass.PropertyAccess ||
7906 eclass == ExprClass.Value)) {
7907 ea.Expr.Error_UnexpectedKind ("variable or value");
7912 Type t = ea.Expr.Type;
7913 if (t.GetArrayRank () != ea.Arguments.Count){
7915 "Incorrect number of indexes for array " +
7916 " expected: " + t.GetArrayRank () + " got: " +
7917 ea.Arguments.Count);
7921 type = TypeManager.GetElementType (t);
7922 if (type.IsPointer && !ec.InUnsafe){
7923 UnsafeError (ea.Location);
7927 foreach (Argument a in ea.Arguments){
7928 Type argtype = a.Type;
7930 if (argtype == TypeManager.int32_type ||
7931 argtype == TypeManager.uint32_type ||
7932 argtype == TypeManager.int64_type ||
7933 argtype == TypeManager.uint64_type)
7937 // Mhm. This is strage, because the Argument.Type is not the same as
7938 // Argument.Expr.Type: the value changes depending on the ref/out setting.
7940 // Wonder if I will run into trouble for this.
7942 a.Expr = ExpressionToArrayArgument (ec, a.Expr, ea.Location);
7947 eclass = ExprClass.Variable;
7953 /// Emits the right opcode to load an object of Type `t'
7954 /// from an array of T
7956 static public void EmitLoadOpcode (ILGenerator ig, Type type)
7958 if (type == TypeManager.byte_type || type == TypeManager.bool_type)
7959 ig.Emit (OpCodes.Ldelem_U1);
7960 else if (type == TypeManager.sbyte_type)
7961 ig.Emit (OpCodes.Ldelem_I1);
7962 else if (type == TypeManager.short_type)
7963 ig.Emit (OpCodes.Ldelem_I2);
7964 else if (type == TypeManager.ushort_type || type == TypeManager.char_type)
7965 ig.Emit (OpCodes.Ldelem_U2);
7966 else if (type == TypeManager.int32_type)
7967 ig.Emit (OpCodes.Ldelem_I4);
7968 else if (type == TypeManager.uint32_type)
7969 ig.Emit (OpCodes.Ldelem_U4);
7970 else if (type == TypeManager.uint64_type)
7971 ig.Emit (OpCodes.Ldelem_I8);
7972 else if (type == TypeManager.int64_type)
7973 ig.Emit (OpCodes.Ldelem_I8);
7974 else if (type == TypeManager.float_type)
7975 ig.Emit (OpCodes.Ldelem_R4);
7976 else if (type == TypeManager.double_type)
7977 ig.Emit (OpCodes.Ldelem_R8);
7978 else if (type == TypeManager.intptr_type)
7979 ig.Emit (OpCodes.Ldelem_I);
7980 else if (TypeManager.IsEnumType (type)){
7981 EmitLoadOpcode (ig, TypeManager.EnumToUnderlying (type));
7982 } else if (type.IsValueType){
7983 ig.Emit (OpCodes.Ldelema, type);
7984 ig.Emit (OpCodes.Ldobj, type);
7985 } else if (type.IsGenericParameter)
7986 ig.Emit (OpCodes.Ldelem_Any, type);
7988 ig.Emit (OpCodes.Ldelem_Ref);
7992 /// Emits the right opcode to store an object of Type `t'
7993 /// from an array of T.
7995 static public void EmitStoreOpcode (ILGenerator ig, Type t)
7997 bool is_stobj, has_type_arg;
7998 OpCode op = GetStoreOpcode (t, out is_stobj, out has_type_arg);
8006 /// Returns the right opcode to store an object of Type `t'
8007 /// from an array of T.
8009 static public OpCode GetStoreOpcode (Type t, out bool is_stobj, out bool has_type_arg)
8011 //Console.WriteLine (new System.Diagnostics.StackTrace ());
8012 has_type_arg = false; is_stobj = false;
8013 t = TypeManager.TypeToCoreType (t);
8014 if (TypeManager.IsEnumType (t) && t != TypeManager.enum_type)
8015 t = TypeManager.EnumToUnderlying (t);
8016 if (t == TypeManager.byte_type || t == TypeManager.sbyte_type ||
8017 t == TypeManager.bool_type)
8018 return OpCodes.Stelem_I1;
8019 else if (t == TypeManager.short_type || t == TypeManager.ushort_type ||
8020 t == TypeManager.char_type)
8021 return OpCodes.Stelem_I2;
8022 else if (t == TypeManager.int32_type || t == TypeManager.uint32_type)
8023 return OpCodes.Stelem_I4;
8024 else if (t == TypeManager.int64_type || t == TypeManager.uint64_type)
8025 return OpCodes.Stelem_I8;
8026 else if (t == TypeManager.float_type)
8027 return OpCodes.Stelem_R4;
8028 else if (t == TypeManager.double_type)
8029 return OpCodes.Stelem_R8;
8030 else if (t == TypeManager.intptr_type) {
8031 has_type_arg = true;
8033 return OpCodes.Stobj;
8034 } else if (t.IsValueType) {
8035 has_type_arg = true;
8037 return OpCodes.Stobj;
8038 } else if (t.IsGenericParameter) {
8039 has_type_arg = true;
8040 return OpCodes.Stelem_Any;
8042 return OpCodes.Stelem_Ref;
8045 MethodInfo FetchGetMethod ()
8047 ModuleBuilder mb = CodeGen.Module.Builder;
8048 int arg_count = ea.Arguments.Count;
8049 Type [] args = new Type [arg_count];
8052 for (int i = 0; i < arg_count; i++){
8053 //args [i++] = a.Type;
8054 args [i] = TypeManager.int32_type;
8057 get = mb.GetArrayMethod (
8058 ea.Expr.Type, "Get",
8059 CallingConventions.HasThis |
8060 CallingConventions.Standard,
8066 MethodInfo FetchAddressMethod ()
8068 ModuleBuilder mb = CodeGen.Module.Builder;
8069 int arg_count = ea.Arguments.Count;
8070 Type [] args = new Type [arg_count];
8074 ret_type = TypeManager.GetReferenceType (type);
8076 for (int i = 0; i < arg_count; i++){
8077 //args [i++] = a.Type;
8078 args [i] = TypeManager.int32_type;
8081 address = mb.GetArrayMethod (
8082 ea.Expr.Type, "Address",
8083 CallingConventions.HasThis |
8084 CallingConventions.Standard,
8091 // Load the array arguments into the stack.
8093 // If we have been requested to cache the values (cached_locations array
8094 // initialized), then load the arguments the first time and store them
8095 // in locals. otherwise load from local variables.
8097 void LoadArrayAndArguments (EmitContext ec)
8099 ILGenerator ig = ec.ig;
8101 if (cached_locations == null){
8103 foreach (Argument a in ea.Arguments){
8104 Type argtype = a.Expr.Type;
8108 if (argtype == TypeManager.int64_type)
8109 ig.Emit (OpCodes.Conv_Ovf_I);
8110 else if (argtype == TypeManager.uint64_type)
8111 ig.Emit (OpCodes.Conv_Ovf_I_Un);
8116 if (cached_locations [0] == null){
8117 cached_locations [0] = new LocalTemporary (ec, ea.Expr.Type);
8119 ig.Emit (OpCodes.Dup);
8120 cached_locations [0].Store (ec);
8124 foreach (Argument a in ea.Arguments){
8125 Type argtype = a.Expr.Type;
8127 cached_locations [j] = new LocalTemporary (ec, TypeManager.intptr_type /* a.Expr.Type */);
8129 if (argtype == TypeManager.int64_type)
8130 ig.Emit (OpCodes.Conv_Ovf_I);
8131 else if (argtype == TypeManager.uint64_type)
8132 ig.Emit (OpCodes.Conv_Ovf_I_Un);
8134 ig.Emit (OpCodes.Dup);
8135 cached_locations [j].Store (ec);
8141 foreach (LocalTemporary lt in cached_locations)
8145 public new void CacheTemporaries (EmitContext ec)
8147 cached_locations = new LocalTemporary [ea.Arguments.Count + 1];
8150 public override void Emit (EmitContext ec)
8152 int rank = ea.Expr.Type.GetArrayRank ();
8153 ILGenerator ig = ec.ig;
8155 LoadArrayAndArguments (ec);
8158 EmitLoadOpcode (ig, type);
8162 method = FetchGetMethod ();
8163 ig.Emit (OpCodes.Call, method);
8167 public void EmitAssign (EmitContext ec, Expression source)
8169 int rank = ea.Expr.Type.GetArrayRank ();
8170 ILGenerator ig = ec.ig;
8171 Type t = source.Type;
8173 LoadArrayAndArguments (ec);
8176 // The stobj opcode used by value types will need
8177 // an address on the stack, not really an array/array
8181 if (t == TypeManager.enum_type || t == TypeManager.decimal_type ||
8182 (t.IsSubclassOf (TypeManager.value_type) && !TypeManager.IsEnumType (t) && !TypeManager.IsBuiltinType (t)))
8183 ig.Emit (OpCodes.Ldelema, t);
8189 EmitStoreOpcode (ig, t);
8191 ModuleBuilder mb = CodeGen.Module.Builder;
8192 int arg_count = ea.Arguments.Count;
8193 Type [] args = new Type [arg_count + 1];
8196 for (int i = 0; i < arg_count; i++){
8197 //args [i++] = a.Type;
8198 args [i] = TypeManager.int32_type;
8201 args [arg_count] = type;
8203 set = mb.GetArrayMethod (
8204 ea.Expr.Type, "Set",
8205 CallingConventions.HasThis |
8206 CallingConventions.Standard,
8207 TypeManager.void_type, args);
8209 ig.Emit (OpCodes.Call, set);
8213 public void AddressOf (EmitContext ec, AddressOp mode)
8215 int rank = ea.Expr.Type.GetArrayRank ();
8216 ILGenerator ig = ec.ig;
8218 LoadArrayAndArguments (ec);
8221 ig.Emit (OpCodes.Ldelema, type);
8223 MethodInfo address = FetchAddressMethod ();
8224 ig.Emit (OpCodes.Call, address);
8231 public ArrayList Properties;
8232 static Hashtable map;
8234 public struct Indexer {
8235 public readonly Type Type;
8236 public readonly MethodInfo Getter, Setter;
8238 public Indexer (Type type, MethodInfo get, MethodInfo set)
8248 map = new Hashtable ();
8253 Properties = new ArrayList ();
8256 void Append (MemberInfo [] mi)
8258 foreach (PropertyInfo property in mi){
8259 MethodInfo get, set;
8261 get = property.GetGetMethod (true);
8262 set = property.GetSetMethod (true);
8263 Properties.Add (new Indexer (property.PropertyType, get, set));
8267 static private MemberInfo [] GetIndexersForTypeOrInterface (Type caller_type, Type lookup_type)
8269 string p_name = TypeManager.IndexerPropertyName (lookup_type);
8271 MemberInfo [] mi = TypeManager.MemberLookup (
8272 caller_type, caller_type, lookup_type, MemberTypes.Property,
8273 BindingFlags.Public | BindingFlags.Instance |
8274 BindingFlags.DeclaredOnly, p_name, null);
8276 if (mi == null || mi.Length == 0)
8282 static public Indexers GetIndexersForType (Type caller_type, Type lookup_type, Location loc)
8284 Indexers ix = (Indexers) map [lookup_type];
8289 Type copy = lookup_type;
8290 while (copy != TypeManager.object_type && copy != null){
8291 MemberInfo [] mi = GetIndexersForTypeOrInterface (caller_type, copy);
8295 ix = new Indexers ();
8300 copy = copy.BaseType;
8303 if (!lookup_type.IsInterface)
8306 TypeExpr [] ifaces = TypeManager.GetInterfaces (lookup_type);
8307 if (ifaces != null) {
8308 foreach (TypeExpr iface in ifaces) {
8309 Type itype = iface.Type;
8310 MemberInfo [] mi = GetIndexersForTypeOrInterface (caller_type, itype);
8313 ix = new Indexers ();
8325 /// Expressions that represent an indexer call.
8327 public class IndexerAccess : Expression, IAssignMethod {
8329 // Points to our "data" repository
8331 MethodInfo get, set;
8332 ArrayList set_arguments;
8333 bool is_base_indexer;
8335 protected Type indexer_type;
8336 protected Type current_type;
8337 protected Expression instance_expr;
8338 protected ArrayList arguments;
8340 public IndexerAccess (ElementAccess ea, Location loc)
8341 : this (ea.Expr, false, loc)
8343 this.arguments = ea.Arguments;
8346 protected IndexerAccess (Expression instance_expr, bool is_base_indexer,
8349 this.instance_expr = instance_expr;
8350 this.is_base_indexer = is_base_indexer;
8351 this.eclass = ExprClass.Value;
8355 protected virtual bool CommonResolve (EmitContext ec)
8357 indexer_type = instance_expr.Type;
8358 current_type = ec.ContainerType;
8363 public override Expression DoResolve (EmitContext ec)
8365 ArrayList AllGetters = new ArrayList();
8366 if (!CommonResolve (ec))
8370 // Step 1: Query for all `Item' *properties*. Notice
8371 // that the actual methods are pointed from here.
8373 // This is a group of properties, piles of them.
8375 bool found_any = false, found_any_getters = false;
8376 Type lookup_type = indexer_type;
8379 ilist = Indexers.GetIndexersForType (current_type, lookup_type, loc);
8380 if (ilist != null) {
8382 if (ilist.Properties != null) {
8383 foreach (Indexers.Indexer ix in ilist.Properties) {
8384 if (ix.Getter != null)
8385 AllGetters.Add(ix.Getter);
8390 if (AllGetters.Count > 0) {
8391 found_any_getters = true;
8392 get = (MethodInfo) Invocation.OverloadResolve (
8393 ec, new MethodGroupExpr (AllGetters, loc),
8394 arguments, false, loc);
8398 Report.Error (21, loc,
8399 "Type `" + TypeManager.CSharpName (indexer_type) +
8400 "' does not have any indexers defined");
8404 if (!found_any_getters) {
8405 Error (154, "indexer can not be used in this context, because " +
8406 "it lacks a `get' accessor");
8411 Error (1501, "No Overload for method `this' takes `" +
8412 arguments.Count + "' arguments");
8417 // Only base will allow this invocation to happen.
8419 if (get.IsAbstract && this is BaseIndexerAccess){
8420 Report.Error (205, loc, "Cannot call an abstract base indexer: " + Invocation.FullMethodDesc (get));
8424 type = get.ReturnType;
8425 if (type.IsPointer && !ec.InUnsafe){
8430 eclass = ExprClass.IndexerAccess;
8434 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
8436 ArrayList AllSetters = new ArrayList();
8437 if (!CommonResolve (ec))
8440 bool found_any = false, found_any_setters = false;
8442 Indexers ilist = Indexers.GetIndexersForType (current_type, indexer_type, loc);
8443 if (ilist != null) {
8445 if (ilist.Properties != null) {
8446 foreach (Indexers.Indexer ix in ilist.Properties) {
8447 if (ix.Setter != null)
8448 AllSetters.Add(ix.Setter);
8452 if (AllSetters.Count > 0) {
8453 found_any_setters = true;
8454 set_arguments = (ArrayList) arguments.Clone ();
8455 set_arguments.Add (new Argument (right_side, Argument.AType.Expression));
8456 set = (MethodInfo) Invocation.OverloadResolve (
8457 ec, new MethodGroupExpr (AllSetters, loc),
8458 set_arguments, false, loc);
8462 Report.Error (21, loc,
8463 "Type `" + TypeManager.CSharpName (indexer_type) +
8464 "' does not have any indexers defined");
8468 if (!found_any_setters) {
8469 Error (154, "indexer can not be used in this context, because " +
8470 "it lacks a `set' accessor");
8475 Error (1501, "No Overload for method `this' takes `" +
8476 arguments.Count + "' arguments");
8481 // Only base will allow this invocation to happen.
8483 if (set.IsAbstract && this is BaseIndexerAccess){
8484 Report.Error (205, loc, "Cannot call an abstract base indexer: " + Invocation.FullMethodDesc (set));
8489 // Now look for the actual match in the list of indexers to set our "return" type
8491 type = TypeManager.void_type; // default value
8492 foreach (Indexers.Indexer ix in ilist.Properties){
8493 if (ix.Setter == set){
8499 eclass = ExprClass.IndexerAccess;
8503 public override void Emit (EmitContext ec)
8505 Invocation.EmitCall (ec, is_base_indexer, false, instance_expr, get, arguments, loc);
8509 // source is ignored, because we already have a copy of it from the
8510 // LValue resolution and we have already constructed a pre-cached
8511 // version of the arguments (ea.set_arguments);
8513 public void EmitAssign (EmitContext ec, Expression source)
8515 Invocation.EmitCall (ec, is_base_indexer, false, instance_expr, set, set_arguments, loc);
8520 /// The base operator for method names
8522 public class BaseAccess : Expression {
8525 public BaseAccess (string member, Location l)
8527 this.member = member;
8531 public override Expression DoResolve (EmitContext ec)
8533 Expression c = CommonResolve (ec);
8539 // MethodGroups use this opportunity to flag an error on lacking ()
8541 if (!(c is MethodGroupExpr))
8542 return c.Resolve (ec);
8546 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
8548 Expression c = CommonResolve (ec);
8554 // MethodGroups use this opportunity to flag an error on lacking ()
8556 if (! (c is MethodGroupExpr))
8557 return c.DoResolveLValue (ec, right_side);
8562 Expression CommonResolve (EmitContext ec)
8564 Expression member_lookup;
8565 Type current_type = ec.ContainerType;
8566 Type base_type = current_type.BaseType;
8570 Error (1511, "Keyword base is not allowed in static method");
8574 if (ec.IsFieldInitializer){
8575 Error (1512, "Keyword base is not available in the current context");
8579 member_lookup = MemberLookup (ec, ec.ContainerType, null, base_type,
8580 member, AllMemberTypes, AllBindingFlags,
8582 if (member_lookup == null) {
8583 MemberLookupFailed (
8584 ec, base_type, base_type, member, null, loc);
8591 left = new TypeExpression (base_type, loc);
8593 left = ec.GetThis (loc);
8595 e = MemberAccess.ResolveMemberAccess (ec, member_lookup, left, loc, null);
8597 if (e is PropertyExpr){
8598 PropertyExpr pe = (PropertyExpr) e;
8606 public override void Emit (EmitContext ec)
8608 throw new Exception ("Should never be called");
8613 /// The base indexer operator
8615 public class BaseIndexerAccess : IndexerAccess {
8616 public BaseIndexerAccess (ArrayList args, Location loc)
8617 : base (null, true, loc)
8619 arguments = new ArrayList ();
8620 foreach (Expression tmp in args)
8621 arguments.Add (new Argument (tmp, Argument.AType.Expression));
8624 protected override bool CommonResolve (EmitContext ec)
8626 instance_expr = ec.GetThis (loc);
8628 current_type = ec.ContainerType.BaseType;
8629 indexer_type = current_type;
8631 foreach (Argument a in arguments){
8632 if (!a.Resolve (ec, loc))
8641 /// This class exists solely to pass the Type around and to be a dummy
8642 /// that can be passed to the conversion functions (this is used by
8643 /// foreach implementation to typecast the object return value from
8644 /// get_Current into the proper type. All code has been generated and
8645 /// we only care about the side effect conversions to be performed
8647 /// This is also now used as a placeholder where a no-action expression
8648 /// is needed (the `New' class).
8650 public class EmptyExpression : Expression {
8651 public EmptyExpression ()
8653 type = TypeManager.object_type;
8654 eclass = ExprClass.Value;
8655 loc = Location.Null;
8658 public EmptyExpression (Type t)
8661 eclass = ExprClass.Value;
8662 loc = Location.Null;
8665 public override Expression DoResolve (EmitContext ec)
8670 public override void Emit (EmitContext ec)
8672 // nothing, as we only exist to not do anything.
8676 // This is just because we might want to reuse this bad boy
8677 // instead of creating gazillions of EmptyExpressions.
8678 // (CanImplicitConversion uses it)
8680 public void SetType (Type t)
8686 public class UserCast : Expression {
8690 public UserCast (MethodInfo method, Expression source, Location l)
8692 this.method = method;
8693 this.source = source;
8694 type = method.ReturnType;
8695 eclass = ExprClass.Value;
8699 public override Expression DoResolve (EmitContext ec)
8702 // We are born fully resolved
8707 public override void Emit (EmitContext ec)
8709 ILGenerator ig = ec.ig;
8713 if (method is MethodInfo)
8714 ig.Emit (OpCodes.Call, (MethodInfo) method);
8716 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
8722 // This class is used to "construct" the type during a typecast
8723 // operation. Since the Type.GetType class in .NET can parse
8724 // the type specification, we just use this to construct the type
8725 // one bit at a time.
8727 public class ComposedCast : TypeExpr {
8731 public ComposedCast (Expression left, string dim, Location l)
8738 public override TypeExpr DoResolveAsTypeStep (EmitContext ec)
8740 Type ltype = ec.DeclSpace.ResolveType (left, false, loc);
8744 if ((ltype == TypeManager.void_type) && (dim != "*")) {
8745 Report.Error (1547, Location,
8746 "Keyword 'void' cannot be used in this context");
8751 while ((pos < dim.Length) && (dim [pos] == '[')) {
8754 if (dim [pos] == ']') {
8755 ltype = ltype.MakeArrayType ();
8758 if (pos < dim.Length)
8762 eclass = ExprClass.Type;
8767 while (dim [pos] == ',') {
8771 if ((dim [pos] != ']') || (pos != dim.Length-1))
8774 type = ltype.MakeArrayType (rank + 1);
8775 eclass = ExprClass.Type;
8780 // ltype.Fullname is already fully qualified, so we can skip
8781 // a lot of probes, and go directly to TypeManager.LookupType
8783 string fname = ltype.FullName != null ? ltype.FullName : ltype.Name;
8784 string cname = fname + dim;
8785 type = TypeManager.LookupTypeDirect (cname);
8788 // For arrays of enumerations we are having a problem
8789 // with the direct lookup. Need to investigate.
8791 // For now, fall back to the full lookup in that case.
8793 TypeExpr texpr = RootContext.LookupType (
8794 ec.DeclSpace, cname, false, loc);
8799 type = texpr.ResolveType (ec);
8804 if (!ec.ResolvingTypeTree){
8806 // If the above flag is set, this is being invoked from the ResolveType function.
8807 // Upper layers take care of the type validity in this context.
8809 if (!ec.InUnsafe && type.IsPointer){
8815 eclass = ExprClass.Type;
8819 public override string Name {
8827 // This class is used to represent the address of an array, used
8828 // only by the Fixed statement, this is like the C "&a [0]" construct.
8830 public class ArrayPtr : Expression {
8833 public ArrayPtr (Expression array, Location l)
8835 Type array_type = TypeManager.GetElementType (array.Type);
8839 type = TypeManager.GetPointerType (array_type);
8840 eclass = ExprClass.Value;
8844 public override void Emit (EmitContext ec)
8846 ILGenerator ig = ec.ig;
8849 IntLiteral.EmitInt (ig, 0);
8850 ig.Emit (OpCodes.Ldelema, TypeManager.GetElementType (array.Type));
8853 public override Expression DoResolve (EmitContext ec)
8856 // We are born fully resolved
8863 // Used by the fixed statement
8865 public class StringPtr : Expression {
8868 public StringPtr (LocalBuilder b, Location l)
8871 eclass = ExprClass.Value;
8872 type = TypeManager.char_ptr_type;
8876 public override Expression DoResolve (EmitContext ec)
8878 // This should never be invoked, we are born in fully
8879 // initialized state.
8884 public override void Emit (EmitContext ec)
8886 ILGenerator ig = ec.ig;
8888 ig.Emit (OpCodes.Ldloc, b);
8889 ig.Emit (OpCodes.Conv_I);
8890 ig.Emit (OpCodes.Call, TypeManager.int_get_offset_to_string_data);
8891 ig.Emit (OpCodes.Add);
8896 // Implements the `stackalloc' keyword
8898 public class StackAlloc : Expression {
8903 public StackAlloc (Expression type, Expression count, Location l)
8910 public override Expression DoResolve (EmitContext ec)
8912 count = count.Resolve (ec);
8916 if (count.Type != TypeManager.int32_type){
8917 count = Convert.ImplicitConversionRequired (ec, count, TypeManager.int32_type, loc);
8922 Constant c = count as Constant;
8923 // TODO: because we don't have property IsNegative
8924 if (c != null && c.ConvertToUInt () == null) {
8925 // "Cannot use a negative size with stackalloc"
8926 Report.Error_T (247, loc);
8930 if (ec.CurrentBranching.InCatch () ||
8931 ec.CurrentBranching.InFinally (true)) {
8933 "stackalloc can not be used in a catch or finally block");
8937 otype = ec.DeclSpace.ResolveType (t, false, loc);
8942 if (!TypeManager.VerifyUnManaged (otype, loc))
8945 type = TypeManager.GetPointerType (otype);
8946 eclass = ExprClass.Value;
8951 public override void Emit (EmitContext ec)
8953 int size = GetTypeSize (otype);
8954 ILGenerator ig = ec.ig;
8957 ig.Emit (OpCodes.Sizeof, otype);
8959 IntConstant.EmitInt (ig, size);
8961 ig.Emit (OpCodes.Mul);
8962 ig.Emit (OpCodes.Localloc);