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)
34 eclass = ExprClass.Value;
37 public override Expression DoResolve (EmitContext ec)
40 // We are born fully resolved
45 public override void Emit (EmitContext ec)
48 Invocation.EmitArguments (ec, mi, args);
50 ec.ig.Emit (OpCodes.Call, mi);
54 static public Expression MakeSimpleCall (EmitContext ec, MethodGroupExpr mg,
55 Expression e, Location loc)
60 args = new ArrayList (1);
61 args.Add (new Argument (e, Argument.AType.Expression));
62 method = Invocation.OverloadResolve (ec, (MethodGroupExpr) mg, args, loc);
67 return new StaticCallExpr ((MethodInfo) method, args);
70 public override void EmitStatement (EmitContext ec)
73 if (type != TypeManager.void_type)
74 ec.ig.Emit (OpCodes.Pop);
79 /// Unary expressions.
83 /// Unary implements unary expressions. It derives from
84 /// ExpressionStatement becuase the pre/post increment/decrement
85 /// operators can be used in a statement context.
87 public class Unary : Expression {
88 public enum Operator : byte {
89 UnaryPlus, UnaryNegation, LogicalNot, OnesComplement,
90 Indirection, AddressOf, TOP
94 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, loc, "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 (Expression 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);
190 Expression Reduce (EmitContext ec, Expression e)
192 Type expr_type = e.Type;
195 case Operator.UnaryPlus:
198 case Operator.UnaryNegation:
199 return TryReduceNegative (e);
201 case Operator.LogicalNot:
202 if (expr_type != TypeManager.bool_type) {
207 BoolConstant b = (BoolConstant) e;
208 return new BoolConstant (!(b.Value));
210 case Operator.OnesComplement:
211 if (!((expr_type == TypeManager.int32_type) ||
212 (expr_type == TypeManager.uint32_type) ||
213 (expr_type == TypeManager.int64_type) ||
214 (expr_type == TypeManager.uint64_type) ||
215 (expr_type.IsSubclassOf (TypeManager.enum_type)))){
220 if (e is EnumConstant){
221 EnumConstant enum_constant = (EnumConstant) e;
223 Expression reduced = Reduce (ec, enum_constant.Child);
225 return new EnumConstant ((Constant) reduced, enum_constant.Type);
228 if (expr_type == TypeManager.int32_type)
229 return new IntConstant (~ ((IntConstant) e).Value);
230 if (expr_type == TypeManager.uint32_type)
231 return new UIntConstant (~ ((UIntConstant) e).Value);
232 if (expr_type == TypeManager.int64_type)
233 return new LongConstant (~ ((LongConstant) e).Value);
234 if (expr_type == TypeManager.uint64_type)
235 return new ULongConstant (~ ((ULongConstant) e).Value);
240 throw new Exception ("Can not constant fold");
243 Expression ResolveOperator (EmitContext ec)
245 Type expr_type = Expr.Type;
248 // Step 1: Perform Operator Overload location
253 op_name = oper_names [(int) Oper];
255 mg = MemberLookup (ec, expr_type, op_name, MemberTypes.Method, AllBindingFlags, loc);
258 Expression e = StaticCallExpr.MakeSimpleCall (
259 ec, (MethodGroupExpr) mg, Expr, loc);
269 // Only perform numeric promotions on:
272 if (expr_type == null)
276 // Step 2: Default operations on CLI native types.
278 if (Expr is Constant)
279 return Reduce (ec, Expr);
281 if (Oper == Operator.LogicalNot){
282 if (expr_type != TypeManager.bool_type) {
287 type = TypeManager.bool_type;
291 if (Oper == Operator.OnesComplement) {
292 if (!((expr_type == TypeManager.int32_type) ||
293 (expr_type == TypeManager.uint32_type) ||
294 (expr_type == TypeManager.int64_type) ||
295 (expr_type == TypeManager.uint64_type) ||
296 (expr_type.IsSubclassOf (TypeManager.enum_type)))){
299 e = ConvertImplicit (ec, Expr, TypeManager.int32_type, loc);
301 type = TypeManager.int32_type;
304 e = ConvertImplicit (ec, Expr, TypeManager.uint32_type, loc);
306 type = TypeManager.uint32_type;
309 e = ConvertImplicit (ec, Expr, TypeManager.int64_type, loc);
311 type = TypeManager.int64_type;
314 e = ConvertImplicit (ec, Expr, TypeManager.uint64_type, loc);
316 type = TypeManager.uint64_type;
326 if (Oper == Operator.UnaryPlus) {
328 // A plus in front of something is just a no-op, so return the child.
334 // Deals with -literals
335 // int operator- (int x)
336 // long operator- (long x)
337 // float operator- (float f)
338 // double operator- (double d)
339 // decimal operator- (decimal d)
341 if (Oper == Operator.UnaryNegation){
345 // transform - - expr into expr
348 Unary unary = (Unary) Expr;
350 if (unary.Oper == Operator.UnaryNegation)
355 // perform numeric promotions to int,
359 // The following is inneficient, because we call
360 // ConvertImplicit too many times.
362 // It is also not clear if we should convert to Float
363 // or Double initially.
365 if (expr_type == TypeManager.uint32_type){
367 // FIXME: handle exception to this rule that
368 // permits the int value -2147483648 (-2^31) to
369 // bt wrote as a decimal interger literal
371 type = TypeManager.int64_type;
372 Expr = ConvertImplicit (ec, Expr, type, loc);
376 if (expr_type == TypeManager.uint64_type){
378 // FIXME: Handle exception of `long value'
379 // -92233720368547758087 (-2^63) to be wrote as
380 // decimal integer literal.
386 if (expr_type == TypeManager.float_type){
391 e = ConvertImplicit (ec, Expr, TypeManager.int32_type, loc);
398 e = ConvertImplicit (ec, Expr, TypeManager.int64_type, loc);
405 e = ConvertImplicit (ec, Expr, TypeManager.double_type, loc);
416 if (Oper == Operator.AddressOf){
417 if (Expr.eclass != ExprClass.Variable){
418 Error (211, loc, "Cannot take the address of non-variables");
427 if (!TypeManager.VerifyUnManaged (Expr.Type, loc)){
431 string ptr_type_name = Expr.Type.FullName + "*";
432 type = TypeManager.LookupType (ptr_type_name);
437 if (Oper == Operator.Indirection){
443 if (!expr_type.IsPointer){
446 "The * or -> operator can only be applied to pointers");
451 // We create an Indirection expression, because
452 // it can implement the IMemoryLocation.
454 return new Indirection (Expr);
457 Error (187, loc, "No such operator '" + OperName (Oper) + "' defined for type '" +
458 TypeManager.CSharpName (expr_type) + "'");
462 public override Expression DoResolve (EmitContext ec)
464 Expr = Expr.Resolve (ec);
469 eclass = ExprClass.Value;
470 return ResolveOperator (ec);
473 public override void Emit (EmitContext ec)
475 ILGenerator ig = ec.ig;
476 Type expr_type = Expr.Type;
479 case Operator.UnaryPlus:
480 throw new Exception ("This should be caught by Resolve");
482 case Operator.UnaryNegation:
484 ig.Emit (OpCodes.Neg);
487 case Operator.LogicalNot:
489 ig.Emit (OpCodes.Ldc_I4_0);
490 ig.Emit (OpCodes.Ceq);
493 case Operator.OnesComplement:
495 ig.Emit (OpCodes.Not);
498 case Operator.AddressOf:
499 ((IMemoryLocation)Expr).AddressOf (ec, AddressOp.LoadStore);
503 throw new Exception ("This should not happen: Operator = "
509 /// This will emit the child expression for `ec' avoiding the logical
510 /// not. The parent will take care of changing brfalse/brtrue
512 public void EmitLogicalNot (EmitContext ec)
514 if (Oper != Operator.LogicalNot)
515 throw new Exception ("EmitLogicalNot can only be called with !expr");
520 public override string ToString ()
522 return "Unary (" + Oper + ", " + Expr + ")";
528 // Unary operators are turned into Indirection expressions
529 // after semantic analysis (this is so we can take the address
530 // of an indirection).
532 public class Indirection : Expression, IMemoryLocation, IAssignMethod {
534 LocalTemporary temporary;
537 public Indirection (Expression expr)
540 this.type = expr.Type.GetElementType ();
541 eclass = ExprClass.Variable;
544 void LoadExprValue (EmitContext ec)
548 public override void Emit (EmitContext ec)
550 ILGenerator ig = ec.ig;
552 if (temporary != null){
558 ec.ig.Emit (OpCodes.Dup);
559 temporary.Store (ec);
560 have_temporary = true;
564 LoadFromPtr (ig, Type);
567 public void EmitAssign (EmitContext ec, Expression source)
569 if (temporary != null){
575 ec.ig.Emit (OpCodes.Dup);
576 temporary.Store (ec);
577 have_temporary = true;
582 StoreFromPtr (ec.ig, type);
585 public void AddressOf (EmitContext ec, AddressOp Mode)
587 if (temporary != null){
593 ec.ig.Emit (OpCodes.Dup);
594 temporary.Store (ec);
595 have_temporary = true;
600 public override Expression DoResolve (EmitContext ec)
603 // Born fully resolved
608 public new void CacheTemporaries (EmitContext ec)
610 temporary = new LocalTemporary (ec, type);
615 /// Unary Mutator expressions (pre and post ++ and --)
619 /// UnaryMutator implements ++ and -- expressions. It derives from
620 /// ExpressionStatement becuase the pre/post increment/decrement
621 /// operators can be used in a statement context.
623 /// FIXME: Idea, we could split this up in two classes, one simpler
624 /// for the common case, and one with the extra fields for more complex
625 /// classes (indexers require temporary access; overloaded require method)
627 /// Maybe we should have classes PreIncrement, PostIncrement, PreDecrement,
628 /// PostDecrement, that way we could save the `Mode' byte as well.
630 public class UnaryMutator : ExpressionStatement {
631 public enum Mode : byte {
632 PreIncrement, PreDecrement, PostIncrement, PostDecrement
638 LocalTemporary temp_storage;
641 // This is expensive for the simplest case.
645 public UnaryMutator (Mode m, Expression e, Location l)
652 static string OperName (Mode mode)
654 return (mode == Mode.PreIncrement || mode == Mode.PostIncrement) ?
658 void Error23 (Type t)
661 23, loc, "Operator " + OperName (mode) +
662 " cannot be applied to operand of type `" +
663 TypeManager.CSharpName (t) + "'");
667 /// Returns whether an object of type `t' can be incremented
668 /// or decremented with add/sub (ie, basically whether we can
669 /// use pre-post incr-decr operations on it, but it is not a
670 /// System.Decimal, which we require operator overloading to catch)
672 static bool IsIncrementableNumber (Type t)
674 return (t == TypeManager.sbyte_type) ||
675 (t == TypeManager.byte_type) ||
676 (t == TypeManager.short_type) ||
677 (t == TypeManager.ushort_type) ||
678 (t == TypeManager.int32_type) ||
679 (t == TypeManager.uint32_type) ||
680 (t == TypeManager.int64_type) ||
681 (t == TypeManager.uint64_type) ||
682 (t == TypeManager.char_type) ||
683 (t.IsSubclassOf (TypeManager.enum_type)) ||
684 (t == TypeManager.float_type) ||
685 (t == TypeManager.double_type) ||
686 (t.IsPointer && t != TypeManager.void_ptr_type);
689 Expression ResolveOperator (EmitContext ec)
691 Type expr_type = expr.Type;
694 // Step 1: Perform Operator Overload location
699 if (mode == Mode.PreIncrement || mode == Mode.PostIncrement)
700 op_name = "op_Increment";
702 op_name = "op_Decrement";
704 mg = MemberLookup (ec, expr_type, op_name, MemberTypes.Method, AllBindingFlags, loc);
706 if (mg == null && expr_type.BaseType != null)
707 mg = MemberLookup (ec, expr_type.BaseType, op_name,
708 MemberTypes.Method, AllBindingFlags, loc);
711 method = StaticCallExpr.MakeSimpleCall (
712 ec, (MethodGroupExpr) mg, expr, loc);
719 // The operand of the prefix/postfix increment decrement operators
720 // should be an expression that is classified as a variable,
721 // a property access or an indexer access
724 if (expr.eclass == ExprClass.Variable){
725 if (IsIncrementableNumber (expr_type) ||
726 expr_type == TypeManager.decimal_type){
729 } else if (expr.eclass == ExprClass.IndexerAccess){
730 IndexerAccess ia = (IndexerAccess) expr;
732 temp_storage = new LocalTemporary (ec, expr.Type);
734 expr = ia.ResolveLValue (ec, temp_storage);
739 } else if (expr.eclass == ExprClass.PropertyAccess){
740 PropertyExpr pe = (PropertyExpr) expr;
742 if (pe.VerifyAssignable ())
747 report118 (loc, expr, "variable, indexer or property access");
751 Error (187, loc, "No such operator '" + OperName (mode) + "' defined for type '" +
752 TypeManager.CSharpName (expr_type) + "'");
756 public override Expression DoResolve (EmitContext ec)
758 expr = expr.Resolve (ec);
763 eclass = ExprClass.Value;
764 return ResolveOperator (ec);
767 static int PtrTypeSize (Type t)
769 return GetTypeSize (t.GetElementType ());
773 // Loads the proper "1" into the stack based on the type
775 static void LoadOne (ILGenerator ig, Type t)
777 if (t == TypeManager.uint64_type || t == TypeManager.int64_type)
778 ig.Emit (OpCodes.Ldc_I8, 1L);
779 else if (t == TypeManager.double_type)
780 ig.Emit (OpCodes.Ldc_R8, 1.0);
781 else if (t == TypeManager.float_type)
782 ig.Emit (OpCodes.Ldc_R4, 1.0F);
783 else if (t.IsPointer){
784 int n = PtrTypeSize (t);
787 ig.Emit (OpCodes.Sizeof, t);
789 IntConstant.EmitInt (ig, n);
791 ig.Emit (OpCodes.Ldc_I4_1);
796 // FIXME: We need some way of avoiding the use of temp_storage
797 // for some types of storage (parameters, local variables,
798 // static fields) and single-dimension array access.
800 void EmitCode (EmitContext ec, bool is_expr)
802 ILGenerator ig = ec.ig;
803 IAssignMethod ia = (IAssignMethod) expr;
804 Type expr_type = expr.Type;
806 if (temp_storage == null)
807 temp_storage = new LocalTemporary (ec, expr_type);
809 ia.CacheTemporaries (ec);
810 ig.Emit (OpCodes.Nop);
812 case Mode.PreIncrement:
813 case Mode.PreDecrement:
817 LoadOne (ig, expr_type);
820 // Select the opcode based on the check state (then the type)
821 // and the actual operation
824 if (expr_type == TypeManager.int32_type ||
825 expr_type == TypeManager.int64_type){
826 if (mode == Mode.PreDecrement)
827 ig.Emit (OpCodes.Sub_Ovf);
829 ig.Emit (OpCodes.Add_Ovf);
830 } else if (expr_type == TypeManager.uint32_type ||
831 expr_type == TypeManager.uint64_type){
832 if (mode == Mode.PreDecrement)
833 ig.Emit (OpCodes.Sub_Ovf_Un);
835 ig.Emit (OpCodes.Add_Ovf_Un);
837 if (mode == Mode.PreDecrement)
838 ig.Emit (OpCodes.Sub_Ovf);
840 ig.Emit (OpCodes.Add_Ovf);
843 if (mode == Mode.PreDecrement)
844 ig.Emit (OpCodes.Sub);
846 ig.Emit (OpCodes.Add);
851 temp_storage.Store (ec);
852 ia.EmitAssign (ec, temp_storage);
854 temp_storage.Emit (ec);
857 case Mode.PostIncrement:
858 case Mode.PostDecrement:
866 ig.Emit (OpCodes.Dup);
868 LoadOne (ig, expr_type);
871 if (expr_type == TypeManager.int32_type ||
872 expr_type == TypeManager.int64_type){
873 if (mode == Mode.PostDecrement)
874 ig.Emit (OpCodes.Sub_Ovf);
876 ig.Emit (OpCodes.Add_Ovf);
877 } else if (expr_type == TypeManager.uint32_type ||
878 expr_type == TypeManager.uint64_type){
879 if (mode == Mode.PostDecrement)
880 ig.Emit (OpCodes.Sub_Ovf_Un);
882 ig.Emit (OpCodes.Add_Ovf_Un);
884 if (mode == Mode.PostDecrement)
885 ig.Emit (OpCodes.Sub_Ovf);
887 ig.Emit (OpCodes.Add_Ovf);
890 if (mode == Mode.PostDecrement)
891 ig.Emit (OpCodes.Sub);
893 ig.Emit (OpCodes.Add);
899 temp_storage.Store (ec);
900 ia.EmitAssign (ec, temp_storage);
905 public override void Emit (EmitContext ec)
911 public override void EmitStatement (EmitContext ec)
913 EmitCode (ec, false);
919 /// Base class for the `Is' and `As' classes.
923 /// FIXME: Split this in two, and we get to save the `Operator' Oper
926 public abstract class Probe : Expression {
927 public readonly string ProbeType;
928 protected Expression expr;
929 protected Type probe_type;
930 protected Location loc;
932 public Probe (Expression expr, string probe_type, Location l)
934 ProbeType = probe_type;
939 public Expression Expr {
945 public override Expression DoResolve (EmitContext ec)
947 probe_type = RootContext.LookupType (ec.DeclSpace, ProbeType, false, loc);
949 if (probe_type == null)
952 expr = expr.Resolve (ec);
959 /// Implementation of the `is' operator.
961 public class Is : Probe {
962 public Is (Expression expr, string probe_type, Location l)
963 : base (expr, probe_type, l)
968 AlwaysTrue, AlwaysNull, AlwaysFalse, LeaveOnStack, Probe
973 public override void Emit (EmitContext ec)
975 ILGenerator ig = ec.ig;
980 case Action.AlwaysFalse:
981 ig.Emit (OpCodes.Pop);
982 IntConstant.EmitInt (ig, 0);
984 case Action.AlwaysTrue:
985 ig.Emit (OpCodes.Pop);
986 ig.Emit (OpCodes.Nop);
987 IntConstant.EmitInt (ig, 1);
989 case Action.LeaveOnStack:
990 // the `e != null' rule.
993 ig.Emit (OpCodes.Isinst, probe_type);
994 ig.Emit (OpCodes.Ldnull);
995 ig.Emit (OpCodes.Cgt_Un);
998 throw new Exception ("never reached");
1001 public override Expression DoResolve (EmitContext ec)
1003 Expression e = base.DoResolve (ec);
1008 Type etype = expr.Type;
1009 bool warning_always_matches = false;
1010 bool warning_never_matches = false;
1012 type = TypeManager.bool_type;
1013 eclass = ExprClass.Value;
1016 // First case, if at compile time, there is an implicit conversion
1017 // then e != null (objects) or true (value types)
1019 e = ConvertImplicitStandard (ec, expr, probe_type, loc);
1022 if (etype.IsValueType)
1023 action = Action.AlwaysTrue;
1025 action = Action.LeaveOnStack;
1027 warning_always_matches = true;
1028 } else if (ExplicitReferenceConversionExists (etype, probe_type)){
1030 // Second case: explicit reference convresion
1032 if (expr is NullLiteral)
1033 action = Action.AlwaysFalse;
1035 action = Action.Probe;
1037 action = Action.AlwaysFalse;
1038 warning_never_matches = true;
1041 if (RootContext.WarningLevel >= 1){
1042 if (warning_always_matches)
1045 "The expression is always of type `" +
1046 TypeManager.CSharpName (probe_type) + "'");
1047 else if (warning_never_matches){
1048 if (!(probe_type.IsInterface || expr.Type.IsInterface))
1051 "The expression is never of type `" +
1052 TypeManager.CSharpName (probe_type) + "'");
1061 /// Implementation of the `as' operator.
1063 public class As : Probe {
1064 public As (Expression expr, string probe_type, Location l)
1065 : base (expr, probe_type, l)
1069 bool do_isinst = false;
1071 public override void Emit (EmitContext ec)
1073 ILGenerator ig = ec.ig;
1078 ig.Emit (OpCodes.Isinst, probe_type);
1081 static void Error_CannotConvertType (Type source, Type target, Location loc)
1084 39, loc, "as operator can not convert from `" +
1085 TypeManager.CSharpName (source) + "' to `" +
1086 TypeManager.CSharpName (target) + "'");
1089 public override Expression DoResolve (EmitContext ec)
1091 Expression e = base.DoResolve (ec);
1097 eclass = ExprClass.Value;
1098 Type etype = expr.Type;
1100 e = ConvertImplicit (ec, expr, probe_type, loc);
1107 if (ExplicitReferenceConversionExists (etype, probe_type)){
1112 Error_CannotConvertType (etype, probe_type, loc);
1118 /// This represents a typecast in the source language.
1120 /// FIXME: Cast expressions have an unusual set of parsing
1121 /// rules, we need to figure those out.
1123 public class Cast : Expression {
1124 Expression target_type;
1128 public Cast (Expression cast_type, Expression expr, Location loc)
1130 this.target_type = cast_type;
1135 public Expression TargetType {
1141 public Expression Expr {
1151 /// Attempts to do a compile-time folding of a constant cast.
1153 Expression TryReduce (EmitContext ec, Type target_type)
1155 if (expr is ByteConstant){
1156 byte v = ((ByteConstant) expr).Value;
1158 if (target_type == TypeManager.sbyte_type)
1159 return new SByteConstant ((sbyte) v);
1160 if (target_type == TypeManager.short_type)
1161 return new ShortConstant ((short) v);
1162 if (target_type == TypeManager.ushort_type)
1163 return new UShortConstant ((ushort) v);
1164 if (target_type == TypeManager.int32_type)
1165 return new IntConstant ((int) v);
1166 if (target_type == TypeManager.uint32_type)
1167 return new UIntConstant ((uint) v);
1168 if (target_type == TypeManager.int64_type)
1169 return new LongConstant ((long) v);
1170 if (target_type == TypeManager.uint64_type)
1171 return new ULongConstant ((ulong) v);
1172 if (target_type == TypeManager.float_type)
1173 return new FloatConstant ((float) v);
1174 if (target_type == TypeManager.double_type)
1175 return new DoubleConstant ((double) v);
1176 if (target_type == TypeManager.char_type)
1177 return new CharConstant ((char) v);
1179 if (expr is SByteConstant){
1180 sbyte v = ((SByteConstant) expr).Value;
1182 if (target_type == TypeManager.byte_type)
1183 return new ByteConstant ((byte) v);
1184 if (target_type == TypeManager.short_type)
1185 return new ShortConstant ((short) v);
1186 if (target_type == TypeManager.ushort_type)
1187 return new UShortConstant ((ushort) v);
1188 if (target_type == TypeManager.int32_type)
1189 return new IntConstant ((int) v);
1190 if (target_type == TypeManager.uint32_type)
1191 return new UIntConstant ((uint) v);
1192 if (target_type == TypeManager.int64_type)
1193 return new LongConstant ((long) v);
1194 if (target_type == TypeManager.uint64_type)
1195 return new ULongConstant ((ulong) v);
1196 if (target_type == TypeManager.float_type)
1197 return new FloatConstant ((float) v);
1198 if (target_type == TypeManager.double_type)
1199 return new DoubleConstant ((double) v);
1200 if (target_type == TypeManager.char_type)
1201 return new CharConstant ((char) v);
1203 if (expr is ShortConstant){
1204 short v = ((ShortConstant) expr).Value;
1206 if (target_type == TypeManager.byte_type)
1207 return new ByteConstant ((byte) v);
1208 if (target_type == TypeManager.sbyte_type)
1209 return new SByteConstant ((sbyte) v);
1210 if (target_type == TypeManager.ushort_type)
1211 return new UShortConstant ((ushort) v);
1212 if (target_type == TypeManager.int32_type)
1213 return new IntConstant ((int) v);
1214 if (target_type == TypeManager.uint32_type)
1215 return new UIntConstant ((uint) v);
1216 if (target_type == TypeManager.int64_type)
1217 return new LongConstant ((long) v);
1218 if (target_type == TypeManager.uint64_type)
1219 return new ULongConstant ((ulong) v);
1220 if (target_type == TypeManager.float_type)
1221 return new FloatConstant ((float) v);
1222 if (target_type == TypeManager.double_type)
1223 return new DoubleConstant ((double) v);
1224 if (target_type == TypeManager.char_type)
1225 return new CharConstant ((char) v);
1227 if (expr is UShortConstant){
1228 ushort v = ((UShortConstant) expr).Value;
1230 if (target_type == TypeManager.byte_type)
1231 return new ByteConstant ((byte) v);
1232 if (target_type == TypeManager.sbyte_type)
1233 return new SByteConstant ((sbyte) v);
1234 if (target_type == TypeManager.short_type)
1235 return new ShortConstant ((short) v);
1236 if (target_type == TypeManager.int32_type)
1237 return new IntConstant ((int) v);
1238 if (target_type == TypeManager.uint32_type)
1239 return new UIntConstant ((uint) v);
1240 if (target_type == TypeManager.int64_type)
1241 return new LongConstant ((long) v);
1242 if (target_type == TypeManager.uint64_type)
1243 return new ULongConstant ((ulong) v);
1244 if (target_type == TypeManager.float_type)
1245 return new FloatConstant ((float) v);
1246 if (target_type == TypeManager.double_type)
1247 return new DoubleConstant ((double) v);
1248 if (target_type == TypeManager.char_type)
1249 return new CharConstant ((char) v);
1251 if (expr is IntConstant){
1252 int v = ((IntConstant) expr).Value;
1254 if (target_type == TypeManager.byte_type)
1255 return new ByteConstant ((byte) v);
1256 if (target_type == TypeManager.sbyte_type)
1257 return new SByteConstant ((sbyte) v);
1258 if (target_type == TypeManager.short_type)
1259 return new ShortConstant ((short) v);
1260 if (target_type == TypeManager.ushort_type)
1261 return new UShortConstant ((ushort) v);
1262 if (target_type == TypeManager.uint32_type)
1263 return new UIntConstant ((uint) v);
1264 if (target_type == TypeManager.int64_type)
1265 return new LongConstant ((long) v);
1266 if (target_type == TypeManager.uint64_type)
1267 return new ULongConstant ((ulong) v);
1268 if (target_type == TypeManager.float_type)
1269 return new FloatConstant ((float) v);
1270 if (target_type == TypeManager.double_type)
1271 return new DoubleConstant ((double) v);
1272 if (target_type == TypeManager.char_type)
1273 return new CharConstant ((char) v);
1275 if (expr is UIntConstant){
1276 uint v = ((UIntConstant) expr).Value;
1278 if (target_type == TypeManager.byte_type)
1279 return new ByteConstant ((byte) v);
1280 if (target_type == TypeManager.sbyte_type)
1281 return new SByteConstant ((sbyte) v);
1282 if (target_type == TypeManager.short_type)
1283 return new ShortConstant ((short) v);
1284 if (target_type == TypeManager.ushort_type)
1285 return new UShortConstant ((ushort) v);
1286 if (target_type == TypeManager.int32_type)
1287 return new IntConstant ((int) v);
1288 if (target_type == TypeManager.int64_type)
1289 return new LongConstant ((long) v);
1290 if (target_type == TypeManager.uint64_type)
1291 return new ULongConstant ((ulong) v);
1292 if (target_type == TypeManager.float_type)
1293 return new FloatConstant ((float) v);
1294 if (target_type == TypeManager.double_type)
1295 return new DoubleConstant ((double) v);
1296 if (target_type == TypeManager.char_type)
1297 return new CharConstant ((char) v);
1299 if (expr is LongConstant){
1300 long v = ((LongConstant) expr).Value;
1302 if (target_type == TypeManager.byte_type)
1303 return new ByteConstant ((byte) v);
1304 if (target_type == TypeManager.sbyte_type)
1305 return new SByteConstant ((sbyte) v);
1306 if (target_type == TypeManager.short_type)
1307 return new ShortConstant ((short) v);
1308 if (target_type == TypeManager.ushort_type)
1309 return new UShortConstant ((ushort) v);
1310 if (target_type == TypeManager.int32_type)
1311 return new IntConstant ((int) v);
1312 if (target_type == TypeManager.uint32_type)
1313 return new UIntConstant ((uint) v);
1314 if (target_type == TypeManager.uint64_type)
1315 return new ULongConstant ((ulong) v);
1316 if (target_type == TypeManager.float_type)
1317 return new FloatConstant ((float) v);
1318 if (target_type == TypeManager.double_type)
1319 return new DoubleConstant ((double) v);
1320 if (target_type == TypeManager.char_type)
1321 return new CharConstant ((char) v);
1323 if (expr is ULongConstant){
1324 ulong v = ((ULongConstant) expr).Value;
1326 if (target_type == TypeManager.byte_type)
1327 return new ByteConstant ((byte) v);
1328 if (target_type == TypeManager.sbyte_type)
1329 return new SByteConstant ((sbyte) v);
1330 if (target_type == TypeManager.short_type)
1331 return new ShortConstant ((short) v);
1332 if (target_type == TypeManager.ushort_type)
1333 return new UShortConstant ((ushort) v);
1334 if (target_type == TypeManager.int32_type)
1335 return new IntConstant ((int) v);
1336 if (target_type == TypeManager.uint32_type)
1337 return new UIntConstant ((uint) v);
1338 if (target_type == TypeManager.int64_type)
1339 return new LongConstant ((long) v);
1340 if (target_type == TypeManager.float_type)
1341 return new FloatConstant ((float) v);
1342 if (target_type == TypeManager.double_type)
1343 return new DoubleConstant ((double) v);
1344 if (target_type == TypeManager.char_type)
1345 return new CharConstant ((char) v);
1347 if (expr is FloatConstant){
1348 float v = ((FloatConstant) expr).Value;
1350 if (target_type == TypeManager.byte_type)
1351 return new ByteConstant ((byte) v);
1352 if (target_type == TypeManager.sbyte_type)
1353 return new SByteConstant ((sbyte) v);
1354 if (target_type == TypeManager.short_type)
1355 return new ShortConstant ((short) v);
1356 if (target_type == TypeManager.ushort_type)
1357 return new UShortConstant ((ushort) v);
1358 if (target_type == TypeManager.int32_type)
1359 return new IntConstant ((int) v);
1360 if (target_type == TypeManager.uint32_type)
1361 return new UIntConstant ((uint) v);
1362 if (target_type == TypeManager.int64_type)
1363 return new LongConstant ((long) v);
1364 if (target_type == TypeManager.uint64_type)
1365 return new ULongConstant ((ulong) v);
1366 if (target_type == TypeManager.double_type)
1367 return new DoubleConstant ((double) v);
1368 if (target_type == TypeManager.char_type)
1369 return new CharConstant ((char) v);
1371 if (expr is DoubleConstant){
1372 double v = ((DoubleConstant) expr).Value;
1374 if (target_type == TypeManager.byte_type)
1375 return new ByteConstant ((byte) v);
1376 if (target_type == TypeManager.sbyte_type)
1377 return new SByteConstant ((sbyte) v);
1378 if (target_type == TypeManager.short_type)
1379 return new ShortConstant ((short) v);
1380 if (target_type == TypeManager.ushort_type)
1381 return new UShortConstant ((ushort) v);
1382 if (target_type == TypeManager.int32_type)
1383 return new IntConstant ((int) v);
1384 if (target_type == TypeManager.uint32_type)
1385 return new UIntConstant ((uint) v);
1386 if (target_type == TypeManager.int64_type)
1387 return new LongConstant ((long) v);
1388 if (target_type == TypeManager.uint64_type)
1389 return new ULongConstant ((ulong) v);
1390 if (target_type == TypeManager.float_type)
1391 return new FloatConstant ((float) v);
1392 if (target_type == TypeManager.char_type)
1393 return new CharConstant ((char) v);
1399 public override Expression DoResolve (EmitContext ec)
1401 expr = expr.Resolve (ec);
1405 bool old_state = ec.OnlyLookupTypes;
1406 ec.OnlyLookupTypes = true;
1407 target_type = target_type.Resolve (ec);
1408 ec.OnlyLookupTypes = old_state;
1410 if (target_type == null){
1411 Report.Error (-10, loc, "Can not resolve type");
1415 if (target_type.eclass != ExprClass.Type){
1416 report118 (loc, target_type, "class");
1420 type = target_type.Type;
1421 eclass = ExprClass.Value;
1426 if (expr is Constant){
1427 Expression e = TryReduce (ec, type);
1433 expr = ConvertExplicit (ec, expr, type, loc);
1437 public override void Emit (EmitContext ec)
1440 // This one will never happen
1442 throw new Exception ("Should not happen");
1447 /// Binary operators
1449 public class Binary : Expression {
1450 public enum Operator : byte {
1451 Multiply, Division, Modulus,
1452 Addition, Subtraction,
1453 LeftShift, RightShift,
1454 LessThan, GreaterThan, LessThanOrEqual, GreaterThanOrEqual,
1455 Equality, Inequality,
1465 Expression left, right;
1468 // After resolution, method might contain the operator overload
1471 protected MethodBase method;
1472 ArrayList Arguments;
1476 bool DelegateOperation;
1478 // This must be kept in sync with Operator!!!
1479 static string [] oper_names;
1483 oper_names = new string [(int) Operator.TOP];
1485 oper_names [(int) Operator.Multiply] = "op_Multiply";
1486 oper_names [(int) Operator.Division] = "op_Division";
1487 oper_names [(int) Operator.Modulus] = "op_Modulus";
1488 oper_names [(int) Operator.Addition] = "op_Addition";
1489 oper_names [(int) Operator.Subtraction] = "op_Subtraction";
1490 oper_names [(int) Operator.LeftShift] = "op_LeftShift";
1491 oper_names [(int) Operator.RightShift] = "op_RightShift";
1492 oper_names [(int) Operator.LessThan] = "op_LessThan";
1493 oper_names [(int) Operator.GreaterThan] = "op_GreaterThan";
1494 oper_names [(int) Operator.LessThanOrEqual] = "op_LessThanOrEqual";
1495 oper_names [(int) Operator.GreaterThanOrEqual] = "op_GreaterThanOrEqual";
1496 oper_names [(int) Operator.Equality] = "op_Equality";
1497 oper_names [(int) Operator.Inequality] = "op_Inequality";
1498 oper_names [(int) Operator.BitwiseAnd] = "op_BitwiseAnd";
1499 oper_names [(int) Operator.BitwiseOr] = "op_BitwiseOr";
1500 oper_names [(int) Operator.ExclusiveOr] = "op_ExclusiveOr";
1501 oper_names [(int) Operator.LogicalOr] = "op_LogicalOr";
1502 oper_names [(int) Operator.LogicalAnd] = "op_LogicalAnd";
1505 public Binary (Operator oper, Expression left, Expression right, Location loc)
1513 public Operator Oper {
1522 public Expression Left {
1531 public Expression Right {
1542 /// Returns a stringified representation of the Operator
1544 static string OperName (Operator oper)
1547 case Operator.Multiply:
1549 case Operator.Division:
1551 case Operator.Modulus:
1553 case Operator.Addition:
1555 case Operator.Subtraction:
1557 case Operator.LeftShift:
1559 case Operator.RightShift:
1561 case Operator.LessThan:
1563 case Operator.GreaterThan:
1565 case Operator.LessThanOrEqual:
1567 case Operator.GreaterThanOrEqual:
1569 case Operator.Equality:
1571 case Operator.Inequality:
1573 case Operator.BitwiseAnd:
1575 case Operator.BitwiseOr:
1577 case Operator.ExclusiveOr:
1579 case Operator.LogicalOr:
1581 case Operator.LogicalAnd:
1585 return oper.ToString ();
1588 public override string ToString ()
1590 return "operator " + OperName (oper) + "(" + left.ToString () + ", " +
1591 right.ToString () + ")";
1594 Expression ForceConversion (EmitContext ec, Expression expr, Type target_type)
1596 if (expr.Type == target_type)
1599 return ConvertImplicit (ec, expr, target_type, new Location (-1));
1602 public static void Error_OperatorAmbiguous (Location loc, Operator oper, Type l, Type r)
1605 34, loc, "Operator `" + OperName (oper)
1606 + "' is ambiguous on operands of type `"
1607 + TypeManager.CSharpName (l) + "' "
1608 + "and `" + TypeManager.CSharpName (r)
1613 // Note that handling the case l == Decimal || r == Decimal
1614 // is taken care of by the Step 1 Operator Overload resolution.
1616 bool DoNumericPromotions (EmitContext ec, Type l, Type r)
1618 if (l == TypeManager.double_type || r == TypeManager.double_type){
1620 // If either operand is of type double, the other operand is
1621 // conveted to type double.
1623 if (r != TypeManager.double_type)
1624 right = ConvertImplicit (ec, right, TypeManager.double_type, loc);
1625 if (l != TypeManager.double_type)
1626 left = ConvertImplicit (ec, left, TypeManager.double_type, loc);
1628 type = TypeManager.double_type;
1629 } else if (l == TypeManager.float_type || r == TypeManager.float_type){
1631 // if either operand is of type float, the other operand is
1632 // converted to type float.
1634 if (r != TypeManager.double_type)
1635 right = ConvertImplicit (ec, right, TypeManager.float_type, loc);
1636 if (l != TypeManager.double_type)
1637 left = ConvertImplicit (ec, left, TypeManager.float_type, loc);
1638 type = TypeManager.float_type;
1639 } else if (l == TypeManager.uint64_type || r == TypeManager.uint64_type){
1643 // If either operand is of type ulong, the other operand is
1644 // converted to type ulong. or an error ocurrs if the other
1645 // operand is of type sbyte, short, int or long
1647 if (l == TypeManager.uint64_type){
1648 if (r != TypeManager.uint64_type){
1649 if (right is IntConstant){
1650 IntConstant ic = (IntConstant) right;
1652 e = TryImplicitIntConversion (l, ic);
1655 } else if (right is LongConstant){
1656 long ll = ((LongConstant) right).Value;
1659 right = new ULongConstant ((ulong) ll);
1661 e = ImplicitNumericConversion (ec, right, l, loc);
1668 if (left is IntConstant){
1669 e = TryImplicitIntConversion (r, (IntConstant) left);
1672 } else if (left is LongConstant){
1673 long ll = ((LongConstant) left).Value;
1676 left = new ULongConstant ((ulong) ll);
1678 e = ImplicitNumericConversion (ec, left, r, loc);
1685 if ((other == TypeManager.sbyte_type) ||
1686 (other == TypeManager.short_type) ||
1687 (other == TypeManager.int32_type) ||
1688 (other == TypeManager.int64_type))
1689 Error_OperatorAmbiguous (loc, oper, l, r);
1690 type = TypeManager.uint64_type;
1691 } else if (l == TypeManager.int64_type || r == TypeManager.int64_type){
1693 // If either operand is of type long, the other operand is converted
1696 if (l != TypeManager.int64_type)
1697 left = ConvertImplicit (ec, left, TypeManager.int64_type, loc);
1698 if (r != TypeManager.int64_type)
1699 right = ConvertImplicit (ec, right, TypeManager.int64_type, loc);
1701 type = TypeManager.int64_type;
1702 } else if (l == TypeManager.uint32_type || r == TypeManager.uint32_type){
1704 // If either operand is of type uint, and the other
1705 // operand is of type sbyte, short or int, othe operands are
1706 // converted to type long.
1710 if (l == TypeManager.uint32_type){
1711 if (right is IntConstant){
1712 IntConstant ic = (IntConstant) right;
1716 right = new UIntConstant ((uint) val);
1723 else if (r == TypeManager.uint32_type){
1724 if (left is IntConstant){
1725 IntConstant ic = (IntConstant) left;
1729 left = new UIntConstant ((uint) val);
1738 if ((other == TypeManager.sbyte_type) ||
1739 (other == TypeManager.short_type) ||
1740 (other == TypeManager.int32_type)){
1741 left = ForceConversion (ec, left, TypeManager.int64_type);
1742 right = ForceConversion (ec, right, TypeManager.int64_type);
1743 type = TypeManager.int64_type;
1746 // if either operand is of type uint, the other
1747 // operand is converd to type uint
1749 left = ForceConversion (ec, left, TypeManager.uint32_type);
1750 right = ForceConversion (ec, right, TypeManager.uint32_type);
1751 type = TypeManager.uint32_type;
1753 } else if (l == TypeManager.decimal_type || r == TypeManager.decimal_type){
1754 if (l != TypeManager.decimal_type)
1755 left = ConvertImplicit (ec, left, TypeManager.decimal_type, loc);
1756 if (r != TypeManager.decimal_type)
1757 right = ConvertImplicit (ec, right, TypeManager.decimal_type, loc);
1759 type = TypeManager.decimal_type;
1761 Expression l_tmp, r_tmp;
1763 l_tmp = ForceConversion (ec, left, TypeManager.int32_type);
1767 r_tmp = ForceConversion (ec, right, TypeManager.int32_type);
1774 type = TypeManager.int32_type;
1780 static public void Error_OperatorCannotBeApplied (Location loc, string name, Type l, Type r)
1783 "Operator " + name + " cannot be applied to operands of type `" +
1784 TypeManager.CSharpName (l) + "' and `" +
1785 TypeManager.CSharpName (r) + "'");
1788 void Error_OperatorCannotBeApplied ()
1790 Error_OperatorCannotBeApplied (loc, OperName (oper), left.Type, right.Type);
1793 static bool is_32_or_64 (Type t)
1795 return (t == TypeManager.int32_type || t == TypeManager.uint32_type ||
1796 t == TypeManager.int64_type || t == TypeManager.uint64_type);
1799 Expression CheckShiftArguments (EmitContext ec)
1803 Type r = right.Type;
1805 e = ForceConversion (ec, right, TypeManager.int32_type);
1807 Error_OperatorCannotBeApplied ();
1812 if (((e = ConvertImplicit (ec, left, TypeManager.int32_type, loc)) != null) ||
1813 ((e = ConvertImplicit (ec, left, TypeManager.uint32_type, loc)) != null) ||
1814 ((e = ConvertImplicit (ec, left, TypeManager.int64_type, loc)) != null) ||
1815 ((e = ConvertImplicit (ec, left, TypeManager.uint64_type, loc)) != null)){
1821 Error_OperatorCannotBeApplied ();
1825 Expression ResolveOperator (EmitContext ec)
1828 Type r = right.Type;
1830 bool overload_failed = false;
1833 // Step 1: Perform Operator Overload location
1835 Expression left_expr, right_expr;
1837 string op = oper_names [(int) oper];
1839 MethodGroupExpr union;
1840 left_expr = MemberLookup (ec, l, op, MemberTypes.Method, AllBindingFlags, loc);
1842 right_expr = MemberLookup (
1843 ec, r, op, MemberTypes.Method, AllBindingFlags, loc);
1844 union = Invocation.MakeUnionSet (left_expr, right_expr, loc);
1846 union = (MethodGroupExpr) left_expr;
1848 if (union != null) {
1849 Arguments = new ArrayList ();
1850 Arguments.Add (new Argument (left, Argument.AType.Expression));
1851 Arguments.Add (new Argument (right, Argument.AType.Expression));
1853 method = Invocation.OverloadResolve (ec, union, Arguments, Location.Null);
1854 if (method != null) {
1855 MethodInfo mi = (MethodInfo) method;
1857 type = mi.ReturnType;
1860 overload_failed = true;
1865 // Step 2: Default operations on CLI native types.
1869 // Step 0: String concatenation (because overloading will get this wrong)
1871 if (oper == Operator.Addition){
1873 // If any of the arguments is a string, cast to string
1876 if (l == TypeManager.string_type){
1878 if (r == TypeManager.void_type) {
1879 Error_OperatorCannotBeApplied ();
1883 if (r == TypeManager.string_type){
1884 if (left is Constant && right is Constant){
1885 StringConstant ls = (StringConstant) left;
1886 StringConstant rs = (StringConstant) right;
1888 return new StringConstant (
1889 ls.Value + rs.Value);
1893 method = TypeManager.string_concat_string_string;
1896 method = TypeManager.string_concat_object_object;
1897 right = ConvertImplicit (ec, right,
1898 TypeManager.object_type, loc);
1900 type = TypeManager.string_type;
1902 Arguments = new ArrayList ();
1903 Arguments.Add (new Argument (left, Argument.AType.Expression));
1904 Arguments.Add (new Argument (right, Argument.AType.Expression));
1908 } else if (r == TypeManager.string_type){
1911 if (l == TypeManager.void_type) {
1912 Error_OperatorCannotBeApplied ();
1916 method = TypeManager.string_concat_object_object;
1917 left = ConvertImplicit (ec, left, TypeManager.object_type, loc);
1918 Arguments = new ArrayList ();
1919 Arguments.Add (new Argument (left, Argument.AType.Expression));
1920 Arguments.Add (new Argument (right, Argument.AType.Expression));
1922 type = TypeManager.string_type;
1928 // Transform a + ( - b) into a - b
1930 if (right is Unary){
1931 Unary right_unary = (Unary) right;
1933 if (right_unary.Oper == Unary.Operator.UnaryNegation){
1934 oper = Operator.Subtraction;
1935 right = right_unary.Expr;
1941 if (oper == Operator.Equality || oper == Operator.Inequality){
1942 if (l == TypeManager.bool_type || r == TypeManager.bool_type){
1943 if (r != TypeManager.bool_type || l != TypeManager.bool_type){
1944 Error_OperatorCannotBeApplied ();
1948 type = TypeManager.bool_type;
1953 // operator != (object a, object b)
1954 // operator == (object a, object b)
1956 // For this to be used, both arguments have to be reference-types.
1957 // Read the rationale on the spec (14.9.6)
1959 // Also, if at compile time we know that the classes do not inherit
1960 // one from the other, then we catch the error there.
1962 if (!(l.IsValueType || r.IsValueType)){
1963 type = TypeManager.bool_type;
1968 if (l.IsSubclassOf (r) || r.IsSubclassOf (l))
1972 // Also, a standard conversion must exist from either one
1974 if (!(StandardConversionExists (left, r) ||
1975 StandardConversionExists (right, l))){
1976 Error_OperatorCannotBeApplied ();
1980 // We are going to have to convert to an object to compare
1982 if (l != TypeManager.object_type)
1983 left = new EmptyCast (left, TypeManager.object_type);
1984 if (r != TypeManager.object_type)
1985 right = new EmptyCast (right, TypeManager.object_type);
1988 // FIXME: CSC here catches errors cs254 and cs252
1994 // Only perform numeric promotions on:
1995 // +, -, *, /, %, &, |, ^, ==, !=, <, >, <=, >=
1997 if (oper == Operator.Addition || oper == Operator.Subtraction) {
1998 if (l.IsSubclassOf (TypeManager.delegate_type) &&
1999 r.IsSubclassOf (TypeManager.delegate_type)) {
2001 Arguments = new ArrayList ();
2002 Arguments.Add (new Argument (left, Argument.AType.Expression));
2003 Arguments.Add (new Argument (right, Argument.AType.Expression));
2005 if (oper == Operator.Addition)
2006 method = TypeManager.delegate_combine_delegate_delegate;
2008 method = TypeManager.delegate_remove_delegate_delegate;
2010 DelegateOperation = true;
2016 // Pointer arithmetic:
2018 // T* operator + (T* x, int y);
2019 // T* operator + (T* x, uint y);
2020 // T* operator + (T* x, long y);
2021 // T* operator + (T* x, ulong y);
2023 // T* operator + (int y, T* x);
2024 // T* operator + (uint y, T *x);
2025 // T* operator + (long y, T *x);
2026 // T* operator + (ulong y, T *x);
2028 // T* operator - (T* x, int y);
2029 // T* operator - (T* x, uint y);
2030 // T* operator - (T* x, long y);
2031 // T* operator - (T* x, ulong y);
2033 // long operator - (T* x, T *y)
2036 if (r.IsPointer && oper == Operator.Subtraction){
2038 return new PointerArithmetic (
2039 false, left, right, TypeManager.int64_type);
2040 } else if (is_32_or_64 (r))
2041 return new PointerArithmetic (
2042 oper == Operator.Addition, left, right, l);
2043 } else if (r.IsPointer && is_32_or_64 (l) && oper == Operator.Addition)
2044 return new PointerArithmetic (
2045 true, right, left, r);
2049 // Enumeration operators
2051 bool lie = TypeManager.IsEnumType (l);
2052 bool rie = TypeManager.IsEnumType (r);
2057 // operator + (E e, U x)
2059 if (oper == Operator.Addition){
2061 Error_OperatorCannotBeApplied ();
2065 Type enum_type = lie ? l : r;
2066 Type other_type = lie ? r : l;
2067 Type underlying_type = TypeManager.EnumToUnderlying (enum_type);
2070 if (underlying_type != other_type){
2071 Error_OperatorCannotBeApplied ();
2080 temp = ConvertImplicit (ec, right, l, loc);
2084 temp = ConvertImplicit (ec, left, r, loc);
2091 if (oper == Operator.Equality || oper == Operator.Inequality ||
2092 oper == Operator.LessThanOrEqual || oper == Operator.LessThan ||
2093 oper == Operator.GreaterThanOrEqual || oper == Operator.GreaterThan){
2094 type = TypeManager.bool_type;
2098 if (oper == Operator.BitwiseAnd ||
2099 oper == Operator.BitwiseOr ||
2100 oper == Operator.ExclusiveOr){
2107 if (oper == Operator.LeftShift || oper == Operator.RightShift)
2108 return CheckShiftArguments (ec);
2110 if (oper == Operator.LogicalOr || oper == Operator.LogicalAnd){
2111 if (l != TypeManager.bool_type || r != TypeManager.bool_type){
2112 Error_OperatorCannotBeApplied ();
2116 type = TypeManager.bool_type;
2121 // operator & (bool x, bool y)
2122 // operator | (bool x, bool y)
2123 // operator ^ (bool x, bool y)
2125 if (l == TypeManager.bool_type && r == TypeManager.bool_type){
2126 if (oper == Operator.BitwiseAnd ||
2127 oper == Operator.BitwiseOr ||
2128 oper == Operator.ExclusiveOr){
2135 // Pointer comparison
2137 if (l.IsPointer && r.IsPointer){
2138 if (oper == Operator.Equality || oper == Operator.Inequality ||
2139 oper == Operator.LessThan || oper == Operator.LessThanOrEqual ||
2140 oper == Operator.GreaterThan || oper == Operator.GreaterThanOrEqual){
2141 type = TypeManager.bool_type;
2147 // We are dealing with numbers
2149 if (overload_failed){
2150 Error_OperatorCannotBeApplied ();
2154 if (!DoNumericPromotions (ec, l, r)){
2155 Error_OperatorCannotBeApplied ();
2159 if (left == null || right == null)
2163 // reload our cached types if required
2168 if (oper == Operator.BitwiseAnd ||
2169 oper == Operator.BitwiseOr ||
2170 oper == Operator.ExclusiveOr){
2172 if (!((l == TypeManager.int32_type) ||
2173 (l == TypeManager.uint32_type) ||
2174 (l == TypeManager.int64_type) ||
2175 (l == TypeManager.uint64_type)))
2178 Error_OperatorCannotBeApplied ();
2183 if (oper == Operator.Equality ||
2184 oper == Operator.Inequality ||
2185 oper == Operator.LessThanOrEqual ||
2186 oper == Operator.LessThan ||
2187 oper == Operator.GreaterThanOrEqual ||
2188 oper == Operator.GreaterThan){
2189 type = TypeManager.bool_type;
2195 public override Expression DoResolve (EmitContext ec)
2197 left = left.Resolve (ec);
2198 right = right.Resolve (ec);
2200 if (left == null || right == null)
2203 if (left.Type == null)
2204 throw new Exception (
2205 "Resolve returned non null, but did not set the type! (" +
2206 left + ") at Line: " + loc.Row);
2207 if (right.Type == null)
2208 throw new Exception (
2209 "Resolve returned non null, but did not set the type! (" +
2210 right + ") at Line: "+ loc.Row);
2212 eclass = ExprClass.Value;
2214 if (left is Constant && right is Constant){
2215 Expression e = ConstantFold.BinaryFold (
2216 ec, oper, (Constant) left, (Constant) right, loc);
2221 return ResolveOperator (ec);
2224 public bool IsBranchable ()
2226 if (oper == Operator.Equality ||
2227 oper == Operator.Inequality ||
2228 oper == Operator.LessThan ||
2229 oper == Operator.GreaterThan ||
2230 oper == Operator.LessThanOrEqual ||
2231 oper == Operator.GreaterThanOrEqual){
2238 /// This entry point is used by routines that might want
2239 /// to emit a brfalse/brtrue after an expression, and instead
2240 /// they could use a more compact notation.
2242 /// Typically the code would generate l.emit/r.emit, followed
2243 /// by the comparission and then a brtrue/brfalse. The comparissions
2244 /// are sometimes inneficient (there are not as complete as the branches
2245 /// look for the hacks in Emit using double ceqs).
2247 /// So for those cases we provide EmitBranchable that can emit the
2248 /// branch with the test
2250 public void EmitBranchable (EmitContext ec, int target)
2253 bool close_target = false;
2254 ILGenerator ig = ec.ig;
2257 // short-circuit operators
2259 if (oper == Operator.LogicalAnd){
2261 ig.Emit (OpCodes.Brfalse, target);
2263 ig.Emit (OpCodes.Brfalse, target);
2264 } else if (oper == Operator.LogicalOr){
2266 ig.Emit (OpCodes.Brtrue, target);
2268 ig.Emit (OpCodes.Brfalse, target);
2275 case Operator.Equality:
2277 opcode = OpCodes.Beq_S;
2279 opcode = OpCodes.Beq;
2282 case Operator.Inequality:
2284 opcode = OpCodes.Bne_Un_S;
2286 opcode = OpCodes.Bne_Un;
2289 case Operator.LessThan:
2291 opcode = OpCodes.Blt_S;
2293 opcode = OpCodes.Blt;
2296 case Operator.GreaterThan:
2298 opcode = OpCodes.Bgt_S;
2300 opcode = OpCodes.Bgt;
2303 case Operator.LessThanOrEqual:
2305 opcode = OpCodes.Ble_S;
2307 opcode = OpCodes.Ble;
2310 case Operator.GreaterThanOrEqual:
2312 opcode = OpCodes.Bge_S;
2314 opcode = OpCodes.Ble;
2318 throw new Exception ("EmitBranchable called on non-EmitBranchable operator: "
2319 + oper.ToString ());
2322 ig.Emit (opcode, target);
2325 public override void Emit (EmitContext ec)
2327 ILGenerator ig = ec.ig;
2329 Type r = right.Type;
2332 if (method != null) {
2334 // Note that operators are static anyway
2336 if (Arguments != null)
2337 Invocation.EmitArguments (ec, method, Arguments);
2339 if (method is MethodInfo)
2340 ig.Emit (OpCodes.Call, (MethodInfo) method);
2342 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
2344 if (DelegateOperation)
2345 ig.Emit (OpCodes.Castclass, type);
2351 // Handle short-circuit operators differently
2354 if (oper == Operator.LogicalAnd){
2355 Label load_zero = ig.DefineLabel ();
2356 Label end = ig.DefineLabel ();
2359 ig.Emit (OpCodes.Brfalse, load_zero);
2361 ig.Emit (OpCodes.Br, end);
2362 ig.MarkLabel (load_zero);
2363 ig.Emit (OpCodes.Ldc_I4_0);
2366 } else if (oper == Operator.LogicalOr){
2367 Label load_one = ig.DefineLabel ();
2368 Label end = ig.DefineLabel ();
2371 ig.Emit (OpCodes.Brtrue, load_one);
2373 ig.Emit (OpCodes.Br, end);
2374 ig.MarkLabel (load_one);
2375 ig.Emit (OpCodes.Ldc_I4_1);
2384 case Operator.Multiply:
2386 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
2387 opcode = OpCodes.Mul_Ovf;
2388 else if (l==TypeManager.uint32_type || l==TypeManager.uint64_type)
2389 opcode = OpCodes.Mul_Ovf_Un;
2391 opcode = OpCodes.Mul;
2393 opcode = OpCodes.Mul;
2397 case Operator.Division:
2398 if (l == TypeManager.uint32_type || l == TypeManager.uint64_type)
2399 opcode = OpCodes.Div_Un;
2401 opcode = OpCodes.Div;
2404 case Operator.Modulus:
2405 if (l == TypeManager.uint32_type || l == TypeManager.uint64_type)
2406 opcode = OpCodes.Rem_Un;
2408 opcode = OpCodes.Rem;
2411 case Operator.Addition:
2413 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
2414 opcode = OpCodes.Add_Ovf;
2415 else if (l==TypeManager.uint32_type || l==TypeManager.uint64_type)
2416 opcode = OpCodes.Add_Ovf_Un;
2418 opcode = OpCodes.Add;
2420 opcode = OpCodes.Add;
2423 case Operator.Subtraction:
2425 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
2426 opcode = OpCodes.Sub_Ovf;
2427 else if (l==TypeManager.uint32_type || l==TypeManager.uint64_type)
2428 opcode = OpCodes.Sub_Ovf_Un;
2430 opcode = OpCodes.Sub;
2432 opcode = OpCodes.Sub;
2435 case Operator.RightShift:
2436 if (l == TypeManager.uint32_type || l == TypeManager.uint64_type)
2437 opcode = OpCodes.Shr_Un;
2439 opcode = OpCodes.Shr;
2442 case Operator.LeftShift:
2443 opcode = OpCodes.Shl;
2446 case Operator.Equality:
2447 opcode = OpCodes.Ceq;
2450 case Operator.Inequality:
2451 ec.ig.Emit (OpCodes.Ceq);
2452 ec.ig.Emit (OpCodes.Ldc_I4_0);
2454 opcode = OpCodes.Ceq;
2457 case Operator.LessThan:
2458 opcode = OpCodes.Clt;
2461 case Operator.GreaterThan:
2462 opcode = OpCodes.Cgt;
2465 case Operator.LessThanOrEqual:
2466 ec.ig.Emit (OpCodes.Cgt);
2467 ec.ig.Emit (OpCodes.Ldc_I4_0);
2469 opcode = OpCodes.Ceq;
2472 case Operator.GreaterThanOrEqual:
2473 ec.ig.Emit (OpCodes.Clt);
2474 ec.ig.Emit (OpCodes.Ldc_I4_1);
2476 opcode = OpCodes.Sub;
2479 case Operator.BitwiseOr:
2480 opcode = OpCodes.Or;
2483 case Operator.BitwiseAnd:
2484 opcode = OpCodes.And;
2487 case Operator.ExclusiveOr:
2488 opcode = OpCodes.Xor;
2492 throw new Exception ("This should not happen: Operator = "
2493 + oper.ToString ());
2499 public bool IsBuiltinOperator {
2501 return method == null;
2506 public class PointerArithmetic : Expression {
2507 Expression left, right;
2511 // We assume that `l' is always a pointer
2513 public PointerArithmetic (bool is_addition, Expression l, Expression r, Type t)
2516 eclass = ExprClass.Variable;
2519 is_add = is_addition;
2522 public override Expression DoResolve (EmitContext ec)
2525 // We are born fully resolved
2530 public override void Emit (EmitContext ec)
2532 Type op_type = left.Type;
2533 ILGenerator ig = ec.ig;
2534 int size = GetTypeSize (op_type.GetElementType ());
2536 if (right.Type.IsPointer){
2538 // handle (pointer - pointer)
2542 ig.Emit (OpCodes.Sub);
2546 ig.Emit (OpCodes.Sizeof, op_type);
2548 IntLiteral.EmitInt (ig, size);
2549 ig.Emit (OpCodes.Div);
2551 ig.Emit (OpCodes.Conv_I8);
2554 // handle + and - on (pointer op int)
2557 ig.Emit (OpCodes.Conv_I);
2561 ig.Emit (OpCodes.Sizeof, op_type);
2563 IntLiteral.EmitInt (ig, size);
2564 ig.Emit (OpCodes.Mul);
2567 ig.Emit (OpCodes.Add);
2569 ig.Emit (OpCodes.Sub);
2575 /// Implements the ternary conditiona operator (?:)
2577 public class Conditional : Expression {
2578 Expression expr, trueExpr, falseExpr;
2581 public Conditional (Expression expr, Expression trueExpr, Expression falseExpr, Location l)
2584 this.trueExpr = trueExpr;
2585 this.falseExpr = falseExpr;
2589 public Expression Expr {
2595 public Expression TrueExpr {
2601 public Expression FalseExpr {
2607 public override Expression DoResolve (EmitContext ec)
2609 expr = expr.Resolve (ec);
2611 if (expr.Type != TypeManager.bool_type)
2612 expr = Expression.ConvertImplicitRequired (
2613 ec, expr, TypeManager.bool_type, loc);
2615 trueExpr = trueExpr.Resolve (ec);
2616 falseExpr = falseExpr.Resolve (ec);
2618 if (expr == null || trueExpr == null || falseExpr == null)
2621 eclass = ExprClass.Value;
2622 if (trueExpr.Type == falseExpr.Type)
2623 type = trueExpr.Type;
2626 Type true_type = trueExpr.Type;
2627 Type false_type = falseExpr.Type;
2629 if (trueExpr is NullLiteral){
2632 } else if (falseExpr is NullLiteral){
2638 // First, if an implicit conversion exists from trueExpr
2639 // to falseExpr, then the result type is of type falseExpr.Type
2641 conv = ConvertImplicit (ec, trueExpr, false_type, loc);
2644 // Check if both can convert implicitl to each other's type
2646 if (ConvertImplicit (ec, falseExpr, true_type, loc) != null){
2649 "Can not compute type of conditional expression " +
2650 "as `" + TypeManager.CSharpName (trueExpr.Type) +
2651 "' and `" + TypeManager.CSharpName (falseExpr.Type) +
2652 "' convert implicitly to each other");
2657 } else if ((conv = ConvertImplicit(ec, falseExpr, true_type,loc))!= null){
2661 Error (173, loc, "The type of the conditional expression can " +
2662 "not be computed because there is no implicit conversion" +
2663 " from `" + TypeManager.CSharpName (trueExpr.Type) + "'" +
2664 " and `" + TypeManager.CSharpName (falseExpr.Type) + "'");
2669 if (expr is BoolConstant){
2670 BoolConstant bc = (BoolConstant) expr;
2681 public override void Emit (EmitContext ec)
2683 ILGenerator ig = ec.ig;
2684 Label false_target = ig.DefineLabel ();
2685 Label end_target = ig.DefineLabel ();
2688 ig.Emit (OpCodes.Brfalse, false_target);
2690 ig.Emit (OpCodes.Br, end_target);
2691 ig.MarkLabel (false_target);
2692 falseExpr.Emit (ec);
2693 ig.MarkLabel (end_target);
2701 public class LocalVariableReference : Expression, IAssignMethod, IMemoryLocation {
2702 public readonly string Name;
2703 public readonly Block Block;
2705 VariableInfo variable_info;
2707 public LocalVariableReference (Block block, string name, Location l)
2712 eclass = ExprClass.Variable;
2715 public VariableInfo VariableInfo {
2717 if (variable_info == null)
2718 variable_info = Block.GetVariableInfo (Name);
2719 return variable_info;
2723 public override Expression DoResolve (EmitContext ec)
2725 VariableInfo vi = VariableInfo;
2727 if (Block.IsConstant (Name)) {
2728 Expression e = Block.GetConstantExpression (Name);
2734 type = vi.VariableType;
2738 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
2740 Expression e = DoResolve (ec);
2745 VariableInfo vi = VariableInfo;
2749 // Sigh: this breaks `using' and `fixed'. Need to review that
2754 "cannot assign to `" + Name + "' because it is readonly");
2762 public override void Emit (EmitContext ec)
2764 VariableInfo vi = VariableInfo;
2765 ILGenerator ig = ec.ig;
2767 ig.Emit (OpCodes.Ldloc, vi.LocalBuilder);
2771 public void EmitAssign (EmitContext ec, Expression source)
2773 ILGenerator ig = ec.ig;
2774 VariableInfo vi = VariableInfo;
2780 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
2783 public void AddressOf (EmitContext ec, AddressOp mode)
2785 VariableInfo vi = VariableInfo;
2787 if ((mode & AddressOp.Load) != 0)
2789 if ((mode & AddressOp.Store) != 0)
2792 ec.ig.Emit (OpCodes.Ldloca, vi.LocalBuilder);
2797 /// This represents a reference to a parameter in the intermediate
2800 public class ParameterReference : Expression, IAssignMethod, IMemoryLocation {
2806 public ParameterReference (Parameters pars, int idx, string name)
2811 eclass = ExprClass.Variable;
2815 // Notice that for ref/out parameters, the type exposed is not the
2816 // same type exposed externally.
2819 // externally we expose "int&"
2820 // here we expose "int".
2822 // We record this in "is_ref". This means that the type system can treat
2823 // the type as it is expected, but when we generate the code, we generate
2824 // the alternate kind of code.
2826 public override Expression DoResolve (EmitContext ec)
2828 type = pars.GetParameterInfo (ec.DeclSpace, idx, out is_ref);
2829 eclass = ExprClass.Variable;
2835 // This method is used by parameters that are references, that are
2836 // being passed as references: we only want to pass the pointer (that
2837 // is already stored in the parameter, not the address of the pointer,
2838 // and not the value of the variable).
2840 public void EmitLoad (EmitContext ec)
2842 ILGenerator ig = ec.ig;
2849 ig.Emit (OpCodes.Ldarg_S, (byte) arg_idx);
2851 ig.Emit (OpCodes.Ldarg, arg_idx);
2854 public override void Emit (EmitContext ec)
2856 ILGenerator ig = ec.ig;
2863 ig.Emit (OpCodes.Ldarg_S, (byte) arg_idx);
2865 ig.Emit (OpCodes.Ldarg, arg_idx);
2871 // If we are a reference, we loaded on the stack a pointer
2872 // Now lets load the real value
2874 LoadFromPtr (ig, type);
2877 public void EmitAssign (EmitContext ec, Expression source)
2879 ILGenerator ig = ec.ig;
2888 ig.Emit (OpCodes.Ldarg_S, (byte) arg_idx);
2890 ig.Emit (OpCodes.Ldarg, arg_idx);
2896 StoreFromPtr (ig, type);
2899 ig.Emit (OpCodes.Starg_S, (byte) arg_idx);
2901 ig.Emit (OpCodes.Starg, arg_idx);
2906 public void AddressOf (EmitContext ec, AddressOp mode)
2914 ec.ig.Emit (OpCodes.Ldarga_S, (byte) arg_idx);
2916 ec.ig.Emit (OpCodes.Ldarga, arg_idx);
2921 /// Used for arguments to New(), Invocation()
2923 public class Argument {
2924 public enum AType : byte {
2930 public readonly AType ArgType;
2931 public Expression expr;
2933 public Argument (Expression expr, AType type)
2936 this.ArgType = type;
2939 public Expression Expr {
2951 if (ArgType == AType.Ref || ArgType == AType.Out)
2952 return TypeManager.LookupType (expr.Type.ToString () + "&");
2958 public Parameter.Modifier GetParameterModifier ()
2960 if (ArgType == AType.Ref || ArgType == AType.Out)
2961 return Parameter.Modifier.OUT;
2963 return Parameter.Modifier.NONE;
2966 public static string FullDesc (Argument a)
2968 return (a.ArgType == AType.Ref ? "ref " :
2969 (a.ArgType == AType.Out ? "out " : "")) +
2970 TypeManager.CSharpName (a.Expr.Type);
2973 public bool Resolve (EmitContext ec, Location loc)
2975 expr = expr.Resolve (ec);
2977 if (ArgType == AType.Expression)
2978 return expr != null;
2980 if (expr.eclass != ExprClass.Variable){
2982 // We just probe to match the CSC output
2984 if (expr.eclass == ExprClass.PropertyAccess ||
2985 expr.eclass == ExprClass.IndexerAccess){
2988 "A property or indexer can not be passed as an out or ref " +
2993 "An lvalue is required as an argument to out or ref");
2998 return expr != null;
3001 public void Emit (EmitContext ec)
3004 // Ref and Out parameters need to have their addresses taken.
3006 // ParameterReferences might already be references, so we want
3007 // to pass just the value
3009 if (ArgType == AType.Ref || ArgType == AType.Out){
3010 AddressOp mode = AddressOp.Store;
3012 if (ArgType == AType.Ref)
3013 mode |= AddressOp.Load;
3015 if (expr is ParameterReference){
3016 ParameterReference pr = (ParameterReference) expr;
3022 pr.AddressOf (ec, mode);
3025 ((IMemoryLocation)expr).AddressOf (ec, mode);
3032 /// Invocation of methods or delegates.
3034 public class Invocation : ExpressionStatement {
3035 public readonly ArrayList Arguments;
3039 MethodBase method = null;
3042 static Hashtable method_parameter_cache;
3044 static Invocation ()
3046 method_parameter_cache = new PtrHashtable ();
3050 // arguments is an ArrayList, but we do not want to typecast,
3051 // as it might be null.
3053 // FIXME: only allow expr to be a method invocation or a
3054 // delegate invocation (7.5.5)
3056 public Invocation (Expression expr, ArrayList arguments, Location l)
3059 Arguments = arguments;
3063 public Expression Expr {
3070 /// Returns the Parameters (a ParameterData interface) for the
3073 public static ParameterData GetParameterData (MethodBase mb)
3075 object pd = method_parameter_cache [mb];
3079 return (ParameterData) pd;
3082 ip = TypeManager.LookupParametersByBuilder (mb);
3084 method_parameter_cache [mb] = ip;
3086 return (ParameterData) ip;
3088 ParameterInfo [] pi = mb.GetParameters ();
3089 ReflectionParameters rp = new ReflectionParameters (pi);
3090 method_parameter_cache [mb] = rp;
3092 return (ParameterData) rp;
3097 /// Determines "better conversion" as specified in 7.4.2.3
3098 /// Returns : 1 if a->p is better
3099 /// 0 if a->q or neither is better
3101 static int BetterConversion (EmitContext ec, Argument a, Type p, Type q, Location loc)
3103 Type argument_type = a.Type;
3104 Expression argument_expr = a.Expr;
3106 if (argument_type == null)
3107 throw new Exception ("Expression of type " + a.Expr + " does not resolve its type");
3112 if (argument_type == p)
3115 if (argument_type == q)
3119 // Now probe whether an implicit constant expression conversion
3122 // An implicit constant expression conversion permits the following
3125 // * A constant-expression of type `int' can be converted to type
3126 // sbyte, byute, short, ushort, uint, ulong provided the value of
3127 // of the expression is withing the range of the destination type.
3129 // * A constant-expression of type long can be converted to type
3130 // ulong, provided the value of the constant expression is not negative
3132 // FIXME: Note that this assumes that constant folding has
3133 // taken place. We dont do constant folding yet.
3136 if (argument_expr is IntConstant){
3137 IntConstant ei = (IntConstant) argument_expr;
3138 int value = ei.Value;
3140 if (p == TypeManager.sbyte_type){
3141 if (value >= SByte.MinValue && value <= SByte.MaxValue)
3143 } else if (p == TypeManager.byte_type){
3144 if (Byte.MinValue >= 0 && value <= Byte.MaxValue)
3146 } else if (p == TypeManager.short_type){
3147 if (value >= Int16.MinValue && value <= Int16.MaxValue)
3149 } else if (p == TypeManager.ushort_type){
3150 if (value >= UInt16.MinValue && value <= UInt16.MaxValue)
3152 } else if (p == TypeManager.uint32_type){
3154 // we can optimize this case: a positive int32
3155 // always fits on a uint32
3159 } else if (p == TypeManager.uint64_type){
3161 // we can optimize this case: a positive int32
3162 // always fits on a uint64
3167 } else if (argument_type == TypeManager.int64_type && argument_expr is LongConstant){
3168 LongConstant lc = (LongConstant) argument_expr;
3170 if (p == TypeManager.uint64_type){
3177 Expression tmp = ConvertImplicit (ec, argument_expr, p, loc);
3185 Expression p_tmp = new EmptyExpression (p);
3186 Expression q_tmp = new EmptyExpression (q);
3188 if (StandardConversionExists (p_tmp, q) == true &&
3189 StandardConversionExists (q_tmp, p) == false)
3192 if (p == TypeManager.sbyte_type)
3193 if (q == TypeManager.byte_type || q == TypeManager.ushort_type ||
3194 q == TypeManager.uint32_type || q == TypeManager.uint64_type)
3197 if (p == TypeManager.short_type)
3198 if (q == TypeManager.ushort_type || q == TypeManager.uint32_type ||
3199 q == TypeManager.uint64_type)
3202 if (p == TypeManager.int32_type)
3203 if (q == TypeManager.uint32_type || q == TypeManager.uint64_type)
3206 if (p == TypeManager.int64_type)
3207 if (q == TypeManager.uint64_type)
3214 /// Determines "Better function"
3217 /// and returns an integer indicating :
3218 /// 0 if candidate ain't better
3219 /// 1 if candidate is better than the current best match
3221 static int BetterFunction (EmitContext ec, ArrayList args,
3222 MethodBase candidate, MethodBase best,
3223 bool expanded_form, Location loc)
3225 ParameterData candidate_pd = GetParameterData (candidate);
3226 ParameterData best_pd;
3232 argument_count = args.Count;
3234 int cand_count = candidate_pd.Count;
3236 if (cand_count == 0 && argument_count == 0)
3239 if (candidate_pd.ParameterModifier (cand_count - 1) != Parameter.Modifier.PARAMS)
3240 if (cand_count != argument_count)
3246 if (argument_count == 0 && cand_count == 1 &&
3247 candidate_pd.ParameterModifier (cand_count - 1) == Parameter.Modifier.PARAMS)
3250 for (int j = argument_count; j > 0;) {
3253 Argument a = (Argument) args [j];
3254 Type t = candidate_pd.ParameterType (j);
3256 if (candidate_pd.ParameterModifier (j) == Parameter.Modifier.PARAMS)
3258 t = t.GetElementType ();
3260 x = BetterConversion (ec, a, t, null, loc);
3272 best_pd = GetParameterData (best);
3274 int rating1 = 0, rating2 = 0;
3276 for (int j = 0; j < argument_count; ++j) {
3279 Argument a = (Argument) args [j];
3281 Type ct = candidate_pd.ParameterType (j);
3282 Type bt = best_pd.ParameterType (j);
3284 if (candidate_pd.ParameterModifier (j) == Parameter.Modifier.PARAMS)
3286 ct = ct.GetElementType ();
3288 if (best_pd.ParameterModifier (j) == Parameter.Modifier.PARAMS)
3290 bt = bt.GetElementType ();
3292 x = BetterConversion (ec, a, ct, bt, loc);
3293 y = BetterConversion (ec, a, bt, ct, loc);
3302 if (rating1 > rating2)
3308 public static string FullMethodDesc (MethodBase mb)
3310 string ret_type = "";
3312 if (mb is MethodInfo)
3313 ret_type = TypeManager.CSharpName (((MethodInfo) mb).ReturnType);
3315 StringBuilder sb = new StringBuilder (ret_type + " " + mb.Name);
3316 ParameterData pd = GetParameterData (mb);
3318 int count = pd.Count;
3321 for (int i = count; i > 0; ) {
3324 sb.Append (pd.ParameterDesc (count - i - 1));
3330 return sb.ToString ();
3333 public static MethodGroupExpr MakeUnionSet (Expression mg1, Expression mg2, Location loc)
3335 MemberInfo [] miset;
3336 MethodGroupExpr union;
3341 return (MethodGroupExpr) mg2;
3344 return (MethodGroupExpr) mg1;
3347 MethodGroupExpr left_set = null, right_set = null;
3348 int length1 = 0, length2 = 0;
3350 left_set = (MethodGroupExpr) mg1;
3351 length1 = left_set.Methods.Length;
3353 right_set = (MethodGroupExpr) mg2;
3354 length2 = right_set.Methods.Length;
3356 ArrayList common = new ArrayList ();
3358 foreach (MethodBase l in left_set.Methods){
3359 foreach (MethodBase r in right_set.Methods){
3367 miset = new MemberInfo [length1 + length2 - common.Count];
3368 left_set.Methods.CopyTo (miset, 0);
3372 foreach (MemberInfo mi in right_set.Methods){
3373 if (!common.Contains (mi))
3377 union = new MethodGroupExpr (miset, loc);
3383 /// Determines is the candidate method, if a params method, is applicable
3384 /// in its expanded form to the given set of arguments
3386 static bool IsParamsMethodApplicable (EmitContext ec, ArrayList arguments, MethodBase candidate)
3390 if (arguments == null)
3393 arg_count = arguments.Count;
3395 ParameterData pd = GetParameterData (candidate);
3397 int pd_count = pd.Count;
3402 if (pd.ParameterModifier (pd_count - 1) != Parameter.Modifier.PARAMS)
3405 if (pd_count - 1 > arg_count)
3408 if (pd_count == 1 && arg_count == 0)
3412 // If we have come this far, the case which remains is when the number of parameters
3413 // is less than or equal to the argument count.
3415 for (int i = 0; i < pd_count - 1; ++i) {
3417 Argument a = (Argument) arguments [i];
3419 Parameter.Modifier a_mod = a.GetParameterModifier ();
3420 Parameter.Modifier p_mod = pd.ParameterModifier (i);
3422 if (a_mod == p_mod) {
3424 if (a_mod == Parameter.Modifier.NONE)
3425 if (!ImplicitConversionExists (ec, a.Expr, pd.ParameterType (i)))
3428 if (a_mod == Parameter.Modifier.REF ||
3429 a_mod == Parameter.Modifier.OUT) {
3430 Type pt = pd.ParameterType (i);
3433 pt = TypeManager.LookupType (pt.FullName + "&");
3443 Type element_type = pd.ParameterType (pd_count - 1).GetElementType ();
3445 for (int i = pd_count - 1; i < arg_count; i++) {
3446 Argument a = (Argument) arguments [i];
3448 if (!StandardConversionExists (a.Expr, element_type))
3456 /// Determines if the candidate method is applicable (section 14.4.2.1)
3457 /// to the given set of arguments
3459 static bool IsApplicable (EmitContext ec, ArrayList arguments, MethodBase candidate)
3463 if (arguments == null)
3466 arg_count = arguments.Count;
3468 ParameterData pd = GetParameterData (candidate);
3470 int pd_count = pd.Count;
3472 if (arg_count != pd.Count)
3475 for (int i = arg_count; i > 0; ) {
3478 Argument a = (Argument) arguments [i];
3480 Parameter.Modifier a_mod = a.GetParameterModifier ();
3481 Parameter.Modifier p_mod = pd.ParameterModifier (i);
3483 if (a_mod == p_mod ||
3484 (a_mod == Parameter.Modifier.NONE && p_mod == Parameter.Modifier.PARAMS)) {
3485 if (a_mod == Parameter.Modifier.NONE)
3486 if (!ImplicitConversionExists (ec, a.Expr, pd.ParameterType (i)))
3489 if (a_mod == Parameter.Modifier.REF ||
3490 a_mod == Parameter.Modifier.OUT) {
3491 Type pt = pd.ParameterType (i);
3494 pt = TypeManager.LookupType (pt.FullName + "&");
3509 /// Find the Applicable Function Members (7.4.2.1)
3511 /// me: Method Group expression with the members to select.
3512 /// it might contain constructors or methods (or anything
3513 /// that maps to a method).
3515 /// Arguments: ArrayList containing resolved Argument objects.
3517 /// loc: The location if we want an error to be reported, or a Null
3518 /// location for "probing" purposes.
3520 /// Returns: The MethodBase (either a ConstructorInfo or a MethodInfo)
3521 /// that is the best match of me on Arguments.
3524 public static MethodBase OverloadResolve (EmitContext ec, MethodGroupExpr me,
3525 ArrayList Arguments, Location loc)
3527 ArrayList afm = new ArrayList ();
3528 MethodBase method = null;
3530 ArrayList candidates = new ArrayList ();
3533 foreach (MethodBase candidate in me.Methods){
3536 // Check if candidate is applicable (section 14.4.2.1)
3537 if (!IsApplicable (ec, Arguments, candidate))
3540 candidates.Add (candidate);
3541 x = BetterFunction (ec, Arguments, candidate, method, false, loc);
3549 if (Arguments == null)
3552 argument_count = Arguments.Count;
3555 // Now we see if we can find params functions, applicable in their expanded form
3556 // since if they were applicable in their normal form, they would have been selected
3559 bool chose_params_expanded = false;
3561 if (method == null) {
3562 candidates = new ArrayList ();
3563 foreach (MethodBase candidate in me.Methods){
3564 if (!IsParamsMethodApplicable (ec, Arguments, candidate))
3567 candidates.Add (candidate);
3569 int x = BetterFunction (ec, Arguments, candidate, method, true, loc);
3574 chose_params_expanded = true;
3582 // Now check that there are no ambiguities i.e the selected method
3583 // should be better than all the others
3586 foreach (MethodBase candidate in candidates){
3587 if (candidate == method)
3591 // If a normal method is applicable in the sense that it has the same
3592 // number of arguments, then the expanded params method is never applicable
3593 // so we debar the params method.
3595 if (IsParamsMethodApplicable (ec, Arguments, candidate) &&
3596 IsApplicable (ec, Arguments, method))
3599 int x = BetterFunction (ec, Arguments, method, candidate,
3600 chose_params_expanded, loc);
3605 "Ambiguous call when selecting function due to implicit casts");
3611 // And now check if the arguments are all compatible, perform conversions
3612 // if necessary etc. and return if everything is all right
3615 if (VerifyArgumentsCompat (ec, Arguments, argument_count, method,
3616 chose_params_expanded, null, loc))
3622 public static bool VerifyArgumentsCompat (EmitContext ec, ArrayList Arguments,
3625 bool chose_params_expanded,
3629 ParameterData pd = GetParameterData (method);
3630 int pd_count = pd.Count;
3632 for (int j = 0; j < argument_count; j++) {
3633 Argument a = (Argument) Arguments [j];
3634 Expression a_expr = a.Expr;
3635 Type parameter_type = pd.ParameterType (j);
3637 if (pd.ParameterModifier (j) == Parameter.Modifier.PARAMS &&
3638 chose_params_expanded)
3639 parameter_type = parameter_type.GetElementType ();
3641 if (a.Type != parameter_type){
3644 conv = ConvertImplicit (ec, a_expr, parameter_type, loc);
3647 if (!Location.IsNull (loc)) {
3648 if (delegate_type == null)
3650 "The best overloaded match for method '" +
3651 FullMethodDesc (method) +
3652 "' has some invalid arguments");
3654 Report.Error (1594, loc,
3655 "Delegate '" + delegate_type.ToString () +
3656 "' has some invalid arguments.");
3658 "Argument " + (j+1) +
3659 ": Cannot convert from '" + Argument.FullDesc (a)
3660 + "' to '" + pd.ParameterDesc (j) + "'");
3667 // Update the argument with the implicit conversion
3673 if (a.GetParameterModifier () != pd.ParameterModifier (j) &&
3674 pd.ParameterModifier (pd_count - 1) != Parameter.Modifier.PARAMS) {
3675 if (!Location.IsNull (loc)) {
3676 Console.WriteLine ("A:P: " + a.GetParameterModifier ());
3677 Console.WriteLine ("PP:: " + pd.ParameterModifier (j));
3678 Console.WriteLine ("PT: " + parameter_type.IsByRef);
3680 "The best overloaded match for method '" + FullMethodDesc (method)+
3681 "' has some invalid arguments");
3683 "Argument " + (j+1) +
3684 ": Cannot convert from '" + Argument.FullDesc (a)
3685 + "' to '" + pd.ParameterDesc (j) + "'");
3695 public override Expression DoResolve (EmitContext ec)
3698 // First, resolve the expression that is used to
3699 // trigger the invocation
3701 if (expr is BaseAccess)
3704 expr = expr.Resolve (ec);
3708 if (!(expr is MethodGroupExpr)) {
3709 Type expr_type = expr.Type;
3711 if (expr_type != null){
3712 bool IsDelegate = TypeManager.IsDelegateType (expr_type);
3714 return (new DelegateInvocation (
3715 this.expr, Arguments, loc)).Resolve (ec);
3719 if (!(expr is MethodGroupExpr)){
3720 report118 (loc, this.expr, "method group");
3725 // Next, evaluate all the expressions in the argument list
3727 if (Arguments != null){
3728 foreach (Argument a in Arguments){
3729 if (!a.Resolve (ec, loc))
3734 method = OverloadResolve (ec, (MethodGroupExpr) this.expr, Arguments, loc);
3736 if (method == null){
3738 "Could not find any applicable function for this argument list");
3742 if (method is MethodInfo)
3743 type = ((MethodInfo)method).ReturnType;
3745 if (type.IsPointer){
3752 eclass = ExprClass.Value;
3757 // Emits the list of arguments as an array
3759 static void EmitParams (EmitContext ec, int idx, ArrayList arguments)
3761 ILGenerator ig = ec.ig;
3762 int count = arguments.Count - idx;
3763 Argument a = (Argument) arguments [idx];
3764 Type t = a.expr.Type;
3765 string array_type = t.FullName + "[]";
3768 array = ig.DeclareLocal (Type.GetType (array_type));
3769 IntConstant.EmitInt (ig, count);
3770 ig.Emit (OpCodes.Newarr, t);
3771 ig.Emit (OpCodes.Stloc, array);
3773 int top = arguments.Count;
3774 for (int j = idx; j < top; j++){
3775 a = (Argument) arguments [j];
3777 ig.Emit (OpCodes.Ldloc, array);
3778 IntConstant.EmitInt (ig, j - idx);
3781 ArrayAccess.EmitStoreOpcode (ig, t);
3783 ig.Emit (OpCodes.Ldloc, array);
3787 /// Emits a list of resolved Arguments that are in the arguments
3790 /// The MethodBase argument might be null if the
3791 /// emission of the arguments is known not to contain
3792 /// a `params' field (for example in constructors or other routines
3793 /// that keep their arguments in this structure
3795 public static void EmitArguments (EmitContext ec, MethodBase mb, ArrayList arguments)
3799 pd = GetParameterData (mb);
3804 // If we are calling a params method with no arguments, special case it
3806 if (arguments == null){
3807 if (pd != null && pd.Count > 0 &&
3808 pd.ParameterModifier (0) == Parameter.Modifier.PARAMS){
3809 ILGenerator ig = ec.ig;
3811 IntConstant.EmitInt (ig, 0);
3812 ig.Emit (OpCodes.Newarr, pd.ParameterType (0).GetElementType ());
3818 int top = arguments.Count;
3820 for (int i = 0; i < top; i++){
3821 Argument a = (Argument) arguments [i];
3824 if (pd.ParameterModifier (i) == Parameter.Modifier.PARAMS){
3826 // Special case if we are passing the same data as the
3827 // params argument, do not put it in an array.
3829 if (pd.ParameterType (i) == a.Type)
3832 EmitParams (ec, i, arguments);
3842 /// is_base tells whether we want to force the use of the `call'
3843 /// opcode instead of using callvirt. Call is required to call
3844 /// a specific method, while callvirt will always use the most
3845 /// recent method in the vtable.
3847 /// is_static tells whether this is an invocation on a static method
3849 /// instance_expr is an expression that represents the instance
3850 /// it must be non-null if is_static is false.
3852 /// method is the method to invoke.
3854 /// Arguments is the list of arguments to pass to the method or constructor.
3856 public static void EmitCall (EmitContext ec, bool is_base,
3857 bool is_static, Expression instance_expr,
3858 MethodBase method, ArrayList Arguments, Location loc)
3860 ILGenerator ig = ec.ig;
3861 bool struct_call = false;
3863 Type decl_type = method.DeclaringType;
3866 // This checks the `ConditionalAttribute' on the method, and the
3867 // ObsoleteAttribute
3869 TypeManager.MethodFlags flags = TypeManager.GetMethodFlags (method);
3870 if ((flags & TypeManager.MethodFlags.IsObsolete) != 0){
3872 612, loc, "`" + TypeManager.CSharpSignature (method)+
3875 if ((flags & TypeManager.MethodFlags.ShouldIgnore) != 0)
3879 if (decl_type.IsValueType)
3882 // If this is ourselves, push "this"
3884 if (instance_expr == null){
3885 ig.Emit (OpCodes.Ldarg_0);
3888 // Push the instance expression
3890 if (instance_expr.Type.IsSubclassOf (TypeManager.value_type)){
3892 // Special case: calls to a function declared in a
3893 // reference-type with a value-type argument need
3894 // to have their value boxed.
3897 if (decl_type.IsValueType){
3899 // If the expression implements IMemoryLocation, then
3900 // we can optimize and use AddressOf on the
3903 // If not we have to use some temporary storage for
3905 if (instance_expr is IMemoryLocation){
3906 ((IMemoryLocation)instance_expr).
3907 AddressOf (ec, AddressOp.LoadStore);
3910 Type t = instance_expr.Type;
3912 instance_expr.Emit (ec);
3913 LocalBuilder temp = ig.DeclareLocal (t);
3914 ig.Emit (OpCodes.Stloc, temp);
3915 ig.Emit (OpCodes.Ldloca, temp);
3918 instance_expr.Emit (ec);
3919 ig.Emit (OpCodes.Box, instance_expr.Type);
3922 instance_expr.Emit (ec);
3926 EmitArguments (ec, method, Arguments);
3928 if (is_static || struct_call || is_base){
3929 if (method is MethodInfo)
3930 ig.Emit (OpCodes.Call, (MethodInfo) method);
3932 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
3934 if (method is MethodInfo)
3935 ig.Emit (OpCodes.Callvirt, (MethodInfo) method);
3937 ig.Emit (OpCodes.Callvirt, (ConstructorInfo) method);
3941 public override void Emit (EmitContext ec)
3943 MethodGroupExpr mg = (MethodGroupExpr) this.expr;
3946 ec, is_base, method.IsStatic, mg.InstanceExpression, method, Arguments, loc);
3949 public override void EmitStatement (EmitContext ec)
3954 // Pop the return value if there is one
3956 if (method is MethodInfo){
3957 if (((MethodInfo)method).ReturnType != TypeManager.void_type)
3958 ec.ig.Emit (OpCodes.Pop);
3964 // This class is used to "disable" the code generation for the
3965 // temporary variable when initializing value types.
3967 class EmptyAddressOf : EmptyExpression, IMemoryLocation {
3968 public void AddressOf (EmitContext ec, AddressOp Mode)
3975 /// Implements the new expression
3977 public class New : ExpressionStatement {
3978 public readonly ArrayList Arguments;
3979 public readonly string RequestedType;
3982 MethodBase method = null;
3985 // If set, the new expression is for a value_target, and
3986 // we will not leave anything on the stack.
3988 Expression value_target;
3990 public New (string requested_type, ArrayList arguments, Location l)
3992 RequestedType = requested_type;
3993 Arguments = arguments;
3997 public Expression ValueTypeVariable {
3999 return value_target;
4003 value_target = value;
4008 // This function is used to disable the following code sequence for
4009 // value type initialization:
4011 // AddressOf (temporary)
4015 // Instead the provide will have provided us with the address on the
4016 // stack to store the results.
4018 static Expression MyEmptyExpression;
4020 public void DisableTemporaryValueType ()
4022 if (MyEmptyExpression == null)
4023 MyEmptyExpression = new EmptyAddressOf ();
4026 // To enable this, look into:
4027 // test-34 and test-89 and self bootstrapping.
4029 // For instance, we can avoid a copy by using `newobj'
4030 // instead of Call + Push-temp on value types.
4031 // value_target = MyEmptyExpression;
4034 public override Expression DoResolve (EmitContext ec)
4036 type = RootContext.LookupType (ec.DeclSpace, RequestedType, false, loc);
4041 bool IsDelegate = TypeManager.IsDelegateType (type);
4044 return (new NewDelegate (type, Arguments, loc)).Resolve (ec);
4046 if (type.IsInterface || type.IsAbstract){
4048 144, loc, "It is not possible to create instances of interfaces " +
4049 "or abstract classes");
4053 bool is_struct = false;
4054 is_struct = type.IsSubclassOf (TypeManager.value_type);
4055 eclass = ExprClass.Value;
4058 // SRE returns a match for .ctor () on structs (the object constructor),
4059 // so we have to manually ignore it.
4061 if (is_struct && Arguments == null)
4065 ml = MemberLookupFinal (ec, type, ".ctor",
4066 MemberTypes.Constructor,
4067 AllBindingFlags | BindingFlags.DeclaredOnly, loc);
4072 if (! (ml is MethodGroupExpr)){
4074 report118 (loc, ml, "method group");
4080 if (Arguments != null){
4081 foreach (Argument a in Arguments){
4082 if (!a.Resolve (ec, loc))
4087 method = Invocation.OverloadResolve (ec, (MethodGroupExpr) ml,
4092 if (method == null && !is_struct) {
4094 "New invocation: Can not find a constructor for " +
4095 "this argument list");
4102 // This DoEmit can be invoked in two contexts:
4103 // * As a mechanism that will leave a value on the stack (new object)
4104 // * As one that wont (init struct)
4106 // You can control whether a value is required on the stack by passing
4107 // need_value_on_stack. The code *might* leave a value on the stack
4108 // so it must be popped manually
4110 // If we are dealing with a ValueType, we have a few
4111 // situations to deal with:
4113 // * The target is a ValueType, and we have been provided
4114 // the instance (this is easy, we are being assigned).
4116 // * The target of New is being passed as an argument,
4117 // to a boxing operation or a function that takes a
4120 // In this case, we need to create a temporary variable
4121 // that is the argument of New.
4123 // Returns whether a value is left on the stack
4125 bool DoEmit (EmitContext ec, bool need_value_on_stack)
4127 bool is_value_type = type.IsSubclassOf (TypeManager.value_type);
4128 ILGenerator ig = ec.ig;
4133 if (value_target == null)
4134 value_target = new LocalTemporary (ec, type);
4136 ml = (IMemoryLocation) value_target;
4137 ml.AddressOf (ec, AddressOp.Store);
4141 Invocation.EmitArguments (ec, method, Arguments);
4145 ig.Emit (OpCodes.Initobj, type);
4147 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
4148 if (need_value_on_stack){
4149 value_target.Emit (ec);
4154 ig.Emit (OpCodes.Newobj, (ConstructorInfo) method);
4159 public override void Emit (EmitContext ec)
4164 public override void EmitStatement (EmitContext ec)
4166 if (DoEmit (ec, false))
4167 ec.ig.Emit (OpCodes.Pop);
4172 /// Represents an array creation expression.
4176 /// There are two possible scenarios here: one is an array creation
4177 /// expression that specifies the dimensions and optionally the
4178 /// initialization data and the other which does not need dimensions
4179 /// specified but where initialization data is mandatory.
4181 public class ArrayCreation : ExpressionStatement {
4182 string RequestedType;
4184 ArrayList Initializers;
4188 // The list of Argument types.
4189 // This is used to constrcut the `newarray' or constructor signature
4191 ArrayList Arguments;
4193 MethodBase method = null;
4194 Type array_element_type;
4195 bool IsOneDimensional = false;
4196 bool IsBuiltinType = false;
4197 bool ExpectInitializers = false;
4200 Type underlying_type;
4202 ArrayList ArrayData;
4207 // The number of array initializers that we can handle
4208 // via the InitializeArray method - through EmitStaticInitializers
4210 int num_automatic_initializers;
4212 public ArrayCreation (string requested_type, ArrayList exprs,
4213 string rank, ArrayList initializers, Location l)
4215 RequestedType = requested_type;
4217 Initializers = initializers;
4220 Arguments = new ArrayList ();
4222 foreach (Expression e in exprs)
4223 Arguments.Add (new Argument (e, Argument.AType.Expression));
4226 public ArrayCreation (string requested_type, string rank, ArrayList initializers, Location l)
4228 RequestedType = requested_type;
4229 Initializers = initializers;
4232 Rank = rank.Substring (0, rank.LastIndexOf ("["));
4234 string tmp = rank.Substring (rank.LastIndexOf ("["));
4236 dimensions = tmp.Length - 1;
4237 ExpectInitializers = true;
4240 public static string FormArrayType (string base_type, int idx_count, string rank)
4242 StringBuilder sb = new StringBuilder (base_type);
4247 for (int i = 1; i < idx_count; i++)
4252 return sb.ToString ();
4255 public static string FormElementType (string base_type, int idx_count, string rank)
4257 StringBuilder sb = new StringBuilder (base_type);
4260 for (int i = 1; i < idx_count; i++)
4267 string val = sb.ToString ();
4269 return val.Substring (0, val.LastIndexOf ("["));
4274 Report.Error (178, loc, "Incorrectly structured array initializer");
4277 public bool CheckIndices (EmitContext ec, ArrayList probe, int idx, bool specified_dims)
4279 if (specified_dims) {
4280 Argument a = (Argument) Arguments [idx];
4282 if (!a.Resolve (ec, loc))
4285 if (!(a.Expr is Constant)) {
4286 Report.Error (150, loc, "A constant value is expected");
4290 int value = (int) ((Constant) a.Expr).GetValue ();
4292 if (value != probe.Count) {
4297 Bounds [idx] = value;
4300 foreach (object o in probe) {
4301 if (o is ArrayList) {
4302 bool ret = CheckIndices (ec, (ArrayList) o, idx + 1, specified_dims);
4306 Expression tmp = (Expression) o;
4307 tmp = tmp.Resolve (ec);
4311 // Handle initialization from vars, fields etc.
4313 Expression conv = ConvertImplicitRequired (
4314 ec, tmp, underlying_type, loc);
4319 if (conv is StringConstant)
4320 ArrayData.Add (conv);
4321 else if (conv is Constant) {
4322 ArrayData.Add (conv);
4323 num_automatic_initializers++;
4325 ArrayData.Add (conv);
4332 public void UpdateIndices (EmitContext ec)
4335 for (ArrayList probe = Initializers; probe != null;) {
4336 if (probe.Count > 0 && probe [0] is ArrayList) {
4337 Expression e = new IntConstant (probe.Count);
4338 Arguments.Add (new Argument (e, Argument.AType.Expression));
4340 Bounds [i++] = probe.Count;
4342 probe = (ArrayList) probe [0];
4345 Expression e = new IntConstant (probe.Count);
4346 Arguments.Add (new Argument (e, Argument.AType.Expression));
4348 Bounds [i++] = probe.Count;
4355 public bool ValidateInitializers (EmitContext ec)
4357 if (Initializers == null) {
4358 if (ExpectInitializers)
4364 underlying_type = RootContext.LookupType (
4365 ec.DeclSpace, RequestedType, false, loc);
4368 // We use this to store all the date values in the order in which we
4369 // will need to store them in the byte blob later
4371 ArrayData = new ArrayList ();
4372 Bounds = new Hashtable ();
4376 if (Arguments != null) {
4377 ret = CheckIndices (ec, Initializers, 0, true);
4381 Arguments = new ArrayList ();
4383 ret = CheckIndices (ec, Initializers, 0, false);
4390 if (Arguments.Count != dimensions) {
4399 public override Expression DoResolve (EmitContext ec)
4404 // First step is to validate the initializers and fill
4405 // in any missing bits
4407 if (!ValidateInitializers (ec))
4410 if (Arguments == null)
4413 arg_count = Arguments.Count;
4414 foreach (Argument a in Arguments){
4415 if (!a.Resolve (ec, loc))
4419 // Now, convert that to an integer
4421 Expression real_arg;
4422 bool old_checked = ec.CheckState;
4423 ec.CheckState = true;
4425 real_arg = ConvertExplicit (
4426 ec, a.expr, TypeManager.uint32_type, loc);
4427 ec.CheckState = old_checked;
4428 if (real_arg == null)
4435 string array_type = FormArrayType (RequestedType, arg_count, Rank);
4436 string element_type = FormElementType (RequestedType, arg_count, Rank);
4438 type = RootContext.LookupType (ec.DeclSpace, array_type, false, loc);
4440 array_element_type = RootContext.LookupType (
4441 ec.DeclSpace, element_type, false, loc);
4446 if (arg_count == 1) {
4447 IsOneDimensional = true;
4448 eclass = ExprClass.Value;
4452 IsBuiltinType = TypeManager.IsBuiltinType (type);
4454 if (IsBuiltinType) {
4458 ml = MemberLookup (ec, type, ".ctor", MemberTypes.Constructor,
4459 AllBindingFlags, loc);
4461 if (!(ml is MethodGroupExpr)){
4462 report118 (loc, ml, "method group");
4467 Report.Error (-6, loc, "New invocation: Can not find a constructor for " +
4468 "this argument list");
4472 method = Invocation.OverloadResolve (ec, (MethodGroupExpr) ml, Arguments, loc);
4474 if (method == null) {
4475 Report.Error (-6, loc, "New invocation: Can not find a constructor for " +
4476 "this argument list");
4480 eclass = ExprClass.Value;
4485 ModuleBuilder mb = CodeGen.ModuleBuilder;
4487 ArrayList args = new ArrayList ();
4488 if (Arguments != null){
4489 for (int i = 0; i < arg_count; i++)
4490 args.Add (TypeManager.int32_type);
4493 Type [] arg_types = null;
4496 arg_types = new Type [args.Count];
4498 args.CopyTo (arg_types, 0);
4500 method = mb.GetArrayMethod (type, ".ctor", CallingConventions.HasThis, null,
4503 if (method == null) {
4504 Report.Error (-6, loc, "New invocation: Can not find a constructor for " +
4505 "this argument list");
4509 eclass = ExprClass.Value;
4515 public static byte [] MakeByteBlob (ArrayList ArrayData, Type underlying_type, Location loc)
4520 int count = ArrayData.Count;
4522 factor = GetTypeSize (underlying_type);
4526 data = new byte [(count * factor + 4) & ~3];
4529 for (int i = 0; i < count; ++i) {
4530 object v = ArrayData [i];
4532 if (v is EnumConstant)
4533 v = ((EnumConstant) v).Child;
4535 if (v is Constant && !(v is StringConstant))
4536 v = ((Constant) v).GetValue ();
4542 if (underlying_type == TypeManager.int64_type){
4543 if (!(v is Expression)){
4544 long val = (long) v;
4546 for (int j = 0; j < factor; ++j) {
4547 data [idx + j] = (byte) (val & 0xFF);
4551 } else if (underlying_type == TypeManager.uint64_type){
4552 if (!(v is Expression)){
4553 ulong val = (ulong) v;
4555 for (int j = 0; j < factor; ++j) {
4556 data [idx + j] = (byte) (val & 0xFF);
4560 } else if (underlying_type == TypeManager.float_type) {
4561 if (!(v is Expression)){
4562 element = BitConverter.GetBytes ((float) v);
4564 for (int j = 0; j < factor; ++j)
4565 data [idx + j] = element [j];
4567 } else if (underlying_type == TypeManager.double_type) {
4568 if (!(v is Expression)){
4569 element = BitConverter.GetBytes ((double) v);
4571 for (int j = 0; j < factor; ++j)
4572 data [idx + j] = element [j];
4574 } else if (underlying_type == TypeManager.char_type){
4575 if (!(v is Expression)){
4576 int val = (int) ((char) v);
4578 data [idx] = (byte) (val & 0xff);
4579 data [idx+1] = (byte) (val >> 8);
4581 } else if (underlying_type == TypeManager.short_type){
4582 if (!(v is Expression)){
4583 int val = (int) ((short) v);
4585 data [idx] = (byte) (val & 0xff);
4586 data [idx+1] = (byte) (val >> 8);
4588 } else if (underlying_type == TypeManager.ushort_type){
4589 if (!(v is Expression)){
4590 int val = (int) ((ushort) v);
4592 data [idx] = (byte) (val & 0xff);
4593 data [idx+1] = (byte) (val >> 8);
4595 } else if (underlying_type == TypeManager.int32_type) {
4596 if (!(v is Expression)){
4599 data [idx] = (byte) (val & 0xff);
4600 data [idx+1] = (byte) ((val >> 8) & 0xff);
4601 data [idx+2] = (byte) ((val >> 16) & 0xff);
4602 data [idx+3] = (byte) (val >> 24);
4604 } else if (underlying_type == TypeManager.uint32_type) {
4605 if (!(v is Expression)){
4606 uint val = (uint) v;
4608 data [idx] = (byte) (val & 0xff);
4609 data [idx+1] = (byte) ((val >> 8) & 0xff);
4610 data [idx+2] = (byte) ((val >> 16) & 0xff);
4611 data [idx+3] = (byte) (val >> 24);
4613 } else if (underlying_type == TypeManager.sbyte_type) {
4614 if (!(v is Expression)){
4615 sbyte val = (sbyte) v;
4616 data [idx] = (byte) val;
4618 } else if (underlying_type == TypeManager.byte_type) {
4619 if (!(v is Expression)){
4620 byte val = (byte) v;
4621 data [idx] = (byte) val;
4623 } else if (underlying_type == TypeManager.bool_type) {
4624 if (!(v is Expression)){
4625 bool val = (bool) v;
4626 data [idx] = (byte) (val ? 1 : 0);
4629 throw new Exception ("Unrecognized type in MakeByteBlob");
4638 // Emits the initializers for the array
4640 void EmitStaticInitializers (EmitContext ec, bool is_expression)
4643 // First, the static data
4646 ILGenerator ig = ec.ig;
4648 byte [] data = MakeByteBlob (ArrayData, underlying_type, loc);
4651 fb = RootContext.MakeStaticData (data);
4654 ig.Emit (OpCodes.Dup);
4655 ig.Emit (OpCodes.Ldtoken, fb);
4656 ig.Emit (OpCodes.Call,
4657 TypeManager.void_initializearray_array_fieldhandle);
4662 // Emits pieces of the array that can not be computed at compile
4663 // time (variables and string locations).
4665 // This always expect the top value on the stack to be the array
4667 void EmitDynamicInitializers (EmitContext ec, bool is_expression)
4669 ILGenerator ig = ec.ig;
4670 int dims = Bounds.Count;
4671 int [] current_pos = new int [dims];
4672 int top = ArrayData.Count;
4673 LocalBuilder temp = ig.DeclareLocal (type);
4675 ig.Emit (OpCodes.Stloc, temp);
4677 MethodInfo set = null;
4681 ModuleBuilder mb = null;
4682 mb = CodeGen.ModuleBuilder;
4683 args = new Type [dims + 1];
4686 for (j = 0; j < dims; j++)
4687 args [j] = TypeManager.int32_type;
4689 args [j] = array_element_type;
4691 set = mb.GetArrayMethod (
4693 CallingConventions.HasThis | CallingConventions.Standard,
4694 TypeManager.void_type, args);
4697 for (int i = 0; i < top; i++){
4699 Expression e = null;
4701 if (ArrayData [i] is Expression)
4702 e = (Expression) ArrayData [i];
4706 // Basically we do this for string literals and
4707 // other non-literal expressions
4709 if (e is StringConstant || !(e is Constant) ||
4710 num_automatic_initializers <= 2) {
4711 Type etype = e.Type;
4713 ig.Emit (OpCodes.Ldloc, temp);
4715 for (int idx = dims; idx > 0; ) {
4717 IntConstant.EmitInt (ig, current_pos [idx]);
4721 // If we are dealing with a struct, get the
4722 // address of it, so we can store it.
4724 if (etype.IsSubclassOf (TypeManager.value_type) &&
4725 !TypeManager.IsBuiltinType (etype)){
4730 // Let new know that we are providing
4731 // the address where to store the results
4733 n.DisableTemporaryValueType ();
4736 ig.Emit (OpCodes.Ldelema, etype);
4742 ArrayAccess.EmitStoreOpcode (ig, array_element_type);
4744 ig.Emit (OpCodes.Call, set);
4751 for (int j = 0; j < dims; j++){
4753 if (current_pos [j] < (int) Bounds [j])
4755 current_pos [j] = 0;
4760 ig.Emit (OpCodes.Ldloc, temp);
4763 void EmitArrayArguments (EmitContext ec)
4765 foreach (Argument a in Arguments)
4769 void DoEmit (EmitContext ec, bool is_statement)
4771 ILGenerator ig = ec.ig;
4773 EmitArrayArguments (ec);
4774 if (IsOneDimensional)
4775 ig.Emit (OpCodes.Newarr, array_element_type);
4778 ig.Emit (OpCodes.Newobj, (ConstructorInfo) method);
4780 ig.Emit (OpCodes.Newobj, (MethodInfo) method);
4783 if (Initializers != null){
4785 // FIXME: Set this variable correctly.
4787 bool dynamic_initializers = true;
4789 if (underlying_type != TypeManager.string_type &&
4790 underlying_type != TypeManager.object_type) {
4791 if (num_automatic_initializers > 2)
4792 EmitStaticInitializers (ec, dynamic_initializers || !is_statement);
4795 if (dynamic_initializers)
4796 EmitDynamicInitializers (ec, !is_statement);
4800 public override void Emit (EmitContext ec)
4805 public override void EmitStatement (EmitContext ec)
4813 /// Represents the `this' construct
4815 public class This : Expression, IAssignMethod, IMemoryLocation {
4818 public This (Location loc)
4823 public override Expression DoResolve (EmitContext ec)
4825 eclass = ExprClass.Variable;
4826 type = ec.ContainerType;
4829 Report.Error (26, loc,
4830 "Keyword this not valid in static code");
4837 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
4841 if (ec.TypeContainer is Class){
4842 Report.Error (1604, loc, "Cannot assign to `this'");
4849 public override void Emit (EmitContext ec)
4851 ec.ig.Emit (OpCodes.Ldarg_0);
4854 public void EmitAssign (EmitContext ec, Expression source)
4857 ec.ig.Emit (OpCodes.Starg, 0);
4860 public void AddressOf (EmitContext ec, AddressOp mode)
4862 ec.ig.Emit (OpCodes.Ldarg_0);
4865 // FIGURE OUT WHY LDARG_S does not work
4867 // consider: struct X { int val; int P { set { val = value; }}}
4869 // Yes, this looks very bad. Look at `NOTAS' for
4871 // ec.ig.Emit (OpCodes.Ldarga_S, (byte) 0);
4876 /// Implements the typeof operator
4878 public class TypeOf : Expression {
4879 public readonly string QueriedType;
4883 public TypeOf (string queried_type, Location l)
4885 QueriedType = queried_type;
4889 public override Expression DoResolve (EmitContext ec)
4891 typearg = RootContext.LookupType (
4892 ec.DeclSpace, QueriedType, false, loc);
4894 if (typearg == null)
4897 type = TypeManager.type_type;
4898 eclass = ExprClass.Type;
4902 public override void Emit (EmitContext ec)
4904 ec.ig.Emit (OpCodes.Ldtoken, typearg);
4905 ec.ig.Emit (OpCodes.Call, TypeManager.system_type_get_type_from_handle);
4908 public Type TypeArg {
4909 get { return typearg; }
4914 /// Implements the sizeof expression
4916 public class SizeOf : Expression {
4917 public readonly string QueriedType;
4921 public SizeOf (string queried_type, Location l)
4923 this.QueriedType = queried_type;
4927 public override Expression DoResolve (EmitContext ec)
4929 type_queried = RootContext.LookupType (
4930 ec.DeclSpace, QueriedType, false, loc);
4931 if (type_queried == null)
4934 type = TypeManager.int32_type;
4935 eclass = ExprClass.Value;
4939 public override void Emit (EmitContext ec)
4941 int size = GetTypeSize (type_queried);
4944 ec.ig.Emit (OpCodes.Sizeof, type_queried);
4946 IntConstant.EmitInt (ec.ig, size);
4951 /// Implements the member access expression
4953 public class MemberAccess : Expression {
4954 public readonly string Identifier;
4956 Expression member_lookup;
4959 public MemberAccess (Expression expr, string id, Location l)
4966 public Expression Expr {
4972 static void error176 (Location loc, string name)
4974 Report.Error (176, loc, "Static member `" +
4975 name + "' cannot be accessed " +
4976 "with an instance reference, qualify with a " +
4977 "type name instead");
4980 static bool IdenticalNameAndTypeName (EmitContext ec, Expression left_original, Location loc)
4982 if (left_original == null)
4985 if (!(left_original is SimpleName))
4988 SimpleName sn = (SimpleName) left_original;
4990 Type t = RootContext.LookupType (ec.DeclSpace, sn.Name, true, loc);
4997 public static Expression ResolveMemberAccess (EmitContext ec, Expression member_lookup,
4998 Expression left, Location loc,
4999 Expression left_original)
5004 if (member_lookup is MethodGroupExpr){
5005 MethodGroupExpr mg = (MethodGroupExpr) member_lookup;
5010 if (left is TypeExpr){
5011 if (!mg.RemoveInstanceMethods ()){
5012 SimpleName.Error120 (loc, mg.Methods [0].Name);
5016 return member_lookup;
5020 // Instance.MethodGroup
5022 if (IdenticalNameAndTypeName (ec, left_original, loc)){
5023 if (mg.RemoveInstanceMethods ())
5024 return member_lookup;
5027 if (!mg.RemoveStaticMethods ()){
5028 error176 (loc, mg.Methods [0].Name);
5032 mg.InstanceExpression = left;
5033 return member_lookup;
5035 if (!mg.RemoveStaticMethods ()){
5036 if (IdenticalNameAndTypeName (ec, left_original, loc)){
5037 if (!mg.RemoveInstanceMethods ()){
5038 SimpleName.Error120 (loc, mg.Methods [0].Name);
5041 return member_lookup;
5044 error176 (loc, mg.Methods [0].Name);
5048 mg.InstanceExpression = left;
5050 return member_lookup;
5054 if (member_lookup is FieldExpr){
5055 FieldExpr fe = (FieldExpr) member_lookup;
5056 FieldInfo fi = fe.FieldInfo;
5057 Type decl_type = fi.DeclaringType;
5059 if (fi is FieldBuilder) {
5060 Const c = TypeManager.LookupConstant ((FieldBuilder) fi);
5063 object o = c.LookupConstantValue (ec);
5064 object real_value = ((Constant) c.Expr).GetValue ();
5066 return Constantify (real_value, fi.FieldType);
5071 Type t = fi.FieldType;
5075 if (fi is FieldBuilder)
5076 o = TypeManager.GetValue ((FieldBuilder) fi);
5078 o = fi.GetValue (fi);
5080 if (decl_type.IsSubclassOf (TypeManager.enum_type)) {
5081 Expression enum_member = MemberLookup (
5082 ec, decl_type, "value__", MemberTypes.Field,
5083 AllBindingFlags, loc);
5085 Enum en = TypeManager.LookupEnum (decl_type);
5089 c = Constantify (o, en.UnderlyingType);
5091 c = Constantify (o, enum_member.Type);
5093 return new EnumConstant (c, decl_type);
5096 Expression exp = Constantify (o, t);
5098 if (!(left is TypeExpr)) {
5099 error176 (loc, fe.FieldInfo.Name);
5106 if (fi.FieldType.IsPointer && !ec.InUnsafe){
5111 if (left is TypeExpr){
5112 // and refers to a type name or an
5113 if (!fe.FieldInfo.IsStatic){
5114 error176 (loc, fe.FieldInfo.Name);
5117 return member_lookup;
5119 if (fe.FieldInfo.IsStatic){
5120 if (IdenticalNameAndTypeName (ec, left_original, loc))
5121 return member_lookup;
5123 error176 (loc, fe.FieldInfo.Name);
5126 fe.InstanceExpression = left;
5132 if (member_lookup is PropertyExpr){
5133 PropertyExpr pe = (PropertyExpr) member_lookup;
5135 if (left is TypeExpr){
5137 SimpleName.Error120 (loc, pe.PropertyInfo.Name);
5143 if (IdenticalNameAndTypeName (ec, left_original, loc))
5144 return member_lookup;
5145 error176 (loc, pe.PropertyInfo.Name);
5148 pe.InstanceExpression = left;
5154 if (member_lookup is EventExpr) {
5156 EventExpr ee = (EventExpr) member_lookup;
5159 // If the event is local to this class, we transform ourselves into
5163 Expression ml = MemberLookup (
5164 ec, ec.ContainerType,
5165 ee.EventInfo.Name, MemberTypes.Event, AllBindingFlags, loc);
5168 MemberInfo mi = ec.TypeContainer.GetFieldFromEvent ((EventExpr) ml);
5172 // If this happens, then we have an event with its own
5173 // accessors and private field etc so there's no need
5174 // to transform ourselves : we should instead flag an error
5176 Assign.error70 (ee.EventInfo, loc);
5180 ml = ExprClassFromMemberInfo (ec, mi, loc);
5183 Report.Error (-200, loc, "Internal error!!");
5186 return ResolveMemberAccess (ec, ml, left, loc, left_original);
5189 if (left is TypeExpr) {
5191 SimpleName.Error120 (loc, ee.EventInfo.Name);
5199 if (IdenticalNameAndTypeName (ec, left_original, loc))
5202 error176 (loc, ee.EventInfo.Name);
5206 ee.InstanceExpression = left;
5212 if (member_lookup is TypeExpr){
5213 member_lookup.Resolve (ec);
5214 return member_lookup;
5217 Console.WriteLine ("Left is: " + left);
5218 Report.Error (-100, loc, "Support for [" + member_lookup + "] is not present yet");
5219 Environment.Exit (0);
5223 public override Expression DoResolve (EmitContext ec)
5226 // We are the sole users of ResolveWithSimpleName (ie, the only
5227 // ones that can cope with it
5229 Expression original = expr;
5230 expr = expr.ResolveWithSimpleName (ec);
5235 if (expr is SimpleName){
5236 SimpleName child_expr = (SimpleName) expr;
5238 expr = new SimpleName (child_expr.Name + "." + Identifier, loc);
5240 return expr.ResolveWithSimpleName (ec);
5244 // TODO: I mailed Ravi about this, and apparently we can get rid
5245 // of this and put it in the right place.
5247 // Handle enums here when they are in transit.
5248 // Note that we cannot afford to hit MemberLookup in this case because
5249 // it will fail to find any members at all
5252 Type expr_type = expr.Type;
5253 if ((expr is TypeExpr) && (expr_type.IsSubclassOf (TypeManager.enum_type))){
5255 Enum en = TypeManager.LookupEnum (expr_type);
5258 object value = en.LookupEnumValue (ec, Identifier, loc);
5261 Constant c = Constantify (value, en.UnderlyingType);
5262 return new EnumConstant (c, expr_type);
5267 if (expr_type.IsPointer){
5268 Report.Error (23, loc,
5269 "The `.' operator can not be applied to pointer operands (" +
5270 TypeManager.CSharpName (expr_type) + ")");
5274 member_lookup = MemberLookup (ec, expr_type, Identifier, loc);
5276 if (member_lookup == null){
5278 // Try looking the member up from the same type, if we find
5279 // it, we know that the error was due to limited visibility
5281 object lookup = TypeManager.MemberLookup (
5282 expr_type, expr_type, AllMemberTypes, AllBindingFlags, Identifier);
5284 Report.Error (117, loc, "`" + expr_type + "' does not contain a " +
5285 "definition for `" + Identifier + "'");
5287 Report.Error (122, loc, "`" + expr_type + "." + Identifier + "' " +
5288 "is inaccessible because of its protection level");
5293 return ResolveMemberAccess (ec, member_lookup, expr, loc, original);
5296 public override void Emit (EmitContext ec)
5298 throw new Exception ("Should not happen");
5303 /// Implements checked expressions
5305 public class CheckedExpr : Expression {
5307 public Expression Expr;
5309 public CheckedExpr (Expression e)
5314 public override Expression DoResolve (EmitContext ec)
5316 bool last_const_check = ec.ConstantCheckState;
5318 ec.ConstantCheckState = true;
5319 Expr = Expr.Resolve (ec);
5320 ec.ConstantCheckState = last_const_check;
5325 eclass = Expr.eclass;
5330 public override void Emit (EmitContext ec)
5332 bool last_check = ec.CheckState;
5333 bool last_const_check = ec.ConstantCheckState;
5335 ec.CheckState = true;
5336 ec.ConstantCheckState = true;
5338 ec.CheckState = last_check;
5339 ec.ConstantCheckState = last_const_check;
5345 /// Implements the unchecked expression
5347 public class UnCheckedExpr : Expression {
5349 public Expression Expr;
5351 public UnCheckedExpr (Expression e)
5356 public override Expression DoResolve (EmitContext ec)
5358 bool last_const_check = ec.ConstantCheckState;
5360 ec.ConstantCheckState = false;
5361 Expr = Expr.Resolve (ec);
5362 ec.ConstantCheckState = last_const_check;
5367 eclass = Expr.eclass;
5372 public override void Emit (EmitContext ec)
5374 bool last_check = ec.CheckState;
5375 bool last_const_check = ec.ConstantCheckState;
5377 ec.CheckState = false;
5378 ec.ConstantCheckState = false;
5380 ec.CheckState = last_check;
5381 ec.ConstantCheckState = last_const_check;
5387 /// An Element Access expression.
5389 /// During semantic analysis these are transformed into
5390 /// IndexerAccess or ArrayAccess
5392 public class ElementAccess : Expression {
5393 public ArrayList Arguments;
5394 public Expression Expr;
5395 public Location loc;
5397 public ElementAccess (Expression e, ArrayList e_list, Location l)
5406 Arguments = new ArrayList ();
5407 foreach (Expression tmp in e_list)
5408 Arguments.Add (new Argument (tmp, Argument.AType.Expression));
5412 bool CommonResolve (EmitContext ec)
5414 Expr = Expr.Resolve (ec);
5419 if (Arguments == null)
5422 foreach (Argument a in Arguments){
5423 if (!a.Resolve (ec, loc))
5430 Expression MakePointerAccess ()
5434 if (t == TypeManager.void_ptr_type){
5437 "The array index operation is not valid for void pointers");
5440 if (Arguments.Count != 1){
5443 "A pointer must be indexed by a single value");
5446 Expression p = new PointerArithmetic (true, Expr, ((Argument)Arguments [0]).Expr, t);
5447 return new Indirection (p);
5450 public override Expression DoResolve (EmitContext ec)
5452 if (!CommonResolve (ec))
5456 // We perform some simple tests, and then to "split" the emit and store
5457 // code we create an instance of a different class, and return that.
5459 // I am experimenting with this pattern.
5463 if (t.IsSubclassOf (TypeManager.array_type))
5464 return (new ArrayAccess (this)).Resolve (ec);
5465 else if (t.IsPointer)
5466 return MakePointerAccess ();
5468 return (new IndexerAccess (this)).Resolve (ec);
5471 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
5473 if (!CommonResolve (ec))
5477 if (t.IsSubclassOf (TypeManager.array_type))
5478 return (new ArrayAccess (this)).ResolveLValue (ec, right_side);
5479 else if (t.IsPointer)
5480 return MakePointerAccess ();
5482 return (new IndexerAccess (this)).ResolveLValue (ec, right_side);
5485 public override void Emit (EmitContext ec)
5487 throw new Exception ("Should never be reached");
5492 /// Implements array access
5494 public class ArrayAccess : Expression, IAssignMethod, IMemoryLocation {
5496 // Points to our "data" repository
5500 LocalTemporary [] cached_locations;
5502 public ArrayAccess (ElementAccess ea_data)
5505 eclass = ExprClass.Variable;
5508 public override Expression DoResolve (EmitContext ec)
5510 ExprClass eclass = ea.Expr.eclass;
5513 // As long as the type is valid
5514 if (!(eclass == ExprClass.Variable || eclass == ExprClass.PropertyAccess ||
5515 eclass == ExprClass.Value)) {
5516 report118 (ea.loc, ea.Expr, "variable or value");
5521 Type t = ea.Expr.Type;
5522 if (t.GetArrayRank () != ea.Arguments.Count){
5523 Report.Error (22, ea.loc,
5524 "Incorrect number of indexes for array " +
5525 " expected: " + t.GetArrayRank () + " got: " +
5526 ea.Arguments.Count);
5529 type = t.GetElementType ();
5530 if (type.IsPointer && !ec.InUnsafe){
5531 UnsafeError (ea.loc);
5535 eclass = ExprClass.Variable;
5541 /// Emits the right opcode to load an object of Type `t'
5542 /// from an array of T
5544 static public void EmitLoadOpcode (ILGenerator ig, Type type)
5546 if (type == TypeManager.byte_type || type == TypeManager.bool_type)
5547 ig.Emit (OpCodes.Ldelem_I1);
5548 else if (type == TypeManager.sbyte_type)
5549 ig.Emit (OpCodes.Ldelem_U1);
5550 else if (type == TypeManager.short_type)
5551 ig.Emit (OpCodes.Ldelem_I2);
5552 else if (type == TypeManager.ushort_type)
5553 ig.Emit (OpCodes.Ldelem_U2);
5554 else if (type == TypeManager.int32_type)
5555 ig.Emit (OpCodes.Ldelem_I4);
5556 else if (type == TypeManager.uint32_type)
5557 ig.Emit (OpCodes.Ldelem_U4);
5558 else if (type == TypeManager.uint64_type)
5559 ig.Emit (OpCodes.Ldelem_I8);
5560 else if (type == TypeManager.int64_type)
5561 ig.Emit (OpCodes.Ldelem_I8);
5562 else if (type == TypeManager.float_type)
5563 ig.Emit (OpCodes.Ldelem_R4);
5564 else if (type == TypeManager.double_type)
5565 ig.Emit (OpCodes.Ldelem_R8);
5566 else if (type == TypeManager.intptr_type)
5567 ig.Emit (OpCodes.Ldelem_I);
5568 else if (type.IsValueType){
5569 ig.Emit (OpCodes.Ldelema, type);
5570 ig.Emit (OpCodes.Ldobj, type);
5572 ig.Emit (OpCodes.Ldelem_Ref);
5576 /// Emits the right opcode to store an object of Type `t'
5577 /// from an array of T.
5579 static public void EmitStoreOpcode (ILGenerator ig, Type t)
5581 if (t == TypeManager.byte_type || t == TypeManager.sbyte_type ||
5582 t == TypeManager.bool_type)
5583 ig.Emit (OpCodes.Stelem_I1);
5584 else if (t == TypeManager.short_type || t == TypeManager.ushort_type || t == TypeManager.char_type)
5585 ig.Emit (OpCodes.Stelem_I2);
5586 else if (t == TypeManager.int32_type || t == TypeManager.uint32_type)
5587 ig.Emit (OpCodes.Stelem_I4);
5588 else if (t == TypeManager.int64_type || t == TypeManager.uint64_type)
5589 ig.Emit (OpCodes.Stelem_I8);
5590 else if (t == TypeManager.float_type)
5591 ig.Emit (OpCodes.Stelem_R4);
5592 else if (t == TypeManager.double_type)
5593 ig.Emit (OpCodes.Stelem_R8);
5594 else if (t == TypeManager.intptr_type)
5595 ig.Emit (OpCodes.Stelem_I);
5596 else if (t.IsValueType)
5597 ig.Emit (OpCodes.Stobj, t);
5599 ig.Emit (OpCodes.Stelem_Ref);
5602 MethodInfo FetchGetMethod ()
5604 ModuleBuilder mb = CodeGen.ModuleBuilder;
5605 int arg_count = ea.Arguments.Count;
5606 Type [] args = new Type [arg_count];
5609 for (int i = 0; i < arg_count; i++){
5610 //args [i++] = a.Type;
5611 args [i] = TypeManager.int32_type;
5614 get = mb.GetArrayMethod (
5615 ea.Expr.Type, "Get",
5616 CallingConventions.HasThis |
5617 CallingConventions.Standard,
5623 MethodInfo FetchAddressMethod ()
5625 ModuleBuilder mb = CodeGen.ModuleBuilder;
5626 int arg_count = ea.Arguments.Count;
5627 Type [] args = new Type [arg_count];
5629 string ptr_type_name;
5632 ptr_type_name = type.FullName + "&";
5633 ret_type = Type.GetType (ptr_type_name);
5636 // It is a type defined by the source code we are compiling
5638 if (ret_type == null){
5639 ret_type = mb.GetType (ptr_type_name);
5642 for (int i = 0; i < arg_count; i++){
5643 //args [i++] = a.Type;
5644 args [i] = TypeManager.int32_type;
5647 address = mb.GetArrayMethod (
5648 ea.Expr.Type, "Address",
5649 CallingConventions.HasThis |
5650 CallingConventions.Standard,
5657 // Load the array arguments into the stack.
5659 // If we have been requested to cache the values (cached_locations array
5660 // initialized), then load the arguments the first time and store them
5661 // in locals. otherwise load from local variables.
5663 void LoadArrayAndArguments (EmitContext ec)
5665 if (cached_locations == null){
5667 foreach (Argument a in ea.Arguments)
5672 ILGenerator ig = ec.ig;
5674 if (cached_locations [0] == null){
5675 cached_locations [0] = new LocalTemporary (ec, ea.Expr.Type);
5677 ig.Emit (OpCodes.Dup);
5678 cached_locations [0].Store (ec);
5682 foreach (Argument a in ea.Arguments){
5683 cached_locations [j] = new LocalTemporary (ec, a.Expr.Type);
5685 ig.Emit (OpCodes.Dup);
5686 cached_locations [j].Store (ec);
5692 foreach (LocalTemporary lt in cached_locations)
5696 public new void CacheTemporaries (EmitContext ec)
5698 cached_locations = new LocalTemporary [ea.Arguments.Count + 1];
5701 public override void Emit (EmitContext ec)
5703 int rank = ea.Expr.Type.GetArrayRank ();
5704 ILGenerator ig = ec.ig;
5706 LoadArrayAndArguments (ec);
5709 EmitLoadOpcode (ig, type);
5713 method = FetchGetMethod ();
5714 ig.Emit (OpCodes.Call, method);
5718 public void EmitAssign (EmitContext ec, Expression source)
5720 int rank = ea.Expr.Type.GetArrayRank ();
5721 ILGenerator ig = ec.ig;
5722 Type t = source.Type;
5724 LoadArrayAndArguments (ec);
5727 // The stobj opcode used by value types will need
5728 // an address on the stack, not really an array/array
5732 if (t.IsValueType && !TypeManager.IsBuiltinType (t))
5733 ig.Emit (OpCodes.Ldelema, t);
5739 EmitStoreOpcode (ig, t);
5741 ModuleBuilder mb = CodeGen.ModuleBuilder;
5742 int arg_count = ea.Arguments.Count;
5743 Type [] args = new Type [arg_count + 1];
5746 for (int i = 0; i < arg_count; i++){
5747 //args [i++] = a.Type;
5748 args [i] = TypeManager.int32_type;
5751 args [arg_count] = type;
5753 set = mb.GetArrayMethod (
5754 ea.Expr.Type, "Set",
5755 CallingConventions.HasThis |
5756 CallingConventions.Standard,
5757 TypeManager.void_type, args);
5759 ig.Emit (OpCodes.Call, set);
5763 public void AddressOf (EmitContext ec, AddressOp mode)
5765 int rank = ea.Expr.Type.GetArrayRank ();
5766 ILGenerator ig = ec.ig;
5768 LoadArrayAndArguments (ec);
5771 ig.Emit (OpCodes.Ldelema, type);
5773 MethodInfo address = FetchAddressMethod ();
5774 ig.Emit (OpCodes.Call, address);
5781 public ArrayList getters, setters;
5782 static Hashtable map;
5786 map = new Hashtable ();
5789 Indexers (MemberInfo [] mi)
5791 foreach (PropertyInfo property in mi){
5792 MethodInfo get, set;
5794 get = property.GetGetMethod (true);
5796 if (getters == null)
5797 getters = new ArrayList ();
5802 set = property.GetSetMethod (true);
5804 if (setters == null)
5805 setters = new ArrayList ();
5811 static private Indexers GetIndexersForTypeOrInterface (Type caller_type, Type lookup_type)
5813 Indexers ix = (Indexers) map [lookup_type];
5818 string p_name = TypeManager.IndexerPropertyName (lookup_type);
5820 MemberInfo [] mi = TypeManager.MemberLookup (
5821 caller_type, lookup_type, MemberTypes.Property,
5822 BindingFlags.Public | BindingFlags.Instance, p_name);
5824 if (mi == null || mi.Length == 0)
5827 ix = new Indexers (mi);
5828 map [lookup_type] = ix;
5833 static public Indexers GetIndexersForType (Type caller_type, Type lookup_type, Location loc)
5835 Indexers ix = (Indexers) map [lookup_type];
5840 ix = GetIndexersForTypeOrInterface (caller_type, lookup_type);
5844 Type [] ifaces = TypeManager.GetInterfaces (lookup_type);
5845 if (ifaces != null) {
5846 foreach (Type itype in ifaces) {
5847 ix = GetIndexersForTypeOrInterface (caller_type, itype);
5853 Report.Error (21, loc,
5854 "Type `" + TypeManager.CSharpName (lookup_type) +
5855 "' does not have any indexers defined");
5861 /// Expressions that represent an indexer call.
5863 public class IndexerAccess : Expression, IAssignMethod {
5865 // Points to our "data" repository
5868 MethodInfo get, set;
5870 ArrayList set_arguments;
5872 public IndexerAccess (ElementAccess ea_data)
5875 eclass = ExprClass.Value;
5878 public override Expression DoResolve (EmitContext ec)
5880 Type indexer_type = ea.Expr.Type;
5883 // Step 1: Query for all `Item' *properties*. Notice
5884 // that the actual methods are pointed from here.
5886 // This is a group of properties, piles of them.
5889 ilist = Indexers.GetIndexersForType (
5890 ec.ContainerType, indexer_type, ea.loc);
5894 // Step 2: find the proper match
5896 if (ilist != null && ilist.getters != null && ilist.getters.Count > 0){
5897 Location loc = ea.loc;
5899 get = (MethodInfo) Invocation.OverloadResolve (
5900 ec, new MethodGroupExpr (ilist.getters, loc), ea.Arguments, loc);
5904 Report.Error (154, ea.loc,
5905 "indexer can not be used in this context, because " +
5906 "it lacks a `get' accessor");
5910 type = get.ReturnType;
5911 if (type.IsPointer && !ec.InUnsafe){
5912 UnsafeError (ea.loc);
5916 eclass = ExprClass.IndexerAccess;
5920 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
5922 Type indexer_type = ea.Expr.Type;
5923 Type right_type = right_side.Type;
5926 ilist = Indexers.GetIndexersForType (
5927 ec.ContainerType, indexer_type, ea.loc);
5929 if (ilist != null && ilist.setters != null && ilist.setters.Count > 0){
5930 Location loc = ea.loc;
5932 set_arguments = (ArrayList) ea.Arguments.Clone ();
5933 set_arguments.Add (new Argument (right_side, Argument.AType.Expression));
5935 set = (MethodInfo) Invocation.OverloadResolve (
5936 ec, new MethodGroupExpr (ilist.setters, loc), set_arguments, loc);
5940 Report.Error (200, ea.loc,
5941 "indexer X.this [" + TypeManager.CSharpName (right_type) +
5942 "] lacks a `set' accessor");
5946 type = TypeManager.void_type;
5947 eclass = ExprClass.IndexerAccess;
5951 public override void Emit (EmitContext ec)
5953 Invocation.EmitCall (ec, false, false, ea.Expr, get, ea.Arguments, ea.loc);
5957 // source is ignored, because we already have a copy of it from the
5958 // LValue resolution and we have already constructed a pre-cached
5959 // version of the arguments (ea.set_arguments);
5961 public void EmitAssign (EmitContext ec, Expression source)
5963 Invocation.EmitCall (ec, false, false, ea.Expr, set, set_arguments, ea.loc);
5968 /// The base operator for method names
5970 public class BaseAccess : Expression {
5974 public BaseAccess (string member, Location l)
5976 this.member = member;
5980 public override Expression DoResolve (EmitContext ec)
5982 Expression member_lookup;
5983 Type current_type = ec.ContainerType;
5984 Type base_type = current_type.BaseType;
5988 Report.Error (1511, loc,
5989 "Keyword base is not allowed in static method");
5993 member_lookup = MemberLookup (ec, base_type, member, loc);
5994 if (member_lookup == null)
6000 left = new TypeExpr (base_type);
6004 e = MemberAccess.ResolveMemberAccess (ec, member_lookup, left, loc, null);
6005 if (e is PropertyExpr){
6006 PropertyExpr pe = (PropertyExpr) e;
6014 public override void Emit (EmitContext ec)
6016 throw new Exception ("Should never be called");
6021 /// The base indexer operator
6023 public class BaseIndexerAccess : Expression {
6024 ArrayList Arguments;
6027 public BaseIndexerAccess (ArrayList args, Location l)
6033 public override Expression DoResolve (EmitContext ec)
6035 Type current_type = ec.ContainerType;
6036 Type base_type = current_type.BaseType;
6037 Expression member_lookup;
6040 Report.Error (1511, loc,
6041 "Keyword base is not allowed in static method");
6045 member_lookup = MemberLookup (ec, base_type, "get_Item", MemberTypes.Method, AllBindingFlags, loc);
6046 if (member_lookup == null)
6049 return MemberAccess.ResolveMemberAccess (ec, member_lookup, ec.This, loc, null);
6052 public override void Emit (EmitContext ec)
6054 throw new Exception ("Should never be called");
6059 /// This class exists solely to pass the Type around and to be a dummy
6060 /// that can be passed to the conversion functions (this is used by
6061 /// foreach implementation to typecast the object return value from
6062 /// get_Current into the proper type. All code has been generated and
6063 /// we only care about the side effect conversions to be performed
6065 /// This is also now used as a placeholder where a no-action expression
6066 /// is needed (the `New' class).
6068 public class EmptyExpression : Expression {
6069 public EmptyExpression ()
6071 type = TypeManager.object_type;
6072 eclass = ExprClass.Value;
6075 public EmptyExpression (Type t)
6078 eclass = ExprClass.Value;
6081 public override Expression DoResolve (EmitContext ec)
6086 public override void Emit (EmitContext ec)
6088 // nothing, as we only exist to not do anything.
6092 // This is just because we might want to reuse this bad boy
6093 // instead of creating gazillions of EmptyExpressions.
6094 // (CanConvertImplicit uses it)
6096 public void SetType (Type t)
6102 public class UserCast : Expression {
6106 public UserCast (MethodInfo method, Expression source)
6108 this.method = method;
6109 this.source = source;
6110 type = method.ReturnType;
6111 eclass = ExprClass.Value;
6114 public override Expression DoResolve (EmitContext ec)
6117 // We are born fully resolved
6122 public override void Emit (EmitContext ec)
6124 ILGenerator ig = ec.ig;
6128 if (method is MethodInfo)
6129 ig.Emit (OpCodes.Call, (MethodInfo) method);
6131 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
6137 // This class is used to "construct" the type during a typecast
6138 // operation. Since the Type.GetType class in .NET can parse
6139 // the type specification, we just use this to construct the type
6140 // one bit at a time.
6142 public class ComposedCast : Expression {
6147 public ComposedCast (Expression left, string dim, Location l)
6154 public override Expression DoResolve (EmitContext ec)
6156 left = left.Resolve (ec);
6160 if (left.eclass != ExprClass.Type){
6161 report118 (loc, left, "type");
6165 type = RootContext.LookupType (
6166 ec.DeclSpace, left.Type.FullName + dim, false, loc);
6170 if (!ec.InUnsafe && type.IsPointer){
6175 eclass = ExprClass.Type;
6179 public override void Emit (EmitContext ec)
6181 throw new Exception ("This should never be called");
6186 // This class is used to represent the address of an array, used
6187 // only by the Fixed statement, this is like the C "&a [0]" construct.
6189 public class ArrayPtr : Expression {
6192 public ArrayPtr (Expression array)
6194 Type array_type = array.Type.GetElementType ();
6198 string array_ptr_type_name = array_type.FullName + "*";
6200 type = Type.GetType (array_ptr_type_name);
6202 ModuleBuilder mb = CodeGen.ModuleBuilder;
6204 type = mb.GetType (array_ptr_type_name);
6207 eclass = ExprClass.Value;
6210 public override void Emit (EmitContext ec)
6212 ILGenerator ig = ec.ig;
6215 IntLiteral.EmitInt (ig, 0);
6216 ig.Emit (OpCodes.Ldelema, array.Type.GetElementType ());
6219 public override Expression DoResolve (EmitContext ec)
6222 // We are born fully resolved
6229 // Used by the fixed statement
6231 public class StringPtr : Expression {
6234 public StringPtr (LocalBuilder b)
6237 eclass = ExprClass.Value;
6238 type = TypeManager.char_ptr_type;
6241 public override Expression DoResolve (EmitContext ec)
6243 // This should never be invoked, we are born in fully
6244 // initialized state.
6249 public override void Emit (EmitContext ec)
6251 ILGenerator ig = ec.ig;
6253 ig.Emit (OpCodes.Ldloc, b);
6254 ig.Emit (OpCodes.Conv_I);
6255 ig.Emit (OpCodes.Call, TypeManager.int_get_offset_to_string_data);
6256 ig.Emit (OpCodes.Add);
6261 // Implements the `stackalloc' keyword
6263 public class StackAlloc : Expression {
6269 public StackAlloc (string type, Expression count, Location l)
6276 public override Expression DoResolve (EmitContext ec)
6278 count = count.Resolve (ec);
6282 if (count.Type != TypeManager.int32_type){
6283 count = ConvertImplicitRequired (ec, count, TypeManager.int32_type, loc);
6288 if (ec.InCatch || ec.InFinally){
6289 Report.Error (255, loc,
6290 "stackalloc can not be used in a catch or finally block");
6294 otype = RootContext.LookupType (ec.DeclSpace, t, false, loc);
6299 if (!TypeManager.VerifyUnManaged (otype, loc))
6302 string ptr_name = otype.FullName + "*";
6303 type = Type.GetType (ptr_name);
6305 ModuleBuilder mb = CodeGen.ModuleBuilder;
6307 type = mb.GetType (ptr_name);
6309 eclass = ExprClass.Value;
6314 public override void Emit (EmitContext ec)
6316 int size = GetTypeSize (otype);
6317 ILGenerator ig = ec.ig;
6320 ig.Emit (OpCodes.Sizeof, otype);
6322 IntConstant.EmitInt (ig, size);
6324 ig.Emit (OpCodes.Mul);
6325 ig.Emit (OpCodes.Localloc);