2 // expression.cs: Expression representation for the IL tree.
5 // Miguel de Icaza (miguel@ximian.com)
7 // (C) 2001 Ximian, Inc.
12 namespace Mono.CSharp {
14 using System.Collections;
15 using System.Reflection;
16 using System.Reflection.Emit;
20 /// This is just a helper class, it is generated by Unary, UnaryMutator
21 /// when an overloaded method has been found. It just emits the code for a
24 public class StaticCallExpr : ExpressionStatement {
28 StaticCallExpr (MethodInfo m, ArrayList a, Location l)
34 eclass = ExprClass.Value;
38 public override Expression DoResolve (EmitContext ec)
41 // We are born fully resolved
46 public override void Emit (EmitContext ec)
49 Invocation.EmitArguments (ec, mi, args);
51 ec.ig.Emit (OpCodes.Call, mi);
55 static public Expression MakeSimpleCall (EmitContext ec, MethodGroupExpr mg,
56 Expression e, Location loc)
61 args = new ArrayList (1);
62 args.Add (new Argument (e, Argument.AType.Expression));
63 method = Invocation.OverloadResolve (ec, (MethodGroupExpr) mg, args, loc);
68 return new StaticCallExpr ((MethodInfo) method, args, loc);
71 public override void EmitStatement (EmitContext ec)
74 if (TypeManager.TypeToCoreType (type) != TypeManager.void_type)
75 ec.ig.Emit (OpCodes.Pop);
80 /// Unary expressions.
84 /// Unary implements unary expressions. It derives from
85 /// ExpressionStatement becuase the pre/post increment/decrement
86 /// operators can be used in a statement context.
88 public class Unary : Expression {
89 public enum Operator : byte {
90 UnaryPlus, UnaryNegation, LogicalNot, OnesComplement,
91 Indirection, AddressOf, TOP
95 public Expression Expr;
97 public Unary (Operator op, Expression expr, Location loc)
105 /// Returns a stringified representation of the Operator
107 static public string OperName (Operator oper)
110 case Operator.UnaryPlus:
112 case Operator.UnaryNegation:
114 case Operator.LogicalNot:
116 case Operator.OnesComplement:
118 case Operator.AddressOf:
120 case Operator.Indirection:
124 return oper.ToString ();
127 static string [] oper_names;
131 oper_names = new string [(int)Operator.TOP];
133 oper_names [(int) Operator.UnaryPlus] = "op_UnaryPlus";
134 oper_names [(int) Operator.UnaryNegation] = "op_UnaryNegation";
135 oper_names [(int) Operator.LogicalNot] = "op_LogicalNot";
136 oper_names [(int) Operator.OnesComplement] = "op_OnesComplement";
137 oper_names [(int) Operator.Indirection] = "op_Indirection";
138 oper_names [(int) Operator.AddressOf] = "op_AddressOf";
141 void Error23 (Type t)
144 23, "Operator " + OperName (Oper) +
145 " cannot be applied to operand of type `" +
146 TypeManager.CSharpName (t) + "'");
150 /// The result has been already resolved:
152 /// FIXME: a minus constant -128 sbyte cant be turned into a
155 static Expression TryReduceNegative (Constant expr)
159 if (expr is IntConstant)
160 e = new IntConstant (-((IntConstant) expr).Value);
161 else if (expr is UIntConstant){
162 uint value = ((UIntConstant) expr).Value;
164 if (value < 2147483649)
165 return new IntConstant (-(int)value);
167 e = new LongConstant (value);
169 else if (expr is LongConstant)
170 e = new LongConstant (-((LongConstant) expr).Value);
171 else if (expr is ULongConstant){
172 ulong value = ((ULongConstant) expr).Value;
174 if (value < 9223372036854775809)
175 return new LongConstant(-(long)value);
177 else if (expr is FloatConstant)
178 e = new FloatConstant (-((FloatConstant) expr).Value);
179 else if (expr is DoubleConstant)
180 e = new DoubleConstant (-((DoubleConstant) expr).Value);
181 else if (expr is DecimalConstant)
182 e = new DecimalConstant (-((DecimalConstant) expr).Value);
183 else if (expr is ShortConstant)
184 e = new IntConstant (-((ShortConstant) expr).Value);
185 else if (expr is UShortConstant)
186 e = new IntConstant (-((UShortConstant) expr).Value);
191 // This routine will attempt to simplify the unary expression when the
192 // argument is a constant. The result is returned in `result' and the
193 // function returns true or false depending on whether a reduction
194 // was performed or not
196 bool Reduce (EmitContext ec, Constant e, out Expression result)
198 Type expr_type = e.Type;
201 case Operator.UnaryPlus:
205 case Operator.UnaryNegation:
206 result = TryReduceNegative (e);
209 case Operator.LogicalNot:
210 if (expr_type != TypeManager.bool_type) {
216 BoolConstant b = (BoolConstant) e;
217 result = new BoolConstant (!(b.Value));
220 case Operator.OnesComplement:
221 if (!((expr_type == TypeManager.int32_type) ||
222 (expr_type == TypeManager.uint32_type) ||
223 (expr_type == TypeManager.int64_type) ||
224 (expr_type == TypeManager.uint64_type) ||
225 (expr_type.IsSubclassOf (TypeManager.enum_type)))){
231 if (e is EnumConstant){
232 EnumConstant enum_constant = (EnumConstant) e;
235 if (Reduce (ec, enum_constant.Child, out reduced)){
236 result = new EnumConstant ((Constant) reduced, enum_constant.Type);
244 if (expr_type == TypeManager.int32_type){
245 result = new IntConstant (~ ((IntConstant) e).Value);
246 } else if (expr_type == TypeManager.uint32_type){
247 result = new UIntConstant (~ ((UIntConstant) e).Value);
248 } else if (expr_type == TypeManager.int64_type){
249 result = new LongConstant (~ ((LongConstant) e).Value);
250 } else if (expr_type == TypeManager.uint64_type){
251 result = new ULongConstant (~ ((ULongConstant) e).Value);
259 case Operator.AddressOf:
263 case Operator.Indirection:
267 throw new Exception ("Can not constant fold: " + Oper.ToString());
270 Expression ResolveOperator (EmitContext ec)
272 Type expr_type = Expr.Type;
275 // Step 1: Perform Operator Overload location
280 op_name = oper_names [(int) Oper];
282 mg = MemberLookup (ec, expr_type, op_name, MemberTypes.Method, AllBindingFlags, loc);
285 Expression e = StaticCallExpr.MakeSimpleCall (
286 ec, (MethodGroupExpr) mg, Expr, loc);
296 // Only perform numeric promotions on:
299 if (expr_type == null)
303 // Step 2: Default operations on CLI native types.
306 // Attempt to use a constant folding operation.
307 if (Expr is Constant){
310 if (Reduce (ec, (Constant) Expr, out result))
315 case Operator.LogicalNot:
316 if (expr_type != TypeManager.bool_type) {
321 type = TypeManager.bool_type;
324 case Operator.OnesComplement:
325 if (!((expr_type == TypeManager.int32_type) ||
326 (expr_type == TypeManager.uint32_type) ||
327 (expr_type == TypeManager.int64_type) ||
328 (expr_type == TypeManager.uint64_type) ||
329 (expr_type.IsSubclassOf (TypeManager.enum_type)))){
332 e = ConvertImplicit (ec, Expr, TypeManager.int32_type, loc);
334 type = TypeManager.int32_type;
337 e = ConvertImplicit (ec, Expr, TypeManager.uint32_type, loc);
339 type = TypeManager.uint32_type;
342 e = ConvertImplicit (ec, Expr, TypeManager.int64_type, loc);
344 type = TypeManager.int64_type;
347 e = ConvertImplicit (ec, Expr, TypeManager.uint64_type, loc);
349 type = TypeManager.uint64_type;
358 case Operator.AddressOf:
359 if (Expr.eclass != ExprClass.Variable){
360 Error (211, "Cannot take the address of non-variables");
369 if (!TypeManager.VerifyUnManaged (Expr.Type, loc)){
373 string ptr_type_name = Expr.Type.FullName + "*";
374 type = TypeManager.LookupType (ptr_type_name);
378 case Operator.Indirection:
384 if (!expr_type.IsPointer){
387 "The * or -> operator can only be applied to pointers");
392 // We create an Indirection expression, because
393 // it can implement the IMemoryLocation.
395 return new Indirection (Expr, loc);
397 case Operator.UnaryPlus:
399 // A plus in front of something is just a no-op, so return the child.
403 case Operator.UnaryNegation:
405 // Deals with -literals
406 // int operator- (int x)
407 // long operator- (long x)
408 // float operator- (float f)
409 // double operator- (double d)
410 // decimal operator- (decimal d)
412 Expression expr = null;
415 // transform - - expr into expr
418 Unary unary = (Unary) Expr;
420 if (unary.Oper == Operator.UnaryNegation)
425 // perform numeric promotions to int,
429 // The following is inneficient, because we call
430 // ConvertImplicit too many times.
432 // It is also not clear if we should convert to Float
433 // or Double initially.
435 if (expr_type == TypeManager.uint32_type){
437 // FIXME: handle exception to this rule that
438 // permits the int value -2147483648 (-2^31) to
439 // bt wrote as a decimal interger literal
441 type = TypeManager.int64_type;
442 Expr = ConvertImplicit (ec, Expr, type, loc);
446 if (expr_type == TypeManager.uint64_type){
448 // FIXME: Handle exception of `long value'
449 // -92233720368547758087 (-2^63) to be wrote as
450 // decimal integer literal.
456 if (expr_type == TypeManager.float_type){
461 expr = ConvertImplicit (ec, Expr, TypeManager.int32_type, loc);
468 expr = ConvertImplicit (ec, Expr, TypeManager.int64_type, loc);
475 expr = ConvertImplicit (ec, Expr, TypeManager.double_type, loc);
486 Error (187, "No such operator '" + OperName (Oper) + "' defined for type '" +
487 TypeManager.CSharpName (expr_type) + "'");
491 public override Expression DoResolve (EmitContext ec)
493 if (Oper == Operator.AddressOf)
494 Expr = Expr.ResolveLValue (ec, new EmptyExpression ());
496 Expr = Expr.Resolve (ec);
501 eclass = ExprClass.Value;
502 return ResolveOperator (ec);
505 public override void Emit (EmitContext ec)
507 ILGenerator ig = ec.ig;
508 Type expr_type = Expr.Type;
511 case Operator.UnaryPlus:
512 throw new Exception ("This should be caught by Resolve");
514 case Operator.UnaryNegation:
516 ig.Emit (OpCodes.Neg);
519 case Operator.LogicalNot:
521 ig.Emit (OpCodes.Ldc_I4_0);
522 ig.Emit (OpCodes.Ceq);
525 case Operator.OnesComplement:
527 ig.Emit (OpCodes.Not);
530 case Operator.AddressOf:
531 ((IMemoryLocation)Expr).AddressOf (ec, AddressOp.LoadStore);
535 throw new Exception ("This should not happen: Operator = "
541 /// This will emit the child expression for `ec' avoiding the logical
542 /// not. The parent will take care of changing brfalse/brtrue
544 public void EmitLogicalNot (EmitContext ec)
546 if (Oper != Operator.LogicalNot)
547 throw new Exception ("EmitLogicalNot can only be called with !expr");
552 public override string ToString ()
554 return "Unary (" + Oper + ", " + Expr + ")";
560 // Unary operators are turned into Indirection expressions
561 // after semantic analysis (this is so we can take the address
562 // of an indirection).
564 public class Indirection : Expression, IMemoryLocation, IAssignMethod {
566 LocalTemporary temporary;
569 public Indirection (Expression expr, Location l)
572 this.type = TypeManager.TypeToCoreType (expr.Type.GetElementType ());
573 eclass = ExprClass.Variable;
577 void LoadExprValue (EmitContext ec)
581 public override void Emit (EmitContext ec)
583 ILGenerator ig = ec.ig;
585 if (temporary != null){
591 ec.ig.Emit (OpCodes.Dup);
592 temporary.Store (ec);
593 have_temporary = true;
597 LoadFromPtr (ig, Type);
600 public void EmitAssign (EmitContext ec, Expression source)
602 if (temporary != null){
608 ec.ig.Emit (OpCodes.Dup);
609 temporary.Store (ec);
610 have_temporary = true;
615 StoreFromPtr (ec.ig, type);
618 public void AddressOf (EmitContext ec, AddressOp Mode)
620 if (temporary != null){
626 ec.ig.Emit (OpCodes.Dup);
627 temporary.Store (ec);
628 have_temporary = true;
633 public override Expression DoResolve (EmitContext ec)
636 // Born fully resolved
641 public new void CacheTemporaries (EmitContext ec)
643 temporary = new LocalTemporary (ec, type);
648 /// Unary Mutator expressions (pre and post ++ and --)
652 /// UnaryMutator implements ++ and -- expressions. It derives from
653 /// ExpressionStatement becuase the pre/post increment/decrement
654 /// operators can be used in a statement context.
656 /// FIXME: Idea, we could split this up in two classes, one simpler
657 /// for the common case, and one with the extra fields for more complex
658 /// classes (indexers require temporary access; overloaded require method)
660 /// Maybe we should have classes PreIncrement, PostIncrement, PreDecrement,
661 /// PostDecrement, that way we could save the `Mode' byte as well.
663 public class UnaryMutator : ExpressionStatement {
664 public enum Mode : byte {
665 PreIncrement, PreDecrement, PostIncrement, PostDecrement
670 LocalTemporary temp_storage;
673 // This is expensive for the simplest case.
677 public UnaryMutator (Mode m, Expression e, Location l)
684 static string OperName (Mode mode)
686 return (mode == Mode.PreIncrement || mode == Mode.PostIncrement) ?
690 void Error23 (Type t)
693 23, "Operator " + OperName (mode) +
694 " cannot be applied to operand of type `" +
695 TypeManager.CSharpName (t) + "'");
699 /// Returns whether an object of type `t' can be incremented
700 /// or decremented with add/sub (ie, basically whether we can
701 /// use pre-post incr-decr operations on it, but it is not a
702 /// System.Decimal, which we require operator overloading to catch)
704 static bool IsIncrementableNumber (Type t)
706 return (t == TypeManager.sbyte_type) ||
707 (t == TypeManager.byte_type) ||
708 (t == TypeManager.short_type) ||
709 (t == TypeManager.ushort_type) ||
710 (t == TypeManager.int32_type) ||
711 (t == TypeManager.uint32_type) ||
712 (t == TypeManager.int64_type) ||
713 (t == TypeManager.uint64_type) ||
714 (t == TypeManager.char_type) ||
715 (t.IsSubclassOf (TypeManager.enum_type)) ||
716 (t == TypeManager.float_type) ||
717 (t == TypeManager.double_type) ||
718 (t.IsPointer && t != TypeManager.void_ptr_type);
721 Expression ResolveOperator (EmitContext ec)
723 Type expr_type = expr.Type;
726 // Step 1: Perform Operator Overload location
731 if (mode == Mode.PreIncrement || mode == Mode.PostIncrement)
732 op_name = "op_Increment";
734 op_name = "op_Decrement";
736 mg = MemberLookup (ec, expr_type, op_name, MemberTypes.Method, AllBindingFlags, loc);
738 if (mg == null && expr_type.BaseType != null)
739 mg = MemberLookup (ec, expr_type.BaseType, op_name,
740 MemberTypes.Method, AllBindingFlags, loc);
743 method = StaticCallExpr.MakeSimpleCall (
744 ec, (MethodGroupExpr) mg, expr, loc);
751 // The operand of the prefix/postfix increment decrement operators
752 // should be an expression that is classified as a variable,
753 // a property access or an indexer access
756 if (expr.eclass == ExprClass.Variable){
757 if (IsIncrementableNumber (expr_type) ||
758 expr_type == TypeManager.decimal_type){
761 } else if (expr.eclass == ExprClass.IndexerAccess){
762 IndexerAccess ia = (IndexerAccess) expr;
764 temp_storage = new LocalTemporary (ec, expr.Type);
766 expr = ia.ResolveLValue (ec, temp_storage);
771 } else if (expr.eclass == ExprClass.PropertyAccess){
772 PropertyExpr pe = (PropertyExpr) expr;
774 if (pe.VerifyAssignable ())
779 expr.Error118 ("variable, indexer or property access");
783 Error (187, "No such operator '" + OperName (mode) + "' defined for type '" +
784 TypeManager.CSharpName (expr_type) + "'");
788 public override Expression DoResolve (EmitContext ec)
790 expr = expr.Resolve (ec);
795 eclass = ExprClass.Value;
796 return ResolveOperator (ec);
799 static int PtrTypeSize (Type t)
801 return GetTypeSize (t.GetElementType ());
805 // Loads the proper "1" into the stack based on the type
807 static void LoadOne (ILGenerator ig, Type t)
809 if (t == TypeManager.uint64_type || t == TypeManager.int64_type)
810 ig.Emit (OpCodes.Ldc_I8, 1L);
811 else if (t == TypeManager.double_type)
812 ig.Emit (OpCodes.Ldc_R8, 1.0);
813 else if (t == TypeManager.float_type)
814 ig.Emit (OpCodes.Ldc_R4, 1.0F);
815 else if (t.IsPointer){
816 int n = PtrTypeSize (t);
819 ig.Emit (OpCodes.Sizeof, t);
821 IntConstant.EmitInt (ig, n);
823 ig.Emit (OpCodes.Ldc_I4_1);
828 // FIXME: We need some way of avoiding the use of temp_storage
829 // for some types of storage (parameters, local variables,
830 // static fields) and single-dimension array access.
832 void EmitCode (EmitContext ec, bool is_expr)
834 ILGenerator ig = ec.ig;
835 IAssignMethod ia = (IAssignMethod) expr;
836 Type expr_type = expr.Type;
838 if (temp_storage == null)
839 temp_storage = new LocalTemporary (ec, expr_type);
841 ia.CacheTemporaries (ec);
842 ig.Emit (OpCodes.Nop);
844 case Mode.PreIncrement:
845 case Mode.PreDecrement:
849 LoadOne (ig, expr_type);
852 // Select the opcode based on the check state (then the type)
853 // and the actual operation
856 if (expr_type == TypeManager.int32_type ||
857 expr_type == TypeManager.int64_type){
858 if (mode == Mode.PreDecrement)
859 ig.Emit (OpCodes.Sub_Ovf);
861 ig.Emit (OpCodes.Add_Ovf);
862 } else if (expr_type == TypeManager.uint32_type ||
863 expr_type == TypeManager.uint64_type){
864 if (mode == Mode.PreDecrement)
865 ig.Emit (OpCodes.Sub_Ovf_Un);
867 ig.Emit (OpCodes.Add_Ovf_Un);
869 if (mode == Mode.PreDecrement)
870 ig.Emit (OpCodes.Sub_Ovf);
872 ig.Emit (OpCodes.Add_Ovf);
875 if (mode == Mode.PreDecrement)
876 ig.Emit (OpCodes.Sub);
878 ig.Emit (OpCodes.Add);
883 temp_storage.Store (ec);
884 ia.EmitAssign (ec, temp_storage);
886 temp_storage.Emit (ec);
889 case Mode.PostIncrement:
890 case Mode.PostDecrement:
898 ig.Emit (OpCodes.Dup);
900 LoadOne (ig, expr_type);
903 if (expr_type == TypeManager.int32_type ||
904 expr_type == TypeManager.int64_type){
905 if (mode == Mode.PostDecrement)
906 ig.Emit (OpCodes.Sub_Ovf);
908 ig.Emit (OpCodes.Add_Ovf);
909 } else if (expr_type == TypeManager.uint32_type ||
910 expr_type == TypeManager.uint64_type){
911 if (mode == Mode.PostDecrement)
912 ig.Emit (OpCodes.Sub_Ovf_Un);
914 ig.Emit (OpCodes.Add_Ovf_Un);
916 if (mode == Mode.PostDecrement)
917 ig.Emit (OpCodes.Sub_Ovf);
919 ig.Emit (OpCodes.Add_Ovf);
922 if (mode == Mode.PostDecrement)
923 ig.Emit (OpCodes.Sub);
925 ig.Emit (OpCodes.Add);
931 temp_storage.Store (ec);
932 ia.EmitAssign (ec, temp_storage);
937 public override void Emit (EmitContext ec)
943 public override void EmitStatement (EmitContext ec)
945 EmitCode (ec, false);
951 /// Base class for the `Is' and `As' classes.
955 /// FIXME: Split this in two, and we get to save the `Operator' Oper
958 public abstract class Probe : Expression {
959 public readonly Expression ProbeType;
960 protected Expression expr;
961 protected Type probe_type;
963 public Probe (Expression expr, Expression probe_type, Location l)
965 ProbeType = probe_type;
970 public Expression Expr {
976 public override Expression DoResolve (EmitContext ec)
978 probe_type = ec.DeclSpace.ResolveType (ProbeType, false, loc);
980 if (probe_type == null)
983 expr = expr.Resolve (ec);
990 /// Implementation of the `is' operator.
992 public class Is : Probe {
993 public Is (Expression expr, Expression probe_type, Location l)
994 : base (expr, probe_type, l)
999 AlwaysTrue, AlwaysNull, AlwaysFalse, LeaveOnStack, Probe
1004 public override void Emit (EmitContext ec)
1006 ILGenerator ig = ec.ig;
1011 case Action.AlwaysFalse:
1012 ig.Emit (OpCodes.Pop);
1013 IntConstant.EmitInt (ig, 0);
1015 case Action.AlwaysTrue:
1016 ig.Emit (OpCodes.Pop);
1017 ig.Emit (OpCodes.Nop);
1018 IntConstant.EmitInt (ig, 1);
1020 case Action.LeaveOnStack:
1021 // the `e != null' rule.
1024 ig.Emit (OpCodes.Isinst, probe_type);
1025 ig.Emit (OpCodes.Ldnull);
1026 ig.Emit (OpCodes.Cgt_Un);
1029 throw new Exception ("never reached");
1032 public override Expression DoResolve (EmitContext ec)
1034 Expression e = base.DoResolve (ec);
1036 if ((e == null) || (expr == null))
1039 Type etype = expr.Type;
1040 bool warning_always_matches = false;
1041 bool warning_never_matches = false;
1043 type = TypeManager.bool_type;
1044 eclass = ExprClass.Value;
1047 // First case, if at compile time, there is an implicit conversion
1048 // then e != null (objects) or true (value types)
1050 e = ConvertImplicitStandard (ec, expr, probe_type, loc);
1053 if (etype.IsValueType)
1054 action = Action.AlwaysTrue;
1056 action = Action.LeaveOnStack;
1058 warning_always_matches = true;
1059 } else if (ExplicitReferenceConversionExists (etype, probe_type)){
1061 // Second case: explicit reference convresion
1063 if (expr is NullLiteral)
1064 action = Action.AlwaysFalse;
1066 action = Action.Probe;
1068 action = Action.AlwaysFalse;
1069 warning_never_matches = true;
1072 if (RootContext.WarningLevel >= 1){
1073 if (warning_always_matches)
1076 "The expression is always of type `" +
1077 TypeManager.CSharpName (probe_type) + "'");
1078 else if (warning_never_matches){
1079 if (!(probe_type.IsInterface || expr.Type.IsInterface))
1082 "The expression is never of type `" +
1083 TypeManager.CSharpName (probe_type) + "'");
1092 /// Implementation of the `as' operator.
1094 public class As : Probe {
1095 public As (Expression expr, Expression probe_type, Location l)
1096 : base (expr, probe_type, l)
1100 bool do_isinst = false;
1102 public override void Emit (EmitContext ec)
1104 ILGenerator ig = ec.ig;
1109 ig.Emit (OpCodes.Isinst, probe_type);
1112 static void Error_CannotConvertType (Type source, Type target, Location loc)
1115 39, loc, "as operator can not convert from `" +
1116 TypeManager.CSharpName (source) + "' to `" +
1117 TypeManager.CSharpName (target) + "'");
1120 public override Expression DoResolve (EmitContext ec)
1122 Expression e = base.DoResolve (ec);
1128 eclass = ExprClass.Value;
1129 Type etype = expr.Type;
1131 e = ConvertImplicit (ec, expr, probe_type, loc);
1138 if (ExplicitReferenceConversionExists (etype, probe_type)){
1143 Error_CannotConvertType (etype, probe_type, loc);
1149 /// This represents a typecast in the source language.
1151 /// FIXME: Cast expressions have an unusual set of parsing
1152 /// rules, we need to figure those out.
1154 public class Cast : Expression {
1155 Expression target_type;
1158 public Cast (Expression cast_type, Expression expr, Location loc)
1160 this.target_type = cast_type;
1165 public Expression TargetType {
1171 public Expression Expr {
1181 /// Attempts to do a compile-time folding of a constant cast.
1183 Expression TryReduce (EmitContext ec, Type target_type)
1185 if (expr is ByteConstant){
1186 byte v = ((ByteConstant) expr).Value;
1188 if (target_type == TypeManager.sbyte_type)
1189 return new SByteConstant ((sbyte) v);
1190 if (target_type == TypeManager.short_type)
1191 return new ShortConstant ((short) v);
1192 if (target_type == TypeManager.ushort_type)
1193 return new UShortConstant ((ushort) v);
1194 if (target_type == TypeManager.int32_type)
1195 return new IntConstant ((int) v);
1196 if (target_type == TypeManager.uint32_type)
1197 return new UIntConstant ((uint) v);
1198 if (target_type == TypeManager.int64_type)
1199 return new LongConstant ((long) v);
1200 if (target_type == TypeManager.uint64_type)
1201 return new ULongConstant ((ulong) v);
1202 if (target_type == TypeManager.float_type)
1203 return new FloatConstant ((float) v);
1204 if (target_type == TypeManager.double_type)
1205 return new DoubleConstant ((double) v);
1206 if (target_type == TypeManager.char_type)
1207 return new CharConstant ((char) v);
1208 if (target_type == TypeManager.decimal_type)
1209 return new DecimalConstant ((decimal) v);
1211 if (expr is SByteConstant){
1212 sbyte v = ((SByteConstant) expr).Value;
1214 if (target_type == TypeManager.byte_type)
1215 return new ByteConstant ((byte) v);
1216 if (target_type == TypeManager.short_type)
1217 return new ShortConstant ((short) v);
1218 if (target_type == TypeManager.ushort_type)
1219 return new UShortConstant ((ushort) v);
1220 if (target_type == TypeManager.int32_type)
1221 return new IntConstant ((int) v);
1222 if (target_type == TypeManager.uint32_type)
1223 return new UIntConstant ((uint) v);
1224 if (target_type == TypeManager.int64_type)
1225 return new LongConstant ((long) v);
1226 if (target_type == TypeManager.uint64_type)
1227 return new ULongConstant ((ulong) v);
1228 if (target_type == TypeManager.float_type)
1229 return new FloatConstant ((float) v);
1230 if (target_type == TypeManager.double_type)
1231 return new DoubleConstant ((double) v);
1232 if (target_type == TypeManager.char_type)
1233 return new CharConstant ((char) v);
1234 if (target_type == TypeManager.decimal_type)
1235 return new DecimalConstant ((decimal) v);
1237 if (expr is ShortConstant){
1238 short v = ((ShortConstant) expr).Value;
1240 if (target_type == TypeManager.byte_type)
1241 return new ByteConstant ((byte) v);
1242 if (target_type == TypeManager.sbyte_type)
1243 return new SByteConstant ((sbyte) v);
1244 if (target_type == TypeManager.ushort_type)
1245 return new UShortConstant ((ushort) v);
1246 if (target_type == TypeManager.int32_type)
1247 return new IntConstant ((int) v);
1248 if (target_type == TypeManager.uint32_type)
1249 return new UIntConstant ((uint) v);
1250 if (target_type == TypeManager.int64_type)
1251 return new LongConstant ((long) v);
1252 if (target_type == TypeManager.uint64_type)
1253 return new ULongConstant ((ulong) v);
1254 if (target_type == TypeManager.float_type)
1255 return new FloatConstant ((float) v);
1256 if (target_type == TypeManager.double_type)
1257 return new DoubleConstant ((double) v);
1258 if (target_type == TypeManager.char_type)
1259 return new CharConstant ((char) v);
1260 if (target_type == TypeManager.decimal_type)
1261 return new DecimalConstant ((decimal) v);
1263 if (expr is UShortConstant){
1264 ushort v = ((UShortConstant) expr).Value;
1266 if (target_type == TypeManager.byte_type)
1267 return new ByteConstant ((byte) v);
1268 if (target_type == TypeManager.sbyte_type)
1269 return new SByteConstant ((sbyte) v);
1270 if (target_type == TypeManager.short_type)
1271 return new ShortConstant ((short) v);
1272 if (target_type == TypeManager.int32_type)
1273 return new IntConstant ((int) v);
1274 if (target_type == TypeManager.uint32_type)
1275 return new UIntConstant ((uint) v);
1276 if (target_type == TypeManager.int64_type)
1277 return new LongConstant ((long) v);
1278 if (target_type == TypeManager.uint64_type)
1279 return new ULongConstant ((ulong) v);
1280 if (target_type == TypeManager.float_type)
1281 return new FloatConstant ((float) v);
1282 if (target_type == TypeManager.double_type)
1283 return new DoubleConstant ((double) v);
1284 if (target_type == TypeManager.char_type)
1285 return new CharConstant ((char) v);
1286 if (target_type == TypeManager.decimal_type)
1287 return new DecimalConstant ((decimal) v);
1289 if (expr is IntConstant){
1290 int v = ((IntConstant) expr).Value;
1292 if (target_type == TypeManager.byte_type)
1293 return new ByteConstant ((byte) v);
1294 if (target_type == TypeManager.sbyte_type)
1295 return new SByteConstant ((sbyte) v);
1296 if (target_type == TypeManager.short_type)
1297 return new ShortConstant ((short) v);
1298 if (target_type == TypeManager.ushort_type)
1299 return new UShortConstant ((ushort) v);
1300 if (target_type == TypeManager.uint32_type)
1301 return new UIntConstant ((uint) v);
1302 if (target_type == TypeManager.int64_type)
1303 return new LongConstant ((long) v);
1304 if (target_type == TypeManager.uint64_type)
1305 return new ULongConstant ((ulong) v);
1306 if (target_type == TypeManager.float_type)
1307 return new FloatConstant ((float) v);
1308 if (target_type == TypeManager.double_type)
1309 return new DoubleConstant ((double) v);
1310 if (target_type == TypeManager.char_type)
1311 return new CharConstant ((char) v);
1312 if (target_type == TypeManager.decimal_type)
1313 return new DecimalConstant ((decimal) v);
1315 if (expr is UIntConstant){
1316 uint v = ((UIntConstant) expr).Value;
1318 if (target_type == TypeManager.byte_type)
1319 return new ByteConstant ((byte) v);
1320 if (target_type == TypeManager.sbyte_type)
1321 return new SByteConstant ((sbyte) v);
1322 if (target_type == TypeManager.short_type)
1323 return new ShortConstant ((short) v);
1324 if (target_type == TypeManager.ushort_type)
1325 return new UShortConstant ((ushort) v);
1326 if (target_type == TypeManager.int32_type)
1327 return new IntConstant ((int) v);
1328 if (target_type == TypeManager.int64_type)
1329 return new LongConstant ((long) v);
1330 if (target_type == TypeManager.uint64_type)
1331 return new ULongConstant ((ulong) v);
1332 if (target_type == TypeManager.float_type)
1333 return new FloatConstant ((float) v);
1334 if (target_type == TypeManager.double_type)
1335 return new DoubleConstant ((double) v);
1336 if (target_type == TypeManager.char_type)
1337 return new CharConstant ((char) v);
1338 if (target_type == TypeManager.decimal_type)
1339 return new DecimalConstant ((decimal) v);
1341 if (expr is LongConstant){
1342 long v = ((LongConstant) expr).Value;
1344 if (target_type == TypeManager.byte_type)
1345 return new ByteConstant ((byte) v);
1346 if (target_type == TypeManager.sbyte_type)
1347 return new SByteConstant ((sbyte) v);
1348 if (target_type == TypeManager.short_type)
1349 return new ShortConstant ((short) v);
1350 if (target_type == TypeManager.ushort_type)
1351 return new UShortConstant ((ushort) v);
1352 if (target_type == TypeManager.int32_type)
1353 return new IntConstant ((int) v);
1354 if (target_type == TypeManager.uint32_type)
1355 return new UIntConstant ((uint) v);
1356 if (target_type == TypeManager.uint64_type)
1357 return new ULongConstant ((ulong) v);
1358 if (target_type == TypeManager.float_type)
1359 return new FloatConstant ((float) v);
1360 if (target_type == TypeManager.double_type)
1361 return new DoubleConstant ((double) v);
1362 if (target_type == TypeManager.char_type)
1363 return new CharConstant ((char) v);
1364 if (target_type == TypeManager.decimal_type)
1365 return new DecimalConstant ((decimal) v);
1367 if (expr is ULongConstant){
1368 ulong v = ((ULongConstant) expr).Value;
1370 if (target_type == TypeManager.byte_type)
1371 return new ByteConstant ((byte) v);
1372 if (target_type == TypeManager.sbyte_type)
1373 return new SByteConstant ((sbyte) v);
1374 if (target_type == TypeManager.short_type)
1375 return new ShortConstant ((short) v);
1376 if (target_type == TypeManager.ushort_type)
1377 return new UShortConstant ((ushort) v);
1378 if (target_type == TypeManager.int32_type)
1379 return new IntConstant ((int) v);
1380 if (target_type == TypeManager.uint32_type)
1381 return new UIntConstant ((uint) v);
1382 if (target_type == TypeManager.int64_type)
1383 return new LongConstant ((long) v);
1384 if (target_type == TypeManager.float_type)
1385 return new FloatConstant ((float) v);
1386 if (target_type == TypeManager.double_type)
1387 return new DoubleConstant ((double) v);
1388 if (target_type == TypeManager.char_type)
1389 return new CharConstant ((char) v);
1390 if (target_type == TypeManager.decimal_type)
1391 return new DecimalConstant ((decimal) v);
1393 if (expr is FloatConstant){
1394 float v = ((FloatConstant) expr).Value;
1396 if (target_type == TypeManager.byte_type)
1397 return new ByteConstant ((byte) v);
1398 if (target_type == TypeManager.sbyte_type)
1399 return new SByteConstant ((sbyte) v);
1400 if (target_type == TypeManager.short_type)
1401 return new ShortConstant ((short) v);
1402 if (target_type == TypeManager.ushort_type)
1403 return new UShortConstant ((ushort) v);
1404 if (target_type == TypeManager.int32_type)
1405 return new IntConstant ((int) v);
1406 if (target_type == TypeManager.uint32_type)
1407 return new UIntConstant ((uint) v);
1408 if (target_type == TypeManager.int64_type)
1409 return new LongConstant ((long) v);
1410 if (target_type == TypeManager.uint64_type)
1411 return new ULongConstant ((ulong) v);
1412 if (target_type == TypeManager.double_type)
1413 return new DoubleConstant ((double) v);
1414 if (target_type == TypeManager.char_type)
1415 return new CharConstant ((char) v);
1416 if (target_type == TypeManager.decimal_type)
1417 return new DecimalConstant ((decimal) v);
1419 if (expr is DoubleConstant){
1420 double v = ((DoubleConstant) expr).Value;
1422 if (target_type == TypeManager.byte_type)
1423 return new ByteConstant ((byte) v);
1424 if (target_type == TypeManager.sbyte_type)
1425 return new SByteConstant ((sbyte) v);
1426 if (target_type == TypeManager.short_type)
1427 return new ShortConstant ((short) v);
1428 if (target_type == TypeManager.ushort_type)
1429 return new UShortConstant ((ushort) v);
1430 if (target_type == TypeManager.int32_type)
1431 return new IntConstant ((int) v);
1432 if (target_type == TypeManager.uint32_type)
1433 return new UIntConstant ((uint) v);
1434 if (target_type == TypeManager.int64_type)
1435 return new LongConstant ((long) v);
1436 if (target_type == TypeManager.uint64_type)
1437 return new ULongConstant ((ulong) v);
1438 if (target_type == TypeManager.float_type)
1439 return new FloatConstant ((float) v);
1440 if (target_type == TypeManager.char_type)
1441 return new CharConstant ((char) v);
1442 if (target_type == TypeManager.decimal_type)
1443 return new DecimalConstant ((decimal) v);
1449 public override Expression DoResolve (EmitContext ec)
1451 expr = expr.Resolve (ec);
1455 int errors = Report.Errors;
1457 type = ec.DeclSpace.ResolveType (target_type, false, Location);
1462 eclass = ExprClass.Value;
1464 if (expr is Constant){
1465 Expression e = TryReduce (ec, type);
1471 expr = ConvertExplicit (ec, expr, type, loc);
1475 public override void Emit (EmitContext ec)
1478 // This one will never happen
1480 throw new Exception ("Should not happen");
1485 /// Binary operators
1487 public class Binary : Expression {
1488 public enum Operator : byte {
1489 Multiply, Division, Modulus,
1490 Addition, Subtraction,
1491 LeftShift, RightShift,
1492 LessThan, GreaterThan, LessThanOrEqual, GreaterThanOrEqual,
1493 Equality, Inequality,
1503 Expression left, right;
1506 // After resolution, method might contain the operator overload
1509 protected MethodBase method;
1510 ArrayList Arguments;
1512 bool DelegateOperation;
1514 // This must be kept in sync with Operator!!!
1515 static string [] oper_names;
1519 oper_names = new string [(int) Operator.TOP];
1521 oper_names [(int) Operator.Multiply] = "op_Multiply";
1522 oper_names [(int) Operator.Division] = "op_Division";
1523 oper_names [(int) Operator.Modulus] = "op_Modulus";
1524 oper_names [(int) Operator.Addition] = "op_Addition";
1525 oper_names [(int) Operator.Subtraction] = "op_Subtraction";
1526 oper_names [(int) Operator.LeftShift] = "op_LeftShift";
1527 oper_names [(int) Operator.RightShift] = "op_RightShift";
1528 oper_names [(int) Operator.LessThan] = "op_LessThan";
1529 oper_names [(int) Operator.GreaterThan] = "op_GreaterThan";
1530 oper_names [(int) Operator.LessThanOrEqual] = "op_LessThanOrEqual";
1531 oper_names [(int) Operator.GreaterThanOrEqual] = "op_GreaterThanOrEqual";
1532 oper_names [(int) Operator.Equality] = "op_Equality";
1533 oper_names [(int) Operator.Inequality] = "op_Inequality";
1534 oper_names [(int) Operator.BitwiseAnd] = "op_BitwiseAnd";
1535 oper_names [(int) Operator.BitwiseOr] = "op_BitwiseOr";
1536 oper_names [(int) Operator.ExclusiveOr] = "op_ExclusiveOr";
1537 oper_names [(int) Operator.LogicalOr] = "op_LogicalOr";
1538 oper_names [(int) Operator.LogicalAnd] = "op_LogicalAnd";
1541 public Binary (Operator oper, Expression left, Expression right, Location loc)
1549 public Operator Oper {
1558 public Expression Left {
1567 public Expression Right {
1578 /// Returns a stringified representation of the Operator
1580 static string OperName (Operator oper)
1583 case Operator.Multiply:
1585 case Operator.Division:
1587 case Operator.Modulus:
1589 case Operator.Addition:
1591 case Operator.Subtraction:
1593 case Operator.LeftShift:
1595 case Operator.RightShift:
1597 case Operator.LessThan:
1599 case Operator.GreaterThan:
1601 case Operator.LessThanOrEqual:
1603 case Operator.GreaterThanOrEqual:
1605 case Operator.Equality:
1607 case Operator.Inequality:
1609 case Operator.BitwiseAnd:
1611 case Operator.BitwiseOr:
1613 case Operator.ExclusiveOr:
1615 case Operator.LogicalOr:
1617 case Operator.LogicalAnd:
1621 return oper.ToString ();
1624 public override string ToString ()
1626 return "operator " + OperName (oper) + "(" + left.ToString () + ", " +
1627 right.ToString () + ")";
1630 Expression ForceConversion (EmitContext ec, Expression expr, Type target_type)
1632 if (expr.Type == target_type)
1635 return ConvertImplicit (ec, expr, target_type, new Location (-1));
1638 public static void Error_OperatorAmbiguous (Location loc, Operator oper, Type l, Type r)
1641 34, loc, "Operator `" + OperName (oper)
1642 + "' is ambiguous on operands of type `"
1643 + TypeManager.CSharpName (l) + "' "
1644 + "and `" + TypeManager.CSharpName (r)
1649 // Note that handling the case l == Decimal || r == Decimal
1650 // is taken care of by the Step 1 Operator Overload resolution.
1652 bool DoNumericPromotions (EmitContext ec, Type l, Type r)
1654 if (l == TypeManager.double_type || r == TypeManager.double_type){
1656 // If either operand is of type double, the other operand is
1657 // conveted to type double.
1659 if (r != TypeManager.double_type)
1660 right = ConvertImplicit (ec, right, TypeManager.double_type, loc);
1661 if (l != TypeManager.double_type)
1662 left = ConvertImplicit (ec, left, TypeManager.double_type, loc);
1664 type = TypeManager.double_type;
1665 } else if (l == TypeManager.float_type || r == TypeManager.float_type){
1667 // if either operand is of type float, the other operand is
1668 // converted to type float.
1670 if (r != TypeManager.double_type)
1671 right = ConvertImplicit (ec, right, TypeManager.float_type, loc);
1672 if (l != TypeManager.double_type)
1673 left = ConvertImplicit (ec, left, TypeManager.float_type, loc);
1674 type = TypeManager.float_type;
1675 } else if (l == TypeManager.uint64_type || r == TypeManager.uint64_type){
1679 // If either operand is of type ulong, the other operand is
1680 // converted to type ulong. or an error ocurrs if the other
1681 // operand is of type sbyte, short, int or long
1683 if (l == TypeManager.uint64_type){
1684 if (r != TypeManager.uint64_type){
1685 if (right is IntConstant){
1686 IntConstant ic = (IntConstant) right;
1688 e = TryImplicitIntConversion (l, ic);
1691 } else if (right is LongConstant){
1692 long ll = ((LongConstant) right).Value;
1695 right = new ULongConstant ((ulong) ll);
1697 e = ImplicitNumericConversion (ec, right, l, loc);
1704 if (left is IntConstant){
1705 e = TryImplicitIntConversion (r, (IntConstant) left);
1708 } else if (left is LongConstant){
1709 long ll = ((LongConstant) left).Value;
1712 left = new ULongConstant ((ulong) ll);
1714 e = ImplicitNumericConversion (ec, left, r, loc);
1721 if ((other == TypeManager.sbyte_type) ||
1722 (other == TypeManager.short_type) ||
1723 (other == TypeManager.int32_type) ||
1724 (other == TypeManager.int64_type))
1725 Error_OperatorAmbiguous (loc, oper, l, r);
1726 type = TypeManager.uint64_type;
1727 } else if (l == TypeManager.int64_type || r == TypeManager.int64_type){
1729 // If either operand is of type long, the other operand is converted
1732 if (l != TypeManager.int64_type)
1733 left = ConvertImplicit (ec, left, TypeManager.int64_type, loc);
1734 if (r != TypeManager.int64_type)
1735 right = ConvertImplicit (ec, right, TypeManager.int64_type, loc);
1737 type = TypeManager.int64_type;
1738 } else if (l == TypeManager.uint32_type || r == TypeManager.uint32_type){
1740 // If either operand is of type uint, and the other
1741 // operand is of type sbyte, short or int, othe operands are
1742 // converted to type long.
1746 if (l == TypeManager.uint32_type){
1747 if (right is IntConstant){
1748 IntConstant ic = (IntConstant) right;
1752 right = new UIntConstant ((uint) val);
1759 else if (r == TypeManager.uint32_type){
1760 if (left is IntConstant){
1761 IntConstant ic = (IntConstant) left;
1765 left = new UIntConstant ((uint) val);
1774 if ((other == TypeManager.sbyte_type) ||
1775 (other == TypeManager.short_type) ||
1776 (other == TypeManager.int32_type)){
1777 left = ForceConversion (ec, left, TypeManager.int64_type);
1778 right = ForceConversion (ec, right, TypeManager.int64_type);
1779 type = TypeManager.int64_type;
1782 // if either operand is of type uint, the other
1783 // operand is converd to type uint
1785 left = ForceConversion (ec, left, TypeManager.uint32_type);
1786 right = ForceConversion (ec, right, TypeManager.uint32_type);
1787 type = TypeManager.uint32_type;
1789 } else if (l == TypeManager.decimal_type || r == TypeManager.decimal_type){
1792 if (l != TypeManager.decimal_type)
1793 left = ConvertImplicit (ec, left, TypeManager.decimal_type, loc);
1795 if (r != TypeManager.decimal_type)
1796 right = ConvertImplicit (ec, right, TypeManager.decimal_type, loc);
1797 type = TypeManager.decimal_type;
1799 Expression l_tmp, r_tmp;
1801 left = ForceConversion (ec, left, TypeManager.int32_type);
1802 right = ForceConversion (ec, right, TypeManager.int32_type);
1804 type = TypeManager.int32_type;
1807 return (left != null) && (right != null);
1810 static public void Error_OperatorCannotBeApplied (Location loc, string name, Type l, Type r)
1812 Report.Error (19, loc,
1813 "Operator " + name + " cannot be applied to operands of type `" +
1814 TypeManager.CSharpName (l) + "' and `" +
1815 TypeManager.CSharpName (r) + "'");
1818 void Error_OperatorCannotBeApplied ()
1820 Error_OperatorCannotBeApplied (loc, OperName (oper), left.Type, right.Type);
1823 static bool is_32_or_64 (Type t)
1825 return (t == TypeManager.int32_type || t == TypeManager.uint32_type ||
1826 t == TypeManager.int64_type || t == TypeManager.uint64_type);
1829 static bool is_unsigned (Type t)
1831 return (t == TypeManager.uint32_type || t == TypeManager.uint64_type ||
1832 t == TypeManager.short_type || t == TypeManager.byte_type);
1835 Expression CheckShiftArguments (EmitContext ec)
1839 Type r = right.Type;
1841 e = ForceConversion (ec, right, TypeManager.int32_type);
1843 Error_OperatorCannotBeApplied ();
1848 if (((e = ConvertImplicit (ec, left, TypeManager.int32_type, loc)) != null) ||
1849 ((e = ConvertImplicit (ec, left, TypeManager.uint32_type, loc)) != null) ||
1850 ((e = ConvertImplicit (ec, left, TypeManager.int64_type, loc)) != null) ||
1851 ((e = ConvertImplicit (ec, left, TypeManager.uint64_type, loc)) != null)){
1857 Error_OperatorCannotBeApplied ();
1861 Expression ResolveOperator (EmitContext ec)
1864 Type r = right.Type;
1866 bool overload_failed = false;
1869 // Step 1: Perform Operator Overload location
1871 Expression left_expr, right_expr;
1873 string op = oper_names [(int) oper];
1875 MethodGroupExpr union;
1876 left_expr = MemberLookup (ec, l, op, MemberTypes.Method, AllBindingFlags, loc);
1878 right_expr = MemberLookup (
1879 ec, r, op, MemberTypes.Method, AllBindingFlags, loc);
1880 union = Invocation.MakeUnionSet (left_expr, right_expr, loc);
1882 union = (MethodGroupExpr) left_expr;
1884 if (union != null) {
1885 Arguments = new ArrayList ();
1886 Arguments.Add (new Argument (left, Argument.AType.Expression));
1887 Arguments.Add (new Argument (right, Argument.AType.Expression));
1889 method = Invocation.OverloadResolve (ec, union, Arguments, Location.Null);
1890 if (method != null) {
1891 MethodInfo mi = (MethodInfo) method;
1893 type = mi.ReturnType;
1896 overload_failed = true;
1901 // Step 2: Default operations on CLI native types.
1905 // Step 0: String concatenation (because overloading will get this wrong)
1907 if (oper == Operator.Addition){
1909 // If any of the arguments is a string, cast to string
1912 if (l == TypeManager.string_type){
1914 if (r == TypeManager.void_type) {
1915 Error_OperatorCannotBeApplied ();
1919 if (r == TypeManager.string_type){
1920 if (left is Constant && right is Constant){
1921 StringConstant ls = (StringConstant) left;
1922 StringConstant rs = (StringConstant) right;
1924 return new StringConstant (
1925 ls.Value + rs.Value);
1929 method = TypeManager.string_concat_string_string;
1932 method = TypeManager.string_concat_object_object;
1933 right = ConvertImplicit (ec, right,
1934 TypeManager.object_type, loc);
1936 type = TypeManager.string_type;
1938 Arguments = new ArrayList ();
1939 Arguments.Add (new Argument (left, Argument.AType.Expression));
1940 Arguments.Add (new Argument (right, Argument.AType.Expression));
1944 } else if (r == TypeManager.string_type){
1947 if (l == TypeManager.void_type) {
1948 Error_OperatorCannotBeApplied ();
1952 method = TypeManager.string_concat_object_object;
1953 left = ConvertImplicit (ec, left, TypeManager.object_type, loc);
1954 Arguments = new ArrayList ();
1955 Arguments.Add (new Argument (left, Argument.AType.Expression));
1956 Arguments.Add (new Argument (right, Argument.AType.Expression));
1958 type = TypeManager.string_type;
1964 // Transform a + ( - b) into a - b
1966 if (right is Unary){
1967 Unary right_unary = (Unary) right;
1969 if (right_unary.Oper == Unary.Operator.UnaryNegation){
1970 oper = Operator.Subtraction;
1971 right = right_unary.Expr;
1977 if (oper == Operator.Equality || oper == Operator.Inequality){
1978 if (l == TypeManager.bool_type || r == TypeManager.bool_type){
1979 if (r != TypeManager.bool_type || l != TypeManager.bool_type){
1980 Error_OperatorCannotBeApplied ();
1984 type = TypeManager.bool_type;
1989 // operator != (object a, object b)
1990 // operator == (object a, object b)
1992 // For this to be used, both arguments have to be reference-types.
1993 // Read the rationale on the spec (14.9.6)
1995 // Also, if at compile time we know that the classes do not inherit
1996 // one from the other, then we catch the error there.
1998 if (!(l.IsValueType || r.IsValueType)){
1999 type = TypeManager.bool_type;
2004 if (l.IsSubclassOf (r) || r.IsSubclassOf (l))
2008 // Also, a standard conversion must exist from either one
2010 if (!(StandardConversionExists (left, r) ||
2011 StandardConversionExists (right, l))){
2012 Error_OperatorCannotBeApplied ();
2016 // We are going to have to convert to an object to compare
2018 if (l != TypeManager.object_type)
2019 left = new EmptyCast (left, TypeManager.object_type);
2020 if (r != TypeManager.object_type)
2021 right = new EmptyCast (right, TypeManager.object_type);
2024 // FIXME: CSC here catches errors cs254 and cs252
2030 // One of them is a valuetype, but the other one is not.
2032 if (!l.IsValueType || !r.IsValueType) {
2033 Error_OperatorCannotBeApplied ();
2038 // Only perform numeric promotions on:
2039 // +, -, *, /, %, &, |, ^, ==, !=, <, >, <=, >=
2041 if (oper == Operator.Addition || oper == Operator.Subtraction) {
2042 if (l.IsSubclassOf (TypeManager.delegate_type) &&
2043 r.IsSubclassOf (TypeManager.delegate_type)) {
2045 Arguments = new ArrayList ();
2046 Arguments.Add (new Argument (left, Argument.AType.Expression));
2047 Arguments.Add (new Argument (right, Argument.AType.Expression));
2049 if (oper == Operator.Addition)
2050 method = TypeManager.delegate_combine_delegate_delegate;
2052 method = TypeManager.delegate_remove_delegate_delegate;
2055 Error_OperatorCannotBeApplied ();
2059 DelegateOperation = true;
2065 // Pointer arithmetic:
2067 // T* operator + (T* x, int y);
2068 // T* operator + (T* x, uint y);
2069 // T* operator + (T* x, long y);
2070 // T* operator + (T* x, ulong y);
2072 // T* operator + (int y, T* x);
2073 // T* operator + (uint y, T *x);
2074 // T* operator + (long y, T *x);
2075 // T* operator + (ulong y, T *x);
2077 // T* operator - (T* x, int y);
2078 // T* operator - (T* x, uint y);
2079 // T* operator - (T* x, long y);
2080 // T* operator - (T* x, ulong y);
2082 // long operator - (T* x, T *y)
2085 if (r.IsPointer && oper == Operator.Subtraction){
2087 return new PointerArithmetic (
2088 false, left, right, TypeManager.int64_type,
2090 } else if (is_32_or_64 (r))
2091 return new PointerArithmetic (
2092 oper == Operator.Addition, left, right, l, loc);
2093 } else if (r.IsPointer && is_32_or_64 (l) && oper == Operator.Addition)
2094 return new PointerArithmetic (
2095 true, right, left, r, loc);
2099 // Enumeration operators
2101 bool lie = TypeManager.IsEnumType (l);
2102 bool rie = TypeManager.IsEnumType (r);
2107 // operator + (E e, U x)
2109 if (oper == Operator.Addition){
2111 Error_OperatorCannotBeApplied ();
2115 Type enum_type = lie ? l : r;
2116 Type other_type = lie ? r : l;
2117 Type underlying_type = TypeManager.EnumToUnderlying (enum_type);
2120 if (underlying_type != other_type){
2121 Error_OperatorCannotBeApplied ();
2130 temp = ConvertImplicit (ec, right, l, loc);
2134 Error_OperatorCannotBeApplied ();
2138 temp = ConvertImplicit (ec, left, r, loc);
2143 Error_OperatorCannotBeApplied ();
2148 if (oper == Operator.Equality || oper == Operator.Inequality ||
2149 oper == Operator.LessThanOrEqual || oper == Operator.LessThan ||
2150 oper == Operator.GreaterThanOrEqual || oper == Operator.GreaterThan){
2151 type = TypeManager.bool_type;
2155 if (oper == Operator.BitwiseAnd ||
2156 oper == Operator.BitwiseOr ||
2157 oper == Operator.ExclusiveOr){
2161 Error_OperatorCannotBeApplied ();
2165 if (oper == Operator.LeftShift || oper == Operator.RightShift)
2166 return CheckShiftArguments (ec);
2168 if (oper == Operator.LogicalOr || oper == Operator.LogicalAnd){
2169 if (l != TypeManager.bool_type || r != TypeManager.bool_type){
2170 Error_OperatorCannotBeApplied ();
2174 type = TypeManager.bool_type;
2179 // operator & (bool x, bool y)
2180 // operator | (bool x, bool y)
2181 // operator ^ (bool x, bool y)
2183 if (l == TypeManager.bool_type && r == TypeManager.bool_type){
2184 if (oper == Operator.BitwiseAnd ||
2185 oper == Operator.BitwiseOr ||
2186 oper == Operator.ExclusiveOr){
2193 // Pointer comparison
2195 if (l.IsPointer && r.IsPointer){
2196 if (oper == Operator.Equality || oper == Operator.Inequality ||
2197 oper == Operator.LessThan || oper == Operator.LessThanOrEqual ||
2198 oper == Operator.GreaterThan || oper == Operator.GreaterThanOrEqual){
2199 type = TypeManager.bool_type;
2205 // We are dealing with numbers
2207 if (overload_failed){
2208 Error_OperatorCannotBeApplied ();
2213 // This will leave left or right set to null if there is an error
2215 DoNumericPromotions (ec, l, r);
2216 if (left == null || right == null){
2217 Error_OperatorCannotBeApplied (loc, OperName (oper), l, r);
2222 // reload our cached types if required
2227 if (oper == Operator.BitwiseAnd ||
2228 oper == Operator.BitwiseOr ||
2229 oper == Operator.ExclusiveOr){
2231 if (!((l == TypeManager.int32_type) ||
2232 (l == TypeManager.uint32_type) ||
2233 (l == TypeManager.int64_type) ||
2234 (l == TypeManager.uint64_type)))
2237 Error_OperatorCannotBeApplied ();
2242 if (oper == Operator.Equality ||
2243 oper == Operator.Inequality ||
2244 oper == Operator.LessThanOrEqual ||
2245 oper == Operator.LessThan ||
2246 oper == Operator.GreaterThanOrEqual ||
2247 oper == Operator.GreaterThan){
2248 type = TypeManager.bool_type;
2254 public override Expression DoResolve (EmitContext ec)
2256 left = left.Resolve (ec);
2257 right = right.Resolve (ec);
2259 if (left == null || right == null)
2262 if (left.Type == null)
2263 throw new Exception (
2264 "Resolve returned non null, but did not set the type! (" +
2265 left + ") at Line: " + loc.Row);
2266 if (right.Type == null)
2267 throw new Exception (
2268 "Resolve returned non null, but did not set the type! (" +
2269 right + ") at Line: "+ loc.Row);
2271 eclass = ExprClass.Value;
2273 if (left is Constant && right is Constant){
2274 Expression e = ConstantFold.BinaryFold (
2275 ec, oper, (Constant) left, (Constant) right, loc);
2280 return ResolveOperator (ec);
2284 /// EmitBranchable is called from Statement.EmitBoolExpression in the
2285 /// context of a conditional bool expression. This function will return
2286 /// false if it is was possible to use EmitBranchable, or true if it was.
2288 /// The expression's code is generated, and we will generate a branch to `target'
2289 /// if the resulting expression value is equal to isTrue
2291 public bool EmitBranchable (EmitContext ec, Label target, bool onTrue)
2296 ILGenerator ig = ec.ig;
2299 // This is more complicated than it looks, but its just to avoid
2300 // duplicated tests: basically, we allow ==, !=, >, <, >= and <=
2301 // but on top of that we want for == and != to use a special path
2302 // if we are comparing against null
2304 if (oper == Operator.Equality || oper == Operator.Inequality){
2305 bool my_on_true = oper == Operator.Inequality ? onTrue : !onTrue;
2307 if (left is NullLiteral){
2310 ig.Emit (OpCodes.Brtrue, target);
2312 ig.Emit (OpCodes.Brfalse, target);
2314 } else if (right is NullLiteral){
2317 ig.Emit (OpCodes.Brtrue, target);
2319 ig.Emit (OpCodes.Brfalse, target);
2322 } else if (!(oper == Operator.LessThan ||
2323 oper == Operator.GreaterThan ||
2324 oper == Operator.LessThanOrEqual ||
2325 oper == Operator.GreaterThanOrEqual))
2333 bool isUnsigned = is_unsigned (left.Type);
2336 case Operator.Equality:
2338 ig.Emit (OpCodes.Beq, target);
2340 ig.Emit (OpCodes.Bne_Un, target);
2343 case Operator.Inequality:
2345 ig.Emit (OpCodes.Bne_Un, target);
2347 ig.Emit (OpCodes.Beq, target);
2350 case Operator.LessThan:
2353 ig.Emit (OpCodes.Blt_Un, target);
2355 ig.Emit (OpCodes.Blt, target);
2358 ig.Emit (OpCodes.Bge_Un, target);
2360 ig.Emit (OpCodes.Bge, target);
2363 case Operator.GreaterThan:
2366 ig.Emit (OpCodes.Bgt_Un, target);
2368 ig.Emit (OpCodes.Bgt, target);
2371 ig.Emit (OpCodes.Ble_Un, target);
2373 ig.Emit (OpCodes.Ble, target);
2376 case Operator.LessThanOrEqual:
2379 ig.Emit (OpCodes.Ble_Un, target);
2381 ig.Emit (OpCodes.Ble, target);
2384 ig.Emit (OpCodes.Bgt_Un, target);
2386 ig.Emit (OpCodes.Bgt, target);
2390 case Operator.GreaterThanOrEqual:
2393 ig.Emit (OpCodes.Bge_Un, target);
2395 ig.Emit (OpCodes.Bge, target);
2398 ig.Emit (OpCodes.Blt_Un, target);
2400 ig.Emit (OpCodes.Blt, target);
2410 public override void Emit (EmitContext ec)
2412 ILGenerator ig = ec.ig;
2414 Type r = right.Type;
2417 if (method != null) {
2419 // Note that operators are static anyway
2421 if (Arguments != null)
2422 Invocation.EmitArguments (ec, method, Arguments);
2424 if (method is MethodInfo)
2425 ig.Emit (OpCodes.Call, (MethodInfo) method);
2427 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
2429 if (DelegateOperation)
2430 ig.Emit (OpCodes.Castclass, type);
2436 // Handle short-circuit operators differently
2439 if (oper == Operator.LogicalAnd){
2440 Label load_zero = ig.DefineLabel ();
2441 Label end = ig.DefineLabel ();
2444 ig.Emit (OpCodes.Brfalse, load_zero);
2446 ig.Emit (OpCodes.Br, end);
2447 ig.MarkLabel (load_zero);
2448 ig.Emit (OpCodes.Ldc_I4_0);
2451 } else if (oper == Operator.LogicalOr){
2452 Label load_one = ig.DefineLabel ();
2453 Label end = ig.DefineLabel ();
2456 ig.Emit (OpCodes.Brtrue, load_one);
2458 ig.Emit (OpCodes.Br, end);
2459 ig.MarkLabel (load_one);
2460 ig.Emit (OpCodes.Ldc_I4_1);
2469 case Operator.Multiply:
2471 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
2472 opcode = OpCodes.Mul_Ovf;
2473 else if (l==TypeManager.uint32_type || l==TypeManager.uint64_type)
2474 opcode = OpCodes.Mul_Ovf_Un;
2476 opcode = OpCodes.Mul;
2478 opcode = OpCodes.Mul;
2482 case Operator.Division:
2483 if (l == TypeManager.uint32_type || l == TypeManager.uint64_type)
2484 opcode = OpCodes.Div_Un;
2486 opcode = OpCodes.Div;
2489 case Operator.Modulus:
2490 if (l == TypeManager.uint32_type || l == TypeManager.uint64_type)
2491 opcode = OpCodes.Rem_Un;
2493 opcode = OpCodes.Rem;
2496 case Operator.Addition:
2498 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
2499 opcode = OpCodes.Add_Ovf;
2500 else if (l==TypeManager.uint32_type || l==TypeManager.uint64_type)
2501 opcode = OpCodes.Add_Ovf_Un;
2503 opcode = OpCodes.Add;
2505 opcode = OpCodes.Add;
2508 case Operator.Subtraction:
2510 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
2511 opcode = OpCodes.Sub_Ovf;
2512 else if (l==TypeManager.uint32_type || l==TypeManager.uint64_type)
2513 opcode = OpCodes.Sub_Ovf_Un;
2515 opcode = OpCodes.Sub;
2517 opcode = OpCodes.Sub;
2520 case Operator.RightShift:
2521 if (l == TypeManager.uint32_type || l == TypeManager.uint64_type)
2522 opcode = OpCodes.Shr_Un;
2524 opcode = OpCodes.Shr;
2527 case Operator.LeftShift:
2528 opcode = OpCodes.Shl;
2531 case Operator.Equality:
2532 opcode = OpCodes.Ceq;
2535 case Operator.Inequality:
2536 ec.ig.Emit (OpCodes.Ceq);
2537 ec.ig.Emit (OpCodes.Ldc_I4_0);
2539 opcode = OpCodes.Ceq;
2542 case Operator.LessThan:
2543 opcode = OpCodes.Clt;
2546 case Operator.GreaterThan:
2547 opcode = OpCodes.Cgt;
2550 case Operator.LessThanOrEqual:
2551 ec.ig.Emit (OpCodes.Cgt);
2552 ec.ig.Emit (OpCodes.Ldc_I4_0);
2554 opcode = OpCodes.Ceq;
2557 case Operator.GreaterThanOrEqual:
2558 ec.ig.Emit (OpCodes.Clt);
2559 ec.ig.Emit (OpCodes.Ldc_I4_1);
2561 opcode = OpCodes.Sub;
2564 case Operator.BitwiseOr:
2565 opcode = OpCodes.Or;
2568 case Operator.BitwiseAnd:
2569 opcode = OpCodes.And;
2572 case Operator.ExclusiveOr:
2573 opcode = OpCodes.Xor;
2577 throw new Exception ("This should not happen: Operator = "
2578 + oper.ToString ());
2584 public bool IsBuiltinOperator {
2586 return method == null;
2591 public class PointerArithmetic : Expression {
2592 Expression left, right;
2596 // We assume that `l' is always a pointer
2598 public PointerArithmetic (bool is_addition, Expression l, Expression r, Type t,
2602 eclass = ExprClass.Variable;
2606 is_add = is_addition;
2609 public override Expression DoResolve (EmitContext ec)
2612 // We are born fully resolved
2617 public override void Emit (EmitContext ec)
2619 Type op_type = left.Type;
2620 ILGenerator ig = ec.ig;
2621 int size = GetTypeSize (op_type.GetElementType ());
2623 if (right.Type.IsPointer){
2625 // handle (pointer - pointer)
2629 ig.Emit (OpCodes.Sub);
2633 ig.Emit (OpCodes.Sizeof, op_type);
2635 IntLiteral.EmitInt (ig, size);
2636 ig.Emit (OpCodes.Div);
2638 ig.Emit (OpCodes.Conv_I8);
2641 // handle + and - on (pointer op int)
2644 ig.Emit (OpCodes.Conv_I);
2648 ig.Emit (OpCodes.Sizeof, op_type);
2650 IntLiteral.EmitInt (ig, size);
2651 ig.Emit (OpCodes.Mul);
2654 ig.Emit (OpCodes.Add);
2656 ig.Emit (OpCodes.Sub);
2662 /// Implements the ternary conditional operator (?:)
2664 public class Conditional : Expression {
2665 Expression expr, trueExpr, falseExpr;
2667 public Conditional (Expression expr, Expression trueExpr, Expression falseExpr, Location l)
2670 this.trueExpr = trueExpr;
2671 this.falseExpr = falseExpr;
2675 public Expression Expr {
2681 public Expression TrueExpr {
2687 public Expression FalseExpr {
2693 public override Expression DoResolve (EmitContext ec)
2695 expr = expr.Resolve (ec);
2700 if (expr.Type != TypeManager.bool_type)
2701 expr = Expression.ConvertImplicitRequired (
2702 ec, expr, TypeManager.bool_type, loc);
2704 trueExpr = trueExpr.Resolve (ec);
2705 falseExpr = falseExpr.Resolve (ec);
2707 if (trueExpr == null || falseExpr == null)
2710 eclass = ExprClass.Value;
2711 if (trueExpr.Type == falseExpr.Type)
2712 type = trueExpr.Type;
2715 Type true_type = trueExpr.Type;
2716 Type false_type = falseExpr.Type;
2718 if (trueExpr is NullLiteral){
2721 } else if (falseExpr is NullLiteral){
2727 // First, if an implicit conversion exists from trueExpr
2728 // to falseExpr, then the result type is of type falseExpr.Type
2730 conv = ConvertImplicit (ec, trueExpr, false_type, loc);
2733 // Check if both can convert implicitl to each other's type
2735 if (ConvertImplicit (ec, falseExpr, true_type, loc) != null){
2737 "Can not compute type of conditional expression " +
2738 "as `" + TypeManager.CSharpName (trueExpr.Type) +
2739 "' and `" + TypeManager.CSharpName (falseExpr.Type) +
2740 "' convert implicitly to each other");
2745 } else if ((conv = ConvertImplicit(ec, falseExpr, true_type,loc))!= null){
2749 Error (173, "The type of the conditional expression can " +
2750 "not be computed because there is no implicit conversion" +
2751 " from `" + TypeManager.CSharpName (trueExpr.Type) + "'" +
2752 " and `" + TypeManager.CSharpName (falseExpr.Type) + "'");
2757 if (expr is BoolConstant){
2758 BoolConstant bc = (BoolConstant) expr;
2769 public override void Emit (EmitContext ec)
2771 ILGenerator ig = ec.ig;
2772 Label false_target = ig.DefineLabel ();
2773 Label end_target = ig.DefineLabel ();
2776 ig.Emit (OpCodes.Brfalse, false_target);
2778 ig.Emit (OpCodes.Br, end_target);
2779 ig.MarkLabel (false_target);
2780 falseExpr.Emit (ec);
2781 ig.MarkLabel (end_target);
2789 public class LocalVariableReference : Expression, IAssignMethod, IMemoryLocation, IVariable {
2790 public readonly string Name;
2791 public readonly Block Block;
2792 VariableInfo variable_info;
2795 public LocalVariableReference (Block block, string name, Location l)
2800 eclass = ExprClass.Variable;
2803 // Setting `is_readonly' to false will allow you to create a writable
2804 // reference to a read-only variable. This is used by foreach and using.
2805 public LocalVariableReference (Block block, string name, Location l,
2806 VariableInfo variable_info, bool is_readonly)
2807 : this (block, name, l)
2809 this.variable_info = variable_info;
2810 this.is_readonly = is_readonly;
2813 public VariableInfo VariableInfo {
2815 if (variable_info == null) {
2816 variable_info = Block.GetVariableInfo (Name);
2817 is_readonly = variable_info.ReadOnly;
2819 return variable_info;
2823 public bool IsAssigned (EmitContext ec, Location loc)
2825 return VariableInfo.IsAssigned (ec, loc);
2828 public bool IsFieldAssigned (EmitContext ec, string name, Location loc)
2830 return VariableInfo.IsFieldAssigned (ec, name, loc);
2833 public void SetAssigned (EmitContext ec)
2835 VariableInfo.SetAssigned (ec);
2838 public void SetFieldAssigned (EmitContext ec, string name)
2840 VariableInfo.SetFieldAssigned (ec, name);
2843 public bool IsReadOnly {
2845 if (variable_info == null) {
2846 variable_info = Block.GetVariableInfo (Name);
2847 is_readonly = variable_info.ReadOnly;
2853 public override Expression DoResolve (EmitContext ec)
2855 VariableInfo vi = VariableInfo;
2857 if (Block.IsConstant (Name)) {
2858 Expression e = Block.GetConstantExpression (Name);
2864 if (ec.DoFlowAnalysis && !IsAssigned (ec, loc))
2867 type = vi.VariableType;
2871 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
2873 VariableInfo vi = VariableInfo;
2875 if (ec.DoFlowAnalysis)
2876 ec.SetVariableAssigned (vi);
2878 Expression e = DoResolve (ec);
2884 Error (1604, "cannot assign to `" + Name + "' because it is readonly");
2891 public override void Emit (EmitContext ec)
2893 VariableInfo vi = VariableInfo;
2894 ILGenerator ig = ec.ig;
2896 ig.Emit (OpCodes.Ldloc, vi.LocalBuilder);
2900 public void EmitAssign (EmitContext ec, Expression source)
2902 ILGenerator ig = ec.ig;
2903 VariableInfo vi = VariableInfo;
2909 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
2912 public void AddressOf (EmitContext ec, AddressOp mode)
2914 VariableInfo vi = VariableInfo;
2916 ec.ig.Emit (OpCodes.Ldloca, vi.LocalBuilder);
2921 /// This represents a reference to a parameter in the intermediate
2924 public class ParameterReference : Expression, IAssignMethod, IMemoryLocation, IVariable {
2928 public Parameter.Modifier mod;
2929 public bool is_ref, is_out;
2931 public ParameterReference (Parameters pars, int idx, string name, Location loc)
2937 eclass = ExprClass.Variable;
2940 public bool IsAssigned (EmitContext ec, Location loc)
2942 if (!is_out || !ec.DoFlowAnalysis)
2945 if (!ec.CurrentBranching.IsParameterAssigned (idx)) {
2946 Report.Error (165, loc,
2947 "Use of unassigned local variable `" + name + "'");
2954 public bool IsFieldAssigned (EmitContext ec, string field_name, Location loc)
2956 if (!is_out || !ec.DoFlowAnalysis)
2959 if (ec.CurrentBranching.IsParameterAssigned (idx))
2962 if (!ec.CurrentBranching.IsParameterAssigned (idx, field_name)) {
2963 Report.Error (170, loc,
2964 "Use of possibly unassigned field `" + field_name + "'");
2971 public void SetAssigned (EmitContext ec)
2973 if (is_out && ec.DoFlowAnalysis)
2974 ec.CurrentBranching.SetParameterAssigned (idx);
2977 public void SetFieldAssigned (EmitContext ec, string field_name)
2979 if (is_out && ec.DoFlowAnalysis)
2980 ec.CurrentBranching.SetParameterAssigned (idx, field_name);
2984 // Notice that for ref/out parameters, the type exposed is not the
2985 // same type exposed externally.
2988 // externally we expose "int&"
2989 // here we expose "int".
2991 // We record this in "is_ref". This means that the type system can treat
2992 // the type as it is expected, but when we generate the code, we generate
2993 // the alternate kind of code.
2995 public override Expression DoResolve (EmitContext ec)
2997 type = pars.GetParameterInfo (ec.DeclSpace, idx, out mod);
2998 is_ref = (mod & Parameter.Modifier.ISBYREF) != 0;
2999 is_out = (mod & Parameter.Modifier.OUT) != 0;
3000 eclass = ExprClass.Variable;
3002 if (is_out && ec.DoFlowAnalysis && !IsAssigned (ec, loc))
3008 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
3010 type = pars.GetParameterInfo (ec.DeclSpace, idx, out mod);
3011 is_ref = (mod & Parameter.Modifier.ISBYREF) != 0;
3012 is_out = (mod & Parameter.Modifier.OUT) != 0;
3013 eclass = ExprClass.Variable;
3015 if (is_out && ec.DoFlowAnalysis)
3016 ec.SetParameterAssigned (idx);
3021 static void EmitLdArg (ILGenerator ig, int x)
3025 case 0: ig.Emit (OpCodes.Ldarg_0); break;
3026 case 1: ig.Emit (OpCodes.Ldarg_1); break;
3027 case 2: ig.Emit (OpCodes.Ldarg_2); break;
3028 case 3: ig.Emit (OpCodes.Ldarg_3); break;
3029 default: ig.Emit (OpCodes.Ldarg_S, (byte) x); break;
3032 ig.Emit (OpCodes.Ldarg, x);
3036 // This method is used by parameters that are references, that are
3037 // being passed as references: we only want to pass the pointer (that
3038 // is already stored in the parameter, not the address of the pointer,
3039 // and not the value of the variable).
3041 public void EmitLoad (EmitContext ec)
3043 ILGenerator ig = ec.ig;
3049 EmitLdArg (ig, arg_idx);
3052 public override void Emit (EmitContext ec)
3054 ILGenerator ig = ec.ig;
3060 EmitLdArg (ig, arg_idx);
3066 // If we are a reference, we loaded on the stack a pointer
3067 // Now lets load the real value
3069 LoadFromPtr (ig, type);
3072 public void EmitAssign (EmitContext ec, Expression source)
3074 ILGenerator ig = ec.ig;
3081 EmitLdArg (ig, arg_idx);
3086 StoreFromPtr (ig, type);
3089 ig.Emit (OpCodes.Starg_S, (byte) arg_idx);
3091 ig.Emit (OpCodes.Starg, arg_idx);
3095 public void AddressOf (EmitContext ec, AddressOp mode)
3104 ec.ig.Emit (OpCodes.Ldarg_S, (byte) arg_idx);
3106 ec.ig.Emit (OpCodes.Ldarg, arg_idx);
3109 ec.ig.Emit (OpCodes.Ldarga_S, (byte) arg_idx);
3111 ec.ig.Emit (OpCodes.Ldarga, arg_idx);
3117 /// Used for arguments to New(), Invocation()
3119 public class Argument {
3120 public enum AType : byte {
3126 public readonly AType ArgType;
3127 public Expression Expr;
3129 public Argument (Expression expr, AType type)
3132 this.ArgType = type;
3137 if (ArgType == AType.Ref || ArgType == AType.Out)
3138 return TypeManager.LookupType (Expr.Type.ToString () + "&");
3144 public Parameter.Modifier GetParameterModifier ()
3148 return Parameter.Modifier.OUT | Parameter.Modifier.ISBYREF;
3151 return Parameter.Modifier.REF | Parameter.Modifier.ISBYREF;
3154 return Parameter.Modifier.NONE;
3158 public static string FullDesc (Argument a)
3160 return (a.ArgType == AType.Ref ? "ref " :
3161 (a.ArgType == AType.Out ? "out " : "")) +
3162 TypeManager.CSharpName (a.Expr.Type);
3165 public bool ResolveMethodGroup (EmitContext ec, Location loc)
3167 // FIXME: csc doesn't report any error if you try to use `ref' or
3168 // `out' in a delegate creation expression.
3169 Expr = Expr.Resolve (ec, ResolveFlags.VariableOrValue | ResolveFlags.MethodGroup);
3176 public bool Resolve (EmitContext ec, Location loc)
3178 if (ArgType == AType.Ref) {
3179 Expr = Expr.Resolve (ec);
3183 Expr = Expr.ResolveLValue (ec, Expr);
3184 } else if (ArgType == AType.Out)
3185 Expr = Expr.ResolveLValue (ec, new EmptyExpression ());
3187 Expr = Expr.Resolve (ec);
3192 if (ArgType == AType.Expression)
3195 if (Expr.eclass != ExprClass.Variable){
3197 // We just probe to match the CSC output
3199 if (Expr.eclass == ExprClass.PropertyAccess ||
3200 Expr.eclass == ExprClass.IndexerAccess){
3203 "A property or indexer can not be passed as an out or ref " +
3208 "An lvalue is required as an argument to out or ref");
3216 public void Emit (EmitContext ec)
3219 // Ref and Out parameters need to have their addresses taken.
3221 // ParameterReferences might already be references, so we want
3222 // to pass just the value
3224 if (ArgType == AType.Ref || ArgType == AType.Out){
3225 AddressOp mode = AddressOp.Store;
3227 if (ArgType == AType.Ref)
3228 mode |= AddressOp.Load;
3230 if (Expr is ParameterReference){
3231 ParameterReference pr = (ParameterReference) Expr;
3237 pr.AddressOf (ec, mode);
3240 ((IMemoryLocation)Expr).AddressOf (ec, mode);
3247 /// Invocation of methods or delegates.
3249 public class Invocation : ExpressionStatement {
3250 public readonly ArrayList Arguments;
3253 MethodBase method = null;
3256 static Hashtable method_parameter_cache;
3258 static Invocation ()
3260 method_parameter_cache = new PtrHashtable ();
3264 // arguments is an ArrayList, but we do not want to typecast,
3265 // as it might be null.
3267 // FIXME: only allow expr to be a method invocation or a
3268 // delegate invocation (7.5.5)
3270 public Invocation (Expression expr, ArrayList arguments, Location l)
3273 Arguments = arguments;
3277 public Expression Expr {
3284 /// Returns the Parameters (a ParameterData interface) for the
3287 public static ParameterData GetParameterData (MethodBase mb)
3289 object pd = method_parameter_cache [mb];
3293 return (ParameterData) pd;
3296 ip = TypeManager.LookupParametersByBuilder (mb);
3298 method_parameter_cache [mb] = ip;
3300 return (ParameterData) ip;
3302 ParameterInfo [] pi = mb.GetParameters ();
3303 ReflectionParameters rp = new ReflectionParameters (pi);
3304 method_parameter_cache [mb] = rp;
3306 return (ParameterData) rp;
3311 /// Determines "better conversion" as specified in 7.4.2.3
3312 /// Returns : 1 if a->p is better
3313 /// 0 if a->q or neither is better
3315 static int BetterConversion (EmitContext ec, Argument a, Type p, Type q, Location loc)
3317 Type argument_type = a.Type;
3318 Expression argument_expr = a.Expr;
3320 if (argument_type == null)
3321 throw new Exception ("Expression of type " + a.Expr + " does not resolve its type");
3324 // This is a special case since csc behaves this way. I can't find
3325 // it anywhere in the spec but oh well ...
3327 if (argument_expr is NullLiteral && p == TypeManager.string_type && q == TypeManager.object_type)
3329 else if (argument_expr is NullLiteral && p == TypeManager.object_type && q == TypeManager.string_type)
3335 if (argument_type == p)
3338 if (argument_type == q)
3342 // Now probe whether an implicit constant expression conversion
3345 // An implicit constant expression conversion permits the following
3348 // * A constant-expression of type `int' can be converted to type
3349 // sbyte, byute, short, ushort, uint, ulong provided the value of
3350 // of the expression is withing the range of the destination type.
3352 // * A constant-expression of type long can be converted to type
3353 // ulong, provided the value of the constant expression is not negative
3355 // FIXME: Note that this assumes that constant folding has
3356 // taken place. We dont do constant folding yet.
3359 if (argument_expr is IntConstant){
3360 IntConstant ei = (IntConstant) argument_expr;
3361 int value = ei.Value;
3363 if (p == TypeManager.sbyte_type){
3364 if (value >= SByte.MinValue && value <= SByte.MaxValue)
3366 } else if (p == TypeManager.byte_type){
3367 if (Byte.MinValue >= 0 && value <= Byte.MaxValue)
3369 } else if (p == TypeManager.short_type){
3370 if (value >= Int16.MinValue && value <= Int16.MaxValue)
3372 } else if (p == TypeManager.ushort_type){
3373 if (value >= UInt16.MinValue && value <= UInt16.MaxValue)
3375 } else if (p == TypeManager.uint32_type){
3377 // we can optimize this case: a positive int32
3378 // always fits on a uint32
3382 } else if (p == TypeManager.uint64_type){
3384 // we can optimize this case: a positive int32
3385 // always fits on a uint64
3390 } else if (argument_type == TypeManager.int64_type && argument_expr is LongConstant){
3391 LongConstant lc = (LongConstant) argument_expr;
3393 if (p == TypeManager.uint64_type){
3400 Expression tmp = ConvertImplicit (ec, argument_expr, p, loc);
3408 Expression p_tmp = new EmptyExpression (p);
3409 Expression q_tmp = new EmptyExpression (q);
3411 if (StandardConversionExists (p_tmp, q) == true &&
3412 StandardConversionExists (q_tmp, p) == false)
3415 if (p == TypeManager.sbyte_type)
3416 if (q == TypeManager.byte_type || q == TypeManager.ushort_type ||
3417 q == TypeManager.uint32_type || q == TypeManager.uint64_type)
3420 if (p == TypeManager.short_type)
3421 if (q == TypeManager.ushort_type || q == TypeManager.uint32_type ||
3422 q == TypeManager.uint64_type)
3425 if (p == TypeManager.int32_type)
3426 if (q == TypeManager.uint32_type || q == TypeManager.uint64_type)
3429 if (p == TypeManager.int64_type)
3430 if (q == TypeManager.uint64_type)
3437 /// Determines "Better function"
3440 /// and returns an integer indicating :
3441 /// 0 if candidate ain't better
3442 /// 1 if candidate is better than the current best match
3444 static int BetterFunction (EmitContext ec, ArrayList args,
3445 MethodBase candidate, MethodBase best,
3446 bool expanded_form, Location loc)
3448 ParameterData candidate_pd = GetParameterData (candidate);
3449 ParameterData best_pd;
3455 argument_count = args.Count;
3457 int cand_count = candidate_pd.Count;
3459 if (cand_count == 0 && argument_count == 0)
3462 if (candidate_pd.ParameterModifier (cand_count - 1) != Parameter.Modifier.PARAMS)
3463 if (cand_count != argument_count)
3469 if (argument_count == 0 && cand_count == 1 &&
3470 candidate_pd.ParameterModifier (cand_count - 1) == Parameter.Modifier.PARAMS)
3473 for (int j = argument_count; j > 0;) {
3476 Argument a = (Argument) args [j];
3477 Type t = candidate_pd.ParameterType (j);
3479 if (candidate_pd.ParameterModifier (j) == Parameter.Modifier.PARAMS)
3481 t = t.GetElementType ();
3483 x = BetterConversion (ec, a, t, null, loc);
3495 best_pd = GetParameterData (best);
3497 int rating1 = 0, rating2 = 0;
3499 for (int j = 0; j < argument_count; ++j) {
3502 Argument a = (Argument) args [j];
3504 Type ct = candidate_pd.ParameterType (j);
3505 Type bt = best_pd.ParameterType (j);
3507 if (candidate_pd.ParameterModifier (j) == Parameter.Modifier.PARAMS)
3509 ct = ct.GetElementType ();
3511 if (best_pd.ParameterModifier (j) == Parameter.Modifier.PARAMS)
3513 bt = bt.GetElementType ();
3515 x = BetterConversion (ec, a, ct, bt, loc);
3516 y = BetterConversion (ec, a, bt, ct, loc);
3525 if (rating1 > rating2)
3531 public static string FullMethodDesc (MethodBase mb)
3533 string ret_type = "";
3535 if (mb is MethodInfo)
3536 ret_type = TypeManager.CSharpName (((MethodInfo) mb).ReturnType);
3538 StringBuilder sb = new StringBuilder (ret_type + " " + mb.Name);
3539 ParameterData pd = GetParameterData (mb);
3541 int count = pd.Count;
3544 for (int i = count; i > 0; ) {
3547 sb.Append (pd.ParameterDesc (count - i - 1));
3553 return sb.ToString ();
3556 public static MethodGroupExpr MakeUnionSet (Expression mg1, Expression mg2, Location loc)
3558 MemberInfo [] miset;
3559 MethodGroupExpr union;
3564 return (MethodGroupExpr) mg2;
3567 return (MethodGroupExpr) mg1;
3570 MethodGroupExpr left_set = null, right_set = null;
3571 int length1 = 0, length2 = 0;
3573 left_set = (MethodGroupExpr) mg1;
3574 length1 = left_set.Methods.Length;
3576 right_set = (MethodGroupExpr) mg2;
3577 length2 = right_set.Methods.Length;
3579 ArrayList common = new ArrayList ();
3581 foreach (MethodBase l in left_set.Methods){
3582 foreach (MethodBase r in right_set.Methods){
3590 miset = new MemberInfo [length1 + length2 - common.Count];
3591 left_set.Methods.CopyTo (miset, 0);
3595 foreach (MemberInfo mi in right_set.Methods){
3596 if (!common.Contains (mi))
3600 union = new MethodGroupExpr (miset, loc);
3606 /// Determines is the candidate method, if a params method, is applicable
3607 /// in its expanded form to the given set of arguments
3609 static bool IsParamsMethodApplicable (EmitContext ec, ArrayList arguments, MethodBase candidate)
3613 if (arguments == null)
3616 arg_count = arguments.Count;
3618 ParameterData pd = GetParameterData (candidate);
3620 int pd_count = pd.Count;
3625 if (pd.ParameterModifier (pd_count - 1) != Parameter.Modifier.PARAMS)
3628 if (pd_count - 1 > arg_count)
3631 if (pd_count == 1 && arg_count == 0)
3635 // If we have come this far, the case which remains is when the number of parameters
3636 // is less than or equal to the argument count.
3638 for (int i = 0; i < pd_count - 1; ++i) {
3640 Argument a = (Argument) arguments [i];
3642 Parameter.Modifier a_mod = a.GetParameterModifier () &
3643 ~(Parameter.Modifier.OUT | Parameter.Modifier.REF);
3644 Parameter.Modifier p_mod = pd.ParameterModifier (i) &
3645 ~(Parameter.Modifier.OUT | Parameter.Modifier.REF);
3647 if (a_mod == p_mod) {
3649 if (a_mod == Parameter.Modifier.NONE)
3650 if (!ImplicitConversionExists (ec, a.Expr, pd.ParameterType (i)))
3653 if ((a_mod & Parameter.Modifier.ISBYREF) != 0) {
3654 Type pt = pd.ParameterType (i);
3657 pt = TypeManager.LookupType (pt.FullName + "&");
3667 Type element_type = pd.ParameterType (pd_count - 1).GetElementType ();
3669 for (int i = pd_count - 1; i < arg_count; i++) {
3670 Argument a = (Argument) arguments [i];
3672 if (!StandardConversionExists (a.Expr, element_type))
3680 /// Determines if the candidate method is applicable (section 14.4.2.1)
3681 /// to the given set of arguments
3683 static bool IsApplicable (EmitContext ec, ArrayList arguments, MethodBase candidate)
3687 if (arguments == null)
3690 arg_count = arguments.Count;
3692 ParameterData pd = GetParameterData (candidate);
3694 int pd_count = pd.Count;
3696 if (arg_count != pd.Count)
3699 for (int i = arg_count; i > 0; ) {
3702 Argument a = (Argument) arguments [i];
3704 Parameter.Modifier a_mod = a.GetParameterModifier () &
3705 ~(Parameter.Modifier.OUT | Parameter.Modifier.REF);
3706 Parameter.Modifier p_mod = pd.ParameterModifier (i) &
3707 ~(Parameter.Modifier.OUT | Parameter.Modifier.REF);
3709 if (a_mod == p_mod ||
3710 (a_mod == Parameter.Modifier.NONE && p_mod == Parameter.Modifier.PARAMS)) {
3711 if (a_mod == Parameter.Modifier.NONE)
3712 if (!ImplicitConversionExists (ec, a.Expr, pd.ParameterType (i)))
3715 if ((a_mod & Parameter.Modifier.ISBYREF) != 0) {
3716 Type pt = pd.ParameterType (i);
3719 pt = TypeManager.LookupType (pt.FullName + "&");
3734 /// Find the Applicable Function Members (7.4.2.1)
3736 /// me: Method Group expression with the members to select.
3737 /// it might contain constructors or methods (or anything
3738 /// that maps to a method).
3740 /// Arguments: ArrayList containing resolved Argument objects.
3742 /// loc: The location if we want an error to be reported, or a Null
3743 /// location for "probing" purposes.
3745 /// Returns: The MethodBase (either a ConstructorInfo or a MethodInfo)
3746 /// that is the best match of me on Arguments.
3749 public static MethodBase OverloadResolve (EmitContext ec, MethodGroupExpr me,
3750 ArrayList Arguments, Location loc)
3752 ArrayList afm = new ArrayList ();
3753 MethodBase method = null;
3754 Type current_type = null;
3756 ArrayList candidates = new ArrayList ();
3759 foreach (MethodBase candidate in me.Methods){
3762 // If we're going one level higher in the class hierarchy, abort if
3763 // we already found an applicable method.
3764 if (candidate.DeclaringType != current_type) {
3765 current_type = candidate.DeclaringType;
3770 // Check if candidate is applicable (section 14.4.2.1)
3771 if (!IsApplicable (ec, Arguments, candidate))
3774 candidates.Add (candidate);
3775 x = BetterFunction (ec, Arguments, candidate, method, false, loc);
3783 if (Arguments == null)
3786 argument_count = Arguments.Count;
3789 // Now we see if we can find params functions, applicable in their expanded form
3790 // since if they were applicable in their normal form, they would have been selected
3793 bool chose_params_expanded = false;
3795 if (method == null) {
3796 candidates = new ArrayList ();
3797 foreach (MethodBase candidate in me.Methods){
3798 if (!IsParamsMethodApplicable (ec, Arguments, candidate))
3801 candidates.Add (candidate);
3803 int x = BetterFunction (ec, Arguments, candidate, method, true, loc);
3808 chose_params_expanded = true;
3812 if (method == null) {
3814 // Okay so we have failed to find anything so we
3815 // return by providing info about the closest match
3817 for (int i = 0; i < me.Methods.Length; ++i) {
3819 MethodBase c = (MethodBase) me.Methods [i];
3820 ParameterData pd = GetParameterData (c);
3822 if (pd.Count != argument_count)
3825 VerifyArgumentsCompat (ec, Arguments, argument_count, c, false,
3833 // Now check that there are no ambiguities i.e the selected method
3834 // should be better than all the others
3837 foreach (MethodBase candidate in candidates){
3838 if (candidate == method)
3842 // If a normal method is applicable in the sense that it has the same
3843 // number of arguments, then the expanded params method is never applicable
3844 // so we debar the params method.
3846 if (IsParamsMethodApplicable (ec, Arguments, candidate) &&
3847 IsApplicable (ec, Arguments, method))
3850 int x = BetterFunction (ec, Arguments, method, candidate,
3851 chose_params_expanded, loc);
3856 "Ambiguous call when selecting function due to implicit casts");
3862 // And now check if the arguments are all compatible, perform conversions
3863 // if necessary etc. and return if everything is all right
3866 if (VerifyArgumentsCompat (ec, Arguments, argument_count, method,
3867 chose_params_expanded, null, loc))
3873 public static bool VerifyArgumentsCompat (EmitContext ec, ArrayList Arguments,
3876 bool chose_params_expanded,
3880 ParameterData pd = GetParameterData (method);
3881 int pd_count = pd.Count;
3883 for (int j = 0; j < argument_count; j++) {
3884 Argument a = (Argument) Arguments [j];
3885 Expression a_expr = a.Expr;
3886 Type parameter_type = pd.ParameterType (j);
3888 if (pd.ParameterModifier (j) == Parameter.Modifier.PARAMS &&
3889 chose_params_expanded)
3890 parameter_type = TypeManager.TypeToCoreType (parameter_type.GetElementType ());
3892 if (a.Type != parameter_type){
3895 conv = ConvertImplicit (ec, a_expr, parameter_type, loc);
3898 if (!Location.IsNull (loc)) {
3899 if (delegate_type == null)
3900 Report.Error (1502, loc,
3901 "The best overloaded match for method '" +
3902 FullMethodDesc (method) +
3903 "' has some invalid arguments");
3905 Report.Error (1594, loc,
3906 "Delegate '" + delegate_type.ToString () +
3907 "' has some invalid arguments.");
3908 Report.Error (1503, loc,
3909 "Argument " + (j+1) +
3910 ": Cannot convert from '" + Argument.FullDesc (a)
3911 + "' to '" + pd.ParameterDesc (j) + "'");
3918 // Update the argument with the implicit conversion
3924 Parameter.Modifier a_mod = a.GetParameterModifier () &
3925 ~(Parameter.Modifier.OUT | Parameter.Modifier.REF);
3926 Parameter.Modifier p_mod = pd.ParameterModifier (j) &
3927 ~(Parameter.Modifier.OUT | Parameter.Modifier.REF);
3930 if (a_mod != p_mod &&
3931 pd.ParameterModifier (pd_count - 1) != Parameter.Modifier.PARAMS) {
3932 if (!Location.IsNull (loc)) {
3933 Console.WriteLine ("A:P: " + a.GetParameterModifier ());
3934 Console.WriteLine ("PP:: " + pd.ParameterModifier (j));
3935 Console.WriteLine ("PT: " + parameter_type.IsByRef);
3936 Report.Error (1502, loc,
3937 "The best overloaded match for method '" + FullMethodDesc (method)+
3938 "' has some invalid arguments");
3939 Report.Error (1503, loc,
3940 "Argument " + (j+1) +
3941 ": Cannot convert from '" + Argument.FullDesc (a)
3942 + "' to '" + pd.ParameterDesc (j) + "'");
3952 public override Expression DoResolve (EmitContext ec)
3955 // First, resolve the expression that is used to
3956 // trigger the invocation
3958 if (expr is BaseAccess)
3961 expr = expr.Resolve (ec, ResolveFlags.VariableOrValue | ResolveFlags.MethodGroup);
3965 if (!(expr is MethodGroupExpr)) {
3966 Type expr_type = expr.Type;
3968 if (expr_type != null){
3969 bool IsDelegate = TypeManager.IsDelegateType (expr_type);
3971 return (new DelegateInvocation (
3972 this.expr, Arguments, loc)).Resolve (ec);
3976 if (!(expr is MethodGroupExpr)){
3977 expr.Error118 (ResolveFlags.MethodGroup);
3982 // Next, evaluate all the expressions in the argument list
3984 if (Arguments != null){
3985 foreach (Argument a in Arguments){
3986 if (!a.Resolve (ec, loc))
3991 MethodGroupExpr mg = (MethodGroupExpr) expr;
3992 method = OverloadResolve (ec, mg, Arguments, loc);
3994 if (method == null){
3996 "Could not find any applicable function for this argument list");
4000 MethodInfo mi = method as MethodInfo;
4002 type = TypeManager.TypeToCoreType (mi.ReturnType);
4003 if (!mi.IsStatic && !mg.IsExplicitImpl && (mg.InstanceExpression == null))
4004 SimpleName.Error_ObjectRefRequired (ec, loc, mi.Name);
4007 if (type.IsPointer){
4014 eclass = ExprClass.Value;
4019 // Emits the list of arguments as an array
4021 static void EmitParams (EmitContext ec, int idx, ArrayList arguments)
4023 ILGenerator ig = ec.ig;
4024 int count = arguments.Count - idx;
4025 Argument a = (Argument) arguments [idx];
4026 Type t = a.Expr.Type;
4027 string array_type = t.FullName + "[]";
4030 array = ig.DeclareLocal (TypeManager.LookupType (array_type));
4031 IntConstant.EmitInt (ig, count);
4032 ig.Emit (OpCodes.Newarr, TypeManager.TypeToCoreType (t));
4033 ig.Emit (OpCodes.Stloc, array);
4035 int top = arguments.Count;
4036 for (int j = idx; j < top; j++){
4037 a = (Argument) arguments [j];
4039 ig.Emit (OpCodes.Ldloc, array);
4040 IntConstant.EmitInt (ig, j - idx);
4043 ArrayAccess.EmitStoreOpcode (ig, t);
4045 ig.Emit (OpCodes.Ldloc, array);
4049 /// Emits a list of resolved Arguments that are in the arguments
4052 /// The MethodBase argument might be null if the
4053 /// emission of the arguments is known not to contain
4054 /// a `params' field (for example in constructors or other routines
4055 /// that keep their arguments in this structure)
4057 public static void EmitArguments (EmitContext ec, MethodBase mb, ArrayList arguments)
4061 pd = GetParameterData (mb);
4066 // If we are calling a params method with no arguments, special case it
4068 if (arguments == null){
4069 if (pd != null && pd.Count > 0 &&
4070 pd.ParameterModifier (0) == Parameter.Modifier.PARAMS){
4071 ILGenerator ig = ec.ig;
4073 IntConstant.EmitInt (ig, 0);
4074 ig.Emit (OpCodes.Newarr, pd.ParameterType (0).GetElementType ());
4080 int top = arguments.Count;
4082 for (int i = 0; i < top; i++){
4083 Argument a = (Argument) arguments [i];
4086 if (pd.ParameterModifier (i) == Parameter.Modifier.PARAMS){
4088 // Special case if we are passing the same data as the
4089 // params argument, do not put it in an array.
4091 if (pd.ParameterType (i) == a.Type)
4094 EmitParams (ec, i, arguments);
4102 if (pd != null && pd.Count > top &&
4103 pd.ParameterModifier (top) == Parameter.Modifier.PARAMS){
4104 ILGenerator ig = ec.ig;
4106 IntConstant.EmitInt (ig, 0);
4107 ig.Emit (OpCodes.Newarr, pd.ParameterType (top).GetElementType ());
4112 /// is_base tells whether we want to force the use of the `call'
4113 /// opcode instead of using callvirt. Call is required to call
4114 /// a specific method, while callvirt will always use the most
4115 /// recent method in the vtable.
4117 /// is_static tells whether this is an invocation on a static method
4119 /// instance_expr is an expression that represents the instance
4120 /// it must be non-null if is_static is false.
4122 /// method is the method to invoke.
4124 /// Arguments is the list of arguments to pass to the method or constructor.
4126 public static void EmitCall (EmitContext ec, bool is_base,
4127 bool is_static, Expression instance_expr,
4128 MethodBase method, ArrayList Arguments, Location loc)
4130 ILGenerator ig = ec.ig;
4131 bool struct_call = false;
4133 Type decl_type = method.DeclaringType;
4135 if (!RootContext.StdLib) {
4136 // Replace any calls to the system's System.Array type with calls to
4137 // the newly created one.
4138 if (method == TypeManager.system_int_array_get_length)
4139 method = TypeManager.int_array_get_length;
4140 else if (method == TypeManager.system_int_array_get_rank)
4141 method = TypeManager.int_array_get_rank;
4142 else if (method == TypeManager.system_object_array_clone)
4143 method = TypeManager.object_array_clone;
4144 else if (method == TypeManager.system_int_array_get_length_int)
4145 method = TypeManager.int_array_get_length_int;
4146 else if (method == TypeManager.system_int_array_get_lower_bound_int)
4147 method = TypeManager.int_array_get_lower_bound_int;
4148 else if (method == TypeManager.system_int_array_get_upper_bound_int)
4149 method = TypeManager.int_array_get_upper_bound_int;
4150 else if (method == TypeManager.system_void_array_copyto_array_int)
4151 method = TypeManager.void_array_copyto_array_int;
4155 // This checks the `ConditionalAttribute' on the method, and the
4156 // ObsoleteAttribute
4158 TypeManager.MethodFlags flags = TypeManager.GetMethodFlags (method, loc);
4159 if ((flags & TypeManager.MethodFlags.IsObsoleteError) != 0)
4161 if ((flags & TypeManager.MethodFlags.ShouldIgnore) != 0)
4165 if (decl_type.IsValueType)
4168 // If this is ourselves, push "this"
4170 if (instance_expr == null){
4171 ig.Emit (OpCodes.Ldarg_0);
4174 // Push the instance expression
4176 if (instance_expr.Type.IsValueType){
4178 // Special case: calls to a function declared in a
4179 // reference-type with a value-type argument need
4180 // to have their value boxed.
4183 if (decl_type.IsValueType){
4185 // If the expression implements IMemoryLocation, then
4186 // we can optimize and use AddressOf on the
4189 // If not we have to use some temporary storage for
4191 if (instance_expr is IMemoryLocation){
4192 ((IMemoryLocation)instance_expr).
4193 AddressOf (ec, AddressOp.LoadStore);
4196 Type t = instance_expr.Type;
4198 instance_expr.Emit (ec);
4199 LocalBuilder temp = ig.DeclareLocal (t);
4200 ig.Emit (OpCodes.Stloc, temp);
4201 ig.Emit (OpCodes.Ldloca, temp);
4204 instance_expr.Emit (ec);
4205 ig.Emit (OpCodes.Box, instance_expr.Type);
4208 instance_expr.Emit (ec);
4212 EmitArguments (ec, method, Arguments);
4214 if (is_static || struct_call || is_base){
4215 if (method is MethodInfo) {
4216 ig.Emit (OpCodes.Call, (MethodInfo) method);
4218 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
4220 if (method is MethodInfo)
4221 ig.Emit (OpCodes.Callvirt, (MethodInfo) method);
4223 ig.Emit (OpCodes.Callvirt, (ConstructorInfo) method);
4227 public override void Emit (EmitContext ec)
4229 MethodGroupExpr mg = (MethodGroupExpr) this.expr;
4232 ec, is_base, method.IsStatic, mg.InstanceExpression, method, Arguments, loc);
4235 public override void EmitStatement (EmitContext ec)
4240 // Pop the return value if there is one
4242 if (method is MethodInfo){
4243 Type ret = ((MethodInfo)method).ReturnType;
4244 if (TypeManager.TypeToCoreType (ret) != TypeManager.void_type)
4245 ec.ig.Emit (OpCodes.Pop);
4251 // This class is used to "disable" the code generation for the
4252 // temporary variable when initializing value types.
4254 class EmptyAddressOf : EmptyExpression, IMemoryLocation {
4255 public void AddressOf (EmitContext ec, AddressOp Mode)
4262 /// Implements the new expression
4264 public class New : ExpressionStatement {
4265 public readonly ArrayList Arguments;
4266 public readonly Expression RequestedType;
4268 MethodBase method = null;
4271 // If set, the new expression is for a value_target, and
4272 // we will not leave anything on the stack.
4274 Expression value_target;
4275 bool value_target_set = false;
4277 public New (Expression requested_type, ArrayList arguments, Location l)
4279 RequestedType = requested_type;
4280 Arguments = arguments;
4284 public Expression ValueTypeVariable {
4286 return value_target;
4290 value_target = value;
4291 value_target_set = true;
4296 // This function is used to disable the following code sequence for
4297 // value type initialization:
4299 // AddressOf (temporary)
4303 // Instead the provide will have provided us with the address on the
4304 // stack to store the results.
4306 static Expression MyEmptyExpression;
4308 public void DisableTemporaryValueType ()
4310 if (MyEmptyExpression == null)
4311 MyEmptyExpression = new EmptyAddressOf ();
4314 // To enable this, look into:
4315 // test-34 and test-89 and self bootstrapping.
4317 // For instance, we can avoid a copy by using `newobj'
4318 // instead of Call + Push-temp on value types.
4319 // value_target = MyEmptyExpression;
4322 public override Expression DoResolve (EmitContext ec)
4324 type = ec.DeclSpace.ResolveType (RequestedType, false, loc);
4329 bool IsDelegate = TypeManager.IsDelegateType (type);
4332 return (new NewDelegate (type, Arguments, loc)).Resolve (ec);
4334 if (type.IsInterface || type.IsAbstract){
4336 144, "It is not possible to create instances of interfaces " +
4337 "or abstract classes");
4341 bool is_struct = false;
4342 is_struct = type.IsValueType;
4343 eclass = ExprClass.Value;
4346 // SRE returns a match for .ctor () on structs (the object constructor),
4347 // so we have to manually ignore it.
4349 if (is_struct && Arguments == null)
4353 ml = MemberLookupFinal (ec, type, ".ctor",
4354 MemberTypes.Constructor,
4355 AllBindingFlags | BindingFlags.DeclaredOnly, loc);
4360 if (! (ml is MethodGroupExpr)){
4362 ml.Error118 ("method group");
4368 if (Arguments != null){
4369 foreach (Argument a in Arguments){
4370 if (!a.Resolve (ec, loc))
4375 method = Invocation.OverloadResolve (ec, (MethodGroupExpr) ml,
4380 if (method == null) {
4381 if (!is_struct || Arguments.Count > 0) {
4383 "New invocation: Can not find a constructor for " +
4384 "this argument list");
4392 // This DoEmit can be invoked in two contexts:
4393 // * As a mechanism that will leave a value on the stack (new object)
4394 // * As one that wont (init struct)
4396 // You can control whether a value is required on the stack by passing
4397 // need_value_on_stack. The code *might* leave a value on the stack
4398 // so it must be popped manually
4400 // If we are dealing with a ValueType, we have a few
4401 // situations to deal with:
4403 // * The target is a ValueType, and we have been provided
4404 // the instance (this is easy, we are being assigned).
4406 // * The target of New is being passed as an argument,
4407 // to a boxing operation or a function that takes a
4410 // In this case, we need to create a temporary variable
4411 // that is the argument of New.
4413 // Returns whether a value is left on the stack
4415 bool DoEmit (EmitContext ec, bool need_value_on_stack)
4417 bool is_value_type = type.IsValueType;
4418 ILGenerator ig = ec.ig;
4423 // Allow DoEmit() to be called multiple times.
4424 // We need to create a new LocalTemporary each time since
4425 // you can't share LocalBuilders among ILGeneators.
4426 if (!value_target_set)
4427 value_target = new LocalTemporary (ec, type);
4429 ml = (IMemoryLocation) value_target;
4430 ml.AddressOf (ec, AddressOp.Store);
4434 Invocation.EmitArguments (ec, method, Arguments);
4438 ig.Emit (OpCodes.Initobj, type);
4440 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
4441 if (need_value_on_stack){
4442 value_target.Emit (ec);
4447 ig.Emit (OpCodes.Newobj, (ConstructorInfo) method);
4452 public override void Emit (EmitContext ec)
4457 public override void EmitStatement (EmitContext ec)
4459 if (DoEmit (ec, false))
4460 ec.ig.Emit (OpCodes.Pop);
4465 /// 14.5.10.2: Represents an array creation expression.
4469 /// There are two possible scenarios here: one is an array creation
4470 /// expression that specifies the dimensions and optionally the
4471 /// initialization data and the other which does not need dimensions
4472 /// specified but where initialization data is mandatory.
4474 public class ArrayCreation : ExpressionStatement {
4475 Expression requested_base_type;
4476 ArrayList initializers;
4479 // The list of Argument types.
4480 // This is used to construct the `newarray' or constructor signature
4482 ArrayList arguments;
4485 // Method used to create the array object.
4487 MethodBase new_method = null;
4489 Type array_element_type;
4490 Type underlying_type;
4491 bool is_one_dimensional = false;
4492 bool is_builtin_type = false;
4493 bool expect_initializers = false;
4494 int num_arguments = 0;
4498 ArrayList array_data;
4503 // The number of array initializers that we can handle
4504 // via the InitializeArray method - through EmitStaticInitializers
4506 int num_automatic_initializers;
4508 public ArrayCreation (Expression requested_base_type, ArrayList exprs, string rank, ArrayList initializers, Location l)
4510 this.requested_base_type = requested_base_type;
4511 this.initializers = initializers;
4515 arguments = new ArrayList ();
4517 foreach (Expression e in exprs) {
4518 arguments.Add (new Argument (e, Argument.AType.Expression));
4523 public ArrayCreation (Expression requested_base_type, string rank, ArrayList initializers, Location l)
4525 this.requested_base_type = requested_base_type;
4526 this.initializers = initializers;
4530 //this.rank = rank.Substring (0, rank.LastIndexOf ("["));
4532 //string tmp = rank.Substring (rank.LastIndexOf ("["));
4534 //dimensions = tmp.Length - 1;
4535 expect_initializers = true;
4538 public Expression FormArrayType (Expression base_type, int idx_count, string rank)
4540 StringBuilder sb = new StringBuilder (rank);
4543 for (int i = 1; i < idx_count; i++)
4548 return new ComposedCast (base_type, sb.ToString (), loc);
4553 Error (178, "Incorrectly structured array initializer");
4556 public bool CheckIndices (EmitContext ec, ArrayList probe, int idx, bool specified_dims)
4558 if (specified_dims) {
4559 Argument a = (Argument) arguments [idx];
4561 if (!a.Resolve (ec, loc))
4564 if (!(a.Expr is Constant)) {
4565 Error (150, "A constant value is expected");
4569 int value = (int) ((Constant) a.Expr).GetValue ();
4571 if (value != probe.Count) {
4576 bounds [idx] = value;
4579 foreach (object o in probe) {
4580 if (o is ArrayList) {
4581 bool ret = CheckIndices (ec, (ArrayList) o, idx + 1, specified_dims);
4585 Expression tmp = (Expression) o;
4586 tmp = tmp.Resolve (ec);
4590 // Console.WriteLine ("I got: " + tmp);
4591 // Handle initialization from vars, fields etc.
4593 Expression conv = ConvertImplicitRequired (
4594 ec, tmp, underlying_type, loc);
4599 if (conv is StringConstant)
4600 array_data.Add (conv);
4601 else if (conv is Constant) {
4602 array_data.Add (conv);
4603 num_automatic_initializers++;
4605 array_data.Add (conv);
4612 public void UpdateIndices (EmitContext ec)
4615 for (ArrayList probe = initializers; probe != null;) {
4616 if (probe.Count > 0 && probe [0] is ArrayList) {
4617 Expression e = new IntConstant (probe.Count);
4618 arguments.Add (new Argument (e, Argument.AType.Expression));
4620 bounds [i++] = probe.Count;
4622 probe = (ArrayList) probe [0];
4625 Expression e = new IntConstant (probe.Count);
4626 arguments.Add (new Argument (e, Argument.AType.Expression));
4628 bounds [i++] = probe.Count;
4635 public bool ValidateInitializers (EmitContext ec, Type array_type)
4637 if (initializers == null) {
4638 if (expect_initializers)
4644 if (underlying_type == null)
4648 // We use this to store all the date values in the order in which we
4649 // will need to store them in the byte blob later
4651 array_data = new ArrayList ();
4652 bounds = new Hashtable ();
4656 if (arguments != null) {
4657 ret = CheckIndices (ec, initializers, 0, true);
4660 arguments = new ArrayList ();
4662 ret = CheckIndices (ec, initializers, 0, false);
4669 if (arguments.Count != dimensions) {
4678 void Error_NegativeArrayIndex ()
4680 Error (284, "Can not create array with a negative size");
4684 // Converts `source' to an int, uint, long or ulong.
4686 Expression ExpressionToArrayArgument (EmitContext ec, Expression source)
4690 bool old_checked = ec.CheckState;
4691 ec.CheckState = true;
4693 target = ConvertImplicit (ec, source, TypeManager.int32_type, loc);
4694 if (target == null){
4695 target = ConvertImplicit (ec, source, TypeManager.uint32_type, loc);
4696 if (target == null){
4697 target = ConvertImplicit (ec, source, TypeManager.int64_type, loc);
4698 if (target == null){
4699 target = ConvertImplicit (ec, source, TypeManager.uint64_type, loc);
4701 Expression.Error_CannotConvertImplicit (loc, source.Type, TypeManager.int32_type);
4705 ec.CheckState = old_checked;
4708 // Only positive constants are allowed at compile time
4710 if (target is Constant){
4711 if (target is IntConstant){
4712 if (((IntConstant) target).Value < 0){
4713 Error_NegativeArrayIndex ();
4718 if (target is LongConstant){
4719 if (((LongConstant) target).Value < 0){
4720 Error_NegativeArrayIndex ();
4731 // Creates the type of the array
4733 bool LookupType (EmitContext ec)
4735 StringBuilder array_qualifier = new StringBuilder (rank);
4738 // `In the first form allocates an array instace of the type that results
4739 // from deleting each of the individual expression from the expression list'
4741 if (num_arguments > 0) {
4742 array_qualifier.Append ("[");
4743 for (int i = num_arguments-1; i > 0; i--)
4744 array_qualifier.Append (",");
4745 array_qualifier.Append ("]");
4751 Expression array_type_expr;
4752 array_type_expr = new ComposedCast (requested_base_type, array_qualifier.ToString (), loc);
4753 type = ec.DeclSpace.ResolveType (array_type_expr, false, loc);
4758 underlying_type = type;
4759 if (underlying_type.IsArray)
4760 underlying_type = TypeManager.TypeToCoreType (underlying_type.GetElementType ());
4761 dimensions = type.GetArrayRank ();
4766 public override Expression DoResolve (EmitContext ec)
4770 if (!LookupType (ec))
4774 // First step is to validate the initializers and fill
4775 // in any missing bits
4777 if (!ValidateInitializers (ec, type))
4780 if (arguments == null)
4783 arg_count = arguments.Count;
4784 foreach (Argument a in arguments){
4785 if (!a.Resolve (ec, loc))
4788 Expression real_arg = ExpressionToArrayArgument (ec, a.Expr, loc);
4789 if (real_arg == null)
4796 array_element_type = TypeManager.TypeToCoreType (type.GetElementType ());
4798 if (arg_count == 1) {
4799 is_one_dimensional = true;
4800 eclass = ExprClass.Value;
4804 is_builtin_type = TypeManager.IsBuiltinType (type);
4806 if (is_builtin_type) {
4809 ml = MemberLookup (ec, type, ".ctor", MemberTypes.Constructor,
4810 AllBindingFlags, loc);
4812 if (!(ml is MethodGroupExpr)) {
4813 ml.Error118 ("method group");
4818 Error (-6, "New invocation: Can not find a constructor for " +
4819 "this argument list");
4823 new_method = Invocation.OverloadResolve (ec, (MethodGroupExpr) ml, arguments, loc);
4825 if (new_method == null) {
4826 Error (-6, "New invocation: Can not find a constructor for " +
4827 "this argument list");
4831 eclass = ExprClass.Value;
4834 ModuleBuilder mb = CodeGen.ModuleBuilder;
4835 ArrayList args = new ArrayList ();
4837 if (arguments != null) {
4838 for (int i = 0; i < arg_count; i++)
4839 args.Add (TypeManager.int32_type);
4842 Type [] arg_types = null;
4845 arg_types = new Type [args.Count];
4847 args.CopyTo (arg_types, 0);
4849 new_method = mb.GetArrayMethod (type, ".ctor", CallingConventions.HasThis, null,
4852 if (new_method == null) {
4853 Error (-6, "New invocation: Can not find a constructor for " +
4854 "this argument list");
4858 eclass = ExprClass.Value;
4863 public static byte [] MakeByteBlob (ArrayList array_data, Type underlying_type, Location loc)
4868 int count = array_data.Count;
4870 if (underlying_type.IsEnum)
4871 underlying_type = TypeManager.EnumToUnderlying (underlying_type);
4873 factor = GetTypeSize (underlying_type);
4875 throw new Exception ("unrecognized type in MakeByteBlob: " + underlying_type);
4877 data = new byte [(count * factor + 4) & ~3];
4880 for (int i = 0; i < count; ++i) {
4881 object v = array_data [i];
4883 if (v is EnumConstant)
4884 v = ((EnumConstant) v).Child;
4886 if (v is Constant && !(v is StringConstant))
4887 v = ((Constant) v).GetValue ();
4893 if (underlying_type == TypeManager.int64_type){
4894 if (!(v is Expression)){
4895 long val = (long) v;
4897 for (int j = 0; j < factor; ++j) {
4898 data [idx + j] = (byte) (val & 0xFF);
4902 } else if (underlying_type == TypeManager.uint64_type){
4903 if (!(v is Expression)){
4904 ulong val = (ulong) v;
4906 for (int j = 0; j < factor; ++j) {
4907 data [idx + j] = (byte) (val & 0xFF);
4911 } else if (underlying_type == TypeManager.float_type) {
4912 if (!(v is Expression)){
4913 element = BitConverter.GetBytes ((float) v);
4915 for (int j = 0; j < factor; ++j)
4916 data [idx + j] = element [j];
4918 } else if (underlying_type == TypeManager.double_type) {
4919 if (!(v is Expression)){
4920 element = BitConverter.GetBytes ((double) v);
4922 for (int j = 0; j < factor; ++j)
4923 data [idx + j] = element [j];
4925 } else if (underlying_type == TypeManager.char_type){
4926 if (!(v is Expression)){
4927 int val = (int) ((char) v);
4929 data [idx] = (byte) (val & 0xff);
4930 data [idx+1] = (byte) (val >> 8);
4932 } else if (underlying_type == TypeManager.short_type){
4933 if (!(v is Expression)){
4934 int val = (int) ((short) v);
4936 data [idx] = (byte) (val & 0xff);
4937 data [idx+1] = (byte) (val >> 8);
4939 } else if (underlying_type == TypeManager.ushort_type){
4940 if (!(v is Expression)){
4941 int val = (int) ((ushort) v);
4943 data [idx] = (byte) (val & 0xff);
4944 data [idx+1] = (byte) (val >> 8);
4946 } else if (underlying_type == TypeManager.int32_type) {
4947 if (!(v is Expression)){
4950 data [idx] = (byte) (val & 0xff);
4951 data [idx+1] = (byte) ((val >> 8) & 0xff);
4952 data [idx+2] = (byte) ((val >> 16) & 0xff);
4953 data [idx+3] = (byte) (val >> 24);
4955 } else if (underlying_type == TypeManager.uint32_type) {
4956 if (!(v is Expression)){
4957 uint val = (uint) v;
4959 data [idx] = (byte) (val & 0xff);
4960 data [idx+1] = (byte) ((val >> 8) & 0xff);
4961 data [idx+2] = (byte) ((val >> 16) & 0xff);
4962 data [idx+3] = (byte) (val >> 24);
4964 } else if (underlying_type == TypeManager.sbyte_type) {
4965 if (!(v is Expression)){
4966 sbyte val = (sbyte) v;
4967 data [idx] = (byte) val;
4969 } else if (underlying_type == TypeManager.byte_type) {
4970 if (!(v is Expression)){
4971 byte val = (byte) v;
4972 data [idx] = (byte) val;
4974 } else if (underlying_type == TypeManager.bool_type) {
4975 if (!(v is Expression)){
4976 bool val = (bool) v;
4977 data [idx] = (byte) (val ? 1 : 0);
4979 } else if (underlying_type == TypeManager.decimal_type){
4980 if (!(v is Expression)){
4981 int [] bits = Decimal.GetBits ((decimal) v);
4984 for (int j = 0; j < 4; j++){
4985 data [p++] = (byte) (bits [j] & 0xff);
4986 data [p++] = (byte) ((bits [j] >> 8) & 0xff);
4987 data [p++] = (byte) ((bits [j] >> 16) & 0xff);
4988 data [p++] = (byte) (bits [j] >> 24);
4992 throw new Exception ("Unrecognized type in MakeByteBlob: " + underlying_type);
5001 // Emits the initializers for the array
5003 void EmitStaticInitializers (EmitContext ec, bool is_expression)
5006 // First, the static data
5009 ILGenerator ig = ec.ig;
5011 byte [] data = MakeByteBlob (array_data, underlying_type, loc);
5013 fb = RootContext.MakeStaticData (data);
5016 ig.Emit (OpCodes.Dup);
5017 ig.Emit (OpCodes.Ldtoken, fb);
5018 ig.Emit (OpCodes.Call,
5019 TypeManager.void_initializearray_array_fieldhandle);
5023 // Emits pieces of the array that can not be computed at compile
5024 // time (variables and string locations).
5026 // This always expect the top value on the stack to be the array
5028 void EmitDynamicInitializers (EmitContext ec, bool is_expression)
5030 ILGenerator ig = ec.ig;
5031 int dims = bounds.Count;
5032 int [] current_pos = new int [dims];
5033 int top = array_data.Count;
5034 LocalBuilder temp = ig.DeclareLocal (type);
5036 ig.Emit (OpCodes.Stloc, temp);
5038 MethodInfo set = null;
5042 ModuleBuilder mb = null;
5043 mb = CodeGen.ModuleBuilder;
5044 args = new Type [dims + 1];
5047 for (j = 0; j < dims; j++)
5048 args [j] = TypeManager.int32_type;
5050 args [j] = array_element_type;
5052 set = mb.GetArrayMethod (
5054 CallingConventions.HasThis | CallingConventions.Standard,
5055 TypeManager.void_type, args);
5058 for (int i = 0; i < top; i++){
5060 Expression e = null;
5062 if (array_data [i] is Expression)
5063 e = (Expression) array_data [i];
5067 // Basically we do this for string literals and
5068 // other non-literal expressions
5070 if (e is StringConstant || !(e is Constant) ||
5071 num_automatic_initializers <= 2) {
5072 Type etype = e.Type;
5074 ig.Emit (OpCodes.Ldloc, temp);
5076 for (int idx = 0; idx < dims; idx++)
5077 IntConstant.EmitInt (ig, current_pos [idx]);
5080 // If we are dealing with a struct, get the
5081 // address of it, so we can store it.
5084 etype.IsSubclassOf (TypeManager.value_type) &&
5085 (!TypeManager.IsBuiltinType (etype) ||
5086 etype == TypeManager.decimal_type)) {
5091 // Let new know that we are providing
5092 // the address where to store the results
5094 n.DisableTemporaryValueType ();
5097 ig.Emit (OpCodes.Ldelema, etype);
5103 ArrayAccess.EmitStoreOpcode (ig, array_element_type);
5105 ig.Emit (OpCodes.Call, set);
5112 for (int j = dims - 1; j >= 0; j--){
5114 if (current_pos [j] < (int) bounds [j])
5116 current_pos [j] = 0;
5121 ig.Emit (OpCodes.Ldloc, temp);
5124 void EmitArrayArguments (EmitContext ec)
5126 ILGenerator ig = ec.ig;
5128 foreach (Argument a in arguments) {
5129 Type atype = a.Type;
5132 if (atype == TypeManager.uint64_type)
5133 ig.Emit (OpCodes.Conv_Ovf_U4);
5134 else if (atype == TypeManager.int64_type)
5135 ig.Emit (OpCodes.Conv_Ovf_I4);
5139 void DoEmit (EmitContext ec, bool is_statement)
5141 ILGenerator ig = ec.ig;
5143 EmitArrayArguments (ec);
5144 if (is_one_dimensional)
5145 ig.Emit (OpCodes.Newarr, array_element_type);
5147 if (is_builtin_type)
5148 ig.Emit (OpCodes.Newobj, (ConstructorInfo) new_method);
5150 ig.Emit (OpCodes.Newobj, (MethodInfo) new_method);
5153 if (initializers != null){
5155 // FIXME: Set this variable correctly.
5157 bool dynamic_initializers = true;
5159 if (underlying_type != TypeManager.string_type &&
5160 underlying_type != TypeManager.object_type) {
5161 if (num_automatic_initializers > 2)
5162 EmitStaticInitializers (ec, dynamic_initializers || !is_statement);
5165 if (dynamic_initializers)
5166 EmitDynamicInitializers (ec, !is_statement);
5170 public override void Emit (EmitContext ec)
5175 public override void EmitStatement (EmitContext ec)
5183 /// Represents the `this' construct
5185 public class This : Expression, IAssignMethod, IMemoryLocation, IVariable {
5190 public This (Block block, Location loc)
5196 public This (Location loc)
5201 public bool IsAssigned (EmitContext ec, Location loc)
5206 return vi.IsAssigned (ec, loc);
5209 public bool IsFieldAssigned (EmitContext ec, string field_name, Location loc)
5214 return vi.IsFieldAssigned (ec, field_name, loc);
5217 public void SetAssigned (EmitContext ec)
5220 vi.SetAssigned (ec);
5223 public void SetFieldAssigned (EmitContext ec, string field_name)
5226 vi.SetFieldAssigned (ec, field_name);
5229 public override Expression DoResolve (EmitContext ec)
5231 eclass = ExprClass.Variable;
5232 type = ec.ContainerType;
5235 Error (26, "Keyword this not valid in static code");
5240 vi = block.ThisVariable;
5245 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
5249 VariableInfo vi = ec.CurrentBlock.ThisVariable;
5251 vi.SetAssigned (ec);
5253 if (ec.TypeContainer is Class){
5254 Error (1604, "Cannot assign to `this'");
5261 public override void Emit (EmitContext ec)
5263 ILGenerator ig = ec.ig;
5265 ig.Emit (OpCodes.Ldarg_0);
5266 if (ec.TypeContainer is Struct)
5267 ig.Emit (OpCodes.Ldobj, type);
5270 public void EmitAssign (EmitContext ec, Expression source)
5272 ILGenerator ig = ec.ig;
5274 if (ec.TypeContainer is Struct){
5275 ig.Emit (OpCodes.Ldarg_0);
5277 ig.Emit (OpCodes.Stobj, type);
5280 ig.Emit (OpCodes.Starg, 0);
5284 public void AddressOf (EmitContext ec, AddressOp mode)
5286 ec.ig.Emit (OpCodes.Ldarg_0);
5289 // FIGURE OUT WHY LDARG_S does not work
5291 // consider: struct X { int val; int P { set { val = value; }}}
5293 // Yes, this looks very bad. Look at `NOTAS' for
5295 // ec.ig.Emit (OpCodes.Ldarga_S, (byte) 0);
5300 /// Implements the typeof operator
5302 public class TypeOf : Expression {
5303 public readonly Expression QueriedType;
5306 public TypeOf (Expression queried_type, Location l)
5308 QueriedType = queried_type;
5312 public override Expression DoResolve (EmitContext ec)
5314 typearg = ec.DeclSpace.ResolveType (QueriedType, false, loc);
5316 if (typearg == null)
5319 type = TypeManager.type_type;
5320 eclass = ExprClass.Type;
5324 public override void Emit (EmitContext ec)
5326 ec.ig.Emit (OpCodes.Ldtoken, typearg);
5327 ec.ig.Emit (OpCodes.Call, TypeManager.system_type_get_type_from_handle);
5330 public Type TypeArg {
5331 get { return typearg; }
5336 /// Implements the sizeof expression
5338 public class SizeOf : Expression {
5339 public readonly Expression QueriedType;
5342 public SizeOf (Expression queried_type, Location l)
5344 this.QueriedType = queried_type;
5348 public override Expression DoResolve (EmitContext ec)
5351 Error (233, "Sizeof may only be used in an unsafe context " +
5352 "(consider using System.Runtime.InteropServices.Marshal.Sizeof");
5356 type_queried = ec.DeclSpace.ResolveType (QueriedType, false, loc);
5357 if (type_queried == null)
5360 if (!TypeManager.IsUnmanagedType (type_queried)){
5361 Report.Error (208, "Cannot take the size of an unmanaged type (" + TypeManager.CSharpName (type_queried) + ")");
5365 type = TypeManager.int32_type;
5366 eclass = ExprClass.Value;
5370 public override void Emit (EmitContext ec)
5372 int size = GetTypeSize (type_queried);
5375 ec.ig.Emit (OpCodes.Sizeof, type_queried);
5377 IntConstant.EmitInt (ec.ig, size);
5382 /// Implements the member access expression
5384 public class MemberAccess : Expression, ITypeExpression {
5385 public readonly string Identifier;
5387 Expression member_lookup;
5389 public MemberAccess (Expression expr, string id, Location l)
5396 public Expression Expr {
5402 static void error176 (Location loc, string name)
5404 Report.Error (176, loc, "Static member `" +
5405 name + "' cannot be accessed " +
5406 "with an instance reference, qualify with a " +
5407 "type name instead");
5410 static bool IdenticalNameAndTypeName (EmitContext ec, Expression left_original, Location loc)
5412 if (left_original == null)
5415 if (!(left_original is SimpleName))
5418 SimpleName sn = (SimpleName) left_original;
5420 Type t = RootContext.LookupType (ec.DeclSpace, sn.Name, true, loc);
5427 public static Expression ResolveMemberAccess (EmitContext ec, Expression member_lookup,
5428 Expression left, Location loc,
5429 Expression left_original)
5431 bool left_is_type, left_is_explicit;
5433 // If `left' is null, then we're called from SimpleNameResolve and this is
5434 // a member in the currently defining class.
5436 left_is_type = ec.IsStatic || ec.IsFieldInitializer;
5437 left_is_explicit = false;
5439 // Implicitly default to `this' unless we're static.
5440 if (!ec.IsStatic && !ec.IsFieldInitializer && !ec.InEnumContext)
5443 left_is_type = left is TypeExpr;
5444 left_is_explicit = true;
5447 if (member_lookup is FieldExpr){
5448 FieldExpr fe = (FieldExpr) member_lookup;
5449 FieldInfo fi = fe.FieldInfo;
5450 Type decl_type = fi.DeclaringType;
5452 if (fi is FieldBuilder) {
5453 Const c = TypeManager.LookupConstant ((FieldBuilder) fi);
5456 object o = c.LookupConstantValue (ec);
5457 object real_value = ((Constant) c.Expr).GetValue ();
5459 return Constantify (real_value, fi.FieldType);
5464 Type t = fi.FieldType;
5468 if (fi is FieldBuilder)
5469 o = TypeManager.GetValue ((FieldBuilder) fi);
5471 o = fi.GetValue (fi);
5473 if (decl_type.IsSubclassOf (TypeManager.enum_type)) {
5474 if (left_is_explicit && !left_is_type &&
5475 !IdenticalNameAndTypeName (ec, left_original, loc)) {
5476 error176 (loc, fe.FieldInfo.Name);
5480 Expression enum_member = MemberLookup (
5481 ec, decl_type, "value__", MemberTypes.Field,
5482 AllBindingFlags, loc);
5484 Enum en = TypeManager.LookupEnum (decl_type);
5488 c = Constantify (o, en.UnderlyingType);
5490 c = Constantify (o, enum_member.Type);
5492 return new EnumConstant (c, decl_type);
5495 Expression exp = Constantify (o, t);
5497 if (left_is_explicit && !left_is_type) {
5498 error176 (loc, fe.FieldInfo.Name);
5505 if (fi.FieldType.IsPointer && !ec.InUnsafe){
5511 if (member_lookup is EventExpr) {
5513 EventExpr ee = (EventExpr) member_lookup;
5516 // If the event is local to this class, we transform ourselves into
5520 if (ee.EventInfo.DeclaringType == ec.ContainerType) {
5521 MemberInfo mi = GetFieldFromEvent (ee);
5525 // If this happens, then we have an event with its own
5526 // accessors and private field etc so there's no need
5527 // to transform ourselves : we should instead flag an error
5529 Assign.error70 (ee.EventInfo, loc);
5533 Expression ml = ExprClassFromMemberInfo (ec, mi, loc);
5536 Report.Error (-200, loc, "Internal error!!");
5540 return ResolveMemberAccess (ec, ml, left, loc, left_original);
5544 if (member_lookup is IMemberExpr) {
5545 IMemberExpr me = (IMemberExpr) member_lookup;
5548 MethodGroupExpr mg = me as MethodGroupExpr;
5549 if ((mg != null) && left_is_explicit && left.Type.IsInterface)
5550 mg.IsExplicitImpl = left_is_explicit;
5553 if (IdenticalNameAndTypeName (ec, left_original, loc))
5554 return member_lookup;
5556 SimpleName.Error_ObjectRefRequired (ec, loc, me.Name);
5561 if (!me.IsInstance){
5562 if (IdenticalNameAndTypeName (ec, left_original, loc))
5563 return member_lookup;
5565 if (left_is_explicit) {
5566 error176 (loc, me.Name);
5572 // Since we can not check for instance objects in SimpleName,
5573 // becaue of the rule that allows types and variables to share
5574 // the name (as long as they can be de-ambiguated later, see
5575 // IdenticalNameAndTypeName), we have to check whether left
5576 // is an instance variable in a static context
5578 // However, if the left-hand value is explicitly given, then
5579 // it is already our instance expression, so we aren't in
5583 if (ec.IsStatic && !left_is_explicit && left is IMemberExpr){
5584 IMemberExpr mexp = (IMemberExpr) left;
5586 if (!mexp.IsStatic){
5587 SimpleName.Error_ObjectRefRequired (ec, loc, mexp.Name);
5592 me.InstanceExpression = left;
5595 return member_lookup;
5598 if (member_lookup is TypeExpr){
5599 member_lookup.Resolve (ec, ResolveFlags.Type);
5600 return member_lookup;
5603 Console.WriteLine ("Left is: " + left);
5604 Report.Error (-100, loc, "Support for [" + member_lookup + "] is not present yet");
5605 Environment.Exit (0);
5609 public Expression DoResolve (EmitContext ec, Expression right_side, ResolveFlags flags)
5612 throw new Exception ();
5614 // Resolve the expression with flow analysis turned off, we'll do the definite
5615 // assignment checks later. This is because we don't know yet what the expression
5616 // will resolve to - it may resolve to a FieldExpr and in this case we must do the
5617 // definite assignment check on the actual field and not on the whole struct.
5620 Expression original = expr;
5621 expr = expr.Resolve (ec, flags | ResolveFlags.DisableFlowAnalysis);
5626 if (expr is SimpleName){
5627 SimpleName child_expr = (SimpleName) expr;
5629 Expression new_expr = new SimpleName (child_expr.Name + "." + Identifier, loc);
5631 return new_expr.Resolve (ec, flags);
5635 // TODO: I mailed Ravi about this, and apparently we can get rid
5636 // of this and put it in the right place.
5638 // Handle enums here when they are in transit.
5639 // Note that we cannot afford to hit MemberLookup in this case because
5640 // it will fail to find any members at all
5643 int errors = Report.Errors;
5645 Type expr_type = expr.Type;
5646 if ((expr is TypeExpr) && (expr_type.IsSubclassOf (TypeManager.enum_type))){
5648 Enum en = TypeManager.LookupEnum (expr_type);
5651 object value = en.LookupEnumValue (ec, Identifier, loc);
5654 Constant c = Constantify (value, en.UnderlyingType);
5655 return new EnumConstant (c, expr_type);
5660 if (expr_type.IsPointer){
5661 Error (23, "The `.' operator can not be applied to pointer operands (" +
5662 TypeManager.CSharpName (expr_type) + ")");
5666 member_lookup = MemberLookup (ec, expr_type, Identifier, loc);
5668 if (member_lookup == null){
5669 // Error has already been reported.
5670 if (errors < Report.Errors)
5674 // Try looking the member up from the same type, if we find
5675 // it, we know that the error was due to limited visibility
5677 object lookup = TypeManager.MemberLookup (
5678 expr_type, expr_type, AllMemberTypes, AllBindingFlags |
5679 BindingFlags.NonPublic, Identifier);
5681 Error (117, "`" + expr_type + "' does not contain a " +
5682 "definition for `" + Identifier + "'");
5683 else if ((expr_type != ec.ContainerType) &&
5684 ec.ContainerType.IsSubclassOf (expr_type)){
5686 // Although a derived class can access protected members of
5687 // its base class it cannot do so through an instance of the
5688 // base class (CS1540). If the expr_type is a parent of the
5689 // ec.ContainerType and the lookup succeeds with the latter one,
5690 // then we are in this situation.
5692 lookup = TypeManager.MemberLookup (
5693 ec.ContainerType, ec.ContainerType, AllMemberTypes,
5694 AllBindingFlags, Identifier);
5697 Error (1540, "Cannot access protected member `" +
5698 expr_type + "." + Identifier + "' " +
5699 "via a qualifier of type `" +
5700 TypeManager.CSharpName (expr_type) + "'; the " +
5701 "qualifier must be of type `" +
5702 TypeManager.CSharpName (ec.ContainerType) + "' " +
5703 "(or derived from it)");
5705 Error (122, "`" + expr_type + "." + Identifier + "' " +
5706 "is inaccessible because of its protection level");
5708 Error (122, "`" + expr_type + "." + Identifier + "' " +
5709 "is inaccessible because of its protection level");
5714 if (member_lookup is TypeExpr){
5715 member_lookup.Resolve (ec, ResolveFlags.Type);
5716 return member_lookup;
5717 } else if ((flags & ResolveFlags.MaskExprClass) == ResolveFlags.Type)
5720 member_lookup = ResolveMemberAccess (ec, member_lookup, expr, loc, original);
5721 if (member_lookup == null)
5724 // The following DoResolve/DoResolveLValue will do the definite assignment
5727 if (right_side != null)
5728 member_lookup = member_lookup.DoResolveLValue (ec, right_side);
5730 member_lookup = member_lookup.DoResolve (ec);
5732 return member_lookup;
5735 public override Expression DoResolve (EmitContext ec)
5737 return DoResolve (ec, null, ResolveFlags.VariableOrValue |
5738 ResolveFlags.SimpleName | ResolveFlags.Type);
5741 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
5743 return DoResolve (ec, right_side, ResolveFlags.VariableOrValue |
5744 ResolveFlags.SimpleName | ResolveFlags.Type);
5747 public Expression DoResolveType (EmitContext ec)
5749 return DoResolve (ec, null, ResolveFlags.Type);
5752 public override void Emit (EmitContext ec)
5754 throw new Exception ("Should not happen");
5757 public override string ToString ()
5759 return expr + "." + Identifier;
5764 /// Implements checked expressions
5766 public class CheckedExpr : Expression {
5768 public Expression Expr;
5770 public CheckedExpr (Expression e, Location l)
5776 public override Expression DoResolve (EmitContext ec)
5778 bool last_const_check = ec.ConstantCheckState;
5780 ec.ConstantCheckState = true;
5781 Expr = Expr.Resolve (ec);
5782 ec.ConstantCheckState = last_const_check;
5787 if (Expr is Constant)
5790 eclass = Expr.eclass;
5795 public override void Emit (EmitContext ec)
5797 bool last_check = ec.CheckState;
5798 bool last_const_check = ec.ConstantCheckState;
5800 ec.CheckState = true;
5801 ec.ConstantCheckState = true;
5803 ec.CheckState = last_check;
5804 ec.ConstantCheckState = last_const_check;
5810 /// Implements the unchecked expression
5812 public class UnCheckedExpr : Expression {
5814 public Expression Expr;
5816 public UnCheckedExpr (Expression e, Location l)
5822 public override Expression DoResolve (EmitContext ec)
5824 bool last_const_check = ec.ConstantCheckState;
5826 ec.ConstantCheckState = false;
5827 Expr = Expr.Resolve (ec);
5828 ec.ConstantCheckState = last_const_check;
5833 if (Expr is Constant)
5836 eclass = Expr.eclass;
5841 public override void Emit (EmitContext ec)
5843 bool last_check = ec.CheckState;
5844 bool last_const_check = ec.ConstantCheckState;
5846 ec.CheckState = false;
5847 ec.ConstantCheckState = false;
5849 ec.CheckState = last_check;
5850 ec.ConstantCheckState = last_const_check;
5856 /// An Element Access expression.
5858 /// During semantic analysis these are transformed into
5859 /// IndexerAccess or ArrayAccess
5861 public class ElementAccess : Expression {
5862 public ArrayList Arguments;
5863 public Expression Expr;
5865 public ElementAccess (Expression e, ArrayList e_list, Location l)
5874 Arguments = new ArrayList ();
5875 foreach (Expression tmp in e_list)
5876 Arguments.Add (new Argument (tmp, Argument.AType.Expression));
5880 bool CommonResolve (EmitContext ec)
5882 Expr = Expr.Resolve (ec);
5887 if (Arguments == null)
5890 foreach (Argument a in Arguments){
5891 if (!a.Resolve (ec, loc))
5898 Expression MakePointerAccess ()
5902 if (t == TypeManager.void_ptr_type){
5905 "The array index operation is not valid for void pointers");
5908 if (Arguments.Count != 1){
5911 "A pointer must be indexed by a single value");
5914 Expression p = new PointerArithmetic (true, Expr, ((Argument)Arguments [0]).Expr,
5916 return new Indirection (p, loc);
5919 public override Expression DoResolve (EmitContext ec)
5921 if (!CommonResolve (ec))
5925 // We perform some simple tests, and then to "split" the emit and store
5926 // code we create an instance of a different class, and return that.
5928 // I am experimenting with this pattern.
5933 return (new ArrayAccess (this, loc)).Resolve (ec);
5934 else if (t.IsPointer)
5935 return MakePointerAccess ();
5937 return (new IndexerAccess (this, loc)).Resolve (ec);
5940 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
5942 if (!CommonResolve (ec))
5947 return (new ArrayAccess (this, loc)).ResolveLValue (ec, right_side);
5948 else if (t.IsPointer)
5949 return MakePointerAccess ();
5951 return (new IndexerAccess (this, loc)).ResolveLValue (ec, right_side);
5954 public override void Emit (EmitContext ec)
5956 throw new Exception ("Should never be reached");
5961 /// Implements array access
5963 public class ArrayAccess : Expression, IAssignMethod, IMemoryLocation {
5965 // Points to our "data" repository
5969 LocalTemporary [] cached_locations;
5971 public ArrayAccess (ElementAccess ea_data, Location l)
5974 eclass = ExprClass.Variable;
5978 public override Expression DoResolve (EmitContext ec)
5980 ExprClass eclass = ea.Expr.eclass;
5983 // As long as the type is valid
5984 if (!(eclass == ExprClass.Variable || eclass == ExprClass.PropertyAccess ||
5985 eclass == ExprClass.Value)) {
5986 ea.Expr.Error118 ("variable or value");
5991 Type t = ea.Expr.Type;
5992 if (t.GetArrayRank () != ea.Arguments.Count){
5994 "Incorrect number of indexes for array " +
5995 " expected: " + t.GetArrayRank () + " got: " +
5996 ea.Arguments.Count);
5999 type = TypeManager.TypeToCoreType (t.GetElementType ());
6000 if (type.IsPointer && !ec.InUnsafe){
6001 UnsafeError (ea.Location);
6005 foreach (Argument a in ea.Arguments){
6006 Type argtype = a.Type;
6008 if (argtype == TypeManager.int32_type ||
6009 argtype == TypeManager.uint32_type ||
6010 argtype == TypeManager.int64_type ||
6011 argtype == TypeManager.uint64_type)
6015 // Mhm. This is strage, because the Argument.Type is not the same as
6016 // Argument.Expr.Type: the value changes depending on the ref/out setting.
6018 // Wonder if I will run into trouble for this.
6020 a.Expr = ExpressionToArrayArgument (ec, a.Expr, ea.Location);
6025 eclass = ExprClass.Variable;
6031 /// Emits the right opcode to load an object of Type `t'
6032 /// from an array of T
6034 static public void EmitLoadOpcode (ILGenerator ig, Type type)
6036 if (type == TypeManager.byte_type || type == TypeManager.bool_type)
6037 ig.Emit (OpCodes.Ldelem_U1);
6038 else if (type == TypeManager.sbyte_type)
6039 ig.Emit (OpCodes.Ldelem_I1);
6040 else if (type == TypeManager.short_type)
6041 ig.Emit (OpCodes.Ldelem_I2);
6042 else if (type == TypeManager.ushort_type || type == TypeManager.char_type)
6043 ig.Emit (OpCodes.Ldelem_U2);
6044 else if (type == TypeManager.int32_type)
6045 ig.Emit (OpCodes.Ldelem_I4);
6046 else if (type == TypeManager.uint32_type)
6047 ig.Emit (OpCodes.Ldelem_U4);
6048 else if (type == TypeManager.uint64_type)
6049 ig.Emit (OpCodes.Ldelem_I8);
6050 else if (type == TypeManager.int64_type)
6051 ig.Emit (OpCodes.Ldelem_I8);
6052 else if (type == TypeManager.float_type)
6053 ig.Emit (OpCodes.Ldelem_R4);
6054 else if (type == TypeManager.double_type)
6055 ig.Emit (OpCodes.Ldelem_R8);
6056 else if (type == TypeManager.intptr_type)
6057 ig.Emit (OpCodes.Ldelem_I);
6058 else if (type.IsValueType){
6059 ig.Emit (OpCodes.Ldelema, type);
6060 ig.Emit (OpCodes.Ldobj, type);
6062 ig.Emit (OpCodes.Ldelem_Ref);
6066 /// Emits the right opcode to store an object of Type `t'
6067 /// from an array of T.
6069 static public void EmitStoreOpcode (ILGenerator ig, Type t)
6071 t = TypeManager.TypeToCoreType (t);
6072 if (TypeManager.IsEnumType (t) && t != TypeManager.enum_type)
6073 t = TypeManager.EnumToUnderlying (t);
6074 if (t == TypeManager.byte_type || t == TypeManager.sbyte_type ||
6075 t == TypeManager.bool_type)
6076 ig.Emit (OpCodes.Stelem_I1);
6077 else if (t == TypeManager.short_type || t == TypeManager.ushort_type || t == TypeManager.char_type)
6078 ig.Emit (OpCodes.Stelem_I2);
6079 else if (t == TypeManager.int32_type || t == TypeManager.uint32_type)
6080 ig.Emit (OpCodes.Stelem_I4);
6081 else if (t == TypeManager.int64_type || t == TypeManager.uint64_type)
6082 ig.Emit (OpCodes.Stelem_I8);
6083 else if (t == TypeManager.float_type)
6084 ig.Emit (OpCodes.Stelem_R4);
6085 else if (t == TypeManager.double_type)
6086 ig.Emit (OpCodes.Stelem_R8);
6087 else if (t == TypeManager.intptr_type)
6088 ig.Emit (OpCodes.Stelem_I);
6089 else if (t.IsValueType){
6090 ig.Emit (OpCodes.Stobj, t);
6092 ig.Emit (OpCodes.Stelem_Ref);
6095 MethodInfo FetchGetMethod ()
6097 ModuleBuilder mb = CodeGen.ModuleBuilder;
6098 int arg_count = ea.Arguments.Count;
6099 Type [] args = new Type [arg_count];
6102 for (int i = 0; i < arg_count; i++){
6103 //args [i++] = a.Type;
6104 args [i] = TypeManager.int32_type;
6107 get = mb.GetArrayMethod (
6108 ea.Expr.Type, "Get",
6109 CallingConventions.HasThis |
6110 CallingConventions.Standard,
6116 MethodInfo FetchAddressMethod ()
6118 ModuleBuilder mb = CodeGen.ModuleBuilder;
6119 int arg_count = ea.Arguments.Count;
6120 Type [] args = new Type [arg_count];
6122 string ptr_type_name;
6125 ptr_type_name = type.FullName + "&";
6126 ret_type = Type.GetType (ptr_type_name);
6129 // It is a type defined by the source code we are compiling
6131 if (ret_type == null){
6132 ret_type = mb.GetType (ptr_type_name);
6135 for (int i = 0; i < arg_count; i++){
6136 //args [i++] = a.Type;
6137 args [i] = TypeManager.int32_type;
6140 address = mb.GetArrayMethod (
6141 ea.Expr.Type, "Address",
6142 CallingConventions.HasThis |
6143 CallingConventions.Standard,
6150 // Load the array arguments into the stack.
6152 // If we have been requested to cache the values (cached_locations array
6153 // initialized), then load the arguments the first time and store them
6154 // in locals. otherwise load from local variables.
6156 void LoadArrayAndArguments (EmitContext ec)
6158 ILGenerator ig = ec.ig;
6160 if (cached_locations == null){
6162 foreach (Argument a in ea.Arguments){
6163 Type argtype = a.Expr.Type;
6167 if (argtype == TypeManager.int64_type)
6168 ig.Emit (OpCodes.Conv_Ovf_I);
6169 else if (argtype == TypeManager.uint64_type)
6170 ig.Emit (OpCodes.Conv_Ovf_I_Un);
6175 if (cached_locations [0] == null){
6176 cached_locations [0] = new LocalTemporary (ec, ea.Expr.Type);
6178 ig.Emit (OpCodes.Dup);
6179 cached_locations [0].Store (ec);
6183 foreach (Argument a in ea.Arguments){
6184 Type argtype = a.Expr.Type;
6186 cached_locations [j] = new LocalTemporary (ec, TypeManager.intptr_type /* a.Expr.Type */);
6188 if (argtype == TypeManager.int64_type)
6189 ig.Emit (OpCodes.Conv_Ovf_I);
6190 else if (argtype == TypeManager.uint64_type)
6191 ig.Emit (OpCodes.Conv_Ovf_I_Un);
6193 ig.Emit (OpCodes.Dup);
6194 cached_locations [j].Store (ec);
6200 foreach (LocalTemporary lt in cached_locations)
6204 public new void CacheTemporaries (EmitContext ec)
6206 cached_locations = new LocalTemporary [ea.Arguments.Count + 1];
6209 public override void Emit (EmitContext ec)
6211 int rank = ea.Expr.Type.GetArrayRank ();
6212 ILGenerator ig = ec.ig;
6214 LoadArrayAndArguments (ec);
6217 EmitLoadOpcode (ig, type);
6221 method = FetchGetMethod ();
6222 ig.Emit (OpCodes.Call, method);
6226 public void EmitAssign (EmitContext ec, Expression source)
6228 int rank = ea.Expr.Type.GetArrayRank ();
6229 ILGenerator ig = ec.ig;
6230 Type t = source.Type;
6232 LoadArrayAndArguments (ec);
6235 // The stobj opcode used by value types will need
6236 // an address on the stack, not really an array/array
6240 if (t.IsSubclassOf (TypeManager.value_type) && (!TypeManager.IsBuiltinType (t) || t == TypeManager.decimal_type))
6241 ig.Emit (OpCodes.Ldelema, t);
6247 EmitStoreOpcode (ig, t);
6249 ModuleBuilder mb = CodeGen.ModuleBuilder;
6250 int arg_count = ea.Arguments.Count;
6251 Type [] args = new Type [arg_count + 1];
6254 for (int i = 0; i < arg_count; i++){
6255 //args [i++] = a.Type;
6256 args [i] = TypeManager.int32_type;
6259 args [arg_count] = type;
6261 set = mb.GetArrayMethod (
6262 ea.Expr.Type, "Set",
6263 CallingConventions.HasThis |
6264 CallingConventions.Standard,
6265 TypeManager.void_type, args);
6267 ig.Emit (OpCodes.Call, set);
6271 public void AddressOf (EmitContext ec, AddressOp mode)
6273 int rank = ea.Expr.Type.GetArrayRank ();
6274 ILGenerator ig = ec.ig;
6276 LoadArrayAndArguments (ec);
6279 ig.Emit (OpCodes.Ldelema, type);
6281 MethodInfo address = FetchAddressMethod ();
6282 ig.Emit (OpCodes.Call, address);
6289 public ArrayList getters, setters;
6290 static Hashtable map;
6294 map = new Hashtable ();
6297 Indexers (MemberInfo [] mi)
6299 foreach (PropertyInfo property in mi){
6300 MethodInfo get, set;
6302 get = property.GetGetMethod (true);
6304 if (getters == null)
6305 getters = new ArrayList ();
6310 set = property.GetSetMethod (true);
6312 if (setters == null)
6313 setters = new ArrayList ();
6319 static private Indexers GetIndexersForTypeOrInterface (Type caller_type, Type lookup_type)
6321 Indexers ix = (Indexers) map [lookup_type];
6326 string p_name = TypeManager.IndexerPropertyName (lookup_type);
6328 MemberInfo [] mi = TypeManager.MemberLookup (
6329 caller_type, lookup_type, MemberTypes.Property,
6330 BindingFlags.Public | BindingFlags.Instance, p_name);
6332 if (mi == null || mi.Length == 0)
6335 ix = new Indexers (mi);
6336 map [lookup_type] = ix;
6341 static public Indexers GetIndexersForType (Type caller_type, Type lookup_type, Location loc)
6343 Indexers ix = (Indexers) map [lookup_type];
6348 ix = GetIndexersForTypeOrInterface (caller_type, lookup_type);
6352 Type [] ifaces = TypeManager.GetInterfaces (lookup_type);
6353 if (ifaces != null) {
6354 foreach (Type itype in ifaces) {
6355 ix = GetIndexersForTypeOrInterface (caller_type, itype);
6361 Report.Error (21, loc,
6362 "Type `" + TypeManager.CSharpName (lookup_type) +
6363 "' does not have any indexers defined");
6369 /// Expressions that represent an indexer call.
6371 public class IndexerAccess : Expression, IAssignMethod {
6373 // Points to our "data" repository
6375 MethodInfo get, set;
6377 ArrayList set_arguments;
6378 bool is_base_indexer;
6380 protected Type indexer_type;
6381 protected Type current_type;
6382 protected Expression instance_expr;
6383 protected ArrayList arguments;
6385 public IndexerAccess (ElementAccess ea, Location loc)
6386 : this (ea.Expr, false, loc)
6388 this.arguments = ea.Arguments;
6391 protected IndexerAccess (Expression instance_expr, bool is_base_indexer,
6394 this.instance_expr = instance_expr;
6395 this.is_base_indexer = is_base_indexer;
6396 this.eclass = ExprClass.Value;
6400 protected virtual bool CommonResolve (EmitContext ec)
6402 indexer_type = instance_expr.Type;
6403 current_type = ec.ContainerType;
6408 public override Expression DoResolve (EmitContext ec)
6410 if (!CommonResolve (ec))
6414 // Step 1: Query for all `Item' *properties*. Notice
6415 // that the actual methods are pointed from here.
6417 // This is a group of properties, piles of them.
6420 ilist = Indexers.GetIndexersForType (
6421 current_type, indexer_type, loc);
6424 // Step 2: find the proper match
6426 if (ilist != null && ilist.getters != null && ilist.getters.Count > 0)
6427 get = (MethodInfo) Invocation.OverloadResolve (
6428 ec, new MethodGroupExpr (ilist.getters, loc), arguments, loc);
6431 Error (154, "indexer can not be used in this context, because " +
6432 "it lacks a `get' accessor");
6436 type = get.ReturnType;
6437 if (type.IsPointer && !ec.InUnsafe){
6442 eclass = ExprClass.IndexerAccess;
6446 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
6448 if (!CommonResolve (ec))
6451 Type right_type = right_side.Type;
6454 ilist = Indexers.GetIndexersForType (
6455 current_type, indexer_type, loc);
6457 if (ilist != null && ilist.setters != null && ilist.setters.Count > 0){
6458 set_arguments = (ArrayList) arguments.Clone ();
6459 set_arguments.Add (new Argument (right_side, Argument.AType.Expression));
6461 set = (MethodInfo) Invocation.OverloadResolve (
6462 ec, new MethodGroupExpr (ilist.setters, loc), set_arguments, loc);
6466 Error (200, "indexer X.this [" + TypeManager.CSharpName (right_type) +
6467 "] lacks a `set' accessor");
6471 type = TypeManager.void_type;
6472 eclass = ExprClass.IndexerAccess;
6476 public override void Emit (EmitContext ec)
6478 Invocation.EmitCall (ec, false, false, instance_expr, get, arguments, loc);
6482 // source is ignored, because we already have a copy of it from the
6483 // LValue resolution and we have already constructed a pre-cached
6484 // version of the arguments (ea.set_arguments);
6486 public void EmitAssign (EmitContext ec, Expression source)
6488 Invocation.EmitCall (ec, false, false, instance_expr, set, set_arguments, loc);
6493 /// The base operator for method names
6495 public class BaseAccess : Expression {
6498 public BaseAccess (string member, Location l)
6500 this.member = member;
6504 public override Expression DoResolve (EmitContext ec)
6506 Expression member_lookup;
6507 Type current_type = ec.ContainerType;
6508 Type base_type = current_type.BaseType;
6513 "Keyword base is not allowed in static method");
6517 member_lookup = MemberLookup (ec, base_type, base_type, member,
6518 AllMemberTypes, AllBindingFlags, loc);
6519 if (member_lookup == null) {
6521 TypeManager.CSharpName (base_type) + " does not " +
6522 "contain a definition for `" + member + "'");
6529 left = new TypeExpr (base_type, loc);
6533 e = MemberAccess.ResolveMemberAccess (ec, member_lookup, left, loc, null);
6535 if (e is PropertyExpr){
6536 PropertyExpr pe = (PropertyExpr) e;
6544 public override void Emit (EmitContext ec)
6546 throw new Exception ("Should never be called");
6551 /// The base indexer operator
6553 public class BaseIndexerAccess : IndexerAccess {
6554 public BaseIndexerAccess (ArrayList args, Location loc)
6555 : base (null, true, loc)
6557 arguments = new ArrayList ();
6558 foreach (Expression tmp in args)
6559 arguments.Add (new Argument (tmp, Argument.AType.Expression));
6562 protected override bool CommonResolve (EmitContext ec)
6564 instance_expr = ec.This;
6566 current_type = ec.ContainerType.BaseType;
6567 indexer_type = current_type;
6569 foreach (Argument a in arguments){
6570 if (!a.Resolve (ec, loc))
6579 /// This class exists solely to pass the Type around and to be a dummy
6580 /// that can be passed to the conversion functions (this is used by
6581 /// foreach implementation to typecast the object return value from
6582 /// get_Current into the proper type. All code has been generated and
6583 /// we only care about the side effect conversions to be performed
6585 /// This is also now used as a placeholder where a no-action expression
6586 /// is needed (the `New' class).
6588 public class EmptyExpression : Expression {
6589 public EmptyExpression ()
6591 type = TypeManager.object_type;
6592 eclass = ExprClass.Value;
6593 loc = Location.Null;
6596 public EmptyExpression (Type t)
6599 eclass = ExprClass.Value;
6600 loc = Location.Null;
6603 public override Expression DoResolve (EmitContext ec)
6608 public override void Emit (EmitContext ec)
6610 // nothing, as we only exist to not do anything.
6614 // This is just because we might want to reuse this bad boy
6615 // instead of creating gazillions of EmptyExpressions.
6616 // (CanConvertImplicit uses it)
6618 public void SetType (Type t)
6624 public class UserCast : Expression {
6628 public UserCast (MethodInfo method, Expression source, Location l)
6630 this.method = method;
6631 this.source = source;
6632 type = method.ReturnType;
6633 eclass = ExprClass.Value;
6637 public override Expression DoResolve (EmitContext ec)
6640 // We are born fully resolved
6645 public override void Emit (EmitContext ec)
6647 ILGenerator ig = ec.ig;
6651 if (method is MethodInfo)
6652 ig.Emit (OpCodes.Call, (MethodInfo) method);
6654 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
6660 // This class is used to "construct" the type during a typecast
6661 // operation. Since the Type.GetType class in .NET can parse
6662 // the type specification, we just use this to construct the type
6663 // one bit at a time.
6665 public class ComposedCast : Expression, ITypeExpression {
6669 public ComposedCast (Expression left, string dim, Location l)
6676 public Expression DoResolveType (EmitContext ec)
6678 Type ltype = ec.DeclSpace.ResolveType (left, false, loc);
6682 type = RootContext.LookupType (
6683 ec.DeclSpace, ltype.FullName + dim, false, loc);
6687 if (!ec.ResolvingTypeTree){
6689 // If the above flag is set, this is being invoked from the ResolveType function.
6690 // Upper layers take care of the type validity in this context.
6692 if (!ec.InUnsafe && type.IsPointer){
6698 eclass = ExprClass.Type;
6702 public override Expression DoResolve (EmitContext ec)
6704 return DoResolveType (ec);
6707 public override void Emit (EmitContext ec)
6709 throw new Exception ("This should never be called");
6712 public override string ToString ()
6719 // This class is used to represent the address of an array, used
6720 // only by the Fixed statement, this is like the C "&a [0]" construct.
6722 public class ArrayPtr : Expression {
6725 public ArrayPtr (Expression array, Location l)
6727 Type array_type = array.Type.GetElementType ();
6731 string array_ptr_type_name = array_type.FullName + "*";
6733 type = Type.GetType (array_ptr_type_name);
6735 ModuleBuilder mb = CodeGen.ModuleBuilder;
6737 type = mb.GetType (array_ptr_type_name);
6740 eclass = ExprClass.Value;
6744 public override void Emit (EmitContext ec)
6746 ILGenerator ig = ec.ig;
6749 IntLiteral.EmitInt (ig, 0);
6750 ig.Emit (OpCodes.Ldelema, array.Type.GetElementType ());
6753 public override Expression DoResolve (EmitContext ec)
6756 // We are born fully resolved
6763 // Used by the fixed statement
6765 public class StringPtr : Expression {
6768 public StringPtr (LocalBuilder b, Location l)
6771 eclass = ExprClass.Value;
6772 type = TypeManager.char_ptr_type;
6776 public override Expression DoResolve (EmitContext ec)
6778 // This should never be invoked, we are born in fully
6779 // initialized state.
6784 public override void Emit (EmitContext ec)
6786 ILGenerator ig = ec.ig;
6788 ig.Emit (OpCodes.Ldloc, b);
6789 ig.Emit (OpCodes.Conv_I);
6790 ig.Emit (OpCodes.Call, TypeManager.int_get_offset_to_string_data);
6791 ig.Emit (OpCodes.Add);
6796 // Implements the `stackalloc' keyword
6798 public class StackAlloc : Expression {
6803 public StackAlloc (Expression type, Expression count, Location l)
6810 public override Expression DoResolve (EmitContext ec)
6812 count = count.Resolve (ec);
6816 if (count.Type != TypeManager.int32_type){
6817 count = ConvertImplicitRequired (ec, count, TypeManager.int32_type, loc);
6822 if (ec.InCatch || ec.InFinally){
6824 "stackalloc can not be used in a catch or finally block");
6828 otype = ec.DeclSpace.ResolveType (t, false, loc);
6833 if (!TypeManager.VerifyUnManaged (otype, loc))
6836 string ptr_name = otype.FullName + "*";
6837 type = Type.GetType (ptr_name);
6839 ModuleBuilder mb = CodeGen.ModuleBuilder;
6841 type = mb.GetType (ptr_name);
6843 eclass = ExprClass.Value;
6848 public override void Emit (EmitContext ec)
6850 int size = GetTypeSize (otype);
6851 ILGenerator ig = ec.ig;
6854 ig.Emit (OpCodes.Sizeof, otype);
6856 IntConstant.EmitInt (ig, size);
6858 ig.Emit (OpCodes.Mul);
6859 ig.Emit (OpCodes.Localloc);