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 target_type = target_type.Resolve (ec, ResolveFlags.Type);
1439 if (target_type == null){
1440 if (errors == Report.Errors)
1441 Error (-10, "Can not resolve type");
1445 type = target_type.Type;
1446 eclass = ExprClass.Value;
1451 if (expr is Constant){
1452 Expression e = TryReduce (ec, type);
1458 expr = ConvertExplicit (ec, expr, type, loc);
1462 public override void Emit (EmitContext ec)
1465 // This one will never happen
1467 throw new Exception ("Should not happen");
1472 /// Binary operators
1474 public class Binary : Expression {
1475 public enum Operator : byte {
1476 Multiply, Division, Modulus,
1477 Addition, Subtraction,
1478 LeftShift, RightShift,
1479 LessThan, GreaterThan, LessThanOrEqual, GreaterThanOrEqual,
1480 Equality, Inequality,
1490 Expression left, right;
1493 // After resolution, method might contain the operator overload
1496 protected MethodBase method;
1497 ArrayList Arguments;
1499 bool DelegateOperation;
1501 // This must be kept in sync with Operator!!!
1502 static string [] oper_names;
1506 oper_names = new string [(int) Operator.TOP];
1508 oper_names [(int) Operator.Multiply] = "op_Multiply";
1509 oper_names [(int) Operator.Division] = "op_Division";
1510 oper_names [(int) Operator.Modulus] = "op_Modulus";
1511 oper_names [(int) Operator.Addition] = "op_Addition";
1512 oper_names [(int) Operator.Subtraction] = "op_Subtraction";
1513 oper_names [(int) Operator.LeftShift] = "op_LeftShift";
1514 oper_names [(int) Operator.RightShift] = "op_RightShift";
1515 oper_names [(int) Operator.LessThan] = "op_LessThan";
1516 oper_names [(int) Operator.GreaterThan] = "op_GreaterThan";
1517 oper_names [(int) Operator.LessThanOrEqual] = "op_LessThanOrEqual";
1518 oper_names [(int) Operator.GreaterThanOrEqual] = "op_GreaterThanOrEqual";
1519 oper_names [(int) Operator.Equality] = "op_Equality";
1520 oper_names [(int) Operator.Inequality] = "op_Inequality";
1521 oper_names [(int) Operator.BitwiseAnd] = "op_BitwiseAnd";
1522 oper_names [(int) Operator.BitwiseOr] = "op_BitwiseOr";
1523 oper_names [(int) Operator.ExclusiveOr] = "op_ExclusiveOr";
1524 oper_names [(int) Operator.LogicalOr] = "op_LogicalOr";
1525 oper_names [(int) Operator.LogicalAnd] = "op_LogicalAnd";
1528 public Binary (Operator oper, Expression left, Expression right, Location loc)
1536 public Operator Oper {
1545 public Expression Left {
1554 public Expression Right {
1565 /// Returns a stringified representation of the Operator
1567 static string OperName (Operator oper)
1570 case Operator.Multiply:
1572 case Operator.Division:
1574 case Operator.Modulus:
1576 case Operator.Addition:
1578 case Operator.Subtraction:
1580 case Operator.LeftShift:
1582 case Operator.RightShift:
1584 case Operator.LessThan:
1586 case Operator.GreaterThan:
1588 case Operator.LessThanOrEqual:
1590 case Operator.GreaterThanOrEqual:
1592 case Operator.Equality:
1594 case Operator.Inequality:
1596 case Operator.BitwiseAnd:
1598 case Operator.BitwiseOr:
1600 case Operator.ExclusiveOr:
1602 case Operator.LogicalOr:
1604 case Operator.LogicalAnd:
1608 return oper.ToString ();
1611 public override string ToString ()
1613 return "operator " + OperName (oper) + "(" + left.ToString () + ", " +
1614 right.ToString () + ")";
1617 Expression ForceConversion (EmitContext ec, Expression expr, Type target_type)
1619 if (expr.Type == target_type)
1622 return ConvertImplicit (ec, expr, target_type, new Location (-1));
1625 public static void Error_OperatorAmbiguous (Location loc, Operator oper, Type l, Type r)
1628 34, loc, "Operator `" + OperName (oper)
1629 + "' is ambiguous on operands of type `"
1630 + TypeManager.CSharpName (l) + "' "
1631 + "and `" + TypeManager.CSharpName (r)
1636 // Note that handling the case l == Decimal || r == Decimal
1637 // is taken care of by the Step 1 Operator Overload resolution.
1639 bool DoNumericPromotions (EmitContext ec, Type l, Type r)
1641 if (l == TypeManager.double_type || r == TypeManager.double_type){
1643 // If either operand is of type double, the other operand is
1644 // conveted to type double.
1646 if (r != TypeManager.double_type)
1647 right = ConvertImplicit (ec, right, TypeManager.double_type, loc);
1648 if (l != TypeManager.double_type)
1649 left = ConvertImplicit (ec, left, TypeManager.double_type, loc);
1651 type = TypeManager.double_type;
1652 } else if (l == TypeManager.float_type || r == TypeManager.float_type){
1654 // if either operand is of type float, the other operand is
1655 // converted to type float.
1657 if (r != TypeManager.double_type)
1658 right = ConvertImplicit (ec, right, TypeManager.float_type, loc);
1659 if (l != TypeManager.double_type)
1660 left = ConvertImplicit (ec, left, TypeManager.float_type, loc);
1661 type = TypeManager.float_type;
1662 } else if (l == TypeManager.uint64_type || r == TypeManager.uint64_type){
1666 // If either operand is of type ulong, the other operand is
1667 // converted to type ulong. or an error ocurrs if the other
1668 // operand is of type sbyte, short, int or long
1670 if (l == TypeManager.uint64_type){
1671 if (r != TypeManager.uint64_type){
1672 if (right is IntConstant){
1673 IntConstant ic = (IntConstant) right;
1675 e = TryImplicitIntConversion (l, ic);
1678 } else if (right is LongConstant){
1679 long ll = ((LongConstant) right).Value;
1682 right = new ULongConstant ((ulong) ll);
1684 e = ImplicitNumericConversion (ec, right, l, loc);
1691 if (left is IntConstant){
1692 e = TryImplicitIntConversion (r, (IntConstant) left);
1695 } else if (left is LongConstant){
1696 long ll = ((LongConstant) left).Value;
1699 left = new ULongConstant ((ulong) ll);
1701 e = ImplicitNumericConversion (ec, left, r, loc);
1708 if ((other == TypeManager.sbyte_type) ||
1709 (other == TypeManager.short_type) ||
1710 (other == TypeManager.int32_type) ||
1711 (other == TypeManager.int64_type))
1712 Error_OperatorAmbiguous (loc, oper, l, r);
1713 type = TypeManager.uint64_type;
1714 } else if (l == TypeManager.int64_type || r == TypeManager.int64_type){
1716 // If either operand is of type long, the other operand is converted
1719 if (l != TypeManager.int64_type)
1720 left = ConvertImplicit (ec, left, TypeManager.int64_type, loc);
1721 if (r != TypeManager.int64_type)
1722 right = ConvertImplicit (ec, right, TypeManager.int64_type, loc);
1724 type = TypeManager.int64_type;
1725 } else if (l == TypeManager.uint32_type || r == TypeManager.uint32_type){
1727 // If either operand is of type uint, and the other
1728 // operand is of type sbyte, short or int, othe operands are
1729 // converted to type long.
1733 if (l == TypeManager.uint32_type){
1734 if (right is IntConstant){
1735 IntConstant ic = (IntConstant) right;
1739 right = new UIntConstant ((uint) val);
1746 else if (r == TypeManager.uint32_type){
1747 if (left is IntConstant){
1748 IntConstant ic = (IntConstant) left;
1752 left = new UIntConstant ((uint) val);
1761 if ((other == TypeManager.sbyte_type) ||
1762 (other == TypeManager.short_type) ||
1763 (other == TypeManager.int32_type)){
1764 left = ForceConversion (ec, left, TypeManager.int64_type);
1765 right = ForceConversion (ec, right, TypeManager.int64_type);
1766 type = TypeManager.int64_type;
1769 // if either operand is of type uint, the other
1770 // operand is converd to type uint
1772 left = ForceConversion (ec, left, TypeManager.uint32_type);
1773 right = ForceConversion (ec, right, TypeManager.uint32_type);
1774 type = TypeManager.uint32_type;
1776 } else if (l == TypeManager.decimal_type || r == TypeManager.decimal_type){
1777 if (l != TypeManager.decimal_type)
1778 left = ConvertImplicit (ec, left, TypeManager.decimal_type, loc);
1779 if (r != TypeManager.decimal_type)
1780 right = ConvertImplicit (ec, right, TypeManager.decimal_type, loc);
1782 type = TypeManager.decimal_type;
1784 Expression l_tmp, r_tmp;
1786 l_tmp = ForceConversion (ec, left, TypeManager.int32_type);
1790 r_tmp = ForceConversion (ec, right, TypeManager.int32_type);
1797 type = TypeManager.int32_type;
1803 static public void Error_OperatorCannotBeApplied (Location loc, string name, Type l, Type r)
1805 Report.Error (19, loc,
1806 "Operator " + name + " cannot be applied to operands of type `" +
1807 TypeManager.CSharpName (l) + "' and `" +
1808 TypeManager.CSharpName (r) + "'");
1811 void Error_OperatorCannotBeApplied ()
1813 Error_OperatorCannotBeApplied (loc, OperName (oper), left.Type, right.Type);
1816 static bool is_32_or_64 (Type t)
1818 return (t == TypeManager.int32_type || t == TypeManager.uint32_type ||
1819 t == TypeManager.int64_type || t == TypeManager.uint64_type);
1822 static bool is_unsigned (Type t)
1824 return (t == TypeManager.uint32_type || t == TypeManager.uint64_type ||
1825 t == TypeManager.short_type || t == TypeManager.byte_type);
1828 Expression CheckShiftArguments (EmitContext ec)
1832 Type r = right.Type;
1834 e = ForceConversion (ec, right, TypeManager.int32_type);
1836 Error_OperatorCannotBeApplied ();
1841 if (((e = ConvertImplicit (ec, left, TypeManager.int32_type, loc)) != null) ||
1842 ((e = ConvertImplicit (ec, left, TypeManager.uint32_type, loc)) != null) ||
1843 ((e = ConvertImplicit (ec, left, TypeManager.int64_type, loc)) != null) ||
1844 ((e = ConvertImplicit (ec, left, TypeManager.uint64_type, loc)) != null)){
1850 Error_OperatorCannotBeApplied ();
1854 Expression ResolveOperator (EmitContext ec)
1857 Type r = right.Type;
1859 bool overload_failed = false;
1862 // Step 1: Perform Operator Overload location
1864 Expression left_expr, right_expr;
1866 string op = oper_names [(int) oper];
1868 MethodGroupExpr union;
1869 left_expr = MemberLookup (ec, l, op, MemberTypes.Method, AllBindingFlags, loc);
1871 right_expr = MemberLookup (
1872 ec, r, op, MemberTypes.Method, AllBindingFlags, loc);
1873 union = Invocation.MakeUnionSet (left_expr, right_expr, loc);
1875 union = (MethodGroupExpr) left_expr;
1877 if (union != null) {
1878 Arguments = new ArrayList ();
1879 Arguments.Add (new Argument (left, Argument.AType.Expression));
1880 Arguments.Add (new Argument (right, Argument.AType.Expression));
1882 method = Invocation.OverloadResolve (ec, union, Arguments, Location.Null);
1883 if (method != null) {
1884 MethodInfo mi = (MethodInfo) method;
1886 type = mi.ReturnType;
1889 overload_failed = true;
1894 // Step 2: Default operations on CLI native types.
1898 // Step 0: String concatenation (because overloading will get this wrong)
1900 if (oper == Operator.Addition){
1902 // If any of the arguments is a string, cast to string
1905 if (l == TypeManager.string_type){
1907 if (r == TypeManager.void_type) {
1908 Error_OperatorCannotBeApplied ();
1912 if (r == TypeManager.string_type){
1913 if (left is Constant && right is Constant){
1914 StringConstant ls = (StringConstant) left;
1915 StringConstant rs = (StringConstant) right;
1917 return new StringConstant (
1918 ls.Value + rs.Value);
1922 method = TypeManager.string_concat_string_string;
1925 method = TypeManager.string_concat_object_object;
1926 right = ConvertImplicit (ec, right,
1927 TypeManager.object_type, loc);
1929 type = TypeManager.string_type;
1931 Arguments = new ArrayList ();
1932 Arguments.Add (new Argument (left, Argument.AType.Expression));
1933 Arguments.Add (new Argument (right, Argument.AType.Expression));
1937 } else if (r == TypeManager.string_type){
1940 if (l == TypeManager.void_type) {
1941 Error_OperatorCannotBeApplied ();
1945 method = TypeManager.string_concat_object_object;
1946 left = ConvertImplicit (ec, left, TypeManager.object_type, loc);
1947 Arguments = new ArrayList ();
1948 Arguments.Add (new Argument (left, Argument.AType.Expression));
1949 Arguments.Add (new Argument (right, Argument.AType.Expression));
1951 type = TypeManager.string_type;
1957 // Transform a + ( - b) into a - b
1959 if (right is Unary){
1960 Unary right_unary = (Unary) right;
1962 if (right_unary.Oper == Unary.Operator.UnaryNegation){
1963 oper = Operator.Subtraction;
1964 right = right_unary.Expr;
1970 if (oper == Operator.Equality || oper == Operator.Inequality){
1971 if (l == TypeManager.bool_type || r == TypeManager.bool_type){
1972 if (r != TypeManager.bool_type || l != TypeManager.bool_type){
1973 Error_OperatorCannotBeApplied ();
1977 type = TypeManager.bool_type;
1982 // operator != (object a, object b)
1983 // operator == (object a, object b)
1985 // For this to be used, both arguments have to be reference-types.
1986 // Read the rationale on the spec (14.9.6)
1988 // Also, if at compile time we know that the classes do not inherit
1989 // one from the other, then we catch the error there.
1991 if (!(l.IsValueType || r.IsValueType)){
1992 type = TypeManager.bool_type;
1997 if (l.IsSubclassOf (r) || r.IsSubclassOf (l))
2001 // Also, a standard conversion must exist from either one
2003 if (!(StandardConversionExists (left, r) ||
2004 StandardConversionExists (right, l))){
2005 Error_OperatorCannotBeApplied ();
2009 // We are going to have to convert to an object to compare
2011 if (l != TypeManager.object_type)
2012 left = new EmptyCast (left, TypeManager.object_type);
2013 if (r != TypeManager.object_type)
2014 right = new EmptyCast (right, TypeManager.object_type);
2017 // FIXME: CSC here catches errors cs254 and cs252
2023 // Only perform numeric promotions on:
2024 // +, -, *, /, %, &, |, ^, ==, !=, <, >, <=, >=
2026 if (oper == Operator.Addition || oper == Operator.Subtraction) {
2027 if (l.IsSubclassOf (TypeManager.delegate_type) &&
2028 r.IsSubclassOf (TypeManager.delegate_type)) {
2030 Arguments = new ArrayList ();
2031 Arguments.Add (new Argument (left, Argument.AType.Expression));
2032 Arguments.Add (new Argument (right, Argument.AType.Expression));
2034 if (oper == Operator.Addition)
2035 method = TypeManager.delegate_combine_delegate_delegate;
2037 method = TypeManager.delegate_remove_delegate_delegate;
2040 Error_OperatorCannotBeApplied ();
2044 DelegateOperation = true;
2050 // Pointer arithmetic:
2052 // T* operator + (T* x, int y);
2053 // T* operator + (T* x, uint y);
2054 // T* operator + (T* x, long y);
2055 // T* operator + (T* x, ulong y);
2057 // T* operator + (int y, T* x);
2058 // T* operator + (uint y, T *x);
2059 // T* operator + (long y, T *x);
2060 // T* operator + (ulong y, T *x);
2062 // T* operator - (T* x, int y);
2063 // T* operator - (T* x, uint y);
2064 // T* operator - (T* x, long y);
2065 // T* operator - (T* x, ulong y);
2067 // long operator - (T* x, T *y)
2070 if (r.IsPointer && oper == Operator.Subtraction){
2072 return new PointerArithmetic (
2073 false, left, right, TypeManager.int64_type,
2075 } else if (is_32_or_64 (r))
2076 return new PointerArithmetic (
2077 oper == Operator.Addition, left, right, l, loc);
2078 } else if (r.IsPointer && is_32_or_64 (l) && oper == Operator.Addition)
2079 return new PointerArithmetic (
2080 true, right, left, r, loc);
2084 // Enumeration operators
2086 bool lie = TypeManager.IsEnumType (l);
2087 bool rie = TypeManager.IsEnumType (r);
2092 // operator + (E e, U x)
2094 if (oper == Operator.Addition){
2096 Error_OperatorCannotBeApplied ();
2100 Type enum_type = lie ? l : r;
2101 Type other_type = lie ? r : l;
2102 Type underlying_type = TypeManager.EnumToUnderlying (enum_type);
2105 if (underlying_type != other_type){
2106 Error_OperatorCannotBeApplied ();
2115 temp = ConvertImplicit (ec, right, l, loc);
2119 Error_OperatorCannotBeApplied ();
2123 temp = ConvertImplicit (ec, left, r, loc);
2128 Error_OperatorCannotBeApplied ();
2133 if (oper == Operator.Equality || oper == Operator.Inequality ||
2134 oper == Operator.LessThanOrEqual || oper == Operator.LessThan ||
2135 oper == Operator.GreaterThanOrEqual || oper == Operator.GreaterThan){
2136 type = TypeManager.bool_type;
2140 if (oper == Operator.BitwiseAnd ||
2141 oper == Operator.BitwiseOr ||
2142 oper == Operator.ExclusiveOr){
2149 if (oper == Operator.LeftShift || oper == Operator.RightShift)
2150 return CheckShiftArguments (ec);
2152 if (oper == Operator.LogicalOr || oper == Operator.LogicalAnd){
2153 if (l != TypeManager.bool_type || r != TypeManager.bool_type){
2154 Error_OperatorCannotBeApplied ();
2158 type = TypeManager.bool_type;
2163 // operator & (bool x, bool y)
2164 // operator | (bool x, bool y)
2165 // operator ^ (bool x, bool y)
2167 if (l == TypeManager.bool_type && r == TypeManager.bool_type){
2168 if (oper == Operator.BitwiseAnd ||
2169 oper == Operator.BitwiseOr ||
2170 oper == Operator.ExclusiveOr){
2177 // Pointer comparison
2179 if (l.IsPointer && r.IsPointer){
2180 if (oper == Operator.Equality || oper == Operator.Inequality ||
2181 oper == Operator.LessThan || oper == Operator.LessThanOrEqual ||
2182 oper == Operator.GreaterThan || oper == Operator.GreaterThanOrEqual){
2183 type = TypeManager.bool_type;
2189 // We are dealing with numbers
2191 if (overload_failed){
2192 Error_OperatorCannotBeApplied ();
2196 if (!DoNumericPromotions (ec, l, r)){
2197 Error_OperatorCannotBeApplied ();
2201 if (left == null || right == null)
2205 // reload our cached types if required
2210 if (oper == Operator.BitwiseAnd ||
2211 oper == Operator.BitwiseOr ||
2212 oper == Operator.ExclusiveOr){
2214 if (!((l == TypeManager.int32_type) ||
2215 (l == TypeManager.uint32_type) ||
2216 (l == TypeManager.int64_type) ||
2217 (l == TypeManager.uint64_type)))
2220 Error_OperatorCannotBeApplied ();
2225 if (oper == Operator.Equality ||
2226 oper == Operator.Inequality ||
2227 oper == Operator.LessThanOrEqual ||
2228 oper == Operator.LessThan ||
2229 oper == Operator.GreaterThanOrEqual ||
2230 oper == Operator.GreaterThan){
2231 type = TypeManager.bool_type;
2237 public override Expression DoResolve (EmitContext ec)
2239 left = left.Resolve (ec);
2240 right = right.Resolve (ec);
2242 if (left == null || right == null)
2245 if (left.Type == null)
2246 throw new Exception (
2247 "Resolve returned non null, but did not set the type! (" +
2248 left + ") at Line: " + loc.Row);
2249 if (right.Type == null)
2250 throw new Exception (
2251 "Resolve returned non null, but did not set the type! (" +
2252 right + ") at Line: "+ loc.Row);
2254 eclass = ExprClass.Value;
2256 if (left is Constant && right is Constant){
2257 Expression e = ConstantFold.BinaryFold (
2258 ec, oper, (Constant) left, (Constant) right, loc);
2263 return ResolveOperator (ec);
2267 /// EmitBranchable is called from Statement.EmitBoolExpression in the
2268 /// context of a conditional bool expression. This function will return
2269 /// false if it is was possible to use EmitBranchable, or true if it was.
2271 /// The expression's code is generated, and we will generate a branch to `target'
2272 /// if the resulting expression value is equal to isTrue
2274 public bool EmitBranchable (EmitContext ec, Label target, bool onTrue)
2279 ILGenerator ig = ec.ig;
2282 // This is more complicated than it looks, but its just to avoid
2283 // duplicated tests: basically, we allow ==, !=, >, <, >= and <=
2284 // but on top of that we want for == and != to use a special path
2285 // if we are comparing against null
2287 if (oper == Operator.Equality || oper == Operator.Inequality){
2288 bool my_on_true = oper == Operator.Inequality ? onTrue : !onTrue;
2290 if (left is NullLiteral){
2293 ig.Emit (OpCodes.Brtrue, target);
2295 ig.Emit (OpCodes.Brfalse, target);
2297 } else if (right is NullLiteral){
2300 ig.Emit (OpCodes.Brtrue, target);
2302 ig.Emit (OpCodes.Brfalse, target);
2305 } else if (!(oper == Operator.LessThan ||
2306 oper == Operator.GreaterThan ||
2307 oper == Operator.LessThanOrEqual ||
2308 oper == Operator.GreaterThanOrEqual))
2316 bool isUnsigned = is_unsigned (left.Type);
2319 case Operator.Equality:
2321 ig.Emit (OpCodes.Beq, target);
2323 ig.Emit (OpCodes.Bne_Un, target);
2326 case Operator.Inequality:
2328 ig.Emit (OpCodes.Bne_Un, target);
2330 ig.Emit (OpCodes.Beq, target);
2333 case Operator.LessThan:
2336 ig.Emit (OpCodes.Blt_Un, target);
2338 ig.Emit (OpCodes.Blt, target);
2341 ig.Emit (OpCodes.Bge_Un, target);
2343 ig.Emit (OpCodes.Bge, target);
2346 case Operator.GreaterThan:
2349 ig.Emit (OpCodes.Bgt_Un, target);
2351 ig.Emit (OpCodes.Bgt, target);
2354 ig.Emit (OpCodes.Ble_Un, target);
2356 ig.Emit (OpCodes.Ble, target);
2359 case Operator.LessThanOrEqual:
2362 ig.Emit (OpCodes.Ble_Un, target);
2364 ig.Emit (OpCodes.Ble, target);
2367 ig.Emit (OpCodes.Bgt_Un, target);
2369 ig.Emit (OpCodes.Bgt, target);
2373 case Operator.GreaterThanOrEqual:
2376 ig.Emit (OpCodes.Bge_Un, target);
2378 ig.Emit (OpCodes.Bge, target);
2381 ig.Emit (OpCodes.Blt_Un, target);
2383 ig.Emit (OpCodes.Blt, target);
2393 public override void Emit (EmitContext ec)
2395 ILGenerator ig = ec.ig;
2397 Type r = right.Type;
2400 if (method != null) {
2402 // Note that operators are static anyway
2404 if (Arguments != null)
2405 Invocation.EmitArguments (ec, method, Arguments);
2407 if (method is MethodInfo)
2408 ig.Emit (OpCodes.Call, (MethodInfo) method);
2410 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
2412 if (DelegateOperation)
2413 ig.Emit (OpCodes.Castclass, type);
2419 // Handle short-circuit operators differently
2422 if (oper == Operator.LogicalAnd){
2423 Label load_zero = ig.DefineLabel ();
2424 Label end = ig.DefineLabel ();
2427 ig.Emit (OpCodes.Brfalse, load_zero);
2429 ig.Emit (OpCodes.Br, end);
2430 ig.MarkLabel (load_zero);
2431 ig.Emit (OpCodes.Ldc_I4_0);
2434 } else if (oper == Operator.LogicalOr){
2435 Label load_one = ig.DefineLabel ();
2436 Label end = ig.DefineLabel ();
2439 ig.Emit (OpCodes.Brtrue, load_one);
2441 ig.Emit (OpCodes.Br, end);
2442 ig.MarkLabel (load_one);
2443 ig.Emit (OpCodes.Ldc_I4_1);
2452 case Operator.Multiply:
2454 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
2455 opcode = OpCodes.Mul_Ovf;
2456 else if (l==TypeManager.uint32_type || l==TypeManager.uint64_type)
2457 opcode = OpCodes.Mul_Ovf_Un;
2459 opcode = OpCodes.Mul;
2461 opcode = OpCodes.Mul;
2465 case Operator.Division:
2466 if (l == TypeManager.uint32_type || l == TypeManager.uint64_type)
2467 opcode = OpCodes.Div_Un;
2469 opcode = OpCodes.Div;
2472 case Operator.Modulus:
2473 if (l == TypeManager.uint32_type || l == TypeManager.uint64_type)
2474 opcode = OpCodes.Rem_Un;
2476 opcode = OpCodes.Rem;
2479 case Operator.Addition:
2481 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
2482 opcode = OpCodes.Add_Ovf;
2483 else if (l==TypeManager.uint32_type || l==TypeManager.uint64_type)
2484 opcode = OpCodes.Add_Ovf_Un;
2486 opcode = OpCodes.Add;
2488 opcode = OpCodes.Add;
2491 case Operator.Subtraction:
2493 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
2494 opcode = OpCodes.Sub_Ovf;
2495 else if (l==TypeManager.uint32_type || l==TypeManager.uint64_type)
2496 opcode = OpCodes.Sub_Ovf_Un;
2498 opcode = OpCodes.Sub;
2500 opcode = OpCodes.Sub;
2503 case Operator.RightShift:
2504 if (l == TypeManager.uint32_type || l == TypeManager.uint64_type)
2505 opcode = OpCodes.Shr_Un;
2507 opcode = OpCodes.Shr;
2510 case Operator.LeftShift:
2511 opcode = OpCodes.Shl;
2514 case Operator.Equality:
2515 opcode = OpCodes.Ceq;
2518 case Operator.Inequality:
2519 ec.ig.Emit (OpCodes.Ceq);
2520 ec.ig.Emit (OpCodes.Ldc_I4_0);
2522 opcode = OpCodes.Ceq;
2525 case Operator.LessThan:
2526 opcode = OpCodes.Clt;
2529 case Operator.GreaterThan:
2530 opcode = OpCodes.Cgt;
2533 case Operator.LessThanOrEqual:
2534 ec.ig.Emit (OpCodes.Cgt);
2535 ec.ig.Emit (OpCodes.Ldc_I4_0);
2537 opcode = OpCodes.Ceq;
2540 case Operator.GreaterThanOrEqual:
2541 ec.ig.Emit (OpCodes.Clt);
2542 ec.ig.Emit (OpCodes.Ldc_I4_1);
2544 opcode = OpCodes.Sub;
2547 case Operator.BitwiseOr:
2548 opcode = OpCodes.Or;
2551 case Operator.BitwiseAnd:
2552 opcode = OpCodes.And;
2555 case Operator.ExclusiveOr:
2556 opcode = OpCodes.Xor;
2560 throw new Exception ("This should not happen: Operator = "
2561 + oper.ToString ());
2567 public bool IsBuiltinOperator {
2569 return method == null;
2574 public class PointerArithmetic : Expression {
2575 Expression left, right;
2579 // We assume that `l' is always a pointer
2581 public PointerArithmetic (bool is_addition, Expression l, Expression r, Type t,
2585 eclass = ExprClass.Variable;
2589 is_add = is_addition;
2592 public override Expression DoResolve (EmitContext ec)
2595 // We are born fully resolved
2600 public override void Emit (EmitContext ec)
2602 Type op_type = left.Type;
2603 ILGenerator ig = ec.ig;
2604 int size = GetTypeSize (op_type.GetElementType ());
2606 if (right.Type.IsPointer){
2608 // handle (pointer - pointer)
2612 ig.Emit (OpCodes.Sub);
2616 ig.Emit (OpCodes.Sizeof, op_type);
2618 IntLiteral.EmitInt (ig, size);
2619 ig.Emit (OpCodes.Div);
2621 ig.Emit (OpCodes.Conv_I8);
2624 // handle + and - on (pointer op int)
2627 ig.Emit (OpCodes.Conv_I);
2631 ig.Emit (OpCodes.Sizeof, op_type);
2633 IntLiteral.EmitInt (ig, size);
2634 ig.Emit (OpCodes.Mul);
2637 ig.Emit (OpCodes.Add);
2639 ig.Emit (OpCodes.Sub);
2645 /// Implements the ternary conditiona operator (?:)
2647 public class Conditional : Expression {
2648 Expression expr, trueExpr, falseExpr;
2650 public Conditional (Expression expr, Expression trueExpr, Expression falseExpr, Location l)
2653 this.trueExpr = trueExpr;
2654 this.falseExpr = falseExpr;
2658 public Expression Expr {
2664 public Expression TrueExpr {
2670 public Expression FalseExpr {
2676 public override Expression DoResolve (EmitContext ec)
2678 expr = expr.Resolve (ec);
2680 if (expr.Type != TypeManager.bool_type)
2681 expr = Expression.ConvertImplicitRequired (
2682 ec, expr, TypeManager.bool_type, loc);
2684 trueExpr = trueExpr.Resolve (ec);
2685 falseExpr = falseExpr.Resolve (ec);
2687 if (expr == null || trueExpr == null || falseExpr == null)
2690 eclass = ExprClass.Value;
2691 if (trueExpr.Type == falseExpr.Type)
2692 type = trueExpr.Type;
2695 Type true_type = trueExpr.Type;
2696 Type false_type = falseExpr.Type;
2698 if (trueExpr is NullLiteral){
2701 } else if (falseExpr is NullLiteral){
2707 // First, if an implicit conversion exists from trueExpr
2708 // to falseExpr, then the result type is of type falseExpr.Type
2710 conv = ConvertImplicit (ec, trueExpr, false_type, loc);
2713 // Check if both can convert implicitl to each other's type
2715 if (ConvertImplicit (ec, falseExpr, true_type, loc) != null){
2717 "Can not compute type of conditional expression " +
2718 "as `" + TypeManager.CSharpName (trueExpr.Type) +
2719 "' and `" + TypeManager.CSharpName (falseExpr.Type) +
2720 "' convert implicitly to each other");
2725 } else if ((conv = ConvertImplicit(ec, falseExpr, true_type,loc))!= null){
2729 Error (173, "The type of the conditional expression can " +
2730 "not be computed because there is no implicit conversion" +
2731 " from `" + TypeManager.CSharpName (trueExpr.Type) + "'" +
2732 " and `" + TypeManager.CSharpName (falseExpr.Type) + "'");
2737 if (expr is BoolConstant){
2738 BoolConstant bc = (BoolConstant) expr;
2749 public override void Emit (EmitContext ec)
2751 ILGenerator ig = ec.ig;
2752 Label false_target = ig.DefineLabel ();
2753 Label end_target = ig.DefineLabel ();
2756 ig.Emit (OpCodes.Brfalse, false_target);
2758 ig.Emit (OpCodes.Br, end_target);
2759 ig.MarkLabel (false_target);
2760 falseExpr.Emit (ec);
2761 ig.MarkLabel (end_target);
2769 public class LocalVariableReference : Expression, IAssignMethod, IMemoryLocation, IVariable {
2770 public readonly string Name;
2771 public readonly Block Block;
2772 VariableInfo variable_info;
2775 public LocalVariableReference (Block block, string name, Location l)
2780 eclass = ExprClass.Variable;
2783 // Setting `is_readonly' to false will allow you to create a writable
2784 // reference to a read-only variable. This is used by foreach and using.
2785 public LocalVariableReference (Block block, string name, Location l,
2786 VariableInfo variable_info, bool is_readonly)
2787 : this (block, name, l)
2789 this.variable_info = variable_info;
2790 this.is_readonly = is_readonly;
2793 public VariableInfo VariableInfo {
2795 if (variable_info == null) {
2796 variable_info = Block.GetVariableInfo (Name);
2797 is_readonly = variable_info.ReadOnly;
2799 return variable_info;
2803 public bool IsAssigned (EmitContext ec, Location loc)
2805 return VariableInfo.IsAssigned (ec, loc);
2808 public bool IsFieldAssigned (EmitContext ec, string name, Location loc)
2810 return VariableInfo.IsFieldAssigned (ec, name, loc);
2813 public void SetAssigned (EmitContext ec)
2815 VariableInfo.SetAssigned (ec);
2818 public void SetFieldAssigned (EmitContext ec, string name)
2820 VariableInfo.SetFieldAssigned (ec, name);
2823 public bool IsReadOnly {
2825 if (variable_info == null) {
2826 variable_info = Block.GetVariableInfo (Name);
2827 is_readonly = variable_info.ReadOnly;
2833 public override Expression DoResolve (EmitContext ec)
2835 VariableInfo vi = VariableInfo;
2837 if (Block.IsConstant (Name)) {
2838 Expression e = Block.GetConstantExpression (Name);
2844 if (ec.DoFlowAnalysis && !IsAssigned (ec, loc))
2847 type = vi.VariableType;
2851 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
2853 VariableInfo vi = VariableInfo;
2855 if (ec.DoFlowAnalysis)
2856 ec.SetVariableAssigned (vi);
2858 Expression e = DoResolve (ec);
2864 Error (1604, "cannot assign to `" + Name + "' because it is readonly");
2871 public override void Emit (EmitContext ec)
2873 VariableInfo vi = VariableInfo;
2874 ILGenerator ig = ec.ig;
2876 ig.Emit (OpCodes.Ldloc, vi.LocalBuilder);
2880 public void EmitAssign (EmitContext ec, Expression source)
2882 ILGenerator ig = ec.ig;
2883 VariableInfo vi = VariableInfo;
2889 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
2892 public void AddressOf (EmitContext ec, AddressOp mode)
2894 VariableInfo vi = VariableInfo;
2896 ec.ig.Emit (OpCodes.Ldloca, vi.LocalBuilder);
2901 /// This represents a reference to a parameter in the intermediate
2904 public class ParameterReference : Expression, IAssignMethod, IMemoryLocation, IVariable {
2908 public Parameter.Modifier mod;
2909 public bool is_ref, is_out;
2911 public ParameterReference (Parameters pars, int idx, string name, Location loc)
2917 eclass = ExprClass.Variable;
2920 public bool IsAssigned (EmitContext ec, Location loc)
2922 if (!is_out || !ec.DoFlowAnalysis)
2925 if (!ec.CurrentBranching.IsParameterAssigned (idx)) {
2926 Report.Error (165, loc,
2927 "Use of unassigned local variable `" + name + "'");
2934 public bool IsFieldAssigned (EmitContext ec, string field_name, Location loc)
2936 if (!is_out || !ec.DoFlowAnalysis)
2939 if (ec.CurrentBranching.IsParameterAssigned (idx))
2942 if (!ec.CurrentBranching.IsParameterAssigned (idx, field_name)) {
2943 Report.Error (170, loc,
2944 "Use of possibly unassigned field `" + field_name + "'");
2951 public void SetAssigned (EmitContext ec)
2953 if (is_out && ec.DoFlowAnalysis)
2954 ec.CurrentBranching.SetParameterAssigned (idx);
2957 public void SetFieldAssigned (EmitContext ec, string field_name)
2959 if (is_out && ec.DoFlowAnalysis)
2960 ec.CurrentBranching.SetParameterAssigned (idx, field_name);
2964 // Notice that for ref/out parameters, the type exposed is not the
2965 // same type exposed externally.
2968 // externally we expose "int&"
2969 // here we expose "int".
2971 // We record this in "is_ref". This means that the type system can treat
2972 // the type as it is expected, but when we generate the code, we generate
2973 // the alternate kind of code.
2975 public override Expression DoResolve (EmitContext ec)
2977 type = pars.GetParameterInfo (ec.DeclSpace, idx, out mod);
2978 is_ref = (mod & Parameter.Modifier.ISBYREF) != 0;
2979 is_out = (mod & Parameter.Modifier.OUT) != 0;
2980 eclass = ExprClass.Variable;
2982 if (is_out && ec.DoFlowAnalysis && !IsAssigned (ec, loc))
2988 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
2990 type = pars.GetParameterInfo (ec.DeclSpace, idx, out mod);
2991 is_ref = (mod & Parameter.Modifier.ISBYREF) != 0;
2992 is_out = (mod & Parameter.Modifier.OUT) != 0;
2993 eclass = ExprClass.Variable;
2995 if (is_out && ec.DoFlowAnalysis)
2996 ec.SetParameterAssigned (idx);
3001 static void EmitLdArg (ILGenerator ig, int x)
3005 case 0: ig.Emit (OpCodes.Ldarg_0); break;
3006 case 1: ig.Emit (OpCodes.Ldarg_1); break;
3007 case 2: ig.Emit (OpCodes.Ldarg_2); break;
3008 case 3: ig.Emit (OpCodes.Ldarg_3); break;
3009 default: ig.Emit (OpCodes.Ldarg_S, (byte) x); break;
3012 ig.Emit (OpCodes.Ldarg, x);
3016 // This method is used by parameters that are references, that are
3017 // being passed as references: we only want to pass the pointer (that
3018 // is already stored in the parameter, not the address of the pointer,
3019 // and not the value of the variable).
3021 public void EmitLoad (EmitContext ec)
3023 ILGenerator ig = ec.ig;
3029 EmitLdArg (ig, arg_idx);
3032 public override void Emit (EmitContext ec)
3034 ILGenerator ig = ec.ig;
3040 EmitLdArg (ig, arg_idx);
3046 // If we are a reference, we loaded on the stack a pointer
3047 // Now lets load the real value
3049 LoadFromPtr (ig, type);
3052 public void EmitAssign (EmitContext ec, Expression source)
3054 ILGenerator ig = ec.ig;
3061 EmitLdArg (ig, arg_idx);
3066 StoreFromPtr (ig, type);
3069 ig.Emit (OpCodes.Starg_S, (byte) arg_idx);
3071 ig.Emit (OpCodes.Starg, arg_idx);
3075 public void AddressOf (EmitContext ec, AddressOp mode)
3084 ec.ig.Emit (OpCodes.Ldarg_S, (byte) arg_idx);
3086 ec.ig.Emit (OpCodes.Ldarg, arg_idx);
3089 ec.ig.Emit (OpCodes.Ldarga_S, (byte) arg_idx);
3091 ec.ig.Emit (OpCodes.Ldarga, arg_idx);
3097 /// Used for arguments to New(), Invocation()
3099 public class Argument {
3100 public enum AType : byte {
3106 public readonly AType ArgType;
3107 public Expression Expr;
3109 public Argument (Expression expr, AType type)
3112 this.ArgType = type;
3117 if (ArgType == AType.Ref || ArgType == AType.Out)
3118 return TypeManager.LookupType (Expr.Type.ToString () + "&");
3124 public Parameter.Modifier GetParameterModifier ()
3128 return Parameter.Modifier.OUT | Parameter.Modifier.ISBYREF;
3131 return Parameter.Modifier.REF | Parameter.Modifier.ISBYREF;
3134 return Parameter.Modifier.NONE;
3138 public static string FullDesc (Argument a)
3140 return (a.ArgType == AType.Ref ? "ref " :
3141 (a.ArgType == AType.Out ? "out " : "")) +
3142 TypeManager.CSharpName (a.Expr.Type);
3145 public bool ResolveMethodGroup (EmitContext ec, Location loc)
3147 // FIXME: csc doesn't report any error if you try to use `ref' or
3148 // `out' in a delegate creation expression.
3149 Expr = Expr.Resolve (ec, ResolveFlags.VariableOrValue | ResolveFlags.MethodGroup);
3156 public bool Resolve (EmitContext ec, Location loc)
3158 if (ArgType == AType.Ref) {
3159 Expr = Expr.Resolve (ec);
3163 Expr = Expr.ResolveLValue (ec, Expr);
3164 } else if (ArgType == AType.Out)
3165 Expr = Expr.ResolveLValue (ec, new EmptyExpression ());
3167 Expr = Expr.Resolve (ec);
3172 if (ArgType == AType.Expression)
3175 if (Expr.eclass != ExprClass.Variable){
3177 // We just probe to match the CSC output
3179 if (Expr.eclass == ExprClass.PropertyAccess ||
3180 Expr.eclass == ExprClass.IndexerAccess){
3183 "A property or indexer can not be passed as an out or ref " +
3188 "An lvalue is required as an argument to out or ref");
3196 public void Emit (EmitContext ec)
3199 // Ref and Out parameters need to have their addresses taken.
3201 // ParameterReferences might already be references, so we want
3202 // to pass just the value
3204 if (ArgType == AType.Ref || ArgType == AType.Out){
3205 AddressOp mode = AddressOp.Store;
3207 if (ArgType == AType.Ref)
3208 mode |= AddressOp.Load;
3210 if (Expr is ParameterReference){
3211 ParameterReference pr = (ParameterReference) Expr;
3217 pr.AddressOf (ec, mode);
3220 ((IMemoryLocation)Expr).AddressOf (ec, mode);
3227 /// Invocation of methods or delegates.
3229 public class Invocation : ExpressionStatement {
3230 public readonly ArrayList Arguments;
3233 MethodBase method = null;
3236 static Hashtable method_parameter_cache;
3238 static Invocation ()
3240 method_parameter_cache = new PtrHashtable ();
3244 // arguments is an ArrayList, but we do not want to typecast,
3245 // as it might be null.
3247 // FIXME: only allow expr to be a method invocation or a
3248 // delegate invocation (7.5.5)
3250 public Invocation (Expression expr, ArrayList arguments, Location l)
3253 Arguments = arguments;
3257 public Expression Expr {
3264 /// Returns the Parameters (a ParameterData interface) for the
3267 public static ParameterData GetParameterData (MethodBase mb)
3269 object pd = method_parameter_cache [mb];
3273 return (ParameterData) pd;
3276 ip = TypeManager.LookupParametersByBuilder (mb);
3278 method_parameter_cache [mb] = ip;
3280 return (ParameterData) ip;
3282 ParameterInfo [] pi = mb.GetParameters ();
3283 ReflectionParameters rp = new ReflectionParameters (pi);
3284 method_parameter_cache [mb] = rp;
3286 return (ParameterData) rp;
3291 /// Determines "better conversion" as specified in 7.4.2.3
3292 /// Returns : 1 if a->p is better
3293 /// 0 if a->q or neither is better
3295 static int BetterConversion (EmitContext ec, Argument a, Type p, Type q, Location loc)
3297 Type argument_type = a.Type;
3298 Expression argument_expr = a.Expr;
3300 if (argument_type == null)
3301 throw new Exception ("Expression of type " + a.Expr + " does not resolve its type");
3306 if (argument_type == p)
3309 if (argument_type == q)
3313 // Now probe whether an implicit constant expression conversion
3316 // An implicit constant expression conversion permits the following
3319 // * A constant-expression of type `int' can be converted to type
3320 // sbyte, byute, short, ushort, uint, ulong provided the value of
3321 // of the expression is withing the range of the destination type.
3323 // * A constant-expression of type long can be converted to type
3324 // ulong, provided the value of the constant expression is not negative
3326 // FIXME: Note that this assumes that constant folding has
3327 // taken place. We dont do constant folding yet.
3330 if (argument_expr is IntConstant){
3331 IntConstant ei = (IntConstant) argument_expr;
3332 int value = ei.Value;
3334 if (p == TypeManager.sbyte_type){
3335 if (value >= SByte.MinValue && value <= SByte.MaxValue)
3337 } else if (p == TypeManager.byte_type){
3338 if (Byte.MinValue >= 0 && value <= Byte.MaxValue)
3340 } else if (p == TypeManager.short_type){
3341 if (value >= Int16.MinValue && value <= Int16.MaxValue)
3343 } else if (p == TypeManager.ushort_type){
3344 if (value >= UInt16.MinValue && value <= UInt16.MaxValue)
3346 } else if (p == TypeManager.uint32_type){
3348 // we can optimize this case: a positive int32
3349 // always fits on a uint32
3353 } else if (p == TypeManager.uint64_type){
3355 // we can optimize this case: a positive int32
3356 // always fits on a uint64
3361 } else if (argument_type == TypeManager.int64_type && argument_expr is LongConstant){
3362 LongConstant lc = (LongConstant) argument_expr;
3364 if (p == TypeManager.uint64_type){
3371 Expression tmp = ConvertImplicit (ec, argument_expr, p, loc);
3379 Expression p_tmp = new EmptyExpression (p);
3380 Expression q_tmp = new EmptyExpression (q);
3382 if (StandardConversionExists (p_tmp, q) == true &&
3383 StandardConversionExists (q_tmp, p) == false)
3386 if (p == TypeManager.sbyte_type)
3387 if (q == TypeManager.byte_type || q == TypeManager.ushort_type ||
3388 q == TypeManager.uint32_type || q == TypeManager.uint64_type)
3391 if (p == TypeManager.short_type)
3392 if (q == TypeManager.ushort_type || q == TypeManager.uint32_type ||
3393 q == TypeManager.uint64_type)
3396 if (p == TypeManager.int32_type)
3397 if (q == TypeManager.uint32_type || q == TypeManager.uint64_type)
3400 if (p == TypeManager.int64_type)
3401 if (q == TypeManager.uint64_type)
3408 /// Determines "Better function"
3411 /// and returns an integer indicating :
3412 /// 0 if candidate ain't better
3413 /// 1 if candidate is better than the current best match
3415 static int BetterFunction (EmitContext ec, ArrayList args,
3416 MethodBase candidate, MethodBase best,
3417 bool expanded_form, Location loc)
3419 ParameterData candidate_pd = GetParameterData (candidate);
3420 ParameterData best_pd;
3426 argument_count = args.Count;
3428 int cand_count = candidate_pd.Count;
3430 if (cand_count == 0 && argument_count == 0)
3433 if (candidate_pd.ParameterModifier (cand_count - 1) != Parameter.Modifier.PARAMS)
3434 if (cand_count != argument_count)
3440 if (argument_count == 0 && cand_count == 1 &&
3441 candidate_pd.ParameterModifier (cand_count - 1) == Parameter.Modifier.PARAMS)
3444 for (int j = argument_count; j > 0;) {
3447 Argument a = (Argument) args [j];
3448 Type t = candidate_pd.ParameterType (j);
3450 if (candidate_pd.ParameterModifier (j) == Parameter.Modifier.PARAMS)
3452 t = t.GetElementType ();
3454 x = BetterConversion (ec, a, t, null, loc);
3466 best_pd = GetParameterData (best);
3468 int rating1 = 0, rating2 = 0;
3470 for (int j = 0; j < argument_count; ++j) {
3473 Argument a = (Argument) args [j];
3475 Type ct = candidate_pd.ParameterType (j);
3476 Type bt = best_pd.ParameterType (j);
3478 if (candidate_pd.ParameterModifier (j) == Parameter.Modifier.PARAMS)
3480 ct = ct.GetElementType ();
3482 if (best_pd.ParameterModifier (j) == Parameter.Modifier.PARAMS)
3484 bt = bt.GetElementType ();
3486 x = BetterConversion (ec, a, ct, bt, loc);
3487 y = BetterConversion (ec, a, bt, ct, loc);
3496 if (rating1 > rating2)
3502 public static string FullMethodDesc (MethodBase mb)
3504 string ret_type = "";
3506 if (mb is MethodInfo)
3507 ret_type = TypeManager.CSharpName (((MethodInfo) mb).ReturnType);
3509 StringBuilder sb = new StringBuilder (ret_type + " " + mb.Name);
3510 ParameterData pd = GetParameterData (mb);
3512 int count = pd.Count;
3515 for (int i = count; i > 0; ) {
3518 sb.Append (pd.ParameterDesc (count - i - 1));
3524 return sb.ToString ();
3527 public static MethodGroupExpr MakeUnionSet (Expression mg1, Expression mg2, Location loc)
3529 MemberInfo [] miset;
3530 MethodGroupExpr union;
3535 return (MethodGroupExpr) mg2;
3538 return (MethodGroupExpr) mg1;
3541 MethodGroupExpr left_set = null, right_set = null;
3542 int length1 = 0, length2 = 0;
3544 left_set = (MethodGroupExpr) mg1;
3545 length1 = left_set.Methods.Length;
3547 right_set = (MethodGroupExpr) mg2;
3548 length2 = right_set.Methods.Length;
3550 ArrayList common = new ArrayList ();
3552 foreach (MethodBase l in left_set.Methods){
3553 foreach (MethodBase r in right_set.Methods){
3561 miset = new MemberInfo [length1 + length2 - common.Count];
3562 left_set.Methods.CopyTo (miset, 0);
3566 foreach (MemberInfo mi in right_set.Methods){
3567 if (!common.Contains (mi))
3571 union = new MethodGroupExpr (miset, loc);
3577 /// Determines is the candidate method, if a params method, is applicable
3578 /// in its expanded form to the given set of arguments
3580 static bool IsParamsMethodApplicable (EmitContext ec, ArrayList arguments, MethodBase candidate)
3584 if (arguments == null)
3587 arg_count = arguments.Count;
3589 ParameterData pd = GetParameterData (candidate);
3591 int pd_count = pd.Count;
3596 if (pd.ParameterModifier (pd_count - 1) != Parameter.Modifier.PARAMS)
3599 if (pd_count - 1 > arg_count)
3602 if (pd_count == 1 && arg_count == 0)
3606 // If we have come this far, the case which remains is when the number of parameters
3607 // is less than or equal to the argument count.
3609 for (int i = 0; i < pd_count - 1; ++i) {
3611 Argument a = (Argument) arguments [i];
3613 Parameter.Modifier a_mod = a.GetParameterModifier () &
3614 ~(Parameter.Modifier.OUT | Parameter.Modifier.REF);
3615 Parameter.Modifier p_mod = pd.ParameterModifier (i) &
3616 ~(Parameter.Modifier.OUT | Parameter.Modifier.REF);
3618 if (a_mod == p_mod) {
3620 if (a_mod == Parameter.Modifier.NONE)
3621 if (!ImplicitConversionExists (ec, a.Expr, pd.ParameterType (i)))
3624 if ((a_mod & Parameter.Modifier.ISBYREF) != 0) {
3625 Type pt = pd.ParameterType (i);
3628 pt = TypeManager.LookupType (pt.FullName + "&");
3638 Type element_type = pd.ParameterType (pd_count - 1).GetElementType ();
3640 for (int i = pd_count - 1; i < arg_count; i++) {
3641 Argument a = (Argument) arguments [i];
3643 if (!StandardConversionExists (a.Expr, element_type))
3651 /// Determines if the candidate method is applicable (section 14.4.2.1)
3652 /// to the given set of arguments
3654 static bool IsApplicable (EmitContext ec, ArrayList arguments, MethodBase candidate)
3658 if (arguments == null)
3661 arg_count = arguments.Count;
3663 ParameterData pd = GetParameterData (candidate);
3665 int pd_count = pd.Count;
3667 if (arg_count != pd.Count)
3670 for (int i = arg_count; i > 0; ) {
3673 Argument a = (Argument) arguments [i];
3675 Parameter.Modifier a_mod = a.GetParameterModifier () &
3676 ~(Parameter.Modifier.OUT | Parameter.Modifier.REF);
3677 Parameter.Modifier p_mod = pd.ParameterModifier (i) &
3678 ~(Parameter.Modifier.OUT | Parameter.Modifier.REF);
3680 if (a_mod == p_mod ||
3681 (a_mod == Parameter.Modifier.NONE && p_mod == Parameter.Modifier.PARAMS)) {
3682 if (a_mod == Parameter.Modifier.NONE)
3683 if (!ImplicitConversionExists (ec, a.Expr, pd.ParameterType (i)))
3686 if ((a_mod & Parameter.Modifier.ISBYREF) != 0) {
3687 Type pt = pd.ParameterType (i);
3690 pt = TypeManager.LookupType (pt.FullName + "&");
3705 /// Find the Applicable Function Members (7.4.2.1)
3707 /// me: Method Group expression with the members to select.
3708 /// it might contain constructors or methods (or anything
3709 /// that maps to a method).
3711 /// Arguments: ArrayList containing resolved Argument objects.
3713 /// loc: The location if we want an error to be reported, or a Null
3714 /// location for "probing" purposes.
3716 /// Returns: The MethodBase (either a ConstructorInfo or a MethodInfo)
3717 /// that is the best match of me on Arguments.
3720 public static MethodBase OverloadResolve (EmitContext ec, MethodGroupExpr me,
3721 ArrayList Arguments, Location loc)
3723 ArrayList afm = new ArrayList ();
3724 MethodBase method = null;
3725 Type current_type = null;
3727 ArrayList candidates = new ArrayList ();
3730 foreach (MethodBase candidate in me.Methods){
3733 // If we're going one level higher in the class hierarchy, abort if
3734 // we already found an applicable method.
3735 if (candidate.DeclaringType != current_type) {
3736 current_type = candidate.DeclaringType;
3741 // Check if candidate is applicable (section 14.4.2.1)
3742 if (!IsApplicable (ec, Arguments, candidate))
3745 candidates.Add (candidate);
3746 x = BetterFunction (ec, Arguments, candidate, method, false, loc);
3754 if (Arguments == null)
3757 argument_count = Arguments.Count;
3760 // Now we see if we can find params functions, applicable in their expanded form
3761 // since if they were applicable in their normal form, they would have been selected
3764 bool chose_params_expanded = false;
3766 if (method == null) {
3767 candidates = new ArrayList ();
3768 foreach (MethodBase candidate in me.Methods){
3769 if (!IsParamsMethodApplicable (ec, Arguments, candidate))
3772 candidates.Add (candidate);
3774 int x = BetterFunction (ec, Arguments, candidate, method, true, loc);
3779 chose_params_expanded = true;
3787 // Now check that there are no ambiguities i.e the selected method
3788 // should be better than all the others
3791 foreach (MethodBase candidate in candidates){
3792 if (candidate == method)
3796 // If a normal method is applicable in the sense that it has the same
3797 // number of arguments, then the expanded params method is never applicable
3798 // so we debar the params method.
3800 if (IsParamsMethodApplicable (ec, Arguments, candidate) &&
3801 IsApplicable (ec, Arguments, method))
3804 int x = BetterFunction (ec, Arguments, method, candidate,
3805 chose_params_expanded, loc);
3810 "Ambiguous call when selecting function due to implicit casts");
3816 // And now check if the arguments are all compatible, perform conversions
3817 // if necessary etc. and return if everything is all right
3820 if (VerifyArgumentsCompat (ec, Arguments, argument_count, method,
3821 chose_params_expanded, null, loc))
3827 public static bool VerifyArgumentsCompat (EmitContext ec, ArrayList Arguments,
3830 bool chose_params_expanded,
3834 ParameterData pd = GetParameterData (method);
3835 int pd_count = pd.Count;
3837 for (int j = 0; j < argument_count; j++) {
3838 Argument a = (Argument) Arguments [j];
3839 Expression a_expr = a.Expr;
3840 Type parameter_type = pd.ParameterType (j);
3842 if (pd.ParameterModifier (j) == Parameter.Modifier.PARAMS &&
3843 chose_params_expanded)
3844 parameter_type = parameter_type.GetElementType ();
3846 if (a.Type != parameter_type){
3849 conv = ConvertImplicit (ec, a_expr, parameter_type, loc);
3852 if (!Location.IsNull (loc)) {
3853 if (delegate_type == null)
3854 Report.Error (1502, loc,
3855 "The best overloaded match for method '" +
3856 FullMethodDesc (method) +
3857 "' has some invalid arguments");
3859 Report.Error (1594, loc,
3860 "Delegate '" + delegate_type.ToString () +
3861 "' has some invalid arguments.");
3862 Report.Error (1503, loc,
3863 "Argument " + (j+1) +
3864 ": Cannot convert from '" + Argument.FullDesc (a)
3865 + "' to '" + pd.ParameterDesc (j) + "'");
3872 // Update the argument with the implicit conversion
3878 Parameter.Modifier a_mod = a.GetParameterModifier () &
3879 ~(Parameter.Modifier.OUT | Parameter.Modifier.REF);
3880 Parameter.Modifier p_mod = pd.ParameterModifier (j) &
3881 ~(Parameter.Modifier.OUT | Parameter.Modifier.REF);
3884 if (a_mod != p_mod &&
3885 pd.ParameterModifier (pd_count - 1) != Parameter.Modifier.PARAMS) {
3886 if (!Location.IsNull (loc)) {
3887 Console.WriteLine ("A:P: " + a.GetParameterModifier ());
3888 Console.WriteLine ("PP:: " + pd.ParameterModifier (j));
3889 Console.WriteLine ("PT: " + parameter_type.IsByRef);
3890 Report.Error (1502, loc,
3891 "The best overloaded match for method '" + FullMethodDesc (method)+
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) + "'");
3906 public override Expression DoResolve (EmitContext ec)
3909 // First, resolve the expression that is used to
3910 // trigger the invocation
3912 if (expr is BaseAccess)
3915 expr = expr.Resolve (ec, ResolveFlags.VariableOrValue | ResolveFlags.MethodGroup);
3919 if (!(expr is MethodGroupExpr)) {
3920 Type expr_type = expr.Type;
3922 if (expr_type != null){
3923 bool IsDelegate = TypeManager.IsDelegateType (expr_type);
3925 return (new DelegateInvocation (
3926 this.expr, Arguments, loc)).Resolve (ec);
3930 if (!(expr is MethodGroupExpr)){
3931 expr.Error118 (ResolveFlags.MethodGroup);
3936 // Next, evaluate all the expressions in the argument list
3938 if (Arguments != null){
3939 foreach (Argument a in Arguments){
3940 if (!a.Resolve (ec, loc))
3945 method = OverloadResolve (ec, (MethodGroupExpr) this.expr, Arguments, loc);
3947 if (method == null){
3949 "Could not find any applicable function for this argument list");
3953 if (method is MethodInfo)
3954 type = TypeManager.TypeToCoreType (((MethodInfo)method).ReturnType);
3956 if (type.IsPointer){
3963 eclass = ExprClass.Value;
3968 // Emits the list of arguments as an array
3970 static void EmitParams (EmitContext ec, int idx, ArrayList arguments)
3972 ILGenerator ig = ec.ig;
3973 int count = arguments.Count - idx;
3974 Argument a = (Argument) arguments [idx];
3975 Type t = a.Expr.Type;
3976 string array_type = t.FullName + "[]";
3979 array = ig.DeclareLocal (TypeManager.LookupType (array_type));
3980 IntConstant.EmitInt (ig, count);
3981 ig.Emit (OpCodes.Newarr, TypeManager.TypeToCoreType (t));
3982 ig.Emit (OpCodes.Stloc, array);
3984 int top = arguments.Count;
3985 for (int j = idx; j < top; j++){
3986 a = (Argument) arguments [j];
3988 ig.Emit (OpCodes.Ldloc, array);
3989 IntConstant.EmitInt (ig, j - idx);
3992 ArrayAccess.EmitStoreOpcode (ig, t);
3994 ig.Emit (OpCodes.Ldloc, array);
3998 /// Emits a list of resolved Arguments that are in the arguments
4001 /// The MethodBase argument might be null if the
4002 /// emission of the arguments is known not to contain
4003 /// a `params' field (for example in constructors or other routines
4004 /// that keep their arguments in this structure)
4006 public static void EmitArguments (EmitContext ec, MethodBase mb, ArrayList arguments)
4010 pd = GetParameterData (mb);
4015 // If we are calling a params method with no arguments, special case it
4017 if (arguments == null){
4018 if (pd != null && pd.Count > 0 &&
4019 pd.ParameterModifier (0) == Parameter.Modifier.PARAMS){
4020 ILGenerator ig = ec.ig;
4022 IntConstant.EmitInt (ig, 0);
4023 ig.Emit (OpCodes.Newarr, pd.ParameterType (0).GetElementType ());
4029 int top = arguments.Count;
4031 for (int i = 0; i < top; i++){
4032 Argument a = (Argument) arguments [i];
4035 if (pd.ParameterModifier (i) == Parameter.Modifier.PARAMS){
4037 // Special case if we are passing the same data as the
4038 // params argument, do not put it in an array.
4040 if (pd.ParameterType (i) == a.Type)
4043 EmitParams (ec, i, arguments);
4051 if (pd != null && pd.Count > top &&
4052 pd.ParameterModifier (top) == Parameter.Modifier.PARAMS){
4053 ILGenerator ig = ec.ig;
4055 IntConstant.EmitInt (ig, 0);
4056 ig.Emit (OpCodes.Newarr, pd.ParameterType (top).GetElementType ());
4061 /// is_base tells whether we want to force the use of the `call'
4062 /// opcode instead of using callvirt. Call is required to call
4063 /// a specific method, while callvirt will always use the most
4064 /// recent method in the vtable.
4066 /// is_static tells whether this is an invocation on a static method
4068 /// instance_expr is an expression that represents the instance
4069 /// it must be non-null if is_static is false.
4071 /// method is the method to invoke.
4073 /// Arguments is the list of arguments to pass to the method or constructor.
4075 public static void EmitCall (EmitContext ec, bool is_base,
4076 bool is_static, Expression instance_expr,
4077 MethodBase method, ArrayList Arguments, Location loc)
4079 ILGenerator ig = ec.ig;
4080 bool struct_call = false;
4082 Type decl_type = method.DeclaringType;
4084 if (!RootContext.StdLib) {
4085 // Replace any calls to the system's System.Array type with calls to
4086 // the newly created one.
4087 if (method == TypeManager.system_int_array_get_length)
4088 method = TypeManager.int_array_get_length;
4089 else if (method == TypeManager.system_int_array_get_rank)
4090 method = TypeManager.int_array_get_rank;
4091 else if (method == TypeManager.system_object_array_clone)
4092 method = TypeManager.object_array_clone;
4093 else if (method == TypeManager.system_int_array_get_length_int)
4094 method = TypeManager.int_array_get_length_int;
4095 else if (method == TypeManager.system_int_array_get_lower_bound_int)
4096 method = TypeManager.int_array_get_lower_bound_int;
4097 else if (method == TypeManager.system_int_array_get_upper_bound_int)
4098 method = TypeManager.int_array_get_upper_bound_int;
4099 else if (method == TypeManager.system_void_array_copyto_array_int)
4100 method = TypeManager.void_array_copyto_array_int;
4104 // This checks the `ConditionalAttribute' on the method, and the
4105 // ObsoleteAttribute
4107 TypeManager.MethodFlags flags = TypeManager.GetMethodFlags (method, loc);
4108 if ((flags & TypeManager.MethodFlags.IsObsoleteError) != 0)
4110 if ((flags & TypeManager.MethodFlags.ShouldIgnore) != 0)
4114 if (decl_type.IsValueType)
4117 // If this is ourselves, push "this"
4119 if (instance_expr == null){
4120 ig.Emit (OpCodes.Ldarg_0);
4123 // Push the instance expression
4125 if (instance_expr.Type.IsValueType){
4127 // Special case: calls to a function declared in a
4128 // reference-type with a value-type argument need
4129 // to have their value boxed.
4132 if (decl_type.IsValueType){
4134 // If the expression implements IMemoryLocation, then
4135 // we can optimize and use AddressOf on the
4138 // If not we have to use some temporary storage for
4140 if (instance_expr is IMemoryLocation){
4141 ((IMemoryLocation)instance_expr).
4142 AddressOf (ec, AddressOp.LoadStore);
4145 Type t = instance_expr.Type;
4147 instance_expr.Emit (ec);
4148 LocalBuilder temp = ig.DeclareLocal (t);
4149 ig.Emit (OpCodes.Stloc, temp);
4150 ig.Emit (OpCodes.Ldloca, temp);
4153 instance_expr.Emit (ec);
4154 ig.Emit (OpCodes.Box, instance_expr.Type);
4157 instance_expr.Emit (ec);
4161 EmitArguments (ec, method, Arguments);
4163 if (is_static || struct_call || is_base){
4164 if (method is MethodInfo) {
4165 ig.Emit (OpCodes.Call, (MethodInfo) method);
4167 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
4169 if (method is MethodInfo)
4170 ig.Emit (OpCodes.Callvirt, (MethodInfo) method);
4172 ig.Emit (OpCodes.Callvirt, (ConstructorInfo) method);
4176 public override void Emit (EmitContext ec)
4178 MethodGroupExpr mg = (MethodGroupExpr) this.expr;
4181 ec, is_base, method.IsStatic, mg.InstanceExpression, method, Arguments, loc);
4184 public override void EmitStatement (EmitContext ec)
4189 // Pop the return value if there is one
4191 if (method is MethodInfo){
4192 Type ret = ((MethodInfo)method).ReturnType;
4193 if (TypeManager.TypeToCoreType (ret) != TypeManager.void_type)
4194 ec.ig.Emit (OpCodes.Pop);
4200 // This class is used to "disable" the code generation for the
4201 // temporary variable when initializing value types.
4203 class EmptyAddressOf : EmptyExpression, IMemoryLocation {
4204 public void AddressOf (EmitContext ec, AddressOp Mode)
4211 /// Implements the new expression
4213 public class New : ExpressionStatement {
4214 public readonly ArrayList Arguments;
4215 public readonly Expression RequestedType;
4217 MethodBase method = null;
4220 // If set, the new expression is for a value_target, and
4221 // we will not leave anything on the stack.
4223 Expression value_target;
4224 bool value_target_set = false;
4226 public New (Expression requested_type, ArrayList arguments, Location l)
4228 RequestedType = requested_type;
4229 Arguments = arguments;
4233 public Expression ValueTypeVariable {
4235 return value_target;
4239 value_target = value;
4240 value_target_set = true;
4245 // This function is used to disable the following code sequence for
4246 // value type initialization:
4248 // AddressOf (temporary)
4252 // Instead the provide will have provided us with the address on the
4253 // stack to store the results.
4255 static Expression MyEmptyExpression;
4257 public void DisableTemporaryValueType ()
4259 if (MyEmptyExpression == null)
4260 MyEmptyExpression = new EmptyAddressOf ();
4263 // To enable this, look into:
4264 // test-34 and test-89 and self bootstrapping.
4266 // For instance, we can avoid a copy by using `newobj'
4267 // instead of Call + Push-temp on value types.
4268 // value_target = MyEmptyExpression;
4271 public override Expression DoResolve (EmitContext ec)
4273 type = ec.DeclSpace.ResolveType (RequestedType, false, loc);
4278 bool IsDelegate = TypeManager.IsDelegateType (type);
4281 return (new NewDelegate (type, Arguments, loc)).Resolve (ec);
4283 if (type.IsInterface || type.IsAbstract){
4285 144, "It is not possible to create instances of interfaces " +
4286 "or abstract classes");
4290 bool is_struct = false;
4291 is_struct = type.IsValueType;
4292 eclass = ExprClass.Value;
4295 // SRE returns a match for .ctor () on structs (the object constructor),
4296 // so we have to manually ignore it.
4298 if (is_struct && Arguments == null)
4302 ml = MemberLookupFinal (ec, type, ".ctor",
4303 MemberTypes.Constructor,
4304 AllBindingFlags | BindingFlags.DeclaredOnly, loc);
4309 if (! (ml is MethodGroupExpr)){
4311 ml.Error118 ("method group");
4317 if (Arguments != null){
4318 foreach (Argument a in Arguments){
4319 if (!a.Resolve (ec, loc))
4324 method = Invocation.OverloadResolve (ec, (MethodGroupExpr) ml,
4329 if (method == null) {
4330 if (!is_struct || Arguments.Count > 0) {
4332 "New invocation: Can not find a constructor for " +
4333 "this argument list");
4341 // This DoEmit can be invoked in two contexts:
4342 // * As a mechanism that will leave a value on the stack (new object)
4343 // * As one that wont (init struct)
4345 // You can control whether a value is required on the stack by passing
4346 // need_value_on_stack. The code *might* leave a value on the stack
4347 // so it must be popped manually
4349 // If we are dealing with a ValueType, we have a few
4350 // situations to deal with:
4352 // * The target is a ValueType, and we have been provided
4353 // the instance (this is easy, we are being assigned).
4355 // * The target of New is being passed as an argument,
4356 // to a boxing operation or a function that takes a
4359 // In this case, we need to create a temporary variable
4360 // that is the argument of New.
4362 // Returns whether a value is left on the stack
4364 bool DoEmit (EmitContext ec, bool need_value_on_stack)
4366 bool is_value_type = type.IsValueType;
4367 ILGenerator ig = ec.ig;
4372 // Allow DoEmit() to be called multiple times.
4373 // We need to create a new LocalTemporary each time since
4374 // you can't share LocalBuilders among ILGeneators.
4375 if (!value_target_set)
4376 value_target = new LocalTemporary (ec, type);
4378 ml = (IMemoryLocation) value_target;
4379 ml.AddressOf (ec, AddressOp.Store);
4383 Invocation.EmitArguments (ec, method, Arguments);
4387 ig.Emit (OpCodes.Initobj, type);
4389 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
4390 if (need_value_on_stack){
4391 value_target.Emit (ec);
4396 ig.Emit (OpCodes.Newobj, (ConstructorInfo) method);
4401 public override void Emit (EmitContext ec)
4406 public override void EmitStatement (EmitContext ec)
4408 if (DoEmit (ec, false))
4409 ec.ig.Emit (OpCodes.Pop);
4414 /// 14.5.10.2: Represents an array creation expression.
4418 /// There are two possible scenarios here: one is an array creation
4419 /// expression that specifies the dimensions and optionally the
4420 /// initialization data and the other which does not need dimensions
4421 /// specified but where initialization data is mandatory.
4423 public class ArrayCreation : ExpressionStatement {
4424 Expression requested_base_type;
4425 ArrayList initializers;
4428 // The list of Argument types.
4429 // This is used to construct the `newarray' or constructor signature
4431 ArrayList arguments;
4434 // Method used to create the array object.
4436 MethodBase new_method = null;
4438 Type array_element_type;
4439 Type underlying_type;
4440 bool is_one_dimensional = false;
4441 bool is_builtin_type = false;
4442 bool expect_initializers = false;
4443 int num_arguments = 0;
4447 ArrayList array_data;
4452 // The number of array initializers that we can handle
4453 // via the InitializeArray method - through EmitStaticInitializers
4455 int num_automatic_initializers;
4457 public ArrayCreation (Expression requested_base_type, ArrayList exprs, string rank, ArrayList initializers, Location l)
4459 this.requested_base_type = requested_base_type;
4460 this.initializers = initializers;
4464 arguments = new ArrayList ();
4466 foreach (Expression e in exprs) {
4467 arguments.Add (new Argument (e, Argument.AType.Expression));
4472 public ArrayCreation (Expression requested_base_type, string rank, ArrayList initializers, Location l)
4474 this.requested_base_type = requested_base_type;
4475 this.initializers = initializers;
4479 //this.rank = rank.Substring (0, rank.LastIndexOf ("["));
4481 //string tmp = rank.Substring (rank.LastIndexOf ("["));
4483 //dimensions = tmp.Length - 1;
4484 expect_initializers = true;
4487 public Expression FormArrayType (Expression base_type, int idx_count, string rank)
4489 StringBuilder sb = new StringBuilder (rank);
4492 for (int i = 1; i < idx_count; i++)
4497 return new ComposedCast (base_type, sb.ToString (), loc);
4502 Error (178, "Incorrectly structured array initializer");
4505 public bool CheckIndices (EmitContext ec, ArrayList probe, int idx, bool specified_dims)
4507 if (specified_dims) {
4508 Argument a = (Argument) arguments [idx];
4510 if (!a.Resolve (ec, loc))
4513 if (!(a.Expr is Constant)) {
4514 Error (150, "A constant value is expected");
4518 int value = (int) ((Constant) a.Expr).GetValue ();
4520 if (value != probe.Count) {
4525 bounds [idx] = value;
4528 foreach (object o in probe) {
4529 if (o is ArrayList) {
4530 bool ret = CheckIndices (ec, (ArrayList) o, idx + 1, specified_dims);
4534 Expression tmp = (Expression) o;
4535 tmp = tmp.Resolve (ec);
4539 // Console.WriteLine ("I got: " + tmp);
4540 // Handle initialization from vars, fields etc.
4542 Expression conv = ConvertImplicitRequired (
4543 ec, tmp, underlying_type, loc);
4548 if (conv is StringConstant)
4549 array_data.Add (conv);
4550 else if (conv is Constant) {
4551 array_data.Add (conv);
4552 num_automatic_initializers++;
4554 array_data.Add (conv);
4561 public void UpdateIndices (EmitContext ec)
4564 for (ArrayList probe = initializers; probe != null;) {
4565 if (probe.Count > 0 && probe [0] is ArrayList) {
4566 Expression e = new IntConstant (probe.Count);
4567 arguments.Add (new Argument (e, Argument.AType.Expression));
4569 bounds [i++] = probe.Count;
4571 probe = (ArrayList) probe [0];
4574 Expression e = new IntConstant (probe.Count);
4575 arguments.Add (new Argument (e, Argument.AType.Expression));
4577 bounds [i++] = probe.Count;
4584 public bool ValidateInitializers (EmitContext ec, Type array_type)
4586 if (initializers == null) {
4587 if (expect_initializers)
4593 if (underlying_type == null)
4597 // We use this to store all the date values in the order in which we
4598 // will need to store them in the byte blob later
4600 array_data = new ArrayList ();
4601 bounds = new Hashtable ();
4605 if (arguments != null) {
4606 ret = CheckIndices (ec, initializers, 0, true);
4609 arguments = new ArrayList ();
4611 ret = CheckIndices (ec, initializers, 0, false);
4618 if (arguments.Count != dimensions) {
4627 void Error_NegativeArrayIndex ()
4629 Error (284, "Can not create array with a negative size");
4633 // Converts `source' to an int, uint, long or ulong.
4635 Expression ExpressionToArrayArgument (EmitContext ec, Expression source)
4639 bool old_checked = ec.CheckState;
4640 ec.CheckState = true;
4642 target = ConvertImplicit (ec, source, TypeManager.int32_type, loc);
4643 if (target == null){
4644 target = ConvertImplicit (ec, source, TypeManager.uint32_type, loc);
4645 if (target == null){
4646 target = ConvertImplicit (ec, source, TypeManager.int64_type, loc);
4647 if (target == null){
4648 target = ConvertImplicit (ec, source, TypeManager.uint64_type, loc);
4650 Expression.Error_CannotConvertImplicit (loc, source.Type, TypeManager.int32_type);
4654 ec.CheckState = old_checked;
4657 // Only positive constants are allowed at compile time
4659 if (target is Constant){
4660 if (target is IntConstant){
4661 if (((IntConstant) target).Value < 0){
4662 Error_NegativeArrayIndex ();
4667 if (target is LongConstant){
4668 if (((LongConstant) target).Value < 0){
4669 Error_NegativeArrayIndex ();
4680 // Creates the type of the array
4682 bool LookupType (EmitContext ec)
4684 StringBuilder array_qualifier = new StringBuilder (rank);
4687 // `In the first form allocates an array instace of the type that results
4688 // from deleting each of the individual expression from the expression list'
4690 if (num_arguments > 0) {
4691 array_qualifier.Append ("[");
4692 for (int i = num_arguments-1; i > 0; i--)
4693 array_qualifier.Append (",");
4694 array_qualifier.Append ("]");
4700 Expression array_type_expr;
4701 array_type_expr = new ComposedCast (requested_base_type, array_qualifier.ToString (), loc);
4702 type = ec.DeclSpace.ResolveType (array_type_expr, false, loc);
4707 underlying_type = type;
4708 if (underlying_type.IsArray)
4709 underlying_type = TypeManager.TypeToCoreType (underlying_type.GetElementType ());
4710 dimensions = type.GetArrayRank ();
4715 public override Expression DoResolve (EmitContext ec)
4719 if (!LookupType (ec))
4723 // First step is to validate the initializers and fill
4724 // in any missing bits
4726 if (!ValidateInitializers (ec, type))
4729 if (arguments == null)
4732 arg_count = arguments.Count;
4733 foreach (Argument a in arguments){
4734 if (!a.Resolve (ec, loc))
4737 Expression real_arg = ExpressionToArrayArgument (ec, a.Expr, loc);
4738 if (real_arg == null)
4745 array_element_type = TypeManager.TypeToCoreType (type.GetElementType ());
4747 if (arg_count == 1) {
4748 is_one_dimensional = true;
4749 eclass = ExprClass.Value;
4753 is_builtin_type = TypeManager.IsBuiltinType (type);
4755 if (is_builtin_type) {
4758 ml = MemberLookup (ec, type, ".ctor", MemberTypes.Constructor,
4759 AllBindingFlags, loc);
4761 if (!(ml is MethodGroupExpr)) {
4762 ml.Error118 ("method group");
4767 Error (-6, "New invocation: Can not find a constructor for " +
4768 "this argument list");
4772 new_method = Invocation.OverloadResolve (ec, (MethodGroupExpr) ml, arguments, loc);
4774 if (new_method == null) {
4775 Error (-6, "New invocation: Can not find a constructor for " +
4776 "this argument list");
4780 eclass = ExprClass.Value;
4783 ModuleBuilder mb = CodeGen.ModuleBuilder;
4784 ArrayList args = new ArrayList ();
4786 if (arguments != null) {
4787 for (int i = 0; i < arg_count; i++)
4788 args.Add (TypeManager.int32_type);
4791 Type [] arg_types = null;
4794 arg_types = new Type [args.Count];
4796 args.CopyTo (arg_types, 0);
4798 new_method = mb.GetArrayMethod (type, ".ctor", CallingConventions.HasThis, null,
4801 if (new_method == null) {
4802 Error (-6, "New invocation: Can not find a constructor for " +
4803 "this argument list");
4807 eclass = ExprClass.Value;
4812 public static byte [] MakeByteBlob (ArrayList array_data, Type underlying_type, Location loc)
4817 int count = array_data.Count;
4819 factor = GetTypeSize (underlying_type);
4823 data = new byte [(count * factor + 4) & ~3];
4826 for (int i = 0; i < count; ++i) {
4827 object v = array_data [i];
4829 if (v is EnumConstant)
4830 v = ((EnumConstant) v).Child;
4832 if (v is Constant && !(v is StringConstant))
4833 v = ((Constant) v).GetValue ();
4839 if (underlying_type == TypeManager.int64_type){
4840 if (!(v is Expression)){
4841 long val = (long) v;
4843 for (int j = 0; j < factor; ++j) {
4844 data [idx + j] = (byte) (val & 0xFF);
4848 } else if (underlying_type == TypeManager.uint64_type){
4849 if (!(v is Expression)){
4850 ulong val = (ulong) v;
4852 for (int j = 0; j < factor; ++j) {
4853 data [idx + j] = (byte) (val & 0xFF);
4857 } else if (underlying_type == TypeManager.float_type) {
4858 if (!(v is Expression)){
4859 element = BitConverter.GetBytes ((float) v);
4861 for (int j = 0; j < factor; ++j)
4862 data [idx + j] = element [j];
4864 } else if (underlying_type == TypeManager.double_type) {
4865 if (!(v is Expression)){
4866 element = BitConverter.GetBytes ((double) v);
4868 for (int j = 0; j < factor; ++j)
4869 data [idx + j] = element [j];
4871 } else if (underlying_type == TypeManager.char_type){
4872 if (!(v is Expression)){
4873 int val = (int) ((char) v);
4875 data [idx] = (byte) (val & 0xff);
4876 data [idx+1] = (byte) (val >> 8);
4878 } else if (underlying_type == TypeManager.short_type){
4879 if (!(v is Expression)){
4880 int val = (int) ((short) v);
4882 data [idx] = (byte) (val & 0xff);
4883 data [idx+1] = (byte) (val >> 8);
4885 } else if (underlying_type == TypeManager.ushort_type){
4886 if (!(v is Expression)){
4887 int val = (int) ((ushort) v);
4889 data [idx] = (byte) (val & 0xff);
4890 data [idx+1] = (byte) (val >> 8);
4892 } else if (underlying_type == TypeManager.int32_type) {
4893 if (!(v is Expression)){
4896 data [idx] = (byte) (val & 0xff);
4897 data [idx+1] = (byte) ((val >> 8) & 0xff);
4898 data [idx+2] = (byte) ((val >> 16) & 0xff);
4899 data [idx+3] = (byte) (val >> 24);
4901 } else if (underlying_type == TypeManager.uint32_type) {
4902 if (!(v is Expression)){
4903 uint val = (uint) v;
4905 data [idx] = (byte) (val & 0xff);
4906 data [idx+1] = (byte) ((val >> 8) & 0xff);
4907 data [idx+2] = (byte) ((val >> 16) & 0xff);
4908 data [idx+3] = (byte) (val >> 24);
4910 } else if (underlying_type == TypeManager.sbyte_type) {
4911 if (!(v is Expression)){
4912 sbyte val = (sbyte) v;
4913 data [idx] = (byte) val;
4915 } else if (underlying_type == TypeManager.byte_type) {
4916 if (!(v is Expression)){
4917 byte val = (byte) v;
4918 data [idx] = (byte) val;
4920 } else if (underlying_type == TypeManager.bool_type) {
4921 if (!(v is Expression)){
4922 bool val = (bool) v;
4923 data [idx] = (byte) (val ? 1 : 0);
4926 throw new Exception ("Unrecognized type in MakeByteBlob");
4935 // Emits the initializers for the array
4937 void EmitStaticInitializers (EmitContext ec, bool is_expression)
4940 // First, the static data
4943 ILGenerator ig = ec.ig;
4945 byte [] data = MakeByteBlob (array_data, underlying_type, loc);
4948 fb = RootContext.MakeStaticData (data);
4951 ig.Emit (OpCodes.Dup);
4952 ig.Emit (OpCodes.Ldtoken, fb);
4953 ig.Emit (OpCodes.Call,
4954 TypeManager.void_initializearray_array_fieldhandle);
4959 // Emits pieces of the array that can not be computed at compile
4960 // time (variables and string locations).
4962 // This always expect the top value on the stack to be the array
4964 void EmitDynamicInitializers (EmitContext ec, bool is_expression)
4966 ILGenerator ig = ec.ig;
4967 int dims = bounds.Count;
4968 int [] current_pos = new int [dims];
4969 int top = array_data.Count;
4970 LocalBuilder temp = ig.DeclareLocal (type);
4972 ig.Emit (OpCodes.Stloc, temp);
4974 MethodInfo set = null;
4978 ModuleBuilder mb = null;
4979 mb = CodeGen.ModuleBuilder;
4980 args = new Type [dims + 1];
4983 for (j = 0; j < dims; j++)
4984 args [j] = TypeManager.int32_type;
4986 args [j] = array_element_type;
4988 set = mb.GetArrayMethod (
4990 CallingConventions.HasThis | CallingConventions.Standard,
4991 TypeManager.void_type, args);
4994 for (int i = 0; i < top; i++){
4996 Expression e = null;
4998 if (array_data [i] is Expression)
4999 e = (Expression) array_data [i];
5003 // Basically we do this for string literals and
5004 // other non-literal expressions
5006 if (e is StringConstant || !(e is Constant) ||
5007 num_automatic_initializers <= 2) {
5008 Type etype = e.Type;
5010 ig.Emit (OpCodes.Ldloc, temp);
5012 for (int idx = dims; idx > 0; ) {
5014 IntConstant.EmitInt (ig, current_pos [idx]);
5018 // If we are dealing with a struct, get the
5019 // address of it, so we can store it.
5022 etype.IsSubclassOf (TypeManager.value_type) &&
5023 (!TypeManager.IsBuiltinType (etype) ||
5024 etype == TypeManager.decimal_type)) {
5029 // Let new know that we are providing
5030 // the address where to store the results
5032 n.DisableTemporaryValueType ();
5035 ig.Emit (OpCodes.Ldelema, etype);
5041 ArrayAccess.EmitStoreOpcode (ig, array_element_type);
5043 ig.Emit (OpCodes.Call, set);
5050 for (int j = 0; j < dims; j++){
5052 if (current_pos [j] < (int) bounds [j])
5054 current_pos [j] = 0;
5059 ig.Emit (OpCodes.Ldloc, temp);
5062 void EmitArrayArguments (EmitContext ec)
5064 ILGenerator ig = ec.ig;
5066 foreach (Argument a in arguments) {
5067 Type atype = a.Type;
5070 if (atype == TypeManager.uint64_type)
5071 ig.Emit (OpCodes.Conv_Ovf_U4);
5072 else if (atype == TypeManager.int64_type)
5073 ig.Emit (OpCodes.Conv_Ovf_I4);
5077 void DoEmit (EmitContext ec, bool is_statement)
5079 ILGenerator ig = ec.ig;
5081 EmitArrayArguments (ec);
5082 if (is_one_dimensional)
5083 ig.Emit (OpCodes.Newarr, array_element_type);
5085 if (is_builtin_type)
5086 ig.Emit (OpCodes.Newobj, (ConstructorInfo) new_method);
5088 ig.Emit (OpCodes.Newobj, (MethodInfo) new_method);
5091 if (initializers != null){
5093 // FIXME: Set this variable correctly.
5095 bool dynamic_initializers = true;
5097 if (underlying_type != TypeManager.string_type &&
5098 underlying_type != TypeManager.object_type) {
5099 if (num_automatic_initializers > 2)
5100 EmitStaticInitializers (ec, dynamic_initializers || !is_statement);
5103 if (dynamic_initializers)
5104 EmitDynamicInitializers (ec, !is_statement);
5108 public override void Emit (EmitContext ec)
5113 public override void EmitStatement (EmitContext ec)
5121 /// Represents the `this' construct
5123 public class This : Expression, IAssignMethod, IMemoryLocation, IVariable {
5128 public This (Block block, Location loc)
5134 public This (Location loc)
5139 public bool IsAssigned (EmitContext ec, Location loc)
5144 return vi.IsAssigned (ec, loc);
5147 public bool IsFieldAssigned (EmitContext ec, string field_name, Location loc)
5152 return vi.IsFieldAssigned (ec, field_name, loc);
5155 public void SetAssigned (EmitContext ec)
5158 vi.SetAssigned (ec);
5161 public void SetFieldAssigned (EmitContext ec, string field_name)
5164 vi.SetFieldAssigned (ec, field_name);
5167 public override Expression DoResolve (EmitContext ec)
5169 eclass = ExprClass.Variable;
5170 type = ec.ContainerType;
5173 Error (26, "Keyword this not valid in static code");
5178 vi = block.ThisVariable;
5183 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
5187 VariableInfo vi = ec.CurrentBlock.ThisVariable;
5189 vi.SetAssigned (ec);
5191 if (ec.TypeContainer is Class){
5192 Error (1604, "Cannot assign to `this'");
5199 public override void Emit (EmitContext ec)
5201 ILGenerator ig = ec.ig;
5203 ig.Emit (OpCodes.Ldarg_0);
5204 if (ec.TypeContainer is Struct)
5205 ig.Emit (OpCodes.Ldobj, type);
5208 public void EmitAssign (EmitContext ec, Expression source)
5210 ILGenerator ig = ec.ig;
5212 if (ec.TypeContainer is Struct){
5213 ig.Emit (OpCodes.Ldarg_0);
5215 ig.Emit (OpCodes.Stobj, type);
5218 ig.Emit (OpCodes.Starg, 0);
5222 public void AddressOf (EmitContext ec, AddressOp mode)
5224 ec.ig.Emit (OpCodes.Ldarg_0);
5227 // FIGURE OUT WHY LDARG_S does not work
5229 // consider: struct X { int val; int P { set { val = value; }}}
5231 // Yes, this looks very bad. Look at `NOTAS' for
5233 // ec.ig.Emit (OpCodes.Ldarga_S, (byte) 0);
5238 /// Implements the typeof operator
5240 public class TypeOf : Expression {
5241 public readonly Expression QueriedType;
5244 public TypeOf (Expression queried_type, Location l)
5246 QueriedType = queried_type;
5250 public override Expression DoResolve (EmitContext ec)
5252 typearg = ec.DeclSpace.ResolveType (QueriedType, false, loc);
5254 if (typearg == null)
5257 type = TypeManager.type_type;
5258 eclass = ExprClass.Type;
5262 public override void Emit (EmitContext ec)
5264 ec.ig.Emit (OpCodes.Ldtoken, typearg);
5265 ec.ig.Emit (OpCodes.Call, TypeManager.system_type_get_type_from_handle);
5268 public Type TypeArg {
5269 get { return typearg; }
5274 /// Implements the sizeof expression
5276 public class SizeOf : Expression {
5277 public readonly Expression QueriedType;
5280 public SizeOf (Expression queried_type, Location l)
5282 this.QueriedType = queried_type;
5286 public override Expression DoResolve (EmitContext ec)
5288 type_queried = ec.DeclSpace.ResolveType (QueriedType, false, loc);
5289 if (type_queried == null)
5292 type = TypeManager.int32_type;
5293 eclass = ExprClass.Value;
5297 public override void Emit (EmitContext ec)
5299 int size = GetTypeSize (type_queried);
5302 ec.ig.Emit (OpCodes.Sizeof, type_queried);
5304 IntConstant.EmitInt (ec.ig, size);
5309 /// Implements the member access expression
5311 public class MemberAccess : Expression, ITypeExpression {
5312 public readonly string Identifier;
5314 Expression member_lookup;
5316 public MemberAccess (Expression expr, string id, Location l)
5323 public Expression Expr {
5329 static void error176 (Location loc, string name)
5331 Report.Error (176, loc, "Static member `" +
5332 name + "' cannot be accessed " +
5333 "with an instance reference, qualify with a " +
5334 "type name instead");
5337 static bool IdenticalNameAndTypeName (EmitContext ec, Expression left_original, Location loc)
5339 if (left_original == null)
5342 if (!(left_original is SimpleName))
5345 SimpleName sn = (SimpleName) left_original;
5347 Type t = RootContext.LookupType (ec.DeclSpace, sn.Name, true, loc);
5354 public static Expression ResolveMemberAccess (EmitContext ec, Expression member_lookup,
5355 Expression left, Location loc,
5356 Expression left_original)
5358 bool left_is_type, left_is_explicit;
5360 // If `left' is null, then we're called from SimpleNameResolve and this is
5361 // a member in the currently defining class.
5363 left_is_type = ec.IsStatic || ec.IsFieldInitializer;
5364 left_is_explicit = false;
5366 // Implicitly default to `this' unless we're static.
5367 if (!ec.IsStatic && !ec.IsFieldInitializer && !ec.InEnumContext)
5370 left_is_type = left is TypeExpr;
5371 left_is_explicit = true;
5374 if (member_lookup is FieldExpr){
5375 FieldExpr fe = (FieldExpr) member_lookup;
5376 FieldInfo fi = fe.FieldInfo;
5377 Type decl_type = fi.DeclaringType;
5379 if (fi is FieldBuilder) {
5380 Const c = TypeManager.LookupConstant ((FieldBuilder) fi);
5383 object o = c.LookupConstantValue (ec);
5384 object real_value = ((Constant) c.Expr).GetValue ();
5386 return Constantify (real_value, fi.FieldType);
5391 Type t = fi.FieldType;
5395 if (fi is FieldBuilder)
5396 o = TypeManager.GetValue ((FieldBuilder) fi);
5398 o = fi.GetValue (fi);
5400 if (decl_type.IsSubclassOf (TypeManager.enum_type)) {
5401 Expression enum_member = MemberLookup (
5402 ec, decl_type, "value__", MemberTypes.Field,
5403 AllBindingFlags, loc);
5405 Enum en = TypeManager.LookupEnum (decl_type);
5409 c = Constantify (o, en.UnderlyingType);
5411 c = Constantify (o, enum_member.Type);
5413 return new EnumConstant (c, decl_type);
5416 Expression exp = Constantify (o, t);
5418 if (left_is_explicit && !left_is_type) {
5419 error176 (loc, fe.FieldInfo.Name);
5426 if (fi.FieldType.IsPointer && !ec.InUnsafe){
5432 if (member_lookup is EventExpr) {
5434 EventExpr ee = (EventExpr) member_lookup;
5437 // If the event is local to this class, we transform ourselves into
5441 Expression ml = MemberLookup (
5442 ec, ec.ContainerType, ee.EventInfo.Name, MemberTypes.Event,
5443 AllBindingFlags | BindingFlags.DeclaredOnly, loc);
5446 MemberInfo mi = GetFieldFromEvent ((EventExpr) ml);
5450 // If this happens, then we have an event with its own
5451 // accessors and private field etc so there's no need
5452 // to transform ourselves : we should instead flag an error
5454 Assign.error70 (ee.EventInfo, loc);
5458 ml = ExprClassFromMemberInfo (ec, mi, loc);
5461 Report.Error (-200, loc, "Internal error!!");
5465 return ResolveMemberAccess (ec, ml, left, loc, left_original);
5469 if (member_lookup is IMemberExpr) {
5470 IMemberExpr me = (IMemberExpr) member_lookup;
5474 if (IdenticalNameAndTypeName (ec, left_original, loc))
5475 return member_lookup;
5477 SimpleName.Error_ObjectRefRequired (ec, loc, me.Name);
5481 if (!me.IsInstance){
5482 if (IdenticalNameAndTypeName (ec, left_original, loc))
5483 return member_lookup;
5485 if (left_is_explicit) {
5486 error176 (loc, me.Name);
5492 // Since we can not check for instance objects in SimpleName,
5493 // becaue of the rule that allows types and variables to share
5494 // the name (as long as they can be de-ambiguated later, see
5495 // IdenticalNameAndTypeName), we have to check whether left
5496 // is an instance variable in a static context
5498 // However, if the left-hand value is explicitly given, then
5499 // it is already our instance expression, so we aren't in
5503 if (ec.IsStatic && !left_is_explicit && left is IMemberExpr){
5504 IMemberExpr mexp = (IMemberExpr) left;
5506 if (!mexp.IsStatic){
5507 SimpleName.Error_ObjectRefRequired (ec, loc, mexp.Name);
5512 me.InstanceExpression = left;
5515 return member_lookup;
5518 if (member_lookup is TypeExpr){
5519 member_lookup.Resolve (ec, ResolveFlags.Type);
5520 return member_lookup;
5523 Console.WriteLine ("Left is: " + left);
5524 Report.Error (-100, loc, "Support for [" + member_lookup + "] is not present yet");
5525 Environment.Exit (0);
5529 public Expression DoResolve (EmitContext ec, Expression right_side, ResolveFlags flags)
5532 throw new Exception ();
5534 // Resolve the expression with flow analysis turned off, we'll do the definite
5535 // assignment checks later. This is because we don't know yet what the expression
5536 // will resolve to - it may resolve to a FieldExpr and in this case we must do the
5537 // definite assignment check on the actual field and not on the whole struct.
5540 Expression original = expr;
5541 expr = expr.Resolve (ec, flags | ResolveFlags.DisableFlowAnalysis);
5546 if (expr is SimpleName){
5547 SimpleName child_expr = (SimpleName) expr;
5549 Expression new_expr = new SimpleName (child_expr.Name + "." + Identifier, loc);
5551 return new_expr.Resolve (ec, flags);
5555 // TODO: I mailed Ravi about this, and apparently we can get rid
5556 // of this and put it in the right place.
5558 // Handle enums here when they are in transit.
5559 // Note that we cannot afford to hit MemberLookup in this case because
5560 // it will fail to find any members at all
5563 int errors = Report.Errors;
5565 Type expr_type = expr.Type;
5566 if ((expr is TypeExpr) && (expr_type.IsSubclassOf (TypeManager.enum_type))){
5568 Enum en = TypeManager.LookupEnum (expr_type);
5571 object value = en.LookupEnumValue (ec, Identifier, loc);
5574 Constant c = Constantify (value, en.UnderlyingType);
5575 return new EnumConstant (c, expr_type);
5580 if (expr_type.IsPointer){
5581 Error (23, "The `.' operator can not be applied to pointer operands (" +
5582 TypeManager.CSharpName (expr_type) + ")");
5586 member_lookup = MemberLookup (ec, expr_type, Identifier, loc);
5588 if (member_lookup == null){
5589 // Error has already been reported.
5590 if (errors < Report.Errors)
5594 // Try looking the member up from the same type, if we find
5595 // it, we know that the error was due to limited visibility
5597 object lookup = TypeManager.MemberLookup (
5598 expr_type, expr_type, AllMemberTypes, AllBindingFlags, Identifier);
5600 Error (117, "`" + expr_type + "' does not contain a " +
5601 "definition for `" + Identifier + "'");
5602 else if ((expr_type != ec.ContainerType) &&
5603 ec.ContainerType.IsSubclassOf (expr_type)){
5605 // Although a derived class can access protected members of
5606 // its base class it cannot do so through an instance of the
5607 // base class (CS1540). If the expr_type is a parent of the
5608 // ec.ContainerType and the lookup succeeds with the latter one,
5609 // then we are in this situation.
5611 lookup = TypeManager.MemberLookup (
5612 ec.ContainerType, ec.ContainerType, AllMemberTypes,
5613 AllBindingFlags, Identifier);
5616 Error (1540, "Cannot access protected member `" +
5617 expr_type + "." + Identifier + "' " +
5618 "via a qualifier of type `" +
5619 TypeManager.CSharpName (expr_type) + "'; the " +
5620 "qualifier must be of type `" +
5621 TypeManager.CSharpName (ec.ContainerType) + "' " +
5622 "(or derived from it)");
5624 Error (122, "`" + expr_type + "." + Identifier + "' " +
5625 "is inaccessible because of its protection level");
5627 Error (122, "`" + expr_type + "." + Identifier + "' " +
5628 "is inaccessible because of its protection level");
5633 if (member_lookup is TypeExpr){
5634 member_lookup.Resolve (ec, ResolveFlags.Type);
5635 return member_lookup;
5636 } else if ((flags & ResolveFlags.MaskExprClass) == ResolveFlags.Type)
5639 member_lookup = ResolveMemberAccess (ec, member_lookup, expr, loc, original);
5640 if (member_lookup == null)
5643 // The following DoResolve/DoResolveLValue will do the definite assignment
5646 if (right_side != null)
5647 member_lookup = member_lookup.DoResolveLValue (ec, right_side);
5649 member_lookup = member_lookup.DoResolve (ec);
5651 return member_lookup;
5654 public override Expression DoResolve (EmitContext ec)
5656 return DoResolve (ec, null, ResolveFlags.VariableOrValue |
5657 ResolveFlags.SimpleName | ResolveFlags.Type);
5660 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
5662 return DoResolve (ec, right_side, ResolveFlags.VariableOrValue |
5663 ResolveFlags.SimpleName | ResolveFlags.Type);
5666 public Expression DoResolveType (EmitContext ec)
5668 return DoResolve (ec, null, ResolveFlags.Type);
5671 public override void Emit (EmitContext ec)
5673 throw new Exception ("Should not happen");
5676 public override string ToString ()
5678 return expr + "." + Identifier;
5683 /// Implements checked expressions
5685 public class CheckedExpr : Expression {
5687 public Expression Expr;
5689 public CheckedExpr (Expression e, Location l)
5695 public override Expression DoResolve (EmitContext ec)
5697 bool last_const_check = ec.ConstantCheckState;
5699 ec.ConstantCheckState = true;
5700 Expr = Expr.Resolve (ec);
5701 ec.ConstantCheckState = last_const_check;
5706 eclass = Expr.eclass;
5711 public override void Emit (EmitContext ec)
5713 bool last_check = ec.CheckState;
5714 bool last_const_check = ec.ConstantCheckState;
5716 ec.CheckState = true;
5717 ec.ConstantCheckState = true;
5719 ec.CheckState = last_check;
5720 ec.ConstantCheckState = last_const_check;
5726 /// Implements the unchecked expression
5728 public class UnCheckedExpr : Expression {
5730 public Expression Expr;
5732 public UnCheckedExpr (Expression e, Location l)
5738 public override Expression DoResolve (EmitContext ec)
5740 bool last_const_check = ec.ConstantCheckState;
5742 ec.ConstantCheckState = false;
5743 Expr = Expr.Resolve (ec);
5744 ec.ConstantCheckState = last_const_check;
5749 eclass = Expr.eclass;
5754 public override void Emit (EmitContext ec)
5756 bool last_check = ec.CheckState;
5757 bool last_const_check = ec.ConstantCheckState;
5759 ec.CheckState = false;
5760 ec.ConstantCheckState = false;
5762 ec.CheckState = last_check;
5763 ec.ConstantCheckState = last_const_check;
5769 /// An Element Access expression.
5771 /// During semantic analysis these are transformed into
5772 /// IndexerAccess or ArrayAccess
5774 public class ElementAccess : Expression {
5775 public ArrayList Arguments;
5776 public Expression Expr;
5778 public ElementAccess (Expression e, ArrayList e_list, Location l)
5787 Arguments = new ArrayList ();
5788 foreach (Expression tmp in e_list)
5789 Arguments.Add (new Argument (tmp, Argument.AType.Expression));
5793 bool CommonResolve (EmitContext ec)
5795 Expr = Expr.Resolve (ec);
5800 if (Arguments == null)
5803 foreach (Argument a in Arguments){
5804 if (!a.Resolve (ec, loc))
5811 Expression MakePointerAccess ()
5815 if (t == TypeManager.void_ptr_type){
5818 "The array index operation is not valid for void pointers");
5821 if (Arguments.Count != 1){
5824 "A pointer must be indexed by a single value");
5827 Expression p = new PointerArithmetic (true, Expr, ((Argument)Arguments [0]).Expr,
5829 return new Indirection (p, loc);
5832 public override Expression DoResolve (EmitContext ec)
5834 if (!CommonResolve (ec))
5838 // We perform some simple tests, and then to "split" the emit and store
5839 // code we create an instance of a different class, and return that.
5841 // I am experimenting with this pattern.
5846 return (new ArrayAccess (this, loc)).Resolve (ec);
5847 else if (t.IsPointer)
5848 return MakePointerAccess ();
5850 return (new IndexerAccess (this, loc)).Resolve (ec);
5853 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
5855 if (!CommonResolve (ec))
5860 return (new ArrayAccess (this, loc)).ResolveLValue (ec, right_side);
5861 else if (t.IsPointer)
5862 return MakePointerAccess ();
5864 return (new IndexerAccess (this, loc)).ResolveLValue (ec, right_side);
5867 public override void Emit (EmitContext ec)
5869 throw new Exception ("Should never be reached");
5874 /// Implements array access
5876 public class ArrayAccess : Expression, IAssignMethod, IMemoryLocation {
5878 // Points to our "data" repository
5882 LocalTemporary [] cached_locations;
5884 public ArrayAccess (ElementAccess ea_data, Location l)
5887 eclass = ExprClass.Variable;
5891 public override Expression DoResolve (EmitContext ec)
5893 ExprClass eclass = ea.Expr.eclass;
5896 // As long as the type is valid
5897 if (!(eclass == ExprClass.Variable || eclass == ExprClass.PropertyAccess ||
5898 eclass == ExprClass.Value)) {
5899 ea.Expr.Error118 ("variable or value");
5904 Type t = ea.Expr.Type;
5905 if (t.GetArrayRank () != ea.Arguments.Count){
5907 "Incorrect number of indexes for array " +
5908 " expected: " + t.GetArrayRank () + " got: " +
5909 ea.Arguments.Count);
5912 type = TypeManager.TypeToCoreType (t.GetElementType ());
5913 if (type.IsPointer && !ec.InUnsafe){
5914 UnsafeError (ea.Location);
5918 foreach (Argument a in ea.Arguments){
5919 Type argtype = a.Type;
5921 if (argtype == TypeManager.int32_type ||
5922 argtype == TypeManager.uint32_type ||
5923 argtype == TypeManager.int64_type ||
5924 argtype == TypeManager.uint64_type)
5928 // Mhm. This is strage, because the Argument.Type is not the same as
5929 // Argument.Expr.Type: the value changes depending on the ref/out setting.
5931 // Wonder if I will run into trouble for this.
5933 a.Expr = ExpressionToArrayArgument (ec, a.Expr, ea.Location);
5938 eclass = ExprClass.Variable;
5944 /// Emits the right opcode to load an object of Type `t'
5945 /// from an array of T
5947 static public void EmitLoadOpcode (ILGenerator ig, Type type)
5949 if (type == TypeManager.byte_type || type == TypeManager.bool_type)
5950 ig.Emit (OpCodes.Ldelem_U1);
5951 else if (type == TypeManager.sbyte_type)
5952 ig.Emit (OpCodes.Ldelem_I1);
5953 else if (type == TypeManager.short_type)
5954 ig.Emit (OpCodes.Ldelem_I2);
5955 else if (type == TypeManager.ushort_type || type == TypeManager.char_type)
5956 ig.Emit (OpCodes.Ldelem_U2);
5957 else if (type == TypeManager.int32_type)
5958 ig.Emit (OpCodes.Ldelem_I4);
5959 else if (type == TypeManager.uint32_type)
5960 ig.Emit (OpCodes.Ldelem_U4);
5961 else if (type == TypeManager.uint64_type)
5962 ig.Emit (OpCodes.Ldelem_I8);
5963 else if (type == TypeManager.int64_type)
5964 ig.Emit (OpCodes.Ldelem_I8);
5965 else if (type == TypeManager.float_type)
5966 ig.Emit (OpCodes.Ldelem_R4);
5967 else if (type == TypeManager.double_type)
5968 ig.Emit (OpCodes.Ldelem_R8);
5969 else if (type == TypeManager.intptr_type)
5970 ig.Emit (OpCodes.Ldelem_I);
5971 else if (type.IsValueType){
5972 ig.Emit (OpCodes.Ldelema, type);
5973 ig.Emit (OpCodes.Ldobj, type);
5975 ig.Emit (OpCodes.Ldelem_Ref);
5979 /// Emits the right opcode to store an object of Type `t'
5980 /// from an array of T.
5982 static public void EmitStoreOpcode (ILGenerator ig, Type t)
5984 t = TypeManager.TypeToCoreType (t);
5985 if (t == TypeManager.byte_type || t == TypeManager.sbyte_type ||
5986 t == TypeManager.bool_type)
5987 ig.Emit (OpCodes.Stelem_I1);
5988 else if (t == TypeManager.short_type || t == TypeManager.ushort_type || t == TypeManager.char_type)
5989 ig.Emit (OpCodes.Stelem_I2);
5990 else if (t == TypeManager.int32_type || t == TypeManager.uint32_type)
5991 ig.Emit (OpCodes.Stelem_I4);
5992 else if (t == TypeManager.int64_type || t == TypeManager.uint64_type)
5993 ig.Emit (OpCodes.Stelem_I8);
5994 else if (t == TypeManager.float_type)
5995 ig.Emit (OpCodes.Stelem_R4);
5996 else if (t == TypeManager.double_type)
5997 ig.Emit (OpCodes.Stelem_R8);
5998 else if (t == TypeManager.intptr_type)
5999 ig.Emit (OpCodes.Stelem_I);
6000 else if (t.IsValueType)
6001 ig.Emit (OpCodes.Stobj, t);
6003 ig.Emit (OpCodes.Stelem_Ref);
6006 MethodInfo FetchGetMethod ()
6008 ModuleBuilder mb = CodeGen.ModuleBuilder;
6009 int arg_count = ea.Arguments.Count;
6010 Type [] args = new Type [arg_count];
6013 for (int i = 0; i < arg_count; i++){
6014 //args [i++] = a.Type;
6015 args [i] = TypeManager.int32_type;
6018 get = mb.GetArrayMethod (
6019 ea.Expr.Type, "Get",
6020 CallingConventions.HasThis |
6021 CallingConventions.Standard,
6027 MethodInfo FetchAddressMethod ()
6029 ModuleBuilder mb = CodeGen.ModuleBuilder;
6030 int arg_count = ea.Arguments.Count;
6031 Type [] args = new Type [arg_count];
6033 string ptr_type_name;
6036 ptr_type_name = type.FullName + "&";
6037 ret_type = Type.GetType (ptr_type_name);
6040 // It is a type defined by the source code we are compiling
6042 if (ret_type == null){
6043 ret_type = mb.GetType (ptr_type_name);
6046 for (int i = 0; i < arg_count; i++){
6047 //args [i++] = a.Type;
6048 args [i] = TypeManager.int32_type;
6051 address = mb.GetArrayMethod (
6052 ea.Expr.Type, "Address",
6053 CallingConventions.HasThis |
6054 CallingConventions.Standard,
6061 // Load the array arguments into the stack.
6063 // If we have been requested to cache the values (cached_locations array
6064 // initialized), then load the arguments the first time and store them
6065 // in locals. otherwise load from local variables.
6067 void LoadArrayAndArguments (EmitContext ec)
6069 ILGenerator ig = ec.ig;
6071 if (cached_locations == null){
6073 foreach (Argument a in ea.Arguments){
6074 Type argtype = a.Expr.Type;
6078 if (argtype == TypeManager.int64_type)
6079 ig.Emit (OpCodes.Conv_Ovf_I);
6080 else if (argtype == TypeManager.uint64_type)
6081 ig.Emit (OpCodes.Conv_Ovf_I_Un);
6086 if (cached_locations [0] == null){
6087 cached_locations [0] = new LocalTemporary (ec, ea.Expr.Type);
6089 ig.Emit (OpCodes.Dup);
6090 cached_locations [0].Store (ec);
6094 foreach (Argument a in ea.Arguments){
6095 Type argtype = a.Expr.Type;
6097 cached_locations [j] = new LocalTemporary (ec, TypeManager.intptr_type /* a.Expr.Type */);
6099 if (argtype == TypeManager.int64_type)
6100 ig.Emit (OpCodes.Conv_Ovf_I);
6101 else if (argtype == TypeManager.uint64_type)
6102 ig.Emit (OpCodes.Conv_Ovf_I_Un);
6104 ig.Emit (OpCodes.Dup);
6105 cached_locations [j].Store (ec);
6111 foreach (LocalTemporary lt in cached_locations)
6115 public new void CacheTemporaries (EmitContext ec)
6117 cached_locations = new LocalTemporary [ea.Arguments.Count + 1];
6120 public override void Emit (EmitContext ec)
6122 int rank = ea.Expr.Type.GetArrayRank ();
6123 ILGenerator ig = ec.ig;
6125 LoadArrayAndArguments (ec);
6128 EmitLoadOpcode (ig, type);
6132 method = FetchGetMethod ();
6133 ig.Emit (OpCodes.Call, method);
6137 public void EmitAssign (EmitContext ec, Expression source)
6139 int rank = ea.Expr.Type.GetArrayRank ();
6140 ILGenerator ig = ec.ig;
6141 Type t = source.Type;
6143 LoadArrayAndArguments (ec);
6146 // The stobj opcode used by value types will need
6147 // an address on the stack, not really an array/array
6151 if (t.IsValueType && !TypeManager.IsBuiltinType (t))
6152 ig.Emit (OpCodes.Ldelema, t);
6158 EmitStoreOpcode (ig, t);
6160 ModuleBuilder mb = CodeGen.ModuleBuilder;
6161 int arg_count = ea.Arguments.Count;
6162 Type [] args = new Type [arg_count + 1];
6165 for (int i = 0; i < arg_count; i++){
6166 //args [i++] = a.Type;
6167 args [i] = TypeManager.int32_type;
6170 args [arg_count] = type;
6172 set = mb.GetArrayMethod (
6173 ea.Expr.Type, "Set",
6174 CallingConventions.HasThis |
6175 CallingConventions.Standard,
6176 TypeManager.void_type, args);
6178 ig.Emit (OpCodes.Call, set);
6182 public void AddressOf (EmitContext ec, AddressOp mode)
6184 int rank = ea.Expr.Type.GetArrayRank ();
6185 ILGenerator ig = ec.ig;
6187 LoadArrayAndArguments (ec);
6190 ig.Emit (OpCodes.Ldelema, type);
6192 MethodInfo address = FetchAddressMethod ();
6193 ig.Emit (OpCodes.Call, address);
6200 public ArrayList getters, setters;
6201 static Hashtable map;
6205 map = new Hashtable ();
6208 Indexers (MemberInfo [] mi)
6210 foreach (PropertyInfo property in mi){
6211 MethodInfo get, set;
6213 get = property.GetGetMethod (true);
6215 if (getters == null)
6216 getters = new ArrayList ();
6221 set = property.GetSetMethod (true);
6223 if (setters == null)
6224 setters = new ArrayList ();
6230 static private Indexers GetIndexersForTypeOrInterface (Type caller_type, Type lookup_type)
6232 Indexers ix = (Indexers) map [lookup_type];
6237 string p_name = TypeManager.IndexerPropertyName (lookup_type);
6239 MemberInfo [] mi = TypeManager.MemberLookup (
6240 caller_type, lookup_type, MemberTypes.Property,
6241 BindingFlags.Public | BindingFlags.Instance, p_name);
6243 if (mi == null || mi.Length == 0)
6246 ix = new Indexers (mi);
6247 map [lookup_type] = ix;
6252 static public Indexers GetIndexersForType (Type caller_type, Type lookup_type, Location loc)
6254 Indexers ix = (Indexers) map [lookup_type];
6259 ix = GetIndexersForTypeOrInterface (caller_type, lookup_type);
6263 Type [] ifaces = TypeManager.GetInterfaces (lookup_type);
6264 if (ifaces != null) {
6265 foreach (Type itype in ifaces) {
6266 ix = GetIndexersForTypeOrInterface (caller_type, itype);
6272 Report.Error (21, loc,
6273 "Type `" + TypeManager.CSharpName (lookup_type) +
6274 "' does not have any indexers defined");
6280 /// Expressions that represent an indexer call.
6282 public class IndexerAccess : Expression, IAssignMethod {
6284 // Points to our "data" repository
6287 MethodInfo get, set;
6289 ArrayList set_arguments;
6291 public IndexerAccess (ElementAccess ea_data, Location l)
6294 eclass = ExprClass.Value;
6298 public override Expression DoResolve (EmitContext ec)
6300 Type indexer_type = ea.Expr.Type;
6303 // Step 1: Query for all `Item' *properties*. Notice
6304 // that the actual methods are pointed from here.
6306 // This is a group of properties, piles of them.
6309 ilist = Indexers.GetIndexersForType (
6310 ec.ContainerType, indexer_type, ea.Location);
6314 // Step 2: find the proper match
6316 if (ilist != null && ilist.getters != null && ilist.getters.Count > 0){
6317 Location loc = ea.Location;
6319 get = (MethodInfo) Invocation.OverloadResolve (
6320 ec, new MethodGroupExpr (ilist.getters, loc), ea.Arguments, loc);
6324 ea.Error (154, "indexer can not be used in this context, because " +
6325 "it lacks a `get' accessor");
6329 type = get.ReturnType;
6330 if (type.IsPointer && !ec.InUnsafe){
6331 UnsafeError (ea.Location);
6335 eclass = ExprClass.IndexerAccess;
6339 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
6341 Type indexer_type = ea.Expr.Type;
6342 Type right_type = right_side.Type;
6345 ilist = Indexers.GetIndexersForType (
6346 ec.ContainerType, indexer_type, ea.Location);
6348 if (ilist != null && ilist.setters != null && ilist.setters.Count > 0){
6349 Location loc = ea.Location;
6351 set_arguments = (ArrayList) ea.Arguments.Clone ();
6352 set_arguments.Add (new Argument (right_side, Argument.AType.Expression));
6354 set = (MethodInfo) Invocation.OverloadResolve (
6355 ec, new MethodGroupExpr (ilist.setters, loc), set_arguments, loc);
6359 ea.Error (200, "indexer X.this [" + TypeManager.CSharpName (right_type) +
6360 "] lacks a `set' accessor");
6364 type = TypeManager.void_type;
6365 eclass = ExprClass.IndexerAccess;
6369 public override void Emit (EmitContext ec)
6371 Invocation.EmitCall (ec, false, false, ea.Expr, get, ea.Arguments, ea.Location);
6375 // source is ignored, because we already have a copy of it from the
6376 // LValue resolution and we have already constructed a pre-cached
6377 // version of the arguments (ea.set_arguments);
6379 public void EmitAssign (EmitContext ec, Expression source)
6381 Invocation.EmitCall (ec, false, false, ea.Expr, set, set_arguments, ea.Location);
6386 /// The base operator for method names
6388 public class BaseAccess : Expression {
6391 public BaseAccess (string member, Location l)
6393 this.member = member;
6397 public override Expression DoResolve (EmitContext ec)
6399 Expression member_lookup;
6400 Type current_type = ec.ContainerType;
6401 Type base_type = current_type.BaseType;
6406 "Keyword base is not allowed in static method");
6410 member_lookup = MemberLookup (ec, base_type, base_type, member,
6411 AllMemberTypes, AllBindingFlags, loc);
6412 if (member_lookup == null) {
6414 TypeManager.CSharpName (base_type) + " does not " +
6415 "contain a definition for `" + member + "'");
6422 left = new TypeExpr (base_type, loc);
6426 e = MemberAccess.ResolveMemberAccess (ec, member_lookup, left, loc, null);
6428 if (e is PropertyExpr){
6429 PropertyExpr pe = (PropertyExpr) e;
6437 public override void Emit (EmitContext ec)
6439 throw new Exception ("Should never be called");
6444 /// The base indexer operator
6446 public class BaseIndexerAccess : Expression {
6447 ArrayList Arguments;
6449 public BaseIndexerAccess (ArrayList args, Location l)
6455 public override Expression DoResolve (EmitContext ec)
6457 Type current_type = ec.ContainerType;
6458 Type base_type = current_type.BaseType;
6459 Expression member_lookup;
6463 "Keyword base is not allowed in static method");
6467 member_lookup = MemberLookup (ec, base_type, base_type, "get_Item",
6468 MemberTypes.Method, AllBindingFlags, loc);
6469 if (member_lookup == null)
6472 return MemberAccess.ResolveMemberAccess (ec, member_lookup, ec.This, loc, null);
6475 public override void Emit (EmitContext ec)
6477 throw new Exception ("Should never be called");
6482 /// This class exists solely to pass the Type around and to be a dummy
6483 /// that can be passed to the conversion functions (this is used by
6484 /// foreach implementation to typecast the object return value from
6485 /// get_Current into the proper type. All code has been generated and
6486 /// we only care about the side effect conversions to be performed
6488 /// This is also now used as a placeholder where a no-action expression
6489 /// is needed (the `New' class).
6491 public class EmptyExpression : Expression {
6492 public EmptyExpression ()
6494 type = TypeManager.object_type;
6495 eclass = ExprClass.Value;
6496 loc = Location.Null;
6499 public EmptyExpression (Type t)
6502 eclass = ExprClass.Value;
6503 loc = Location.Null;
6506 public override Expression DoResolve (EmitContext ec)
6511 public override void Emit (EmitContext ec)
6513 // nothing, as we only exist to not do anything.
6517 // This is just because we might want to reuse this bad boy
6518 // instead of creating gazillions of EmptyExpressions.
6519 // (CanConvertImplicit uses it)
6521 public void SetType (Type t)
6527 public class UserCast : Expression {
6531 public UserCast (MethodInfo method, Expression source, Location l)
6533 this.method = method;
6534 this.source = source;
6535 type = method.ReturnType;
6536 eclass = ExprClass.Value;
6540 public override Expression DoResolve (EmitContext ec)
6543 // We are born fully resolved
6548 public override void Emit (EmitContext ec)
6550 ILGenerator ig = ec.ig;
6554 if (method is MethodInfo)
6555 ig.Emit (OpCodes.Call, (MethodInfo) method);
6557 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
6563 // This class is used to "construct" the type during a typecast
6564 // operation. Since the Type.GetType class in .NET can parse
6565 // the type specification, we just use this to construct the type
6566 // one bit at a time.
6568 public class ComposedCast : Expression, ITypeExpression {
6572 public ComposedCast (Expression left, string dim, Location l)
6579 public Expression DoResolveType (EmitContext ec)
6581 left = left.Resolve (ec, ResolveFlags.Type);
6585 type = RootContext.LookupType (
6586 ec.DeclSpace, left.Type.FullName + dim, false, loc);
6590 if (!ec.ResolvingTypeTree){
6592 // If the above flag is set, this is being invoked from the ResolveType function.
6593 // Upper layers take care of the type validity in this context.
6595 if (!ec.InUnsafe && type.IsPointer){
6601 eclass = ExprClass.Type;
6605 public override Expression DoResolve (EmitContext ec)
6607 return DoResolveType (ec);
6610 public override void Emit (EmitContext ec)
6612 throw new Exception ("This should never be called");
6615 public override string ToString ()
6622 // This class is used to represent the address of an array, used
6623 // only by the Fixed statement, this is like the C "&a [0]" construct.
6625 public class ArrayPtr : Expression {
6628 public ArrayPtr (Expression array, Location l)
6630 Type array_type = array.Type.GetElementType ();
6634 string array_ptr_type_name = array_type.FullName + "*";
6636 type = Type.GetType (array_ptr_type_name);
6638 ModuleBuilder mb = CodeGen.ModuleBuilder;
6640 type = mb.GetType (array_ptr_type_name);
6643 eclass = ExprClass.Value;
6647 public override void Emit (EmitContext ec)
6649 ILGenerator ig = ec.ig;
6652 IntLiteral.EmitInt (ig, 0);
6653 ig.Emit (OpCodes.Ldelema, array.Type.GetElementType ());
6656 public override Expression DoResolve (EmitContext ec)
6659 // We are born fully resolved
6666 // Used by the fixed statement
6668 public class StringPtr : Expression {
6671 public StringPtr (LocalBuilder b, Location l)
6674 eclass = ExprClass.Value;
6675 type = TypeManager.char_ptr_type;
6679 public override Expression DoResolve (EmitContext ec)
6681 // This should never be invoked, we are born in fully
6682 // initialized state.
6687 public override void Emit (EmitContext ec)
6689 ILGenerator ig = ec.ig;
6691 ig.Emit (OpCodes.Ldloc, b);
6692 ig.Emit (OpCodes.Conv_I);
6693 ig.Emit (OpCodes.Call, TypeManager.int_get_offset_to_string_data);
6694 ig.Emit (OpCodes.Add);
6699 // Implements the `stackalloc' keyword
6701 public class StackAlloc : Expression {
6706 public StackAlloc (Expression type, Expression count, Location l)
6713 public override Expression DoResolve (EmitContext ec)
6715 count = count.Resolve (ec);
6719 if (count.Type != TypeManager.int32_type){
6720 count = ConvertImplicitRequired (ec, count, TypeManager.int32_type, loc);
6725 if (ec.InCatch || ec.InFinally){
6727 "stackalloc can not be used in a catch or finally block");
6731 otype = ec.DeclSpace.ResolveType (t, false, loc);
6736 if (!TypeManager.VerifyUnManaged (otype, loc))
6739 string ptr_name = otype.FullName + "*";
6740 type = Type.GetType (ptr_name);
6742 ModuleBuilder mb = CodeGen.ModuleBuilder;
6744 type = mb.GetType (ptr_name);
6746 eclass = ExprClass.Value;
6751 public override void Emit (EmitContext ec)
6753 int size = GetTypeSize (otype);
6754 ILGenerator ig = ec.ig;
6757 ig.Emit (OpCodes.Sizeof, otype);
6759 IntConstant.EmitInt (ig, size);
6761 ig.Emit (OpCodes.Mul);
6762 ig.Emit (OpCodes.Localloc);