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);
1209 if (expr is SByteConstant){
1210 sbyte v = ((SByteConstant) expr).Value;
1212 if (target_type == TypeManager.byte_type)
1213 return new ByteConstant ((byte) v);
1214 if (target_type == TypeManager.short_type)
1215 return new ShortConstant ((short) v);
1216 if (target_type == TypeManager.ushort_type)
1217 return new UShortConstant ((ushort) v);
1218 if (target_type == TypeManager.int32_type)
1219 return new IntConstant ((int) v);
1220 if (target_type == TypeManager.uint32_type)
1221 return new UIntConstant ((uint) v);
1222 if (target_type == TypeManager.int64_type)
1223 return new LongConstant ((long) v);
1224 if (target_type == TypeManager.uint64_type)
1225 return new ULongConstant ((ulong) v);
1226 if (target_type == TypeManager.float_type)
1227 return new FloatConstant ((float) v);
1228 if (target_type == TypeManager.double_type)
1229 return new DoubleConstant ((double) v);
1230 if (target_type == TypeManager.char_type)
1231 return new CharConstant ((char) v);
1233 if (expr is ShortConstant){
1234 short v = ((ShortConstant) expr).Value;
1236 if (target_type == TypeManager.byte_type)
1237 return new ByteConstant ((byte) v);
1238 if (target_type == TypeManager.sbyte_type)
1239 return new SByteConstant ((sbyte) v);
1240 if (target_type == TypeManager.ushort_type)
1241 return new UShortConstant ((ushort) v);
1242 if (target_type == TypeManager.int32_type)
1243 return new IntConstant ((int) v);
1244 if (target_type == TypeManager.uint32_type)
1245 return new UIntConstant ((uint) v);
1246 if (target_type == TypeManager.int64_type)
1247 return new LongConstant ((long) v);
1248 if (target_type == TypeManager.uint64_type)
1249 return new ULongConstant ((ulong) v);
1250 if (target_type == TypeManager.float_type)
1251 return new FloatConstant ((float) v);
1252 if (target_type == TypeManager.double_type)
1253 return new DoubleConstant ((double) v);
1254 if (target_type == TypeManager.char_type)
1255 return new CharConstant ((char) v);
1257 if (expr is UShortConstant){
1258 ushort v = ((UShortConstant) expr).Value;
1260 if (target_type == TypeManager.byte_type)
1261 return new ByteConstant ((byte) v);
1262 if (target_type == TypeManager.sbyte_type)
1263 return new SByteConstant ((sbyte) v);
1264 if (target_type == TypeManager.short_type)
1265 return new ShortConstant ((short) v);
1266 if (target_type == TypeManager.int32_type)
1267 return new IntConstant ((int) v);
1268 if (target_type == TypeManager.uint32_type)
1269 return new UIntConstant ((uint) v);
1270 if (target_type == TypeManager.int64_type)
1271 return new LongConstant ((long) v);
1272 if (target_type == TypeManager.uint64_type)
1273 return new ULongConstant ((ulong) v);
1274 if (target_type == TypeManager.float_type)
1275 return new FloatConstant ((float) v);
1276 if (target_type == TypeManager.double_type)
1277 return new DoubleConstant ((double) v);
1278 if (target_type == TypeManager.char_type)
1279 return new CharConstant ((char) v);
1281 if (expr is IntConstant){
1282 int v = ((IntConstant) expr).Value;
1284 if (target_type == TypeManager.byte_type)
1285 return new ByteConstant ((byte) v);
1286 if (target_type == TypeManager.sbyte_type)
1287 return new SByteConstant ((sbyte) v);
1288 if (target_type == TypeManager.short_type)
1289 return new ShortConstant ((short) v);
1290 if (target_type == TypeManager.ushort_type)
1291 return new UShortConstant ((ushort) v);
1292 if (target_type == TypeManager.uint32_type)
1293 return new UIntConstant ((uint) v);
1294 if (target_type == TypeManager.int64_type)
1295 return new LongConstant ((long) v);
1296 if (target_type == TypeManager.uint64_type)
1297 return new ULongConstant ((ulong) v);
1298 if (target_type == TypeManager.float_type)
1299 return new FloatConstant ((float) v);
1300 if (target_type == TypeManager.double_type)
1301 return new DoubleConstant ((double) v);
1302 if (target_type == TypeManager.char_type)
1303 return new CharConstant ((char) v);
1305 if (expr is UIntConstant){
1306 uint v = ((UIntConstant) expr).Value;
1308 if (target_type == TypeManager.byte_type)
1309 return new ByteConstant ((byte) v);
1310 if (target_type == TypeManager.sbyte_type)
1311 return new SByteConstant ((sbyte) v);
1312 if (target_type == TypeManager.short_type)
1313 return new ShortConstant ((short) v);
1314 if (target_type == TypeManager.ushort_type)
1315 return new UShortConstant ((ushort) v);
1316 if (target_type == TypeManager.int32_type)
1317 return new IntConstant ((int) v);
1318 if (target_type == TypeManager.int64_type)
1319 return new LongConstant ((long) v);
1320 if (target_type == TypeManager.uint64_type)
1321 return new ULongConstant ((ulong) v);
1322 if (target_type == TypeManager.float_type)
1323 return new FloatConstant ((float) v);
1324 if (target_type == TypeManager.double_type)
1325 return new DoubleConstant ((double) v);
1326 if (target_type == TypeManager.char_type)
1327 return new CharConstant ((char) v);
1329 if (expr is LongConstant){
1330 long v = ((LongConstant) expr).Value;
1332 if (target_type == TypeManager.byte_type)
1333 return new ByteConstant ((byte) v);
1334 if (target_type == TypeManager.sbyte_type)
1335 return new SByteConstant ((sbyte) v);
1336 if (target_type == TypeManager.short_type)
1337 return new ShortConstant ((short) v);
1338 if (target_type == TypeManager.ushort_type)
1339 return new UShortConstant ((ushort) v);
1340 if (target_type == TypeManager.int32_type)
1341 return new IntConstant ((int) v);
1342 if (target_type == TypeManager.uint32_type)
1343 return new UIntConstant ((uint) v);
1344 if (target_type == TypeManager.uint64_type)
1345 return new ULongConstant ((ulong) v);
1346 if (target_type == TypeManager.float_type)
1347 return new FloatConstant ((float) v);
1348 if (target_type == TypeManager.double_type)
1349 return new DoubleConstant ((double) v);
1350 if (target_type == TypeManager.char_type)
1351 return new CharConstant ((char) v);
1353 if (expr is ULongConstant){
1354 ulong v = ((ULongConstant) expr).Value;
1356 if (target_type == TypeManager.byte_type)
1357 return new ByteConstant ((byte) v);
1358 if (target_type == TypeManager.sbyte_type)
1359 return new SByteConstant ((sbyte) v);
1360 if (target_type == TypeManager.short_type)
1361 return new ShortConstant ((short) v);
1362 if (target_type == TypeManager.ushort_type)
1363 return new UShortConstant ((ushort) v);
1364 if (target_type == TypeManager.int32_type)
1365 return new IntConstant ((int) v);
1366 if (target_type == TypeManager.uint32_type)
1367 return new UIntConstant ((uint) v);
1368 if (target_type == TypeManager.int64_type)
1369 return new LongConstant ((long) v);
1370 if (target_type == TypeManager.float_type)
1371 return new FloatConstant ((float) v);
1372 if (target_type == TypeManager.double_type)
1373 return new DoubleConstant ((double) v);
1374 if (target_type == TypeManager.char_type)
1375 return new CharConstant ((char) v);
1377 if (expr is FloatConstant){
1378 float v = ((FloatConstant) expr).Value;
1380 if (target_type == TypeManager.byte_type)
1381 return new ByteConstant ((byte) v);
1382 if (target_type == TypeManager.sbyte_type)
1383 return new SByteConstant ((sbyte) v);
1384 if (target_type == TypeManager.short_type)
1385 return new ShortConstant ((short) v);
1386 if (target_type == TypeManager.ushort_type)
1387 return new UShortConstant ((ushort) v);
1388 if (target_type == TypeManager.int32_type)
1389 return new IntConstant ((int) v);
1390 if (target_type == TypeManager.uint32_type)
1391 return new UIntConstant ((uint) v);
1392 if (target_type == TypeManager.int64_type)
1393 return new LongConstant ((long) v);
1394 if (target_type == TypeManager.uint64_type)
1395 return new ULongConstant ((ulong) v);
1396 if (target_type == TypeManager.double_type)
1397 return new DoubleConstant ((double) v);
1398 if (target_type == TypeManager.char_type)
1399 return new CharConstant ((char) v);
1401 if (expr is DoubleConstant){
1402 double v = ((DoubleConstant) expr).Value;
1404 if (target_type == TypeManager.byte_type)
1405 return new ByteConstant ((byte) v);
1406 if (target_type == TypeManager.sbyte_type)
1407 return new SByteConstant ((sbyte) v);
1408 if (target_type == TypeManager.short_type)
1409 return new ShortConstant ((short) v);
1410 if (target_type == TypeManager.ushort_type)
1411 return new UShortConstant ((ushort) v);
1412 if (target_type == TypeManager.int32_type)
1413 return new IntConstant ((int) v);
1414 if (target_type == TypeManager.uint32_type)
1415 return new UIntConstant ((uint) v);
1416 if (target_type == TypeManager.int64_type)
1417 return new LongConstant ((long) v);
1418 if (target_type == TypeManager.uint64_type)
1419 return new ULongConstant ((ulong) v);
1420 if (target_type == TypeManager.float_type)
1421 return new FloatConstant ((float) v);
1422 if (target_type == TypeManager.char_type)
1423 return new CharConstant ((char) v);
1429 public override Expression DoResolve (EmitContext ec)
1431 expr = expr.Resolve (ec);
1435 int errors = Report.Errors;
1437 type = ec.DeclSpace.ResolveType (target_type, false, Location);
1442 eclass = ExprClass.Value;
1444 if (expr is Constant){
1445 Expression e = TryReduce (ec, type);
1451 expr = ConvertExplicit (ec, expr, type, loc);
1455 public override void Emit (EmitContext ec)
1458 // This one will never happen
1460 throw new Exception ("Should not happen");
1465 /// Binary operators
1467 public class Binary : Expression {
1468 public enum Operator : byte {
1469 Multiply, Division, Modulus,
1470 Addition, Subtraction,
1471 LeftShift, RightShift,
1472 LessThan, GreaterThan, LessThanOrEqual, GreaterThanOrEqual,
1473 Equality, Inequality,
1483 Expression left, right;
1486 // After resolution, method might contain the operator overload
1489 protected MethodBase method;
1490 ArrayList Arguments;
1492 bool DelegateOperation;
1494 // This must be kept in sync with Operator!!!
1495 static string [] oper_names;
1499 oper_names = new string [(int) Operator.TOP];
1501 oper_names [(int) Operator.Multiply] = "op_Multiply";
1502 oper_names [(int) Operator.Division] = "op_Division";
1503 oper_names [(int) Operator.Modulus] = "op_Modulus";
1504 oper_names [(int) Operator.Addition] = "op_Addition";
1505 oper_names [(int) Operator.Subtraction] = "op_Subtraction";
1506 oper_names [(int) Operator.LeftShift] = "op_LeftShift";
1507 oper_names [(int) Operator.RightShift] = "op_RightShift";
1508 oper_names [(int) Operator.LessThan] = "op_LessThan";
1509 oper_names [(int) Operator.GreaterThan] = "op_GreaterThan";
1510 oper_names [(int) Operator.LessThanOrEqual] = "op_LessThanOrEqual";
1511 oper_names [(int) Operator.GreaterThanOrEqual] = "op_GreaterThanOrEqual";
1512 oper_names [(int) Operator.Equality] = "op_Equality";
1513 oper_names [(int) Operator.Inequality] = "op_Inequality";
1514 oper_names [(int) Operator.BitwiseAnd] = "op_BitwiseAnd";
1515 oper_names [(int) Operator.BitwiseOr] = "op_BitwiseOr";
1516 oper_names [(int) Operator.ExclusiveOr] = "op_ExclusiveOr";
1517 oper_names [(int) Operator.LogicalOr] = "op_LogicalOr";
1518 oper_names [(int) Operator.LogicalAnd] = "op_LogicalAnd";
1521 public Binary (Operator oper, Expression left, Expression right, Location loc)
1529 public Operator Oper {
1538 public Expression Left {
1547 public Expression Right {
1558 /// Returns a stringified representation of the Operator
1560 static string OperName (Operator oper)
1563 case Operator.Multiply:
1565 case Operator.Division:
1567 case Operator.Modulus:
1569 case Operator.Addition:
1571 case Operator.Subtraction:
1573 case Operator.LeftShift:
1575 case Operator.RightShift:
1577 case Operator.LessThan:
1579 case Operator.GreaterThan:
1581 case Operator.LessThanOrEqual:
1583 case Operator.GreaterThanOrEqual:
1585 case Operator.Equality:
1587 case Operator.Inequality:
1589 case Operator.BitwiseAnd:
1591 case Operator.BitwiseOr:
1593 case Operator.ExclusiveOr:
1595 case Operator.LogicalOr:
1597 case Operator.LogicalAnd:
1601 return oper.ToString ();
1604 public override string ToString ()
1606 return "operator " + OperName (oper) + "(" + left.ToString () + ", " +
1607 right.ToString () + ")";
1610 Expression ForceConversion (EmitContext ec, Expression expr, Type target_type)
1612 if (expr.Type == target_type)
1615 return ConvertImplicit (ec, expr, target_type, new Location (-1));
1618 public static void Error_OperatorAmbiguous (Location loc, Operator oper, Type l, Type r)
1621 34, loc, "Operator `" + OperName (oper)
1622 + "' is ambiguous on operands of type `"
1623 + TypeManager.CSharpName (l) + "' "
1624 + "and `" + TypeManager.CSharpName (r)
1629 // Note that handling the case l == Decimal || r == Decimal
1630 // is taken care of by the Step 1 Operator Overload resolution.
1632 bool DoNumericPromotions (EmitContext ec, Type l, Type r)
1634 if (l == TypeManager.double_type || r == TypeManager.double_type){
1636 // If either operand is of type double, the other operand is
1637 // conveted to type double.
1639 if (r != TypeManager.double_type)
1640 right = ConvertImplicit (ec, right, TypeManager.double_type, loc);
1641 if (l != TypeManager.double_type)
1642 left = ConvertImplicit (ec, left, TypeManager.double_type, loc);
1644 type = TypeManager.double_type;
1645 } else if (l == TypeManager.float_type || r == TypeManager.float_type){
1647 // if either operand is of type float, the other operand is
1648 // converted to type float.
1650 if (r != TypeManager.double_type)
1651 right = ConvertImplicit (ec, right, TypeManager.float_type, loc);
1652 if (l != TypeManager.double_type)
1653 left = ConvertImplicit (ec, left, TypeManager.float_type, loc);
1654 type = TypeManager.float_type;
1655 } else if (l == TypeManager.uint64_type || r == TypeManager.uint64_type){
1659 // If either operand is of type ulong, the other operand is
1660 // converted to type ulong. or an error ocurrs if the other
1661 // operand is of type sbyte, short, int or long
1663 if (l == TypeManager.uint64_type){
1664 if (r != TypeManager.uint64_type){
1665 if (right is IntConstant){
1666 IntConstant ic = (IntConstant) right;
1668 e = TryImplicitIntConversion (l, ic);
1671 } else if (right is LongConstant){
1672 long ll = ((LongConstant) right).Value;
1675 right = new ULongConstant ((ulong) ll);
1677 e = ImplicitNumericConversion (ec, right, l, loc);
1684 if (left is IntConstant){
1685 e = TryImplicitIntConversion (r, (IntConstant) left);
1688 } else if (left is LongConstant){
1689 long ll = ((LongConstant) left).Value;
1692 left = new ULongConstant ((ulong) ll);
1694 e = ImplicitNumericConversion (ec, left, r, loc);
1701 if ((other == TypeManager.sbyte_type) ||
1702 (other == TypeManager.short_type) ||
1703 (other == TypeManager.int32_type) ||
1704 (other == TypeManager.int64_type))
1705 Error_OperatorAmbiguous (loc, oper, l, r);
1706 type = TypeManager.uint64_type;
1707 } else if (l == TypeManager.int64_type || r == TypeManager.int64_type){
1709 // If either operand is of type long, the other operand is converted
1712 if (l != TypeManager.int64_type)
1713 left = ConvertImplicit (ec, left, TypeManager.int64_type, loc);
1714 if (r != TypeManager.int64_type)
1715 right = ConvertImplicit (ec, right, TypeManager.int64_type, loc);
1717 type = TypeManager.int64_type;
1718 } else if (l == TypeManager.uint32_type || r == TypeManager.uint32_type){
1720 // If either operand is of type uint, and the other
1721 // operand is of type sbyte, short or int, othe operands are
1722 // converted to type long.
1726 if (l == TypeManager.uint32_type){
1727 if (right is IntConstant){
1728 IntConstant ic = (IntConstant) right;
1732 right = new UIntConstant ((uint) val);
1739 else if (r == TypeManager.uint32_type){
1740 if (left is IntConstant){
1741 IntConstant ic = (IntConstant) left;
1745 left = new UIntConstant ((uint) val);
1754 if ((other == TypeManager.sbyte_type) ||
1755 (other == TypeManager.short_type) ||
1756 (other == TypeManager.int32_type)){
1757 left = ForceConversion (ec, left, TypeManager.int64_type);
1758 right = ForceConversion (ec, right, TypeManager.int64_type);
1759 type = TypeManager.int64_type;
1762 // if either operand is of type uint, the other
1763 // operand is converd to type uint
1765 left = ForceConversion (ec, left, TypeManager.uint32_type);
1766 right = ForceConversion (ec, right, TypeManager.uint32_type);
1767 type = TypeManager.uint32_type;
1769 } else if (l == TypeManager.decimal_type || r == TypeManager.decimal_type){
1770 if (l != TypeManager.decimal_type)
1771 left = ConvertImplicit (ec, left, TypeManager.decimal_type, loc);
1772 if (r != TypeManager.decimal_type)
1773 right = ConvertImplicit (ec, right, TypeManager.decimal_type, loc);
1775 type = TypeManager.decimal_type;
1777 Expression l_tmp, r_tmp;
1779 l_tmp = ForceConversion (ec, left, TypeManager.int32_type);
1783 r_tmp = ForceConversion (ec, right, TypeManager.int32_type);
1790 type = TypeManager.int32_type;
1796 static public void Error_OperatorCannotBeApplied (Location loc, string name, Type l, Type r)
1798 Report.Error (19, loc,
1799 "Operator " + name + " cannot be applied to operands of type `" +
1800 TypeManager.CSharpName (l) + "' and `" +
1801 TypeManager.CSharpName (r) + "'");
1804 void Error_OperatorCannotBeApplied ()
1806 Error_OperatorCannotBeApplied (loc, OperName (oper), left.Type, right.Type);
1809 static bool is_32_or_64 (Type t)
1811 return (t == TypeManager.int32_type || t == TypeManager.uint32_type ||
1812 t == TypeManager.int64_type || t == TypeManager.uint64_type);
1815 static bool is_unsigned (Type t)
1817 return (t == TypeManager.uint32_type || t == TypeManager.uint64_type ||
1818 t == TypeManager.short_type || t == TypeManager.byte_type);
1821 Expression CheckShiftArguments (EmitContext ec)
1825 Type r = right.Type;
1827 e = ForceConversion (ec, right, TypeManager.int32_type);
1829 Error_OperatorCannotBeApplied ();
1834 if (((e = ConvertImplicit (ec, left, TypeManager.int32_type, loc)) != null) ||
1835 ((e = ConvertImplicit (ec, left, TypeManager.uint32_type, loc)) != null) ||
1836 ((e = ConvertImplicit (ec, left, TypeManager.int64_type, loc)) != null) ||
1837 ((e = ConvertImplicit (ec, left, TypeManager.uint64_type, loc)) != null)){
1843 Error_OperatorCannotBeApplied ();
1847 Expression ResolveOperator (EmitContext ec)
1850 Type r = right.Type;
1852 bool overload_failed = false;
1855 // Step 1: Perform Operator Overload location
1857 Expression left_expr, right_expr;
1859 string op = oper_names [(int) oper];
1861 MethodGroupExpr union;
1862 left_expr = MemberLookup (ec, l, op, MemberTypes.Method, AllBindingFlags, loc);
1864 right_expr = MemberLookup (
1865 ec, r, op, MemberTypes.Method, AllBindingFlags, loc);
1866 union = Invocation.MakeUnionSet (left_expr, right_expr, loc);
1868 union = (MethodGroupExpr) left_expr;
1870 if (union != null) {
1871 Arguments = new ArrayList ();
1872 Arguments.Add (new Argument (left, Argument.AType.Expression));
1873 Arguments.Add (new Argument (right, Argument.AType.Expression));
1875 method = Invocation.OverloadResolve (ec, union, Arguments, Location.Null);
1876 if (method != null) {
1877 MethodInfo mi = (MethodInfo) method;
1879 type = mi.ReturnType;
1882 overload_failed = true;
1887 // Step 2: Default operations on CLI native types.
1891 // Step 0: String concatenation (because overloading will get this wrong)
1893 if (oper == Operator.Addition){
1895 // If any of the arguments is a string, cast to string
1898 if (l == TypeManager.string_type){
1900 if (r == TypeManager.void_type) {
1901 Error_OperatorCannotBeApplied ();
1905 if (r == TypeManager.string_type){
1906 if (left is Constant && right is Constant){
1907 StringConstant ls = (StringConstant) left;
1908 StringConstant rs = (StringConstant) right;
1910 return new StringConstant (
1911 ls.Value + rs.Value);
1915 method = TypeManager.string_concat_string_string;
1918 method = TypeManager.string_concat_object_object;
1919 right = ConvertImplicit (ec, right,
1920 TypeManager.object_type, loc);
1922 type = TypeManager.string_type;
1924 Arguments = new ArrayList ();
1925 Arguments.Add (new Argument (left, Argument.AType.Expression));
1926 Arguments.Add (new Argument (right, Argument.AType.Expression));
1930 } else if (r == TypeManager.string_type){
1933 if (l == TypeManager.void_type) {
1934 Error_OperatorCannotBeApplied ();
1938 method = TypeManager.string_concat_object_object;
1939 left = ConvertImplicit (ec, left, TypeManager.object_type, loc);
1940 Arguments = new ArrayList ();
1941 Arguments.Add (new Argument (left, Argument.AType.Expression));
1942 Arguments.Add (new Argument (right, Argument.AType.Expression));
1944 type = TypeManager.string_type;
1950 // Transform a + ( - b) into a - b
1952 if (right is Unary){
1953 Unary right_unary = (Unary) right;
1955 if (right_unary.Oper == Unary.Operator.UnaryNegation){
1956 oper = Operator.Subtraction;
1957 right = right_unary.Expr;
1963 if (oper == Operator.Equality || oper == Operator.Inequality){
1964 if (l == TypeManager.bool_type || r == TypeManager.bool_type){
1965 if (r != TypeManager.bool_type || l != TypeManager.bool_type){
1966 Error_OperatorCannotBeApplied ();
1970 type = TypeManager.bool_type;
1975 // operator != (object a, object b)
1976 // operator == (object a, object b)
1978 // For this to be used, both arguments have to be reference-types.
1979 // Read the rationale on the spec (14.9.6)
1981 // Also, if at compile time we know that the classes do not inherit
1982 // one from the other, then we catch the error there.
1984 if (!(l.IsValueType || r.IsValueType)){
1985 type = TypeManager.bool_type;
1990 if (l.IsSubclassOf (r) || r.IsSubclassOf (l))
1994 // Also, a standard conversion must exist from either one
1996 if (!(StandardConversionExists (left, r) ||
1997 StandardConversionExists (right, l))){
1998 Error_OperatorCannotBeApplied ();
2002 // We are going to have to convert to an object to compare
2004 if (l != TypeManager.object_type)
2005 left = new EmptyCast (left, TypeManager.object_type);
2006 if (r != TypeManager.object_type)
2007 right = new EmptyCast (right, TypeManager.object_type);
2010 // FIXME: CSC here catches errors cs254 and cs252
2016 // One of them is a valuetype, but the other one is not.
2018 if (!l.IsValueType || !r.IsValueType) {
2019 Error_OperatorCannotBeApplied ();
2024 // Only perform numeric promotions on:
2025 // +, -, *, /, %, &, |, ^, ==, !=, <, >, <=, >=
2027 if (oper == Operator.Addition || oper == Operator.Subtraction) {
2028 if (l.IsSubclassOf (TypeManager.delegate_type) &&
2029 r.IsSubclassOf (TypeManager.delegate_type)) {
2031 Arguments = new ArrayList ();
2032 Arguments.Add (new Argument (left, Argument.AType.Expression));
2033 Arguments.Add (new Argument (right, Argument.AType.Expression));
2035 if (oper == Operator.Addition)
2036 method = TypeManager.delegate_combine_delegate_delegate;
2038 method = TypeManager.delegate_remove_delegate_delegate;
2041 Error_OperatorCannotBeApplied ();
2045 DelegateOperation = true;
2051 // Pointer arithmetic:
2053 // T* operator + (T* x, int y);
2054 // T* operator + (T* x, uint y);
2055 // T* operator + (T* x, long y);
2056 // T* operator + (T* x, ulong y);
2058 // T* operator + (int y, T* x);
2059 // T* operator + (uint y, T *x);
2060 // T* operator + (long y, T *x);
2061 // T* operator + (ulong y, T *x);
2063 // T* operator - (T* x, int y);
2064 // T* operator - (T* x, uint y);
2065 // T* operator - (T* x, long y);
2066 // T* operator - (T* x, ulong y);
2068 // long operator - (T* x, T *y)
2071 if (r.IsPointer && oper == Operator.Subtraction){
2073 return new PointerArithmetic (
2074 false, left, right, TypeManager.int64_type,
2076 } else if (is_32_or_64 (r))
2077 return new PointerArithmetic (
2078 oper == Operator.Addition, left, right, l, loc);
2079 } else if (r.IsPointer && is_32_or_64 (l) && oper == Operator.Addition)
2080 return new PointerArithmetic (
2081 true, right, left, r, loc);
2085 // Enumeration operators
2087 bool lie = TypeManager.IsEnumType (l);
2088 bool rie = TypeManager.IsEnumType (r);
2093 // operator + (E e, U x)
2095 if (oper == Operator.Addition){
2097 Error_OperatorCannotBeApplied ();
2101 Type enum_type = lie ? l : r;
2102 Type other_type = lie ? r : l;
2103 Type underlying_type = TypeManager.EnumToUnderlying (enum_type);
2106 if (underlying_type != other_type){
2107 Error_OperatorCannotBeApplied ();
2116 temp = ConvertImplicit (ec, right, l, loc);
2120 Error_OperatorCannotBeApplied ();
2124 temp = ConvertImplicit (ec, left, r, loc);
2129 Error_OperatorCannotBeApplied ();
2134 if (oper == Operator.Equality || oper == Operator.Inequality ||
2135 oper == Operator.LessThanOrEqual || oper == Operator.LessThan ||
2136 oper == Operator.GreaterThanOrEqual || oper == Operator.GreaterThan){
2137 type = TypeManager.bool_type;
2141 if (oper == Operator.BitwiseAnd ||
2142 oper == Operator.BitwiseOr ||
2143 oper == Operator.ExclusiveOr){
2147 Error_OperatorCannotBeApplied ();
2151 if (oper == Operator.LeftShift || oper == Operator.RightShift)
2152 return CheckShiftArguments (ec);
2154 if (oper == Operator.LogicalOr || oper == Operator.LogicalAnd){
2155 if (l != TypeManager.bool_type || r != TypeManager.bool_type){
2156 Error_OperatorCannotBeApplied ();
2160 type = TypeManager.bool_type;
2165 // operator & (bool x, bool y)
2166 // operator | (bool x, bool y)
2167 // operator ^ (bool x, bool y)
2169 if (l == TypeManager.bool_type && r == TypeManager.bool_type){
2170 if (oper == Operator.BitwiseAnd ||
2171 oper == Operator.BitwiseOr ||
2172 oper == Operator.ExclusiveOr){
2179 // Pointer comparison
2181 if (l.IsPointer && r.IsPointer){
2182 if (oper == Operator.Equality || oper == Operator.Inequality ||
2183 oper == Operator.LessThan || oper == Operator.LessThanOrEqual ||
2184 oper == Operator.GreaterThan || oper == Operator.GreaterThanOrEqual){
2185 type = TypeManager.bool_type;
2191 // We are dealing with numbers
2193 if (overload_failed){
2194 Error_OperatorCannotBeApplied ();
2198 if (!DoNumericPromotions (ec, l, r)){
2199 Error_OperatorCannotBeApplied ();
2203 if (left == null || right == null)
2207 // reload our cached types if required
2212 if (oper == Operator.BitwiseAnd ||
2213 oper == Operator.BitwiseOr ||
2214 oper == Operator.ExclusiveOr){
2216 if (!((l == TypeManager.int32_type) ||
2217 (l == TypeManager.uint32_type) ||
2218 (l == TypeManager.int64_type) ||
2219 (l == TypeManager.uint64_type)))
2222 Error_OperatorCannotBeApplied ();
2227 if (oper == Operator.Equality ||
2228 oper == Operator.Inequality ||
2229 oper == Operator.LessThanOrEqual ||
2230 oper == Operator.LessThan ||
2231 oper == Operator.GreaterThanOrEqual ||
2232 oper == Operator.GreaterThan){
2233 type = TypeManager.bool_type;
2239 public override Expression DoResolve (EmitContext ec)
2241 left = left.Resolve (ec);
2242 right = right.Resolve (ec);
2244 if (left == null || right == null)
2247 if (left.Type == null)
2248 throw new Exception (
2249 "Resolve returned non null, but did not set the type! (" +
2250 left + ") at Line: " + loc.Row);
2251 if (right.Type == null)
2252 throw new Exception (
2253 "Resolve returned non null, but did not set the type! (" +
2254 right + ") at Line: "+ loc.Row);
2256 eclass = ExprClass.Value;
2258 if (left is Constant && right is Constant){
2259 Expression e = ConstantFold.BinaryFold (
2260 ec, oper, (Constant) left, (Constant) right, loc);
2265 return ResolveOperator (ec);
2269 /// EmitBranchable is called from Statement.EmitBoolExpression in the
2270 /// context of a conditional bool expression. This function will return
2271 /// false if it is was possible to use EmitBranchable, or true if it was.
2273 /// The expression's code is generated, and we will generate a branch to `target'
2274 /// if the resulting expression value is equal to isTrue
2276 public bool EmitBranchable (EmitContext ec, Label target, bool onTrue)
2281 ILGenerator ig = ec.ig;
2284 // This is more complicated than it looks, but its just to avoid
2285 // duplicated tests: basically, we allow ==, !=, >, <, >= and <=
2286 // but on top of that we want for == and != to use a special path
2287 // if we are comparing against null
2289 if (oper == Operator.Equality || oper == Operator.Inequality){
2290 bool my_on_true = oper == Operator.Inequality ? onTrue : !onTrue;
2292 if (left is NullLiteral){
2295 ig.Emit (OpCodes.Brtrue, target);
2297 ig.Emit (OpCodes.Brfalse, target);
2299 } else if (right is NullLiteral){
2302 ig.Emit (OpCodes.Brtrue, target);
2304 ig.Emit (OpCodes.Brfalse, target);
2307 } else if (!(oper == Operator.LessThan ||
2308 oper == Operator.GreaterThan ||
2309 oper == Operator.LessThanOrEqual ||
2310 oper == Operator.GreaterThanOrEqual))
2318 bool isUnsigned = is_unsigned (left.Type);
2321 case Operator.Equality:
2323 ig.Emit (OpCodes.Beq, target);
2325 ig.Emit (OpCodes.Bne_Un, target);
2328 case Operator.Inequality:
2330 ig.Emit (OpCodes.Bne_Un, target);
2332 ig.Emit (OpCodes.Beq, target);
2335 case Operator.LessThan:
2338 ig.Emit (OpCodes.Blt_Un, target);
2340 ig.Emit (OpCodes.Blt, target);
2343 ig.Emit (OpCodes.Bge_Un, target);
2345 ig.Emit (OpCodes.Bge, target);
2348 case Operator.GreaterThan:
2351 ig.Emit (OpCodes.Bgt_Un, target);
2353 ig.Emit (OpCodes.Bgt, target);
2356 ig.Emit (OpCodes.Ble_Un, target);
2358 ig.Emit (OpCodes.Ble, target);
2361 case Operator.LessThanOrEqual:
2364 ig.Emit (OpCodes.Ble_Un, target);
2366 ig.Emit (OpCodes.Ble, target);
2369 ig.Emit (OpCodes.Bgt_Un, target);
2371 ig.Emit (OpCodes.Bgt, target);
2375 case Operator.GreaterThanOrEqual:
2378 ig.Emit (OpCodes.Bge_Un, target);
2380 ig.Emit (OpCodes.Bge, target);
2383 ig.Emit (OpCodes.Blt_Un, target);
2385 ig.Emit (OpCodes.Blt, target);
2395 public override void Emit (EmitContext ec)
2397 ILGenerator ig = ec.ig;
2399 Type r = right.Type;
2402 if (method != null) {
2404 // Note that operators are static anyway
2406 if (Arguments != null)
2407 Invocation.EmitArguments (ec, method, Arguments);
2409 if (method is MethodInfo)
2410 ig.Emit (OpCodes.Call, (MethodInfo) method);
2412 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
2414 if (DelegateOperation)
2415 ig.Emit (OpCodes.Castclass, type);
2421 // Handle short-circuit operators differently
2424 if (oper == Operator.LogicalAnd){
2425 Label load_zero = ig.DefineLabel ();
2426 Label end = ig.DefineLabel ();
2429 ig.Emit (OpCodes.Brfalse, load_zero);
2431 ig.Emit (OpCodes.Br, end);
2432 ig.MarkLabel (load_zero);
2433 ig.Emit (OpCodes.Ldc_I4_0);
2436 } else if (oper == Operator.LogicalOr){
2437 Label load_one = ig.DefineLabel ();
2438 Label end = ig.DefineLabel ();
2441 ig.Emit (OpCodes.Brtrue, load_one);
2443 ig.Emit (OpCodes.Br, end);
2444 ig.MarkLabel (load_one);
2445 ig.Emit (OpCodes.Ldc_I4_1);
2454 case Operator.Multiply:
2456 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
2457 opcode = OpCodes.Mul_Ovf;
2458 else if (l==TypeManager.uint32_type || l==TypeManager.uint64_type)
2459 opcode = OpCodes.Mul_Ovf_Un;
2461 opcode = OpCodes.Mul;
2463 opcode = OpCodes.Mul;
2467 case Operator.Division:
2468 if (l == TypeManager.uint32_type || l == TypeManager.uint64_type)
2469 opcode = OpCodes.Div_Un;
2471 opcode = OpCodes.Div;
2474 case Operator.Modulus:
2475 if (l == TypeManager.uint32_type || l == TypeManager.uint64_type)
2476 opcode = OpCodes.Rem_Un;
2478 opcode = OpCodes.Rem;
2481 case Operator.Addition:
2483 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
2484 opcode = OpCodes.Add_Ovf;
2485 else if (l==TypeManager.uint32_type || l==TypeManager.uint64_type)
2486 opcode = OpCodes.Add_Ovf_Un;
2488 opcode = OpCodes.Add;
2490 opcode = OpCodes.Add;
2493 case Operator.Subtraction:
2495 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
2496 opcode = OpCodes.Sub_Ovf;
2497 else if (l==TypeManager.uint32_type || l==TypeManager.uint64_type)
2498 opcode = OpCodes.Sub_Ovf_Un;
2500 opcode = OpCodes.Sub;
2502 opcode = OpCodes.Sub;
2505 case Operator.RightShift:
2506 if (l == TypeManager.uint32_type || l == TypeManager.uint64_type)
2507 opcode = OpCodes.Shr_Un;
2509 opcode = OpCodes.Shr;
2512 case Operator.LeftShift:
2513 opcode = OpCodes.Shl;
2516 case Operator.Equality:
2517 opcode = OpCodes.Ceq;
2520 case Operator.Inequality:
2521 ec.ig.Emit (OpCodes.Ceq);
2522 ec.ig.Emit (OpCodes.Ldc_I4_0);
2524 opcode = OpCodes.Ceq;
2527 case Operator.LessThan:
2528 opcode = OpCodes.Clt;
2531 case Operator.GreaterThan:
2532 opcode = OpCodes.Cgt;
2535 case Operator.LessThanOrEqual:
2536 ec.ig.Emit (OpCodes.Cgt);
2537 ec.ig.Emit (OpCodes.Ldc_I4_0);
2539 opcode = OpCodes.Ceq;
2542 case Operator.GreaterThanOrEqual:
2543 ec.ig.Emit (OpCodes.Clt);
2544 ec.ig.Emit (OpCodes.Ldc_I4_1);
2546 opcode = OpCodes.Sub;
2549 case Operator.BitwiseOr:
2550 opcode = OpCodes.Or;
2553 case Operator.BitwiseAnd:
2554 opcode = OpCodes.And;
2557 case Operator.ExclusiveOr:
2558 opcode = OpCodes.Xor;
2562 throw new Exception ("This should not happen: Operator = "
2563 + oper.ToString ());
2569 public bool IsBuiltinOperator {
2571 return method == null;
2576 public class PointerArithmetic : Expression {
2577 Expression left, right;
2581 // We assume that `l' is always a pointer
2583 public PointerArithmetic (bool is_addition, Expression l, Expression r, Type t,
2587 eclass = ExprClass.Variable;
2591 is_add = is_addition;
2594 public override Expression DoResolve (EmitContext ec)
2597 // We are born fully resolved
2602 public override void Emit (EmitContext ec)
2604 Type op_type = left.Type;
2605 ILGenerator ig = ec.ig;
2606 int size = GetTypeSize (op_type.GetElementType ());
2608 if (right.Type.IsPointer){
2610 // handle (pointer - pointer)
2614 ig.Emit (OpCodes.Sub);
2618 ig.Emit (OpCodes.Sizeof, op_type);
2620 IntLiteral.EmitInt (ig, size);
2621 ig.Emit (OpCodes.Div);
2623 ig.Emit (OpCodes.Conv_I8);
2626 // handle + and - on (pointer op int)
2629 ig.Emit (OpCodes.Conv_I);
2633 ig.Emit (OpCodes.Sizeof, op_type);
2635 IntLiteral.EmitInt (ig, size);
2636 ig.Emit (OpCodes.Mul);
2639 ig.Emit (OpCodes.Add);
2641 ig.Emit (OpCodes.Sub);
2647 /// Implements the ternary conditional operator (?:)
2649 public class Conditional : Expression {
2650 Expression expr, trueExpr, falseExpr;
2652 public Conditional (Expression expr, Expression trueExpr, Expression falseExpr, Location l)
2655 this.trueExpr = trueExpr;
2656 this.falseExpr = falseExpr;
2660 public Expression Expr {
2666 public Expression TrueExpr {
2672 public Expression FalseExpr {
2678 public override Expression DoResolve (EmitContext ec)
2680 expr = expr.Resolve (ec);
2685 if (expr.Type != TypeManager.bool_type)
2686 expr = Expression.ConvertImplicitRequired (
2687 ec, expr, TypeManager.bool_type, loc);
2689 trueExpr = trueExpr.Resolve (ec);
2690 falseExpr = falseExpr.Resolve (ec);
2692 if (trueExpr == null || falseExpr == null)
2695 eclass = ExprClass.Value;
2696 if (trueExpr.Type == falseExpr.Type)
2697 type = trueExpr.Type;
2700 Type true_type = trueExpr.Type;
2701 Type false_type = falseExpr.Type;
2703 if (trueExpr is NullLiteral){
2706 } else if (falseExpr is NullLiteral){
2712 // First, if an implicit conversion exists from trueExpr
2713 // to falseExpr, then the result type is of type falseExpr.Type
2715 conv = ConvertImplicit (ec, trueExpr, false_type, loc);
2718 // Check if both can convert implicitl to each other's type
2720 if (ConvertImplicit (ec, falseExpr, true_type, loc) != null){
2722 "Can not compute type of conditional expression " +
2723 "as `" + TypeManager.CSharpName (trueExpr.Type) +
2724 "' and `" + TypeManager.CSharpName (falseExpr.Type) +
2725 "' convert implicitly to each other");
2730 } else if ((conv = ConvertImplicit(ec, falseExpr, true_type,loc))!= null){
2734 Error (173, "The type of the conditional expression can " +
2735 "not be computed because there is no implicit conversion" +
2736 " from `" + TypeManager.CSharpName (trueExpr.Type) + "'" +
2737 " and `" + TypeManager.CSharpName (falseExpr.Type) + "'");
2742 if (expr is BoolConstant){
2743 BoolConstant bc = (BoolConstant) expr;
2754 public override void Emit (EmitContext ec)
2756 ILGenerator ig = ec.ig;
2757 Label false_target = ig.DefineLabel ();
2758 Label end_target = ig.DefineLabel ();
2761 ig.Emit (OpCodes.Brfalse, false_target);
2763 ig.Emit (OpCodes.Br, end_target);
2764 ig.MarkLabel (false_target);
2765 falseExpr.Emit (ec);
2766 ig.MarkLabel (end_target);
2774 public class LocalVariableReference : Expression, IAssignMethod, IMemoryLocation, IVariable {
2775 public readonly string Name;
2776 public readonly Block Block;
2777 VariableInfo variable_info;
2780 public LocalVariableReference (Block block, string name, Location l)
2785 eclass = ExprClass.Variable;
2788 // Setting `is_readonly' to false will allow you to create a writable
2789 // reference to a read-only variable. This is used by foreach and using.
2790 public LocalVariableReference (Block block, string name, Location l,
2791 VariableInfo variable_info, bool is_readonly)
2792 : this (block, name, l)
2794 this.variable_info = variable_info;
2795 this.is_readonly = is_readonly;
2798 public VariableInfo VariableInfo {
2800 if (variable_info == null) {
2801 variable_info = Block.GetVariableInfo (Name);
2802 is_readonly = variable_info.ReadOnly;
2804 return variable_info;
2808 public bool IsAssigned (EmitContext ec, Location loc)
2810 return VariableInfo.IsAssigned (ec, loc);
2813 public bool IsFieldAssigned (EmitContext ec, string name, Location loc)
2815 return VariableInfo.IsFieldAssigned (ec, name, loc);
2818 public void SetAssigned (EmitContext ec)
2820 VariableInfo.SetAssigned (ec);
2823 public void SetFieldAssigned (EmitContext ec, string name)
2825 VariableInfo.SetFieldAssigned (ec, name);
2828 public bool IsReadOnly {
2830 if (variable_info == null) {
2831 variable_info = Block.GetVariableInfo (Name);
2832 is_readonly = variable_info.ReadOnly;
2838 public override Expression DoResolve (EmitContext ec)
2840 VariableInfo vi = VariableInfo;
2842 if (Block.IsConstant (Name)) {
2843 Expression e = Block.GetConstantExpression (Name);
2849 if (ec.DoFlowAnalysis && !IsAssigned (ec, loc))
2852 type = vi.VariableType;
2856 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
2858 VariableInfo vi = VariableInfo;
2860 if (ec.DoFlowAnalysis)
2861 ec.SetVariableAssigned (vi);
2863 Expression e = DoResolve (ec);
2869 Error (1604, "cannot assign to `" + Name + "' because it is readonly");
2876 public override void Emit (EmitContext ec)
2878 VariableInfo vi = VariableInfo;
2879 ILGenerator ig = ec.ig;
2881 ig.Emit (OpCodes.Ldloc, vi.LocalBuilder);
2885 public void EmitAssign (EmitContext ec, Expression source)
2887 ILGenerator ig = ec.ig;
2888 VariableInfo vi = VariableInfo;
2894 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
2897 public void AddressOf (EmitContext ec, AddressOp mode)
2899 VariableInfo vi = VariableInfo;
2901 ec.ig.Emit (OpCodes.Ldloca, vi.LocalBuilder);
2906 /// This represents a reference to a parameter in the intermediate
2909 public class ParameterReference : Expression, IAssignMethod, IMemoryLocation, IVariable {
2913 public Parameter.Modifier mod;
2914 public bool is_ref, is_out;
2916 public ParameterReference (Parameters pars, int idx, string name, Location loc)
2922 eclass = ExprClass.Variable;
2925 public bool IsAssigned (EmitContext ec, Location loc)
2927 if (!is_out || !ec.DoFlowAnalysis)
2930 if (!ec.CurrentBranching.IsParameterAssigned (idx)) {
2931 Report.Error (165, loc,
2932 "Use of unassigned local variable `" + name + "'");
2939 public bool IsFieldAssigned (EmitContext ec, string field_name, Location loc)
2941 if (!is_out || !ec.DoFlowAnalysis)
2944 if (ec.CurrentBranching.IsParameterAssigned (idx))
2947 if (!ec.CurrentBranching.IsParameterAssigned (idx, field_name)) {
2948 Report.Error (170, loc,
2949 "Use of possibly unassigned field `" + field_name + "'");
2956 public void SetAssigned (EmitContext ec)
2958 if (is_out && ec.DoFlowAnalysis)
2959 ec.CurrentBranching.SetParameterAssigned (idx);
2962 public void SetFieldAssigned (EmitContext ec, string field_name)
2964 if (is_out && ec.DoFlowAnalysis)
2965 ec.CurrentBranching.SetParameterAssigned (idx, field_name);
2969 // Notice that for ref/out parameters, the type exposed is not the
2970 // same type exposed externally.
2973 // externally we expose "int&"
2974 // here we expose "int".
2976 // We record this in "is_ref". This means that the type system can treat
2977 // the type as it is expected, but when we generate the code, we generate
2978 // the alternate kind of code.
2980 public override Expression DoResolve (EmitContext ec)
2982 type = pars.GetParameterInfo (ec.DeclSpace, idx, out mod);
2983 is_ref = (mod & Parameter.Modifier.ISBYREF) != 0;
2984 is_out = (mod & Parameter.Modifier.OUT) != 0;
2985 eclass = ExprClass.Variable;
2987 if (is_out && ec.DoFlowAnalysis && !IsAssigned (ec, loc))
2993 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
2995 type = pars.GetParameterInfo (ec.DeclSpace, idx, out mod);
2996 is_ref = (mod & Parameter.Modifier.ISBYREF) != 0;
2997 is_out = (mod & Parameter.Modifier.OUT) != 0;
2998 eclass = ExprClass.Variable;
3000 if (is_out && ec.DoFlowAnalysis)
3001 ec.SetParameterAssigned (idx);
3006 static void EmitLdArg (ILGenerator ig, int x)
3010 case 0: ig.Emit (OpCodes.Ldarg_0); break;
3011 case 1: ig.Emit (OpCodes.Ldarg_1); break;
3012 case 2: ig.Emit (OpCodes.Ldarg_2); break;
3013 case 3: ig.Emit (OpCodes.Ldarg_3); break;
3014 default: ig.Emit (OpCodes.Ldarg_S, (byte) x); break;
3017 ig.Emit (OpCodes.Ldarg, x);
3021 // This method is used by parameters that are references, that are
3022 // being passed as references: we only want to pass the pointer (that
3023 // is already stored in the parameter, not the address of the pointer,
3024 // and not the value of the variable).
3026 public void EmitLoad (EmitContext ec)
3028 ILGenerator ig = ec.ig;
3034 EmitLdArg (ig, arg_idx);
3037 public override void Emit (EmitContext ec)
3039 ILGenerator ig = ec.ig;
3045 EmitLdArg (ig, arg_idx);
3051 // If we are a reference, we loaded on the stack a pointer
3052 // Now lets load the real value
3054 LoadFromPtr (ig, type);
3057 public void EmitAssign (EmitContext ec, Expression source)
3059 ILGenerator ig = ec.ig;
3066 EmitLdArg (ig, arg_idx);
3071 StoreFromPtr (ig, type);
3074 ig.Emit (OpCodes.Starg_S, (byte) arg_idx);
3076 ig.Emit (OpCodes.Starg, arg_idx);
3080 public void AddressOf (EmitContext ec, AddressOp mode)
3089 ec.ig.Emit (OpCodes.Ldarg_S, (byte) arg_idx);
3091 ec.ig.Emit (OpCodes.Ldarg, arg_idx);
3094 ec.ig.Emit (OpCodes.Ldarga_S, (byte) arg_idx);
3096 ec.ig.Emit (OpCodes.Ldarga, arg_idx);
3102 /// Used for arguments to New(), Invocation()
3104 public class Argument {
3105 public enum AType : byte {
3111 public readonly AType ArgType;
3112 public Expression Expr;
3114 public Argument (Expression expr, AType type)
3117 this.ArgType = type;
3122 if (ArgType == AType.Ref || ArgType == AType.Out)
3123 return TypeManager.LookupType (Expr.Type.ToString () + "&");
3129 public Parameter.Modifier GetParameterModifier ()
3133 return Parameter.Modifier.OUT | Parameter.Modifier.ISBYREF;
3136 return Parameter.Modifier.REF | Parameter.Modifier.ISBYREF;
3139 return Parameter.Modifier.NONE;
3143 public static string FullDesc (Argument a)
3145 return (a.ArgType == AType.Ref ? "ref " :
3146 (a.ArgType == AType.Out ? "out " : "")) +
3147 TypeManager.CSharpName (a.Expr.Type);
3150 public bool ResolveMethodGroup (EmitContext ec, Location loc)
3152 // FIXME: csc doesn't report any error if you try to use `ref' or
3153 // `out' in a delegate creation expression.
3154 Expr = Expr.Resolve (ec, ResolveFlags.VariableOrValue | ResolveFlags.MethodGroup);
3161 public bool Resolve (EmitContext ec, Location loc)
3163 if (ArgType == AType.Ref) {
3164 Expr = Expr.Resolve (ec);
3168 Expr = Expr.ResolveLValue (ec, Expr);
3169 } else if (ArgType == AType.Out)
3170 Expr = Expr.ResolveLValue (ec, new EmptyExpression ());
3172 Expr = Expr.Resolve (ec);
3177 if (ArgType == AType.Expression)
3180 if (Expr.eclass != ExprClass.Variable){
3182 // We just probe to match the CSC output
3184 if (Expr.eclass == ExprClass.PropertyAccess ||
3185 Expr.eclass == ExprClass.IndexerAccess){
3188 "A property or indexer can not be passed as an out or ref " +
3193 "An lvalue is required as an argument to out or ref");
3201 public void Emit (EmitContext ec)
3204 // Ref and Out parameters need to have their addresses taken.
3206 // ParameterReferences might already be references, so we want
3207 // to pass just the value
3209 if (ArgType == AType.Ref || ArgType == AType.Out){
3210 AddressOp mode = AddressOp.Store;
3212 if (ArgType == AType.Ref)
3213 mode |= AddressOp.Load;
3215 if (Expr is ParameterReference){
3216 ParameterReference pr = (ParameterReference) Expr;
3222 pr.AddressOf (ec, mode);
3225 ((IMemoryLocation)Expr).AddressOf (ec, mode);
3232 /// Invocation of methods or delegates.
3234 public class Invocation : ExpressionStatement {
3235 public readonly ArrayList Arguments;
3238 MethodBase method = null;
3241 static Hashtable method_parameter_cache;
3243 static Invocation ()
3245 method_parameter_cache = new PtrHashtable ();
3249 // arguments is an ArrayList, but we do not want to typecast,
3250 // as it might be null.
3252 // FIXME: only allow expr to be a method invocation or a
3253 // delegate invocation (7.5.5)
3255 public Invocation (Expression expr, ArrayList arguments, Location l)
3258 Arguments = arguments;
3262 public Expression Expr {
3269 /// Returns the Parameters (a ParameterData interface) for the
3272 public static ParameterData GetParameterData (MethodBase mb)
3274 object pd = method_parameter_cache [mb];
3278 return (ParameterData) pd;
3281 ip = TypeManager.LookupParametersByBuilder (mb);
3283 method_parameter_cache [mb] = ip;
3285 return (ParameterData) ip;
3287 ParameterInfo [] pi = mb.GetParameters ();
3288 ReflectionParameters rp = new ReflectionParameters (pi);
3289 method_parameter_cache [mb] = rp;
3291 return (ParameterData) rp;
3296 /// Determines "better conversion" as specified in 7.4.2.3
3297 /// Returns : 1 if a->p is better
3298 /// 0 if a->q or neither is better
3300 static int BetterConversion (EmitContext ec, Argument a, Type p, Type q, Location loc)
3302 Type argument_type = a.Type;
3303 Expression argument_expr = a.Expr;
3305 if (argument_type == null)
3306 throw new Exception ("Expression of type " + a.Expr + " does not resolve its type");
3309 // This is a special case since csc behaves this way. I can't find
3310 // it anywhere in the spec but oh well ...
3312 if (argument_expr is NullLiteral && p == TypeManager.string_type && q == TypeManager.object_type)
3314 else if (argument_expr is NullLiteral && p == TypeManager.object_type && q == TypeManager.string_type)
3320 if (argument_type == p)
3323 if (argument_type == q)
3327 // Now probe whether an implicit constant expression conversion
3330 // An implicit constant expression conversion permits the following
3333 // * A constant-expression of type `int' can be converted to type
3334 // sbyte, byute, short, ushort, uint, ulong provided the value of
3335 // of the expression is withing the range of the destination type.
3337 // * A constant-expression of type long can be converted to type
3338 // ulong, provided the value of the constant expression is not negative
3340 // FIXME: Note that this assumes that constant folding has
3341 // taken place. We dont do constant folding yet.
3344 if (argument_expr is IntConstant){
3345 IntConstant ei = (IntConstant) argument_expr;
3346 int value = ei.Value;
3348 if (p == TypeManager.sbyte_type){
3349 if (value >= SByte.MinValue && value <= SByte.MaxValue)
3351 } else if (p == TypeManager.byte_type){
3352 if (Byte.MinValue >= 0 && value <= Byte.MaxValue)
3354 } else if (p == TypeManager.short_type){
3355 if (value >= Int16.MinValue && value <= Int16.MaxValue)
3357 } else if (p == TypeManager.ushort_type){
3358 if (value >= UInt16.MinValue && value <= UInt16.MaxValue)
3360 } else if (p == TypeManager.uint32_type){
3362 // we can optimize this case: a positive int32
3363 // always fits on a uint32
3367 } else if (p == TypeManager.uint64_type){
3369 // we can optimize this case: a positive int32
3370 // always fits on a uint64
3375 } else if (argument_type == TypeManager.int64_type && argument_expr is LongConstant){
3376 LongConstant lc = (LongConstant) argument_expr;
3378 if (p == TypeManager.uint64_type){
3385 Expression tmp = ConvertImplicit (ec, argument_expr, p, loc);
3393 Expression p_tmp = new EmptyExpression (p);
3394 Expression q_tmp = new EmptyExpression (q);
3396 if (StandardConversionExists (p_tmp, q) == true &&
3397 StandardConversionExists (q_tmp, p) == false)
3400 if (p == TypeManager.sbyte_type)
3401 if (q == TypeManager.byte_type || q == TypeManager.ushort_type ||
3402 q == TypeManager.uint32_type || q == TypeManager.uint64_type)
3405 if (p == TypeManager.short_type)
3406 if (q == TypeManager.ushort_type || q == TypeManager.uint32_type ||
3407 q == TypeManager.uint64_type)
3410 if (p == TypeManager.int32_type)
3411 if (q == TypeManager.uint32_type || q == TypeManager.uint64_type)
3414 if (p == TypeManager.int64_type)
3415 if (q == TypeManager.uint64_type)
3422 /// Determines "Better function"
3425 /// and returns an integer indicating :
3426 /// 0 if candidate ain't better
3427 /// 1 if candidate is better than the current best match
3429 static int BetterFunction (EmitContext ec, ArrayList args,
3430 MethodBase candidate, MethodBase best,
3431 bool expanded_form, Location loc)
3433 ParameterData candidate_pd = GetParameterData (candidate);
3434 ParameterData best_pd;
3440 argument_count = args.Count;
3442 int cand_count = candidate_pd.Count;
3444 if (cand_count == 0 && argument_count == 0)
3447 if (candidate_pd.ParameterModifier (cand_count - 1) != Parameter.Modifier.PARAMS)
3448 if (cand_count != argument_count)
3454 if (argument_count == 0 && cand_count == 1 &&
3455 candidate_pd.ParameterModifier (cand_count - 1) == Parameter.Modifier.PARAMS)
3458 for (int j = argument_count; j > 0;) {
3461 Argument a = (Argument) args [j];
3462 Type t = candidate_pd.ParameterType (j);
3464 if (candidate_pd.ParameterModifier (j) == Parameter.Modifier.PARAMS)
3466 t = t.GetElementType ();
3468 x = BetterConversion (ec, a, t, null, loc);
3480 best_pd = GetParameterData (best);
3482 int rating1 = 0, rating2 = 0;
3484 for (int j = 0; j < argument_count; ++j) {
3487 Argument a = (Argument) args [j];
3489 Type ct = candidate_pd.ParameterType (j);
3490 Type bt = best_pd.ParameterType (j);
3492 if (candidate_pd.ParameterModifier (j) == Parameter.Modifier.PARAMS)
3494 ct = ct.GetElementType ();
3496 if (best_pd.ParameterModifier (j) == Parameter.Modifier.PARAMS)
3498 bt = bt.GetElementType ();
3500 x = BetterConversion (ec, a, ct, bt, loc);
3501 y = BetterConversion (ec, a, bt, ct, loc);
3510 if (rating1 > rating2)
3516 public static string FullMethodDesc (MethodBase mb)
3518 string ret_type = "";
3520 if (mb is MethodInfo)
3521 ret_type = TypeManager.CSharpName (((MethodInfo) mb).ReturnType);
3523 StringBuilder sb = new StringBuilder (ret_type + " " + mb.Name);
3524 ParameterData pd = GetParameterData (mb);
3526 int count = pd.Count;
3529 for (int i = count; i > 0; ) {
3532 sb.Append (pd.ParameterDesc (count - i - 1));
3538 return sb.ToString ();
3541 public static MethodGroupExpr MakeUnionSet (Expression mg1, Expression mg2, Location loc)
3543 MemberInfo [] miset;
3544 MethodGroupExpr union;
3549 return (MethodGroupExpr) mg2;
3552 return (MethodGroupExpr) mg1;
3555 MethodGroupExpr left_set = null, right_set = null;
3556 int length1 = 0, length2 = 0;
3558 left_set = (MethodGroupExpr) mg1;
3559 length1 = left_set.Methods.Length;
3561 right_set = (MethodGroupExpr) mg2;
3562 length2 = right_set.Methods.Length;
3564 ArrayList common = new ArrayList ();
3566 foreach (MethodBase l in left_set.Methods){
3567 foreach (MethodBase r in right_set.Methods){
3575 miset = new MemberInfo [length1 + length2 - common.Count];
3576 left_set.Methods.CopyTo (miset, 0);
3580 foreach (MemberInfo mi in right_set.Methods){
3581 if (!common.Contains (mi))
3585 union = new MethodGroupExpr (miset, loc);
3591 /// Determines is the candidate method, if a params method, is applicable
3592 /// in its expanded form to the given set of arguments
3594 static bool IsParamsMethodApplicable (EmitContext ec, ArrayList arguments, MethodBase candidate)
3598 if (arguments == null)
3601 arg_count = arguments.Count;
3603 ParameterData pd = GetParameterData (candidate);
3605 int pd_count = pd.Count;
3610 if (pd.ParameterModifier (pd_count - 1) != Parameter.Modifier.PARAMS)
3613 if (pd_count - 1 > arg_count)
3616 if (pd_count == 1 && arg_count == 0)
3620 // If we have come this far, the case which remains is when the number of parameters
3621 // is less than or equal to the argument count.
3623 for (int i = 0; i < pd_count - 1; ++i) {
3625 Argument a = (Argument) arguments [i];
3627 Parameter.Modifier a_mod = a.GetParameterModifier () &
3628 ~(Parameter.Modifier.OUT | Parameter.Modifier.REF);
3629 Parameter.Modifier p_mod = pd.ParameterModifier (i) &
3630 ~(Parameter.Modifier.OUT | Parameter.Modifier.REF);
3632 if (a_mod == p_mod) {
3634 if (a_mod == Parameter.Modifier.NONE)
3635 if (!ImplicitConversionExists (ec, a.Expr, pd.ParameterType (i)))
3638 if ((a_mod & Parameter.Modifier.ISBYREF) != 0) {
3639 Type pt = pd.ParameterType (i);
3642 pt = TypeManager.LookupType (pt.FullName + "&");
3652 Type element_type = pd.ParameterType (pd_count - 1).GetElementType ();
3654 for (int i = pd_count - 1; i < arg_count; i++) {
3655 Argument a = (Argument) arguments [i];
3657 if (!StandardConversionExists (a.Expr, element_type))
3665 /// Determines if the candidate method is applicable (section 14.4.2.1)
3666 /// to the given set of arguments
3668 static bool IsApplicable (EmitContext ec, ArrayList arguments, MethodBase candidate)
3672 if (arguments == null)
3675 arg_count = arguments.Count;
3677 ParameterData pd = GetParameterData (candidate);
3679 int pd_count = pd.Count;
3681 if (arg_count != pd.Count)
3684 for (int i = arg_count; i > 0; ) {
3687 Argument a = (Argument) arguments [i];
3689 Parameter.Modifier a_mod = a.GetParameterModifier () &
3690 ~(Parameter.Modifier.OUT | Parameter.Modifier.REF);
3691 Parameter.Modifier p_mod = pd.ParameterModifier (i) &
3692 ~(Parameter.Modifier.OUT | Parameter.Modifier.REF);
3694 if (a_mod == p_mod ||
3695 (a_mod == Parameter.Modifier.NONE && p_mod == Parameter.Modifier.PARAMS)) {
3696 if (a_mod == Parameter.Modifier.NONE)
3697 if (!ImplicitConversionExists (ec, a.Expr, pd.ParameterType (i)))
3700 if ((a_mod & Parameter.Modifier.ISBYREF) != 0) {
3701 Type pt = pd.ParameterType (i);
3704 pt = TypeManager.LookupType (pt.FullName + "&");
3719 /// Find the Applicable Function Members (7.4.2.1)
3721 /// me: Method Group expression with the members to select.
3722 /// it might contain constructors or methods (or anything
3723 /// that maps to a method).
3725 /// Arguments: ArrayList containing resolved Argument objects.
3727 /// loc: The location if we want an error to be reported, or a Null
3728 /// location for "probing" purposes.
3730 /// Returns: The MethodBase (either a ConstructorInfo or a MethodInfo)
3731 /// that is the best match of me on Arguments.
3734 public static MethodBase OverloadResolve (EmitContext ec, MethodGroupExpr me,
3735 ArrayList Arguments, Location loc)
3737 ArrayList afm = new ArrayList ();
3738 MethodBase method = null;
3739 Type current_type = null;
3741 ArrayList candidates = new ArrayList ();
3744 foreach (MethodBase candidate in me.Methods){
3747 // If we're going one level higher in the class hierarchy, abort if
3748 // we already found an applicable method.
3749 if (candidate.DeclaringType != current_type) {
3750 current_type = candidate.DeclaringType;
3755 // Check if candidate is applicable (section 14.4.2.1)
3756 if (!IsApplicable (ec, Arguments, candidate))
3759 candidates.Add (candidate);
3760 x = BetterFunction (ec, Arguments, candidate, method, false, loc);
3768 if (Arguments == null)
3771 argument_count = Arguments.Count;
3774 // Now we see if we can find params functions, applicable in their expanded form
3775 // since if they were applicable in their normal form, they would have been selected
3778 bool chose_params_expanded = false;
3780 if (method == null) {
3781 candidates = new ArrayList ();
3782 foreach (MethodBase candidate in me.Methods){
3783 if (!IsParamsMethodApplicable (ec, Arguments, candidate))
3786 candidates.Add (candidate);
3788 int x = BetterFunction (ec, Arguments, candidate, method, true, loc);
3793 chose_params_expanded = true;
3797 if (method == null) {
3799 // Okay so we have failed to find anything so we
3800 // return by providing info about the closest match
3802 for (int i = 0; i < me.Methods.Length; ++i) {
3804 MethodBase c = (MethodBase) me.Methods [i];
3805 ParameterData pd = GetParameterData (c);
3807 if (pd.Count != argument_count)
3810 VerifyArgumentsCompat (ec, Arguments, argument_count, c, false,
3818 // Now check that there are no ambiguities i.e the selected method
3819 // should be better than all the others
3822 foreach (MethodBase candidate in candidates){
3823 if (candidate == method)
3827 // If a normal method is applicable in the sense that it has the same
3828 // number of arguments, then the expanded params method is never applicable
3829 // so we debar the params method.
3831 if (IsParamsMethodApplicable (ec, Arguments, candidate) &&
3832 IsApplicable (ec, Arguments, method))
3835 int x = BetterFunction (ec, Arguments, method, candidate,
3836 chose_params_expanded, loc);
3841 "Ambiguous call when selecting function due to implicit casts");
3847 // And now check if the arguments are all compatible, perform conversions
3848 // if necessary etc. and return if everything is all right
3851 if (VerifyArgumentsCompat (ec, Arguments, argument_count, method,
3852 chose_params_expanded, null, loc))
3858 public static bool VerifyArgumentsCompat (EmitContext ec, ArrayList Arguments,
3861 bool chose_params_expanded,
3865 ParameterData pd = GetParameterData (method);
3866 int pd_count = pd.Count;
3868 for (int j = 0; j < argument_count; j++) {
3869 Argument a = (Argument) Arguments [j];
3870 Expression a_expr = a.Expr;
3871 Type parameter_type = pd.ParameterType (j);
3873 if (pd.ParameterModifier (j) == Parameter.Modifier.PARAMS &&
3874 chose_params_expanded)
3875 parameter_type = TypeManager.TypeToCoreType (parameter_type.GetElementType ());
3877 if (a.Type != parameter_type){
3880 conv = ConvertImplicit (ec, a_expr, parameter_type, loc);
3883 if (!Location.IsNull (loc)) {
3884 if (delegate_type == null)
3885 Report.Error (1502, loc,
3886 "The best overloaded match for method '" +
3887 FullMethodDesc (method) +
3888 "' has some invalid arguments");
3890 Report.Error (1594, loc,
3891 "Delegate '" + delegate_type.ToString () +
3892 "' has some invalid arguments.");
3893 Report.Error (1503, loc,
3894 "Argument " + (j+1) +
3895 ": Cannot convert from '" + Argument.FullDesc (a)
3896 + "' to '" + pd.ParameterDesc (j) + "'");
3903 // Update the argument with the implicit conversion
3909 Parameter.Modifier a_mod = a.GetParameterModifier () &
3910 ~(Parameter.Modifier.OUT | Parameter.Modifier.REF);
3911 Parameter.Modifier p_mod = pd.ParameterModifier (j) &
3912 ~(Parameter.Modifier.OUT | Parameter.Modifier.REF);
3915 if (a_mod != p_mod &&
3916 pd.ParameterModifier (pd_count - 1) != Parameter.Modifier.PARAMS) {
3917 if (!Location.IsNull (loc)) {
3918 Console.WriteLine ("A:P: " + a.GetParameterModifier ());
3919 Console.WriteLine ("PP:: " + pd.ParameterModifier (j));
3920 Console.WriteLine ("PT: " + parameter_type.IsByRef);
3921 Report.Error (1502, loc,
3922 "The best overloaded match for method '" + FullMethodDesc (method)+
3923 "' has some invalid arguments");
3924 Report.Error (1503, loc,
3925 "Argument " + (j+1) +
3926 ": Cannot convert from '" + Argument.FullDesc (a)
3927 + "' to '" + pd.ParameterDesc (j) + "'");
3937 public override Expression DoResolve (EmitContext ec)
3940 // First, resolve the expression that is used to
3941 // trigger the invocation
3943 if (expr is BaseAccess)
3946 expr = expr.Resolve (ec, ResolveFlags.VariableOrValue | ResolveFlags.MethodGroup);
3950 if (!(expr is MethodGroupExpr)) {
3951 Type expr_type = expr.Type;
3953 if (expr_type != null){
3954 bool IsDelegate = TypeManager.IsDelegateType (expr_type);
3956 return (new DelegateInvocation (
3957 this.expr, Arguments, loc)).Resolve (ec);
3961 if (!(expr is MethodGroupExpr)){
3962 expr.Error118 (ResolveFlags.MethodGroup);
3967 // Next, evaluate all the expressions in the argument list
3969 if (Arguments != null){
3970 foreach (Argument a in Arguments){
3971 if (!a.Resolve (ec, loc))
3976 MethodGroupExpr mg = (MethodGroupExpr) expr;
3977 method = OverloadResolve (ec, mg, Arguments, loc);
3979 if (method == null){
3981 "Could not find any applicable function for this argument list");
3985 MethodInfo mi = method as MethodInfo;
3987 type = TypeManager.TypeToCoreType (mi.ReturnType);
3988 if (!mi.IsStatic && !mg.IsExplicitImpl && (mg.InstanceExpression == null))
3989 SimpleName.Error_ObjectRefRequired (ec, loc, mi.Name);
3992 if (type.IsPointer){
3999 eclass = ExprClass.Value;
4004 // Emits the list of arguments as an array
4006 static void EmitParams (EmitContext ec, int idx, ArrayList arguments)
4008 ILGenerator ig = ec.ig;
4009 int count = arguments.Count - idx;
4010 Argument a = (Argument) arguments [idx];
4011 Type t = a.Expr.Type;
4012 string array_type = t.FullName + "[]";
4015 array = ig.DeclareLocal (TypeManager.LookupType (array_type));
4016 IntConstant.EmitInt (ig, count);
4017 ig.Emit (OpCodes.Newarr, TypeManager.TypeToCoreType (t));
4018 ig.Emit (OpCodes.Stloc, array);
4020 int top = arguments.Count;
4021 for (int j = idx; j < top; j++){
4022 a = (Argument) arguments [j];
4024 ig.Emit (OpCodes.Ldloc, array);
4025 IntConstant.EmitInt (ig, j - idx);
4028 ArrayAccess.EmitStoreOpcode (ig, t);
4030 ig.Emit (OpCodes.Ldloc, array);
4034 /// Emits a list of resolved Arguments that are in the arguments
4037 /// The MethodBase argument might be null if the
4038 /// emission of the arguments is known not to contain
4039 /// a `params' field (for example in constructors or other routines
4040 /// that keep their arguments in this structure)
4042 public static void EmitArguments (EmitContext ec, MethodBase mb, ArrayList arguments)
4046 pd = GetParameterData (mb);
4051 // If we are calling a params method with no arguments, special case it
4053 if (arguments == null){
4054 if (pd != null && pd.Count > 0 &&
4055 pd.ParameterModifier (0) == Parameter.Modifier.PARAMS){
4056 ILGenerator ig = ec.ig;
4058 IntConstant.EmitInt (ig, 0);
4059 ig.Emit (OpCodes.Newarr, pd.ParameterType (0).GetElementType ());
4065 int top = arguments.Count;
4067 for (int i = 0; i < top; i++){
4068 Argument a = (Argument) arguments [i];
4071 if (pd.ParameterModifier (i) == Parameter.Modifier.PARAMS){
4073 // Special case if we are passing the same data as the
4074 // params argument, do not put it in an array.
4076 if (pd.ParameterType (i) == a.Type)
4079 EmitParams (ec, i, arguments);
4087 if (pd != null && pd.Count > top &&
4088 pd.ParameterModifier (top) == Parameter.Modifier.PARAMS){
4089 ILGenerator ig = ec.ig;
4091 IntConstant.EmitInt (ig, 0);
4092 ig.Emit (OpCodes.Newarr, pd.ParameterType (top).GetElementType ());
4097 /// is_base tells whether we want to force the use of the `call'
4098 /// opcode instead of using callvirt. Call is required to call
4099 /// a specific method, while callvirt will always use the most
4100 /// recent method in the vtable.
4102 /// is_static tells whether this is an invocation on a static method
4104 /// instance_expr is an expression that represents the instance
4105 /// it must be non-null if is_static is false.
4107 /// method is the method to invoke.
4109 /// Arguments is the list of arguments to pass to the method or constructor.
4111 public static void EmitCall (EmitContext ec, bool is_base,
4112 bool is_static, Expression instance_expr,
4113 MethodBase method, ArrayList Arguments, Location loc)
4115 ILGenerator ig = ec.ig;
4116 bool struct_call = false;
4118 Type decl_type = method.DeclaringType;
4120 if (!RootContext.StdLib) {
4121 // Replace any calls to the system's System.Array type with calls to
4122 // the newly created one.
4123 if (method == TypeManager.system_int_array_get_length)
4124 method = TypeManager.int_array_get_length;
4125 else if (method == TypeManager.system_int_array_get_rank)
4126 method = TypeManager.int_array_get_rank;
4127 else if (method == TypeManager.system_object_array_clone)
4128 method = TypeManager.object_array_clone;
4129 else if (method == TypeManager.system_int_array_get_length_int)
4130 method = TypeManager.int_array_get_length_int;
4131 else if (method == TypeManager.system_int_array_get_lower_bound_int)
4132 method = TypeManager.int_array_get_lower_bound_int;
4133 else if (method == TypeManager.system_int_array_get_upper_bound_int)
4134 method = TypeManager.int_array_get_upper_bound_int;
4135 else if (method == TypeManager.system_void_array_copyto_array_int)
4136 method = TypeManager.void_array_copyto_array_int;
4140 // This checks the `ConditionalAttribute' on the method, and the
4141 // ObsoleteAttribute
4143 TypeManager.MethodFlags flags = TypeManager.GetMethodFlags (method, loc);
4144 if ((flags & TypeManager.MethodFlags.IsObsoleteError) != 0)
4146 if ((flags & TypeManager.MethodFlags.ShouldIgnore) != 0)
4150 if (decl_type.IsValueType)
4153 // If this is ourselves, push "this"
4155 if (instance_expr == null){
4156 ig.Emit (OpCodes.Ldarg_0);
4159 // Push the instance expression
4161 if (instance_expr.Type.IsValueType){
4163 // Special case: calls to a function declared in a
4164 // reference-type with a value-type argument need
4165 // to have their value boxed.
4168 if (decl_type.IsValueType){
4170 // If the expression implements IMemoryLocation, then
4171 // we can optimize and use AddressOf on the
4174 // If not we have to use some temporary storage for
4176 if (instance_expr is IMemoryLocation){
4177 ((IMemoryLocation)instance_expr).
4178 AddressOf (ec, AddressOp.LoadStore);
4181 Type t = instance_expr.Type;
4183 instance_expr.Emit (ec);
4184 LocalBuilder temp = ig.DeclareLocal (t);
4185 ig.Emit (OpCodes.Stloc, temp);
4186 ig.Emit (OpCodes.Ldloca, temp);
4189 instance_expr.Emit (ec);
4190 ig.Emit (OpCodes.Box, instance_expr.Type);
4193 instance_expr.Emit (ec);
4197 EmitArguments (ec, method, Arguments);
4199 if (is_static || struct_call || is_base){
4200 if (method is MethodInfo) {
4201 ig.Emit (OpCodes.Call, (MethodInfo) method);
4203 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
4205 if (method is MethodInfo)
4206 ig.Emit (OpCodes.Callvirt, (MethodInfo) method);
4208 ig.Emit (OpCodes.Callvirt, (ConstructorInfo) method);
4212 public override void Emit (EmitContext ec)
4214 MethodGroupExpr mg = (MethodGroupExpr) this.expr;
4217 ec, is_base, method.IsStatic, mg.InstanceExpression, method, Arguments, loc);
4220 public override void EmitStatement (EmitContext ec)
4225 // Pop the return value if there is one
4227 if (method is MethodInfo){
4228 Type ret = ((MethodInfo)method).ReturnType;
4229 if (TypeManager.TypeToCoreType (ret) != TypeManager.void_type)
4230 ec.ig.Emit (OpCodes.Pop);
4236 // This class is used to "disable" the code generation for the
4237 // temporary variable when initializing value types.
4239 class EmptyAddressOf : EmptyExpression, IMemoryLocation {
4240 public void AddressOf (EmitContext ec, AddressOp Mode)
4247 /// Implements the new expression
4249 public class New : ExpressionStatement {
4250 public readonly ArrayList Arguments;
4251 public readonly Expression RequestedType;
4253 MethodBase method = null;
4256 // If set, the new expression is for a value_target, and
4257 // we will not leave anything on the stack.
4259 Expression value_target;
4260 bool value_target_set = false;
4262 public New (Expression requested_type, ArrayList arguments, Location l)
4264 RequestedType = requested_type;
4265 Arguments = arguments;
4269 public Expression ValueTypeVariable {
4271 return value_target;
4275 value_target = value;
4276 value_target_set = true;
4281 // This function is used to disable the following code sequence for
4282 // value type initialization:
4284 // AddressOf (temporary)
4288 // Instead the provide will have provided us with the address on the
4289 // stack to store the results.
4291 static Expression MyEmptyExpression;
4293 public void DisableTemporaryValueType ()
4295 if (MyEmptyExpression == null)
4296 MyEmptyExpression = new EmptyAddressOf ();
4299 // To enable this, look into:
4300 // test-34 and test-89 and self bootstrapping.
4302 // For instance, we can avoid a copy by using `newobj'
4303 // instead of Call + Push-temp on value types.
4304 // value_target = MyEmptyExpression;
4307 public override Expression DoResolve (EmitContext ec)
4309 type = ec.DeclSpace.ResolveType (RequestedType, false, loc);
4314 bool IsDelegate = TypeManager.IsDelegateType (type);
4317 return (new NewDelegate (type, Arguments, loc)).Resolve (ec);
4319 if (type.IsInterface || type.IsAbstract){
4321 144, "It is not possible to create instances of interfaces " +
4322 "or abstract classes");
4326 bool is_struct = false;
4327 is_struct = type.IsValueType;
4328 eclass = ExprClass.Value;
4331 // SRE returns a match for .ctor () on structs (the object constructor),
4332 // so we have to manually ignore it.
4334 if (is_struct && Arguments == null)
4338 ml = MemberLookupFinal (ec, type, ".ctor",
4339 MemberTypes.Constructor,
4340 AllBindingFlags | BindingFlags.DeclaredOnly, loc);
4345 if (! (ml is MethodGroupExpr)){
4347 ml.Error118 ("method group");
4353 if (Arguments != null){
4354 foreach (Argument a in Arguments){
4355 if (!a.Resolve (ec, loc))
4360 method = Invocation.OverloadResolve (ec, (MethodGroupExpr) ml,
4365 if (method == null) {
4366 if (!is_struct || Arguments.Count > 0) {
4368 "New invocation: Can not find a constructor for " +
4369 "this argument list");
4377 // This DoEmit can be invoked in two contexts:
4378 // * As a mechanism that will leave a value on the stack (new object)
4379 // * As one that wont (init struct)
4381 // You can control whether a value is required on the stack by passing
4382 // need_value_on_stack. The code *might* leave a value on the stack
4383 // so it must be popped manually
4385 // If we are dealing with a ValueType, we have a few
4386 // situations to deal with:
4388 // * The target is a ValueType, and we have been provided
4389 // the instance (this is easy, we are being assigned).
4391 // * The target of New is being passed as an argument,
4392 // to a boxing operation or a function that takes a
4395 // In this case, we need to create a temporary variable
4396 // that is the argument of New.
4398 // Returns whether a value is left on the stack
4400 bool DoEmit (EmitContext ec, bool need_value_on_stack)
4402 bool is_value_type = type.IsValueType;
4403 ILGenerator ig = ec.ig;
4408 // Allow DoEmit() to be called multiple times.
4409 // We need to create a new LocalTemporary each time since
4410 // you can't share LocalBuilders among ILGeneators.
4411 if (!value_target_set)
4412 value_target = new LocalTemporary (ec, type);
4414 ml = (IMemoryLocation) value_target;
4415 ml.AddressOf (ec, AddressOp.Store);
4419 Invocation.EmitArguments (ec, method, Arguments);
4423 ig.Emit (OpCodes.Initobj, type);
4425 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
4426 if (need_value_on_stack){
4427 value_target.Emit (ec);
4432 ig.Emit (OpCodes.Newobj, (ConstructorInfo) method);
4437 public override void Emit (EmitContext ec)
4442 public override void EmitStatement (EmitContext ec)
4444 if (DoEmit (ec, false))
4445 ec.ig.Emit (OpCodes.Pop);
4450 /// 14.5.10.2: Represents an array creation expression.
4454 /// There are two possible scenarios here: one is an array creation
4455 /// expression that specifies the dimensions and optionally the
4456 /// initialization data and the other which does not need dimensions
4457 /// specified but where initialization data is mandatory.
4459 public class ArrayCreation : ExpressionStatement {
4460 Expression requested_base_type;
4461 ArrayList initializers;
4464 // The list of Argument types.
4465 // This is used to construct the `newarray' or constructor signature
4467 ArrayList arguments;
4470 // Method used to create the array object.
4472 MethodBase new_method = null;
4474 Type array_element_type;
4475 Type underlying_type;
4476 bool is_one_dimensional = false;
4477 bool is_builtin_type = false;
4478 bool expect_initializers = false;
4479 int num_arguments = 0;
4483 ArrayList array_data;
4488 // The number of array initializers that we can handle
4489 // via the InitializeArray method - through EmitStaticInitializers
4491 int num_automatic_initializers;
4493 public ArrayCreation (Expression requested_base_type, ArrayList exprs, string rank, ArrayList initializers, Location l)
4495 this.requested_base_type = requested_base_type;
4496 this.initializers = initializers;
4500 arguments = new ArrayList ();
4502 foreach (Expression e in exprs) {
4503 arguments.Add (new Argument (e, Argument.AType.Expression));
4508 public ArrayCreation (Expression requested_base_type, string rank, ArrayList initializers, Location l)
4510 this.requested_base_type = requested_base_type;
4511 this.initializers = initializers;
4515 //this.rank = rank.Substring (0, rank.LastIndexOf ("["));
4517 //string tmp = rank.Substring (rank.LastIndexOf ("["));
4519 //dimensions = tmp.Length - 1;
4520 expect_initializers = true;
4523 public Expression FormArrayType (Expression base_type, int idx_count, string rank)
4525 StringBuilder sb = new StringBuilder (rank);
4528 for (int i = 1; i < idx_count; i++)
4533 return new ComposedCast (base_type, sb.ToString (), loc);
4538 Error (178, "Incorrectly structured array initializer");
4541 public bool CheckIndices (EmitContext ec, ArrayList probe, int idx, bool specified_dims)
4543 if (specified_dims) {
4544 Argument a = (Argument) arguments [idx];
4546 if (!a.Resolve (ec, loc))
4549 if (!(a.Expr is Constant)) {
4550 Error (150, "A constant value is expected");
4554 int value = (int) ((Constant) a.Expr).GetValue ();
4556 if (value != probe.Count) {
4561 bounds [idx] = value;
4564 foreach (object o in probe) {
4565 if (o is ArrayList) {
4566 bool ret = CheckIndices (ec, (ArrayList) o, idx + 1, specified_dims);
4570 Expression tmp = (Expression) o;
4571 tmp = tmp.Resolve (ec);
4575 // Console.WriteLine ("I got: " + tmp);
4576 // Handle initialization from vars, fields etc.
4578 Expression conv = ConvertImplicitRequired (
4579 ec, tmp, underlying_type, loc);
4584 if (conv is StringConstant)
4585 array_data.Add (conv);
4586 else if (conv is Constant) {
4587 array_data.Add (conv);
4588 num_automatic_initializers++;
4590 array_data.Add (conv);
4597 public void UpdateIndices (EmitContext ec)
4600 for (ArrayList probe = initializers; probe != null;) {
4601 if (probe.Count > 0 && probe [0] is ArrayList) {
4602 Expression e = new IntConstant (probe.Count);
4603 arguments.Add (new Argument (e, Argument.AType.Expression));
4605 bounds [i++] = probe.Count;
4607 probe = (ArrayList) probe [0];
4610 Expression e = new IntConstant (probe.Count);
4611 arguments.Add (new Argument (e, Argument.AType.Expression));
4613 bounds [i++] = probe.Count;
4620 public bool ValidateInitializers (EmitContext ec, Type array_type)
4622 if (initializers == null) {
4623 if (expect_initializers)
4629 if (underlying_type == null)
4633 // We use this to store all the date values in the order in which we
4634 // will need to store them in the byte blob later
4636 array_data = new ArrayList ();
4637 bounds = new Hashtable ();
4641 if (arguments != null) {
4642 ret = CheckIndices (ec, initializers, 0, true);
4645 arguments = new ArrayList ();
4647 ret = CheckIndices (ec, initializers, 0, false);
4654 if (arguments.Count != dimensions) {
4663 void Error_NegativeArrayIndex ()
4665 Error (284, "Can not create array with a negative size");
4669 // Converts `source' to an int, uint, long or ulong.
4671 Expression ExpressionToArrayArgument (EmitContext ec, Expression source)
4675 bool old_checked = ec.CheckState;
4676 ec.CheckState = true;
4678 target = ConvertImplicit (ec, source, TypeManager.int32_type, loc);
4679 if (target == null){
4680 target = ConvertImplicit (ec, source, TypeManager.uint32_type, loc);
4681 if (target == null){
4682 target = ConvertImplicit (ec, source, TypeManager.int64_type, loc);
4683 if (target == null){
4684 target = ConvertImplicit (ec, source, TypeManager.uint64_type, loc);
4686 Expression.Error_CannotConvertImplicit (loc, source.Type, TypeManager.int32_type);
4690 ec.CheckState = old_checked;
4693 // Only positive constants are allowed at compile time
4695 if (target is Constant){
4696 if (target is IntConstant){
4697 if (((IntConstant) target).Value < 0){
4698 Error_NegativeArrayIndex ();
4703 if (target is LongConstant){
4704 if (((LongConstant) target).Value < 0){
4705 Error_NegativeArrayIndex ();
4716 // Creates the type of the array
4718 bool LookupType (EmitContext ec)
4720 StringBuilder array_qualifier = new StringBuilder (rank);
4723 // `In the first form allocates an array instace of the type that results
4724 // from deleting each of the individual expression from the expression list'
4726 if (num_arguments > 0) {
4727 array_qualifier.Append ("[");
4728 for (int i = num_arguments-1; i > 0; i--)
4729 array_qualifier.Append (",");
4730 array_qualifier.Append ("]");
4736 Expression array_type_expr;
4737 array_type_expr = new ComposedCast (requested_base_type, array_qualifier.ToString (), loc);
4738 type = ec.DeclSpace.ResolveType (array_type_expr, false, loc);
4743 underlying_type = type;
4744 if (underlying_type.IsArray)
4745 underlying_type = TypeManager.TypeToCoreType (underlying_type.GetElementType ());
4746 dimensions = type.GetArrayRank ();
4751 public override Expression DoResolve (EmitContext ec)
4755 if (!LookupType (ec))
4759 // First step is to validate the initializers and fill
4760 // in any missing bits
4762 if (!ValidateInitializers (ec, type))
4765 if (arguments == null)
4768 arg_count = arguments.Count;
4769 foreach (Argument a in arguments){
4770 if (!a.Resolve (ec, loc))
4773 Expression real_arg = ExpressionToArrayArgument (ec, a.Expr, loc);
4774 if (real_arg == null)
4781 array_element_type = TypeManager.TypeToCoreType (type.GetElementType ());
4783 if (arg_count == 1) {
4784 is_one_dimensional = true;
4785 eclass = ExprClass.Value;
4789 is_builtin_type = TypeManager.IsBuiltinType (type);
4791 if (is_builtin_type) {
4794 ml = MemberLookup (ec, type, ".ctor", MemberTypes.Constructor,
4795 AllBindingFlags, loc);
4797 if (!(ml is MethodGroupExpr)) {
4798 ml.Error118 ("method group");
4803 Error (-6, "New invocation: Can not find a constructor for " +
4804 "this argument list");
4808 new_method = Invocation.OverloadResolve (ec, (MethodGroupExpr) ml, arguments, loc);
4810 if (new_method == null) {
4811 Error (-6, "New invocation: Can not find a constructor for " +
4812 "this argument list");
4816 eclass = ExprClass.Value;
4819 ModuleBuilder mb = CodeGen.ModuleBuilder;
4820 ArrayList args = new ArrayList ();
4822 if (arguments != null) {
4823 for (int i = 0; i < arg_count; i++)
4824 args.Add (TypeManager.int32_type);
4827 Type [] arg_types = null;
4830 arg_types = new Type [args.Count];
4832 args.CopyTo (arg_types, 0);
4834 new_method = mb.GetArrayMethod (type, ".ctor", CallingConventions.HasThis, null,
4837 if (new_method == null) {
4838 Error (-6, "New invocation: Can not find a constructor for " +
4839 "this argument list");
4843 eclass = ExprClass.Value;
4848 public static byte [] MakeByteBlob (ArrayList array_data, Type underlying_type, Location loc)
4853 int count = array_data.Count;
4855 if (underlying_type.IsEnum)
4856 underlying_type = TypeManager.EnumToUnderlying (underlying_type);
4858 factor = GetTypeSize (underlying_type);
4860 throw new Exception ("Unrecognized type in MakeByteBlob: " + underlying_type);
4862 data = new byte [(count * factor + 4) & ~3];
4865 for (int i = 0; i < count; ++i) {
4866 object v = array_data [i];
4868 if (v is EnumConstant)
4869 v = ((EnumConstant) v).Child;
4871 if (v is Constant && !(v is StringConstant))
4872 v = ((Constant) v).GetValue ();
4878 if (underlying_type == TypeManager.int64_type){
4879 if (!(v is Expression)){
4880 long val = (long) v;
4882 for (int j = 0; j < factor; ++j) {
4883 data [idx + j] = (byte) (val & 0xFF);
4887 } else if (underlying_type == TypeManager.uint64_type){
4888 if (!(v is Expression)){
4889 ulong val = (ulong) v;
4891 for (int j = 0; j < factor; ++j) {
4892 data [idx + j] = (byte) (val & 0xFF);
4896 } else if (underlying_type == TypeManager.float_type) {
4897 if (!(v is Expression)){
4898 element = BitConverter.GetBytes ((float) v);
4900 for (int j = 0; j < factor; ++j)
4901 data [idx + j] = element [j];
4903 } else if (underlying_type == TypeManager.double_type) {
4904 if (!(v is Expression)){
4905 element = BitConverter.GetBytes ((double) v);
4907 for (int j = 0; j < factor; ++j)
4908 data [idx + j] = element [j];
4910 } else if (underlying_type == TypeManager.char_type){
4911 if (!(v is Expression)){
4912 int val = (int) ((char) v);
4914 data [idx] = (byte) (val & 0xff);
4915 data [idx+1] = (byte) (val >> 8);
4917 } else if (underlying_type == TypeManager.short_type){
4918 if (!(v is Expression)){
4919 int val = (int) ((short) v);
4921 data [idx] = (byte) (val & 0xff);
4922 data [idx+1] = (byte) (val >> 8);
4924 } else if (underlying_type == TypeManager.ushort_type){
4925 if (!(v is Expression)){
4926 int val = (int) ((ushort) v);
4928 data [idx] = (byte) (val & 0xff);
4929 data [idx+1] = (byte) (val >> 8);
4931 } else if (underlying_type == TypeManager.int32_type) {
4932 if (!(v is Expression)){
4935 data [idx] = (byte) (val & 0xff);
4936 data [idx+1] = (byte) ((val >> 8) & 0xff);
4937 data [idx+2] = (byte) ((val >> 16) & 0xff);
4938 data [idx+3] = (byte) (val >> 24);
4940 } else if (underlying_type == TypeManager.uint32_type) {
4941 if (!(v is Expression)){
4942 uint val = (uint) v;
4944 data [idx] = (byte) (val & 0xff);
4945 data [idx+1] = (byte) ((val >> 8) & 0xff);
4946 data [idx+2] = (byte) ((val >> 16) & 0xff);
4947 data [idx+3] = (byte) (val >> 24);
4949 } else if (underlying_type == TypeManager.sbyte_type) {
4950 if (!(v is Expression)){
4951 sbyte val = (sbyte) v;
4952 data [idx] = (byte) val;
4954 } else if (underlying_type == TypeManager.byte_type) {
4955 if (!(v is Expression)){
4956 byte val = (byte) v;
4957 data [idx] = (byte) val;
4959 } else if (underlying_type == TypeManager.bool_type) {
4960 if (!(v is Expression)){
4961 bool val = (bool) v;
4962 data [idx] = (byte) (val ? 1 : 0);
4965 throw new Exception ("Unrecognized type in MakeByteBlob");
4974 // Emits the initializers for the array
4976 void EmitStaticInitializers (EmitContext ec, bool is_expression)
4979 // First, the static data
4982 ILGenerator ig = ec.ig;
4984 byte [] data = MakeByteBlob (array_data, underlying_type, loc);
4986 fb = RootContext.MakeStaticData (data);
4989 ig.Emit (OpCodes.Dup);
4990 ig.Emit (OpCodes.Ldtoken, fb);
4991 ig.Emit (OpCodes.Call,
4992 TypeManager.void_initializearray_array_fieldhandle);
4996 // Emits pieces of the array that can not be computed at compile
4997 // time (variables and string locations).
4999 // This always expect the top value on the stack to be the array
5001 void EmitDynamicInitializers (EmitContext ec, bool is_expression)
5003 ILGenerator ig = ec.ig;
5004 int dims = bounds.Count;
5005 int [] current_pos = new int [dims];
5006 int top = array_data.Count;
5007 LocalBuilder temp = ig.DeclareLocal (type);
5009 ig.Emit (OpCodes.Stloc, temp);
5011 MethodInfo set = null;
5015 ModuleBuilder mb = null;
5016 mb = CodeGen.ModuleBuilder;
5017 args = new Type [dims + 1];
5020 for (j = 0; j < dims; j++)
5021 args [j] = TypeManager.int32_type;
5023 args [j] = array_element_type;
5025 set = mb.GetArrayMethod (
5027 CallingConventions.HasThis | CallingConventions.Standard,
5028 TypeManager.void_type, args);
5031 for (int i = 0; i < top; i++){
5033 Expression e = null;
5035 if (array_data [i] is Expression)
5036 e = (Expression) array_data [i];
5040 // Basically we do this for string literals and
5041 // other non-literal expressions
5043 if (e is StringConstant || !(e is Constant) ||
5044 num_automatic_initializers <= 2) {
5045 Type etype = e.Type;
5047 ig.Emit (OpCodes.Ldloc, temp);
5049 for (int idx = dims; idx > 0; ) {
5051 IntConstant.EmitInt (ig, current_pos [idx]);
5055 // If we are dealing with a struct, get the
5056 // address of it, so we can store it.
5059 etype.IsSubclassOf (TypeManager.value_type) &&
5060 (!TypeManager.IsBuiltinType (etype) ||
5061 etype == TypeManager.decimal_type)) {
5066 // Let new know that we are providing
5067 // the address where to store the results
5069 n.DisableTemporaryValueType ();
5072 ig.Emit (OpCodes.Ldelema, etype);
5078 ArrayAccess.EmitStoreOpcode (ig, array_element_type);
5080 ig.Emit (OpCodes.Call, set);
5087 for (int j = 0; j < dims; j++){
5089 if (current_pos [j] < (int) bounds [j])
5091 current_pos [j] = 0;
5096 ig.Emit (OpCodes.Ldloc, temp);
5099 void EmitArrayArguments (EmitContext ec)
5101 ILGenerator ig = ec.ig;
5103 foreach (Argument a in arguments) {
5104 Type atype = a.Type;
5107 if (atype == TypeManager.uint64_type)
5108 ig.Emit (OpCodes.Conv_Ovf_U4);
5109 else if (atype == TypeManager.int64_type)
5110 ig.Emit (OpCodes.Conv_Ovf_I4);
5114 void DoEmit (EmitContext ec, bool is_statement)
5116 ILGenerator ig = ec.ig;
5118 EmitArrayArguments (ec);
5119 if (is_one_dimensional)
5120 ig.Emit (OpCodes.Newarr, array_element_type);
5122 if (is_builtin_type)
5123 ig.Emit (OpCodes.Newobj, (ConstructorInfo) new_method);
5125 ig.Emit (OpCodes.Newobj, (MethodInfo) new_method);
5128 if (initializers != null){
5130 // FIXME: Set this variable correctly.
5132 bool dynamic_initializers = true;
5134 if (underlying_type != TypeManager.string_type &&
5135 underlying_type != TypeManager.object_type) {
5136 if (num_automatic_initializers > 2)
5137 EmitStaticInitializers (ec, dynamic_initializers || !is_statement);
5140 if (dynamic_initializers)
5141 EmitDynamicInitializers (ec, !is_statement);
5145 public override void Emit (EmitContext ec)
5150 public override void EmitStatement (EmitContext ec)
5158 /// Represents the `this' construct
5160 public class This : Expression, IAssignMethod, IMemoryLocation, IVariable {
5165 public This (Block block, Location loc)
5171 public This (Location loc)
5176 public bool IsAssigned (EmitContext ec, Location loc)
5181 return vi.IsAssigned (ec, loc);
5184 public bool IsFieldAssigned (EmitContext ec, string field_name, Location loc)
5189 return vi.IsFieldAssigned (ec, field_name, loc);
5192 public void SetAssigned (EmitContext ec)
5195 vi.SetAssigned (ec);
5198 public void SetFieldAssigned (EmitContext ec, string field_name)
5201 vi.SetFieldAssigned (ec, field_name);
5204 public override Expression DoResolve (EmitContext ec)
5206 eclass = ExprClass.Variable;
5207 type = ec.ContainerType;
5210 Error (26, "Keyword this not valid in static code");
5215 vi = block.ThisVariable;
5220 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
5224 VariableInfo vi = ec.CurrentBlock.ThisVariable;
5226 vi.SetAssigned (ec);
5228 if (ec.TypeContainer is Class){
5229 Error (1604, "Cannot assign to `this'");
5236 public override void Emit (EmitContext ec)
5238 ILGenerator ig = ec.ig;
5240 ig.Emit (OpCodes.Ldarg_0);
5241 if (ec.TypeContainer is Struct)
5242 ig.Emit (OpCodes.Ldobj, type);
5245 public void EmitAssign (EmitContext ec, Expression source)
5247 ILGenerator ig = ec.ig;
5249 if (ec.TypeContainer is Struct){
5250 ig.Emit (OpCodes.Ldarg_0);
5252 ig.Emit (OpCodes.Stobj, type);
5255 ig.Emit (OpCodes.Starg, 0);
5259 public void AddressOf (EmitContext ec, AddressOp mode)
5261 ec.ig.Emit (OpCodes.Ldarg_0);
5264 // FIGURE OUT WHY LDARG_S does not work
5266 // consider: struct X { int val; int P { set { val = value; }}}
5268 // Yes, this looks very bad. Look at `NOTAS' for
5270 // ec.ig.Emit (OpCodes.Ldarga_S, (byte) 0);
5275 /// Implements the typeof operator
5277 public class TypeOf : Expression {
5278 public readonly Expression QueriedType;
5281 public TypeOf (Expression queried_type, Location l)
5283 QueriedType = queried_type;
5287 public override Expression DoResolve (EmitContext ec)
5289 typearg = ec.DeclSpace.ResolveType (QueriedType, false, loc);
5291 if (typearg == null)
5294 type = TypeManager.type_type;
5295 eclass = ExprClass.Type;
5299 public override void Emit (EmitContext ec)
5301 ec.ig.Emit (OpCodes.Ldtoken, typearg);
5302 ec.ig.Emit (OpCodes.Call, TypeManager.system_type_get_type_from_handle);
5305 public Type TypeArg {
5306 get { return typearg; }
5311 /// Implements the sizeof expression
5313 public class SizeOf : Expression {
5314 public readonly Expression QueriedType;
5317 public SizeOf (Expression queried_type, Location l)
5319 this.QueriedType = queried_type;
5323 public override Expression DoResolve (EmitContext ec)
5326 Error (233, "Sizeof may only be used in an unsafe context " +
5327 "(consider using System.Runtime.InteropServices.Marshal.Sizeof");
5331 type_queried = ec.DeclSpace.ResolveType (QueriedType, false, loc);
5332 if (type_queried == null)
5335 type = TypeManager.int32_type;
5336 eclass = ExprClass.Value;
5340 public override void Emit (EmitContext ec)
5342 int size = GetTypeSize (type_queried);
5345 ec.ig.Emit (OpCodes.Sizeof, type_queried);
5347 IntConstant.EmitInt (ec.ig, size);
5352 /// Implements the member access expression
5354 public class MemberAccess : Expression, ITypeExpression {
5355 public readonly string Identifier;
5357 Expression member_lookup;
5359 public MemberAccess (Expression expr, string id, Location l)
5366 public Expression Expr {
5372 static void error176 (Location loc, string name)
5374 Report.Error (176, loc, "Static member `" +
5375 name + "' cannot be accessed " +
5376 "with an instance reference, qualify with a " +
5377 "type name instead");
5380 static bool IdenticalNameAndTypeName (EmitContext ec, Expression left_original, Location loc)
5382 if (left_original == null)
5385 if (!(left_original is SimpleName))
5388 SimpleName sn = (SimpleName) left_original;
5390 Type t = RootContext.LookupType (ec.DeclSpace, sn.Name, true, loc);
5397 public static Expression ResolveMemberAccess (EmitContext ec, Expression member_lookup,
5398 Expression left, Location loc,
5399 Expression left_original)
5401 bool left_is_type, left_is_explicit;
5403 // If `left' is null, then we're called from SimpleNameResolve and this is
5404 // a member in the currently defining class.
5406 left_is_type = ec.IsStatic || ec.IsFieldInitializer;
5407 left_is_explicit = false;
5409 // Implicitly default to `this' unless we're static.
5410 if (!ec.IsStatic && !ec.IsFieldInitializer && !ec.InEnumContext)
5413 left_is_type = left is TypeExpr;
5414 left_is_explicit = true;
5417 if (member_lookup is FieldExpr){
5418 FieldExpr fe = (FieldExpr) member_lookup;
5419 FieldInfo fi = fe.FieldInfo;
5420 Type decl_type = fi.DeclaringType;
5422 if (fi is FieldBuilder) {
5423 Const c = TypeManager.LookupConstant ((FieldBuilder) fi);
5426 object o = c.LookupConstantValue (ec);
5427 object real_value = ((Constant) c.Expr).GetValue ();
5429 return Constantify (real_value, fi.FieldType);
5434 Type t = fi.FieldType;
5438 if (fi is FieldBuilder)
5439 o = TypeManager.GetValue ((FieldBuilder) fi);
5441 o = fi.GetValue (fi);
5443 if (decl_type.IsSubclassOf (TypeManager.enum_type)) {
5444 Expression enum_member = MemberLookup (
5445 ec, decl_type, "value__", MemberTypes.Field,
5446 AllBindingFlags, loc);
5448 Enum en = TypeManager.LookupEnum (decl_type);
5452 c = Constantify (o, en.UnderlyingType);
5454 c = Constantify (o, enum_member.Type);
5456 return new EnumConstant (c, decl_type);
5459 Expression exp = Constantify (o, t);
5461 if (left_is_explicit && !left_is_type) {
5462 error176 (loc, fe.FieldInfo.Name);
5469 if (fi.FieldType.IsPointer && !ec.InUnsafe){
5475 if (member_lookup is EventExpr) {
5477 EventExpr ee = (EventExpr) member_lookup;
5480 // If the event is local to this class, we transform ourselves into
5484 if (ee.EventInfo.DeclaringType == ec.ContainerType) {
5485 MemberInfo mi = GetFieldFromEvent (ee);
5489 // If this happens, then we have an event with its own
5490 // accessors and private field etc so there's no need
5491 // to transform ourselves : we should instead flag an error
5493 Assign.error70 (ee.EventInfo, loc);
5497 Expression ml = ExprClassFromMemberInfo (ec, mi, loc);
5500 Report.Error (-200, loc, "Internal error!!");
5504 return ResolveMemberAccess (ec, ml, left, loc, left_original);
5508 if (member_lookup is IMemberExpr) {
5509 IMemberExpr me = (IMemberExpr) member_lookup;
5512 MethodGroupExpr mg = me as MethodGroupExpr;
5513 if ((mg != null) && left_is_explicit && left.Type.IsInterface)
5514 mg.IsExplicitImpl = left_is_explicit;
5517 if (IdenticalNameAndTypeName (ec, left_original, loc))
5518 return member_lookup;
5520 SimpleName.Error_ObjectRefRequired (ec, loc, me.Name);
5525 if (!me.IsInstance){
5526 if (IdenticalNameAndTypeName (ec, left_original, loc))
5527 return member_lookup;
5529 if (left_is_explicit) {
5530 error176 (loc, me.Name);
5536 // Since we can not check for instance objects in SimpleName,
5537 // becaue of the rule that allows types and variables to share
5538 // the name (as long as they can be de-ambiguated later, see
5539 // IdenticalNameAndTypeName), we have to check whether left
5540 // is an instance variable in a static context
5542 // However, if the left-hand value is explicitly given, then
5543 // it is already our instance expression, so we aren't in
5547 if (ec.IsStatic && !left_is_explicit && left is IMemberExpr){
5548 IMemberExpr mexp = (IMemberExpr) left;
5550 if (!mexp.IsStatic){
5551 SimpleName.Error_ObjectRefRequired (ec, loc, mexp.Name);
5556 me.InstanceExpression = left;
5559 return member_lookup;
5562 if (member_lookup is TypeExpr){
5563 member_lookup.Resolve (ec, ResolveFlags.Type);
5564 return member_lookup;
5567 Console.WriteLine ("Left is: " + left);
5568 Report.Error (-100, loc, "Support for [" + member_lookup + "] is not present yet");
5569 Environment.Exit (0);
5573 public Expression DoResolve (EmitContext ec, Expression right_side, ResolveFlags flags)
5576 throw new Exception ();
5578 // Resolve the expression with flow analysis turned off, we'll do the definite
5579 // assignment checks later. This is because we don't know yet what the expression
5580 // will resolve to - it may resolve to a FieldExpr and in this case we must do the
5581 // definite assignment check on the actual field and not on the whole struct.
5584 Expression original = expr;
5585 expr = expr.Resolve (ec, flags | ResolveFlags.DisableFlowAnalysis);
5590 if (expr is SimpleName){
5591 SimpleName child_expr = (SimpleName) expr;
5593 Expression new_expr = new SimpleName (child_expr.Name + "." + Identifier, loc);
5595 return new_expr.Resolve (ec, flags);
5599 // TODO: I mailed Ravi about this, and apparently we can get rid
5600 // of this and put it in the right place.
5602 // Handle enums here when they are in transit.
5603 // Note that we cannot afford to hit MemberLookup in this case because
5604 // it will fail to find any members at all
5607 int errors = Report.Errors;
5609 Type expr_type = expr.Type;
5610 if ((expr is TypeExpr) && (expr_type.IsSubclassOf (TypeManager.enum_type))){
5612 Enum en = TypeManager.LookupEnum (expr_type);
5615 object value = en.LookupEnumValue (ec, Identifier, loc);
5618 Constant c = Constantify (value, en.UnderlyingType);
5619 return new EnumConstant (c, expr_type);
5624 if (expr_type.IsPointer){
5625 Error (23, "The `.' operator can not be applied to pointer operands (" +
5626 TypeManager.CSharpName (expr_type) + ")");
5630 member_lookup = MemberLookup (ec, expr_type, Identifier, loc);
5632 if (member_lookup == null){
5633 // Error has already been reported.
5634 if (errors < Report.Errors)
5638 // Try looking the member up from the same type, if we find
5639 // it, we know that the error was due to limited visibility
5641 object lookup = TypeManager.MemberLookup (
5642 expr_type, expr_type, AllMemberTypes, AllBindingFlags |
5643 BindingFlags.NonPublic, Identifier);
5645 Error (117, "`" + expr_type + "' does not contain a " +
5646 "definition for `" + Identifier + "'");
5647 else if ((expr_type != ec.ContainerType) &&
5648 ec.ContainerType.IsSubclassOf (expr_type)){
5650 // Although a derived class can access protected members of
5651 // its base class it cannot do so through an instance of the
5652 // base class (CS1540). If the expr_type is a parent of the
5653 // ec.ContainerType and the lookup succeeds with the latter one,
5654 // then we are in this situation.
5656 lookup = TypeManager.MemberLookup (
5657 ec.ContainerType, ec.ContainerType, AllMemberTypes,
5658 AllBindingFlags, Identifier);
5661 Error (1540, "Cannot access protected member `" +
5662 expr_type + "." + Identifier + "' " +
5663 "via a qualifier of type `" +
5664 TypeManager.CSharpName (expr_type) + "'; the " +
5665 "qualifier must be of type `" +
5666 TypeManager.CSharpName (ec.ContainerType) + "' " +
5667 "(or derived from it)");
5669 Error (122, "`" + expr_type + "." + Identifier + "' " +
5670 "is inaccessible because of its protection level");
5672 Error (122, "`" + expr_type + "." + Identifier + "' " +
5673 "is inaccessible because of its protection level");
5678 if (member_lookup is TypeExpr){
5679 member_lookup.Resolve (ec, ResolveFlags.Type);
5680 return member_lookup;
5681 } else if ((flags & ResolveFlags.MaskExprClass) == ResolveFlags.Type)
5684 member_lookup = ResolveMemberAccess (ec, member_lookup, expr, loc, original);
5685 if (member_lookup == null)
5688 // The following DoResolve/DoResolveLValue will do the definite assignment
5691 if (right_side != null)
5692 member_lookup = member_lookup.DoResolveLValue (ec, right_side);
5694 member_lookup = member_lookup.DoResolve (ec);
5696 return member_lookup;
5699 public override Expression DoResolve (EmitContext ec)
5701 return DoResolve (ec, null, ResolveFlags.VariableOrValue |
5702 ResolveFlags.SimpleName | ResolveFlags.Type);
5705 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
5707 return DoResolve (ec, right_side, ResolveFlags.VariableOrValue |
5708 ResolveFlags.SimpleName | ResolveFlags.Type);
5711 public Expression DoResolveType (EmitContext ec)
5713 return DoResolve (ec, null, ResolveFlags.Type);
5716 public override void Emit (EmitContext ec)
5718 throw new Exception ("Should not happen");
5721 public override string ToString ()
5723 return expr + "." + Identifier;
5728 /// Implements checked expressions
5730 public class CheckedExpr : Expression {
5732 public Expression Expr;
5734 public CheckedExpr (Expression e, Location l)
5740 public override Expression DoResolve (EmitContext ec)
5742 bool last_const_check = ec.ConstantCheckState;
5744 ec.ConstantCheckState = true;
5745 Expr = Expr.Resolve (ec);
5746 ec.ConstantCheckState = last_const_check;
5751 if (Expr is Constant)
5754 eclass = Expr.eclass;
5759 public override void Emit (EmitContext ec)
5761 bool last_check = ec.CheckState;
5762 bool last_const_check = ec.ConstantCheckState;
5764 ec.CheckState = true;
5765 ec.ConstantCheckState = true;
5767 ec.CheckState = last_check;
5768 ec.ConstantCheckState = last_const_check;
5774 /// Implements the unchecked expression
5776 public class UnCheckedExpr : Expression {
5778 public Expression Expr;
5780 public UnCheckedExpr (Expression e, Location l)
5786 public override Expression DoResolve (EmitContext ec)
5788 bool last_const_check = ec.ConstantCheckState;
5790 ec.ConstantCheckState = false;
5791 Expr = Expr.Resolve (ec);
5792 ec.ConstantCheckState = last_const_check;
5797 if (Expr is Constant)
5800 eclass = Expr.eclass;
5805 public override void Emit (EmitContext ec)
5807 bool last_check = ec.CheckState;
5808 bool last_const_check = ec.ConstantCheckState;
5810 ec.CheckState = false;
5811 ec.ConstantCheckState = false;
5813 ec.CheckState = last_check;
5814 ec.ConstantCheckState = last_const_check;
5820 /// An Element Access expression.
5822 /// During semantic analysis these are transformed into
5823 /// IndexerAccess or ArrayAccess
5825 public class ElementAccess : Expression {
5826 public ArrayList Arguments;
5827 public Expression Expr;
5829 public ElementAccess (Expression e, ArrayList e_list, Location l)
5838 Arguments = new ArrayList ();
5839 foreach (Expression tmp in e_list)
5840 Arguments.Add (new Argument (tmp, Argument.AType.Expression));
5844 bool CommonResolve (EmitContext ec)
5846 Expr = Expr.Resolve (ec);
5851 if (Arguments == null)
5854 foreach (Argument a in Arguments){
5855 if (!a.Resolve (ec, loc))
5862 Expression MakePointerAccess ()
5866 if (t == TypeManager.void_ptr_type){
5869 "The array index operation is not valid for void pointers");
5872 if (Arguments.Count != 1){
5875 "A pointer must be indexed by a single value");
5878 Expression p = new PointerArithmetic (true, Expr, ((Argument)Arguments [0]).Expr,
5880 return new Indirection (p, loc);
5883 public override Expression DoResolve (EmitContext ec)
5885 if (!CommonResolve (ec))
5889 // We perform some simple tests, and then to "split" the emit and store
5890 // code we create an instance of a different class, and return that.
5892 // I am experimenting with this pattern.
5897 return (new ArrayAccess (this, loc)).Resolve (ec);
5898 else if (t.IsPointer)
5899 return MakePointerAccess ();
5901 return (new IndexerAccess (this, loc)).Resolve (ec);
5904 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
5906 if (!CommonResolve (ec))
5911 return (new ArrayAccess (this, loc)).ResolveLValue (ec, right_side);
5912 else if (t.IsPointer)
5913 return MakePointerAccess ();
5915 return (new IndexerAccess (this, loc)).ResolveLValue (ec, right_side);
5918 public override void Emit (EmitContext ec)
5920 throw new Exception ("Should never be reached");
5925 /// Implements array access
5927 public class ArrayAccess : Expression, IAssignMethod, IMemoryLocation {
5929 // Points to our "data" repository
5933 LocalTemporary [] cached_locations;
5935 public ArrayAccess (ElementAccess ea_data, Location l)
5938 eclass = ExprClass.Variable;
5942 public override Expression DoResolve (EmitContext ec)
5944 ExprClass eclass = ea.Expr.eclass;
5947 // As long as the type is valid
5948 if (!(eclass == ExprClass.Variable || eclass == ExprClass.PropertyAccess ||
5949 eclass == ExprClass.Value)) {
5950 ea.Expr.Error118 ("variable or value");
5955 Type t = ea.Expr.Type;
5956 if (t.GetArrayRank () != ea.Arguments.Count){
5958 "Incorrect number of indexes for array " +
5959 " expected: " + t.GetArrayRank () + " got: " +
5960 ea.Arguments.Count);
5963 type = TypeManager.TypeToCoreType (t.GetElementType ());
5964 if (type.IsPointer && !ec.InUnsafe){
5965 UnsafeError (ea.Location);
5969 foreach (Argument a in ea.Arguments){
5970 Type argtype = a.Type;
5972 if (argtype == TypeManager.int32_type ||
5973 argtype == TypeManager.uint32_type ||
5974 argtype == TypeManager.int64_type ||
5975 argtype == TypeManager.uint64_type)
5979 // Mhm. This is strage, because the Argument.Type is not the same as
5980 // Argument.Expr.Type: the value changes depending on the ref/out setting.
5982 // Wonder if I will run into trouble for this.
5984 a.Expr = ExpressionToArrayArgument (ec, a.Expr, ea.Location);
5989 eclass = ExprClass.Variable;
5995 /// Emits the right opcode to load an object of Type `t'
5996 /// from an array of T
5998 static public void EmitLoadOpcode (ILGenerator ig, Type type)
6000 if (type == TypeManager.byte_type || type == TypeManager.bool_type)
6001 ig.Emit (OpCodes.Ldelem_U1);
6002 else if (type == TypeManager.sbyte_type)
6003 ig.Emit (OpCodes.Ldelem_I1);
6004 else if (type == TypeManager.short_type)
6005 ig.Emit (OpCodes.Ldelem_I2);
6006 else if (type == TypeManager.ushort_type || type == TypeManager.char_type)
6007 ig.Emit (OpCodes.Ldelem_U2);
6008 else if (type == TypeManager.int32_type)
6009 ig.Emit (OpCodes.Ldelem_I4);
6010 else if (type == TypeManager.uint32_type)
6011 ig.Emit (OpCodes.Ldelem_U4);
6012 else if (type == TypeManager.uint64_type)
6013 ig.Emit (OpCodes.Ldelem_I8);
6014 else if (type == TypeManager.int64_type)
6015 ig.Emit (OpCodes.Ldelem_I8);
6016 else if (type == TypeManager.float_type)
6017 ig.Emit (OpCodes.Ldelem_R4);
6018 else if (type == TypeManager.double_type)
6019 ig.Emit (OpCodes.Ldelem_R8);
6020 else if (type == TypeManager.intptr_type)
6021 ig.Emit (OpCodes.Ldelem_I);
6022 else if (type.IsValueType){
6023 ig.Emit (OpCodes.Ldelema, type);
6024 ig.Emit (OpCodes.Ldobj, type);
6026 ig.Emit (OpCodes.Ldelem_Ref);
6030 /// Emits the right opcode to store an object of Type `t'
6031 /// from an array of T.
6033 static public void EmitStoreOpcode (ILGenerator ig, Type t)
6035 t = TypeManager.TypeToCoreType (t);
6036 if (t == TypeManager.byte_type || t == TypeManager.sbyte_type ||
6037 t == TypeManager.bool_type)
6038 ig.Emit (OpCodes.Stelem_I1);
6039 else if (t == TypeManager.short_type || t == TypeManager.ushort_type || t == TypeManager.char_type)
6040 ig.Emit (OpCodes.Stelem_I2);
6041 else if (t == TypeManager.int32_type || t == TypeManager.uint32_type)
6042 ig.Emit (OpCodes.Stelem_I4);
6043 else if (t == TypeManager.int64_type || t == TypeManager.uint64_type)
6044 ig.Emit (OpCodes.Stelem_I8);
6045 else if (t == TypeManager.float_type)
6046 ig.Emit (OpCodes.Stelem_R4);
6047 else if (t == TypeManager.double_type)
6048 ig.Emit (OpCodes.Stelem_R8);
6049 else if (t == TypeManager.intptr_type)
6050 ig.Emit (OpCodes.Stelem_I);
6051 else if (t.IsValueType)
6052 ig.Emit (OpCodes.Stobj, t);
6054 ig.Emit (OpCodes.Stelem_Ref);
6057 MethodInfo FetchGetMethod ()
6059 ModuleBuilder mb = CodeGen.ModuleBuilder;
6060 int arg_count = ea.Arguments.Count;
6061 Type [] args = new Type [arg_count];
6064 for (int i = 0; i < arg_count; i++){
6065 //args [i++] = a.Type;
6066 args [i] = TypeManager.int32_type;
6069 get = mb.GetArrayMethod (
6070 ea.Expr.Type, "Get",
6071 CallingConventions.HasThis |
6072 CallingConventions.Standard,
6078 MethodInfo FetchAddressMethod ()
6080 ModuleBuilder mb = CodeGen.ModuleBuilder;
6081 int arg_count = ea.Arguments.Count;
6082 Type [] args = new Type [arg_count];
6084 string ptr_type_name;
6087 ptr_type_name = type.FullName + "&";
6088 ret_type = Type.GetType (ptr_type_name);
6091 // It is a type defined by the source code we are compiling
6093 if (ret_type == null){
6094 ret_type = mb.GetType (ptr_type_name);
6097 for (int i = 0; i < arg_count; i++){
6098 //args [i++] = a.Type;
6099 args [i] = TypeManager.int32_type;
6102 address = mb.GetArrayMethod (
6103 ea.Expr.Type, "Address",
6104 CallingConventions.HasThis |
6105 CallingConventions.Standard,
6112 // Load the array arguments into the stack.
6114 // If we have been requested to cache the values (cached_locations array
6115 // initialized), then load the arguments the first time and store them
6116 // in locals. otherwise load from local variables.
6118 void LoadArrayAndArguments (EmitContext ec)
6120 ILGenerator ig = ec.ig;
6122 if (cached_locations == null){
6124 foreach (Argument a in ea.Arguments){
6125 Type argtype = a.Expr.Type;
6129 if (argtype == TypeManager.int64_type)
6130 ig.Emit (OpCodes.Conv_Ovf_I);
6131 else if (argtype == TypeManager.uint64_type)
6132 ig.Emit (OpCodes.Conv_Ovf_I_Un);
6137 if (cached_locations [0] == null){
6138 cached_locations [0] = new LocalTemporary (ec, ea.Expr.Type);
6140 ig.Emit (OpCodes.Dup);
6141 cached_locations [0].Store (ec);
6145 foreach (Argument a in ea.Arguments){
6146 Type argtype = a.Expr.Type;
6148 cached_locations [j] = new LocalTemporary (ec, TypeManager.intptr_type /* a.Expr.Type */);
6150 if (argtype == TypeManager.int64_type)
6151 ig.Emit (OpCodes.Conv_Ovf_I);
6152 else if (argtype == TypeManager.uint64_type)
6153 ig.Emit (OpCodes.Conv_Ovf_I_Un);
6155 ig.Emit (OpCodes.Dup);
6156 cached_locations [j].Store (ec);
6162 foreach (LocalTemporary lt in cached_locations)
6166 public new void CacheTemporaries (EmitContext ec)
6168 cached_locations = new LocalTemporary [ea.Arguments.Count + 1];
6171 public override void Emit (EmitContext ec)
6173 int rank = ea.Expr.Type.GetArrayRank ();
6174 ILGenerator ig = ec.ig;
6176 LoadArrayAndArguments (ec);
6179 EmitLoadOpcode (ig, type);
6183 method = FetchGetMethod ();
6184 ig.Emit (OpCodes.Call, method);
6188 public void EmitAssign (EmitContext ec, Expression source)
6190 int rank = ea.Expr.Type.GetArrayRank ();
6191 ILGenerator ig = ec.ig;
6192 Type t = source.Type;
6194 LoadArrayAndArguments (ec);
6197 // The stobj opcode used by value types will need
6198 // an address on the stack, not really an array/array
6202 if (t.IsValueType && !TypeManager.IsBuiltinType (t))
6203 ig.Emit (OpCodes.Ldelema, t);
6209 EmitStoreOpcode (ig, t);
6211 ModuleBuilder mb = CodeGen.ModuleBuilder;
6212 int arg_count = ea.Arguments.Count;
6213 Type [] args = new Type [arg_count + 1];
6216 for (int i = 0; i < arg_count; i++){
6217 //args [i++] = a.Type;
6218 args [i] = TypeManager.int32_type;
6221 args [arg_count] = type;
6223 set = mb.GetArrayMethod (
6224 ea.Expr.Type, "Set",
6225 CallingConventions.HasThis |
6226 CallingConventions.Standard,
6227 TypeManager.void_type, args);
6229 ig.Emit (OpCodes.Call, set);
6233 public void AddressOf (EmitContext ec, AddressOp mode)
6235 int rank = ea.Expr.Type.GetArrayRank ();
6236 ILGenerator ig = ec.ig;
6238 LoadArrayAndArguments (ec);
6241 ig.Emit (OpCodes.Ldelema, type);
6243 MethodInfo address = FetchAddressMethod ();
6244 ig.Emit (OpCodes.Call, address);
6251 public ArrayList getters, setters;
6252 static Hashtable map;
6256 map = new Hashtable ();
6259 Indexers (MemberInfo [] mi)
6261 foreach (PropertyInfo property in mi){
6262 MethodInfo get, set;
6264 get = property.GetGetMethod (true);
6266 if (getters == null)
6267 getters = new ArrayList ();
6272 set = property.GetSetMethod (true);
6274 if (setters == null)
6275 setters = new ArrayList ();
6281 static private Indexers GetIndexersForTypeOrInterface (Type caller_type, Type lookup_type)
6283 Indexers ix = (Indexers) map [lookup_type];
6288 string p_name = TypeManager.IndexerPropertyName (lookup_type);
6290 MemberInfo [] mi = TypeManager.MemberLookup (
6291 caller_type, lookup_type, MemberTypes.Property,
6292 BindingFlags.Public | BindingFlags.Instance, p_name);
6294 if (mi == null || mi.Length == 0)
6297 ix = new Indexers (mi);
6298 map [lookup_type] = ix;
6303 static public Indexers GetIndexersForType (Type caller_type, Type lookup_type, Location loc)
6305 Indexers ix = (Indexers) map [lookup_type];
6310 ix = GetIndexersForTypeOrInterface (caller_type, lookup_type);
6314 Type [] ifaces = TypeManager.GetInterfaces (lookup_type);
6315 if (ifaces != null) {
6316 foreach (Type itype in ifaces) {
6317 ix = GetIndexersForTypeOrInterface (caller_type, itype);
6323 Report.Error (21, loc,
6324 "Type `" + TypeManager.CSharpName (lookup_type) +
6325 "' does not have any indexers defined");
6331 /// Expressions that represent an indexer call.
6333 public class IndexerAccess : Expression, IAssignMethod {
6335 // Points to our "data" repository
6337 MethodInfo get, set;
6339 ArrayList set_arguments;
6340 bool is_base_indexer;
6342 protected Type indexer_type;
6343 protected Type current_type;
6344 protected Expression instance_expr;
6345 protected ArrayList arguments;
6347 public IndexerAccess (ElementAccess ea, Location loc)
6348 : this (ea.Expr, false, loc)
6350 this.arguments = ea.Arguments;
6353 protected IndexerAccess (Expression instance_expr, bool is_base_indexer,
6356 this.instance_expr = instance_expr;
6357 this.is_base_indexer = is_base_indexer;
6358 this.eclass = ExprClass.Value;
6362 protected virtual bool CommonResolve (EmitContext ec)
6364 indexer_type = instance_expr.Type;
6365 current_type = ec.ContainerType;
6370 public override Expression DoResolve (EmitContext ec)
6372 if (!CommonResolve (ec))
6376 // Step 1: Query for all `Item' *properties*. Notice
6377 // that the actual methods are pointed from here.
6379 // This is a group of properties, piles of them.
6382 ilist = Indexers.GetIndexersForType (
6383 current_type, indexer_type, loc);
6386 // Step 2: find the proper match
6388 if (ilist != null && ilist.getters != null && ilist.getters.Count > 0)
6389 get = (MethodInfo) Invocation.OverloadResolve (
6390 ec, new MethodGroupExpr (ilist.getters, loc), arguments, loc);
6393 Error (154, "indexer can not be used in this context, because " +
6394 "it lacks a `get' accessor");
6398 type = get.ReturnType;
6399 if (type.IsPointer && !ec.InUnsafe){
6404 eclass = ExprClass.IndexerAccess;
6408 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
6410 if (!CommonResolve (ec))
6413 Type right_type = right_side.Type;
6416 ilist = Indexers.GetIndexersForType (
6417 current_type, indexer_type, loc);
6419 if (ilist != null && ilist.setters != null && ilist.setters.Count > 0){
6420 set_arguments = (ArrayList) arguments.Clone ();
6421 set_arguments.Add (new Argument (right_side, Argument.AType.Expression));
6423 set = (MethodInfo) Invocation.OverloadResolve (
6424 ec, new MethodGroupExpr (ilist.setters, loc), set_arguments, loc);
6428 Error (200, "indexer X.this [" + TypeManager.CSharpName (right_type) +
6429 "] lacks a `set' accessor");
6433 type = TypeManager.void_type;
6434 eclass = ExprClass.IndexerAccess;
6438 public override void Emit (EmitContext ec)
6440 Invocation.EmitCall (ec, false, false, instance_expr, get, arguments, loc);
6444 // source is ignored, because we already have a copy of it from the
6445 // LValue resolution and we have already constructed a pre-cached
6446 // version of the arguments (ea.set_arguments);
6448 public void EmitAssign (EmitContext ec, Expression source)
6450 Invocation.EmitCall (ec, false, false, instance_expr, set, set_arguments, loc);
6455 /// The base operator for method names
6457 public class BaseAccess : Expression {
6460 public BaseAccess (string member, Location l)
6462 this.member = member;
6466 public override Expression DoResolve (EmitContext ec)
6468 Expression member_lookup;
6469 Type current_type = ec.ContainerType;
6470 Type base_type = current_type.BaseType;
6475 "Keyword base is not allowed in static method");
6479 member_lookup = MemberLookup (ec, base_type, base_type, member,
6480 AllMemberTypes, AllBindingFlags, loc);
6481 if (member_lookup == null) {
6483 TypeManager.CSharpName (base_type) + " does not " +
6484 "contain a definition for `" + member + "'");
6491 left = new TypeExpr (base_type, loc);
6495 e = MemberAccess.ResolveMemberAccess (ec, member_lookup, left, loc, null);
6497 if (e is PropertyExpr){
6498 PropertyExpr pe = (PropertyExpr) e;
6506 public override void Emit (EmitContext ec)
6508 throw new Exception ("Should never be called");
6513 /// The base indexer operator
6515 public class BaseIndexerAccess : IndexerAccess {
6516 public BaseIndexerAccess (ArrayList args, Location loc)
6517 : base (null, true, loc)
6519 arguments = new ArrayList ();
6520 foreach (Expression tmp in args)
6521 arguments.Add (new Argument (tmp, Argument.AType.Expression));
6524 protected override bool CommonResolve (EmitContext ec)
6526 instance_expr = ec.This;
6528 current_type = ec.ContainerType.BaseType;
6529 indexer_type = current_type;
6531 foreach (Argument a in arguments){
6532 if (!a.Resolve (ec, loc))
6541 /// This class exists solely to pass the Type around and to be a dummy
6542 /// that can be passed to the conversion functions (this is used by
6543 /// foreach implementation to typecast the object return value from
6544 /// get_Current into the proper type. All code has been generated and
6545 /// we only care about the side effect conversions to be performed
6547 /// This is also now used as a placeholder where a no-action expression
6548 /// is needed (the `New' class).
6550 public class EmptyExpression : Expression {
6551 public EmptyExpression ()
6553 type = TypeManager.object_type;
6554 eclass = ExprClass.Value;
6555 loc = Location.Null;
6558 public EmptyExpression (Type t)
6561 eclass = ExprClass.Value;
6562 loc = Location.Null;
6565 public override Expression DoResolve (EmitContext ec)
6570 public override void Emit (EmitContext ec)
6572 // nothing, as we only exist to not do anything.
6576 // This is just because we might want to reuse this bad boy
6577 // instead of creating gazillions of EmptyExpressions.
6578 // (CanConvertImplicit uses it)
6580 public void SetType (Type t)
6586 public class UserCast : Expression {
6590 public UserCast (MethodInfo method, Expression source, Location l)
6592 this.method = method;
6593 this.source = source;
6594 type = method.ReturnType;
6595 eclass = ExprClass.Value;
6599 public override Expression DoResolve (EmitContext ec)
6602 // We are born fully resolved
6607 public override void Emit (EmitContext ec)
6609 ILGenerator ig = ec.ig;
6613 if (method is MethodInfo)
6614 ig.Emit (OpCodes.Call, (MethodInfo) method);
6616 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
6622 // This class is used to "construct" the type during a typecast
6623 // operation. Since the Type.GetType class in .NET can parse
6624 // the type specification, we just use this to construct the type
6625 // one bit at a time.
6627 public class ComposedCast : Expression, ITypeExpression {
6631 public ComposedCast (Expression left, string dim, Location l)
6638 public Expression DoResolveType (EmitContext ec)
6640 Type ltype = ec.DeclSpace.ResolveType (left, false, loc);
6644 type = RootContext.LookupType (
6645 ec.DeclSpace, ltype.FullName + dim, false, loc);
6649 if (!ec.ResolvingTypeTree){
6651 // If the above flag is set, this is being invoked from the ResolveType function.
6652 // Upper layers take care of the type validity in this context.
6654 if (!ec.InUnsafe && type.IsPointer){
6660 eclass = ExprClass.Type;
6664 public override Expression DoResolve (EmitContext ec)
6666 return DoResolveType (ec);
6669 public override void Emit (EmitContext ec)
6671 throw new Exception ("This should never be called");
6674 public override string ToString ()
6681 // This class is used to represent the address of an array, used
6682 // only by the Fixed statement, this is like the C "&a [0]" construct.
6684 public class ArrayPtr : Expression {
6687 public ArrayPtr (Expression array, Location l)
6689 Type array_type = array.Type.GetElementType ();
6693 string array_ptr_type_name = array_type.FullName + "*";
6695 type = Type.GetType (array_ptr_type_name);
6697 ModuleBuilder mb = CodeGen.ModuleBuilder;
6699 type = mb.GetType (array_ptr_type_name);
6702 eclass = ExprClass.Value;
6706 public override void Emit (EmitContext ec)
6708 ILGenerator ig = ec.ig;
6711 IntLiteral.EmitInt (ig, 0);
6712 ig.Emit (OpCodes.Ldelema, array.Type.GetElementType ());
6715 public override Expression DoResolve (EmitContext ec)
6718 // We are born fully resolved
6725 // Used by the fixed statement
6727 public class StringPtr : Expression {
6730 public StringPtr (LocalBuilder b, Location l)
6733 eclass = ExprClass.Value;
6734 type = TypeManager.char_ptr_type;
6738 public override Expression DoResolve (EmitContext ec)
6740 // This should never be invoked, we are born in fully
6741 // initialized state.
6746 public override void Emit (EmitContext ec)
6748 ILGenerator ig = ec.ig;
6750 ig.Emit (OpCodes.Ldloc, b);
6751 ig.Emit (OpCodes.Conv_I);
6752 ig.Emit (OpCodes.Call, TypeManager.int_get_offset_to_string_data);
6753 ig.Emit (OpCodes.Add);
6758 // Implements the `stackalloc' keyword
6760 public class StackAlloc : Expression {
6765 public StackAlloc (Expression type, Expression count, Location l)
6772 public override Expression DoResolve (EmitContext ec)
6774 count = count.Resolve (ec);
6778 if (count.Type != TypeManager.int32_type){
6779 count = ConvertImplicitRequired (ec, count, TypeManager.int32_type, loc);
6784 if (ec.InCatch || ec.InFinally){
6786 "stackalloc can not be used in a catch or finally block");
6790 otype = ec.DeclSpace.ResolveType (t, false, loc);
6795 if (!TypeManager.VerifyUnManaged (otype, loc))
6798 string ptr_name = otype.FullName + "*";
6799 type = Type.GetType (ptr_name);
6801 ModuleBuilder mb = CodeGen.ModuleBuilder;
6803 type = mb.GetType (ptr_name);
6805 eclass = ExprClass.Value;
6810 public override void Emit (EmitContext ec)
6812 int size = GetTypeSize (otype);
6813 ILGenerator ig = ec.ig;
6816 ig.Emit (OpCodes.Sizeof, otype);
6818 IntConstant.EmitInt (ig, size);
6820 ig.Emit (OpCodes.Mul);
6821 ig.Emit (OpCodes.Localloc);