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.Diagnostics;
16 using System.Reflection;
17 using System.Reflection.Emit;
21 /// This is just a helper class, it is generated by Unary, UnaryMutator
22 /// when an overloaded method has been found. It just emits the code for a
25 public class StaticCallExpr : ExpressionStatement {
29 StaticCallExpr (MethodInfo m, ArrayList a)
35 eclass = ExprClass.Value;
38 public override Expression DoResolve (EmitContext ec)
41 // We are born fully resolved
46 public override void Emit (EmitContext ec)
49 Invocation.EmitArguments (ec, mi, args);
51 ec.ig.Emit (OpCodes.Call, mi);
55 static public Expression MakeSimpleCall (EmitContext ec, MethodGroupExpr mg,
56 Expression e, Location loc)
61 args = new ArrayList (1);
62 args.Add (new Argument (e, Argument.AType.Expression));
63 method = Invocation.OverloadResolve (ec, (MethodGroupExpr) mg, args, loc);
68 return new StaticCallExpr ((MethodInfo) method, args);
71 public override void EmitStatement (EmitContext ec)
74 if (type != TypeManager.void_type)
75 ec.ig.Emit (OpCodes.Pop);
80 /// Unary expressions.
84 /// Unary implements unary expressions. It derives from
85 /// ExpressionStatement becuase the pre/post increment/decrement
86 /// operators can be used in a statement context.
88 public class Unary : Expression {
89 public enum Operator : byte {
90 UnaryPlus, UnaryNegation, LogicalNot, OnesComplement,
91 Indirection, AddressOf, TOP
98 public Unary (Operator op, Expression expr, Location loc)
105 public Expression Expr {
115 public Operator Oper {
126 /// Returns a stringified representation of the Operator
128 static public string OperName (Operator oper)
131 case Operator.UnaryPlus:
133 case Operator.UnaryNegation:
135 case Operator.LogicalNot:
137 case Operator.OnesComplement:
139 case Operator.AddressOf:
141 case Operator.Indirection:
145 return oper.ToString ();
148 static string [] oper_names;
152 oper_names = new string [(int)Operator.TOP];
154 oper_names [(int) Operator.UnaryPlus] = "op_UnaryPlus";
155 oper_names [(int) Operator.UnaryNegation] = "op_UnaryNegation";
156 oper_names [(int) Operator.LogicalNot] = "op_LogicalNot";
157 oper_names [(int) Operator.OnesComplement] = "op_OnesComplement";
158 oper_names [(int) Operator.Indirection] = "op_Indirection";
159 oper_names [(int) Operator.AddressOf] = "op_AddressOf";
162 void Error23 (Type t)
165 23, loc, "Operator " + OperName (oper) +
166 " cannot be applied to operand of type `" +
167 TypeManager.CSharpName (t) + "'");
171 /// The result has been already resolved:
173 /// FIXME: a minus constant -128 sbyte cant be turned into a
176 static Expression TryReduceNegative (Expression expr)
180 if (expr is IntConstant)
181 e = new IntConstant (-((IntConstant) expr).Value);
182 else if (expr is UIntConstant)
183 e = new LongConstant (-((UIntConstant) expr).Value);
184 else if (expr is LongConstant)
185 e = new LongConstant (-((LongConstant) expr).Value);
186 else if (expr is FloatConstant)
187 e = new FloatConstant (-((FloatConstant) expr).Value);
188 else if (expr is DoubleConstant)
189 e = new DoubleConstant (-((DoubleConstant) expr).Value);
190 else if (expr is DecimalConstant)
191 e = new DecimalConstant (-((DecimalConstant) expr).Value);
192 else if (expr is ShortConstant)
193 e = new IntConstant (-((ShortConstant) expr).Value);
194 else if (expr is UShortConstant)
195 e = new IntConstant (-((UShortConstant) expr).Value);
200 Expression Reduce (EmitContext ec, Expression e)
202 Type expr_type = e.Type;
205 case Operator.UnaryPlus:
208 case Operator.UnaryNegation:
209 return TryReduceNegative (e);
211 case Operator.LogicalNot:
212 if (expr_type != TypeManager.bool_type) {
217 BoolConstant b = (BoolConstant) e;
218 return new BoolConstant (!(b.Value));
220 case Operator.OnesComplement:
221 if (!((expr_type == TypeManager.int32_type) ||
222 (expr_type == TypeManager.uint32_type) ||
223 (expr_type == TypeManager.int64_type) ||
224 (expr_type == TypeManager.uint64_type) ||
225 (expr_type.IsSubclassOf (TypeManager.enum_type)))){
230 if (e is EnumConstant){
231 EnumConstant enum_constant = (EnumConstant) e;
233 Expression reduced = Reduce (ec, enum_constant.Child);
235 return new EnumConstant ((Constant) reduced, enum_constant.Type);
238 if (expr_type == TypeManager.int32_type)
239 return new IntConstant (~ ((IntConstant) e).Value);
240 if (expr_type == TypeManager.uint32_type)
241 return new UIntConstant (~ ((UIntConstant) e).Value);
242 if (expr_type == TypeManager.int64_type)
243 return new LongConstant (~ ((LongConstant) e).Value);
244 if (expr_type == TypeManager.uint64_type)
245 return new ULongConstant (~ ((ULongConstant) e).Value);
250 throw new Exception ("Can not constant fold");
253 Expression ResolveOperator (EmitContext ec)
255 Type expr_type = expr.Type;
258 // Step 1: Perform Operator Overload location
263 op_name = oper_names [(int) oper];
265 mg = MemberLookup (ec, expr_type, op_name, MemberTypes.Method, AllBindingFlags, loc);
268 Expression e = StaticCallExpr.MakeSimpleCall (
269 ec, (MethodGroupExpr) mg, expr, loc);
279 // Only perform numeric promotions on:
282 if (expr_type == null)
286 // Step 2: Default operations on CLI native types.
288 if (expr is Constant)
289 return Reduce (ec, expr);
291 if (oper == Operator.LogicalNot){
292 if (expr_type != TypeManager.bool_type) {
297 type = TypeManager.bool_type;
301 if (oper == Operator.OnesComplement) {
302 if (!((expr_type == TypeManager.int32_type) ||
303 (expr_type == TypeManager.uint32_type) ||
304 (expr_type == TypeManager.int64_type) ||
305 (expr_type == TypeManager.uint64_type) ||
306 (expr_type.IsSubclassOf (TypeManager.enum_type)))){
314 if (oper == Operator.UnaryPlus) {
316 // A plus in front of something is just a no-op, so return the child.
322 // Deals with -literals
323 // int operator- (int x)
324 // long operator- (long x)
325 // float operator- (float f)
326 // double operator- (double d)
327 // decimal operator- (decimal d)
329 if (oper == Operator.UnaryNegation){
333 // perform numeric promotions to int,
337 // The following is inneficient, because we call
338 // ConvertImplicit too many times.
340 // It is also not clear if we should convert to Float
341 // or Double initially.
343 if (expr_type == TypeManager.uint32_type){
345 // FIXME: handle exception to this rule that
346 // permits the int value -2147483648 (-2^31) to
347 // bt wrote as a decimal interger literal
349 type = TypeManager.int64_type;
350 expr = ConvertImplicit (ec, expr, type, loc);
354 if (expr_type == TypeManager.uint64_type){
356 // FIXME: Handle exception of `long value'
357 // -92233720368547758087 (-2^63) to be wrote as
358 // decimal integer literal.
364 if (expr_type == TypeManager.float_type){
369 e = ConvertImplicit (ec, expr, TypeManager.int32_type, loc);
376 e = ConvertImplicit (ec, expr, TypeManager.int64_type, loc);
383 e = ConvertImplicit (ec, expr, TypeManager.double_type, loc);
394 if (oper == Operator.AddressOf){
395 if (expr.eclass != ExprClass.Variable){
396 Error (211, loc, "Cannot take the address of non-variables");
405 if (!TypeManager.VerifyUnManaged (expr.Type, loc)){
410 // This construct is needed because dynamic types
411 // are not known by Type.GetType, so we have to try then to use
412 // ModuleBuilder.GetType.
414 string ptr_type_name = expr.Type.FullName + "*";
415 type = Type.GetType (ptr_type_name);
417 type = RootContext.ModuleBuilder.GetType (ptr_type_name);
422 if (oper == Operator.Indirection){
428 if (!expr_type.IsPointer){
431 "The * or -> operator can only be applied to pointers");
436 // We create an Indirection expression, because
437 // it can implement the IMemoryLocation.
439 return new Indirection (expr);
442 Error (187, loc, "No such operator '" + OperName (oper) + "' defined for type '" +
443 TypeManager.CSharpName (expr_type) + "'");
447 public override Expression DoResolve (EmitContext ec)
449 expr = expr.Resolve (ec);
454 eclass = ExprClass.Value;
455 return ResolveOperator (ec);
458 public override void Emit (EmitContext ec)
460 ILGenerator ig = ec.ig;
461 Type expr_type = expr.Type;
464 case Operator.UnaryPlus:
465 throw new Exception ("This should be caught by Resolve");
467 case Operator.UnaryNegation:
469 ig.Emit (OpCodes.Neg);
472 case Operator.LogicalNot:
474 ig.Emit (OpCodes.Ldc_I4_0);
475 ig.Emit (OpCodes.Ceq);
478 case Operator.OnesComplement:
480 ig.Emit (OpCodes.Not);
483 case Operator.AddressOf:
484 ((IMemoryLocation)expr).AddressOf (ec, AddressOp.LoadStore);
488 throw new Exception ("This should not happen: Operator = "
494 /// This will emit the child expression for `ec' avoiding the logical
495 /// not. The parent will take care of changing brfalse/brtrue
497 public void EmitLogicalNot (EmitContext ec)
499 if (oper != Operator.LogicalNot)
500 throw new Exception ("EmitLogicalNot can only be called with !expr");
505 public override string ToString ()
507 return "Unary (" + oper + ", " + expr + ")";
513 // Unary operators are turned into Indirection expressions
514 // after semantic analysis (this is so we can take the address
515 // of an indirection).
517 public class Indirection : Expression, IMemoryLocation, IAssignMethod {
520 public Indirection (Expression expr)
523 this.type = expr.Type.GetElementType ();
524 eclass = ExprClass.Variable;
527 public override void Emit (EmitContext ec)
530 LoadFromPtr (ec.ig, Type, false);
533 public void EmitAssign (EmitContext ec, Expression source)
537 StoreFromPtr (ec.ig, type);
540 public void AddressOf (EmitContext ec, AddressOp Mode)
545 public override Expression DoResolve (EmitContext ec)
548 // Born fully resolved
555 /// Unary Mutator expressions (pre and post ++ and --)
559 /// UnaryMutator implements ++ and -- expressions. It derives from
560 /// ExpressionStatement becuase the pre/post increment/decrement
561 /// operators can be used in a statement context.
563 /// FIXME: Idea, we could split this up in two classes, one simpler
564 /// for the common case, and one with the extra fields for more complex
565 /// classes (indexers require temporary access; overloaded require method)
567 /// Maybe we should have classes PreIncrement, PostIncrement, PreDecrement,
568 /// PostDecrement, that way we could save the `Mode' byte as well.
570 public class UnaryMutator : ExpressionStatement {
571 public enum Mode : byte {
572 PreIncrement, PreDecrement, PostIncrement, PostDecrement
578 LocalTemporary temp_storage;
581 // This is expensive for the simplest case.
585 public UnaryMutator (Mode m, Expression e, Location l)
592 static string OperName (Mode mode)
594 return (mode == Mode.PreIncrement || mode == Mode.PostIncrement) ?
598 void Error23 (Type t)
601 23, loc, "Operator " + OperName (mode) +
602 " cannot be applied to operand of type `" +
603 TypeManager.CSharpName (t) + "'");
607 /// Returns whether an object of type `t' can be incremented
608 /// or decremented with add/sub (ie, basically whether we can
609 /// use pre-post incr-decr operations on it, but it is not a
610 /// System.Decimal, which we require operator overloading to catch)
612 static bool IsIncrementableNumber (Type t)
614 return (t == TypeManager.sbyte_type) ||
615 (t == TypeManager.byte_type) ||
616 (t == TypeManager.short_type) ||
617 (t == TypeManager.ushort_type) ||
618 (t == TypeManager.int32_type) ||
619 (t == TypeManager.uint32_type) ||
620 (t == TypeManager.int64_type) ||
621 (t == TypeManager.uint64_type) ||
622 (t == TypeManager.char_type) ||
623 (t.IsSubclassOf (TypeManager.enum_type)) ||
624 (t == TypeManager.float_type) ||
625 (t == TypeManager.double_type) ||
626 (t.IsPointer && t != TypeManager.void_ptr_type);
629 Expression ResolveOperator (EmitContext ec)
631 Type expr_type = expr.Type;
634 // Step 1: Perform Operator Overload location
639 if (mode == Mode.PreIncrement || mode == Mode.PostIncrement)
640 op_name = "op_Increment";
642 op_name = "op_Decrement";
644 mg = MemberLookup (ec, expr_type, op_name, MemberTypes.Method, AllBindingFlags, loc);
646 if (mg == null && expr_type.BaseType != null)
647 mg = MemberLookup (ec, expr_type.BaseType, op_name,
648 MemberTypes.Method, AllBindingFlags, loc);
651 method = StaticCallExpr.MakeSimpleCall (
652 ec, (MethodGroupExpr) mg, expr, loc);
659 // The operand of the prefix/postfix increment decrement operators
660 // should be an expression that is classified as a variable,
661 // a property access or an indexer access
664 if (expr.eclass == ExprClass.Variable){
665 if (IsIncrementableNumber (expr_type) ||
666 expr_type == TypeManager.decimal_type){
669 } else if (expr.eclass == ExprClass.IndexerAccess){
670 IndexerAccess ia = (IndexerAccess) expr;
672 temp_storage = new LocalTemporary (ec, expr.Type);
674 expr = ia.ResolveLValue (ec, temp_storage);
679 } else if (expr.eclass == ExprClass.PropertyAccess){
680 PropertyExpr pe = (PropertyExpr) expr;
682 if (pe.VerifyAssignable ())
687 report118 (loc, expr, "variable, indexer or property access");
691 Error (187, loc, "No such operator '" + OperName (mode) + "' defined for type '" +
692 TypeManager.CSharpName (expr_type) + "'");
696 public override Expression DoResolve (EmitContext ec)
698 expr = expr.Resolve (ec);
703 eclass = ExprClass.Value;
704 return ResolveOperator (ec);
707 static int PtrTypeSize (Type t)
709 return GetTypeSize (t.GetElementType ());
714 // FIXME: We need some way of avoiding the use of temp_storage
715 // for some types of storage (parameters, local variables,
716 // static fields) and single-dimension array access.
718 void EmitCode (EmitContext ec, bool is_expr)
720 ILGenerator ig = ec.ig;
721 IAssignMethod ia = (IAssignMethod) expr;
722 Type expr_type = expr.Type;
724 if (temp_storage == null)
725 temp_storage = new LocalTemporary (ec, expr_type);
728 case Mode.PreIncrement:
729 case Mode.PreDecrement:
733 if (expr_type == TypeManager.uint64_type ||
734 expr_type == TypeManager.int64_type)
735 ig.Emit (OpCodes.Ldc_I8, 1L);
736 else if (expr_type == TypeManager.double_type)
737 ig.Emit (OpCodes.Ldc_R8, 1.0);
738 else if (expr_type == TypeManager.float_type)
739 ig.Emit (OpCodes.Ldc_R4, 1.0F);
740 else if (expr_type.IsPointer){
741 int n = PtrTypeSize (expr_type);
744 ig.Emit (OpCodes.Sizeof, expr_type);
746 IntConstant.EmitInt (ig, n);
748 ig.Emit (OpCodes.Ldc_I4_1);
750 if (mode == Mode.PreDecrement)
751 ig.Emit (OpCodes.Sub);
753 ig.Emit (OpCodes.Add);
757 temp_storage.Store (ec);
758 ia.EmitAssign (ec, temp_storage);
760 temp_storage.Emit (ec);
763 case Mode.PostIncrement:
764 case Mode.PostDecrement:
772 ig.Emit (OpCodes.Dup);
774 if (expr_type == TypeManager.uint64_type ||
775 expr_type == TypeManager.int64_type)
776 ig.Emit (OpCodes.Ldc_I8, 1L);
777 else if (expr_type == TypeManager.double_type)
778 ig.Emit (OpCodes.Ldc_R8, 1.0);
779 else if (expr_type == TypeManager.float_type)
780 ig.Emit (OpCodes.Ldc_R4, 1.0F);
781 else if (expr_type.IsPointer){
782 int n = PtrTypeSize (expr_type);
785 ig.Emit (OpCodes.Sizeof, expr_type);
787 IntConstant.EmitInt (ig, n);
789 ig.Emit (OpCodes.Ldc_I4_1);
791 if (mode == Mode.PostDecrement)
792 ig.Emit (OpCodes.Sub);
794 ig.Emit (OpCodes.Add);
799 temp_storage.Store (ec);
800 ia.EmitAssign (ec, temp_storage);
805 public override void Emit (EmitContext ec)
811 public override void EmitStatement (EmitContext ec)
813 EmitCode (ec, false);
819 /// Base class for the `Is' and `As' classes.
823 /// FIXME: Split this in two, and we get to save the `Operator' Oper
826 public abstract class Probe : Expression {
827 public readonly string ProbeType;
828 protected Expression expr;
829 protected Type probe_type;
830 protected Location loc;
832 public Probe (Expression expr, string probe_type, Location l)
834 ProbeType = probe_type;
839 public Expression Expr {
845 public override Expression DoResolve (EmitContext ec)
847 probe_type = RootContext.LookupType (ec.TypeContainer, ProbeType, false, loc);
849 if (probe_type == null)
852 expr = expr.Resolve (ec);
859 /// Implementation of the `is' operator.
861 public class Is : Probe {
862 public Is (Expression expr, string probe_type, Location l)
863 : base (expr, probe_type, l)
867 public override void Emit (EmitContext ec)
869 ILGenerator ig = ec.ig;
873 ig.Emit (OpCodes.Isinst, probe_type);
874 ig.Emit (OpCodes.Ldnull);
875 ig.Emit (OpCodes.Cgt_Un);
878 public override Expression DoResolve (EmitContext ec)
880 Expression e = base.DoResolve (ec);
885 if (RootContext.WarningLevel >= 1){
886 if (expr.Type == probe_type || expr.Type.IsSubclassOf (probe_type)){
889 "The expression is always of type `" +
890 TypeManager.CSharpName (probe_type) + "'");
893 if (expr.Type != probe_type && !probe_type.IsSubclassOf (expr.Type)){
894 if (!probe_type.IsInterface)
897 "The expression is never of type `" +
898 TypeManager.CSharpName (probe_type) + "'");
902 type = TypeManager.bool_type;
903 eclass = ExprClass.Value;
910 /// Implementation of the `as' operator.
912 public class As : Probe {
913 public As (Expression expr, string probe_type, Location l)
914 : base (expr, probe_type, l)
918 public override void Emit (EmitContext ec)
920 ILGenerator ig = ec.ig;
923 ig.Emit (OpCodes.Isinst, probe_type);
926 public override Expression DoResolve (EmitContext ec)
928 Expression e = base.DoResolve (ec);
934 eclass = ExprClass.Value;
941 /// This represents a typecast in the source language.
943 /// FIXME: Cast expressions have an unusual set of parsing
944 /// rules, we need to figure those out.
946 public class Cast : Expression {
947 Expression target_type;
951 public Cast (Expression cast_type, Expression expr, Location loc)
953 this.target_type = cast_type;
958 public Expression TargetType {
964 public Expression Expr {
974 /// Attempts to do a compile-time folding of a constant cast.
976 Expression TryReduce (EmitContext ec, Type target_type)
978 if (expr is ByteConstant){
979 byte v = ((ByteConstant) expr).Value;
981 if (target_type == TypeManager.sbyte_type)
982 return new SByteConstant ((sbyte) v);
983 if (target_type == TypeManager.short_type)
984 return new ShortConstant ((short) v);
985 if (target_type == TypeManager.ushort_type)
986 return new UShortConstant ((ushort) v);
987 if (target_type == TypeManager.int32_type)
988 return new IntConstant ((int) v);
989 if (target_type == TypeManager.uint32_type)
990 return new UIntConstant ((uint) v);
991 if (target_type == TypeManager.int64_type)
992 return new LongConstant ((long) v);
993 if (target_type == TypeManager.uint64_type)
994 return new ULongConstant ((ulong) v);
995 if (target_type == TypeManager.float_type)
996 return new FloatConstant ((float) v);
997 if (target_type == TypeManager.double_type)
998 return new DoubleConstant ((double) v);
1000 if (expr is SByteConstant){
1001 sbyte v = ((SByteConstant) expr).Value;
1003 if (target_type == TypeManager.byte_type)
1004 return new ByteConstant ((byte) v);
1005 if (target_type == TypeManager.short_type)
1006 return new ShortConstant ((short) v);
1007 if (target_type == TypeManager.ushort_type)
1008 return new UShortConstant ((ushort) v);
1009 if (target_type == TypeManager.int32_type)
1010 return new IntConstant ((int) v);
1011 if (target_type == TypeManager.uint32_type)
1012 return new UIntConstant ((uint) v);
1013 if (target_type == TypeManager.int64_type)
1014 return new LongConstant ((long) v);
1015 if (target_type == TypeManager.uint64_type)
1016 return new ULongConstant ((ulong) v);
1017 if (target_type == TypeManager.float_type)
1018 return new FloatConstant ((float) v);
1019 if (target_type == TypeManager.double_type)
1020 return new DoubleConstant ((double) v);
1022 if (expr is ShortConstant){
1023 short v = ((ShortConstant) expr).Value;
1025 if (target_type == TypeManager.byte_type)
1026 return new ByteConstant ((byte) v);
1027 if (target_type == TypeManager.sbyte_type)
1028 return new SByteConstant ((sbyte) v);
1029 if (target_type == TypeManager.ushort_type)
1030 return new UShortConstant ((ushort) v);
1031 if (target_type == TypeManager.int32_type)
1032 return new IntConstant ((int) v);
1033 if (target_type == TypeManager.uint32_type)
1034 return new UIntConstant ((uint) v);
1035 if (target_type == TypeManager.int64_type)
1036 return new LongConstant ((long) v);
1037 if (target_type == TypeManager.uint64_type)
1038 return new ULongConstant ((ulong) v);
1039 if (target_type == TypeManager.float_type)
1040 return new FloatConstant ((float) v);
1041 if (target_type == TypeManager.double_type)
1042 return new DoubleConstant ((double) v);
1044 if (expr is UShortConstant){
1045 ushort v = ((UShortConstant) expr).Value;
1047 if (target_type == TypeManager.byte_type)
1048 return new ByteConstant ((byte) v);
1049 if (target_type == TypeManager.sbyte_type)
1050 return new SByteConstant ((sbyte) v);
1051 if (target_type == TypeManager.short_type)
1052 return new ShortConstant ((short) v);
1053 if (target_type == TypeManager.int32_type)
1054 return new IntConstant ((int) v);
1055 if (target_type == TypeManager.uint32_type)
1056 return new UIntConstant ((uint) v);
1057 if (target_type == TypeManager.int64_type)
1058 return new LongConstant ((long) v);
1059 if (target_type == TypeManager.uint64_type)
1060 return new ULongConstant ((ulong) v);
1061 if (target_type == TypeManager.float_type)
1062 return new FloatConstant ((float) v);
1063 if (target_type == TypeManager.double_type)
1064 return new DoubleConstant ((double) v);
1066 if (expr is IntConstant){
1067 int v = ((IntConstant) expr).Value;
1069 if (target_type == TypeManager.byte_type)
1070 return new ByteConstant ((byte) v);
1071 if (target_type == TypeManager.sbyte_type)
1072 return new SByteConstant ((sbyte) v);
1073 if (target_type == TypeManager.short_type)
1074 return new ShortConstant ((short) v);
1075 if (target_type == TypeManager.ushort_type)
1076 return new UShortConstant ((ushort) v);
1077 if (target_type == TypeManager.uint32_type)
1078 return new UIntConstant ((uint) v);
1079 if (target_type == TypeManager.int64_type)
1080 return new LongConstant ((long) v);
1081 if (target_type == TypeManager.uint64_type)
1082 return new ULongConstant ((ulong) v);
1083 if (target_type == TypeManager.float_type)
1084 return new FloatConstant ((float) v);
1085 if (target_type == TypeManager.double_type)
1086 return new DoubleConstant ((double) v);
1088 if (expr is UIntConstant){
1089 uint v = ((UIntConstant) expr).Value;
1091 if (target_type == TypeManager.byte_type)
1092 return new ByteConstant ((byte) v);
1093 if (target_type == TypeManager.sbyte_type)
1094 return new SByteConstant ((sbyte) v);
1095 if (target_type == TypeManager.short_type)
1096 return new ShortConstant ((short) v);
1097 if (target_type == TypeManager.ushort_type)
1098 return new UShortConstant ((ushort) v);
1099 if (target_type == TypeManager.int32_type)
1100 return new IntConstant ((int) v);
1101 if (target_type == TypeManager.int64_type)
1102 return new LongConstant ((long) v);
1103 if (target_type == TypeManager.uint64_type)
1104 return new ULongConstant ((ulong) v);
1105 if (target_type == TypeManager.float_type)
1106 return new FloatConstant ((float) v);
1107 if (target_type == TypeManager.double_type)
1108 return new DoubleConstant ((double) v);
1110 if (expr is LongConstant){
1111 long v = ((LongConstant) expr).Value;
1113 if (target_type == TypeManager.byte_type)
1114 return new ByteConstant ((byte) v);
1115 if (target_type == TypeManager.sbyte_type)
1116 return new SByteConstant ((sbyte) v);
1117 if (target_type == TypeManager.short_type)
1118 return new ShortConstant ((short) v);
1119 if (target_type == TypeManager.ushort_type)
1120 return new UShortConstant ((ushort) v);
1121 if (target_type == TypeManager.int32_type)
1122 return new IntConstant ((int) v);
1123 if (target_type == TypeManager.uint32_type)
1124 return new UIntConstant ((uint) v);
1125 if (target_type == TypeManager.uint64_type)
1126 return new ULongConstant ((ulong) v);
1127 if (target_type == TypeManager.float_type)
1128 return new FloatConstant ((float) v);
1129 if (target_type == TypeManager.double_type)
1130 return new DoubleConstant ((double) v);
1132 if (expr is ULongConstant){
1133 ulong v = ((ULongConstant) expr).Value;
1135 if (target_type == TypeManager.byte_type)
1136 return new ByteConstant ((byte) v);
1137 if (target_type == TypeManager.sbyte_type)
1138 return new SByteConstant ((sbyte) v);
1139 if (target_type == TypeManager.short_type)
1140 return new ShortConstant ((short) v);
1141 if (target_type == TypeManager.ushort_type)
1142 return new UShortConstant ((ushort) v);
1143 if (target_type == TypeManager.int32_type)
1144 return new IntConstant ((int) v);
1145 if (target_type == TypeManager.uint32_type)
1146 return new UIntConstant ((uint) v);
1147 if (target_type == TypeManager.int64_type)
1148 return new LongConstant ((long) v);
1149 if (target_type == TypeManager.float_type)
1150 return new FloatConstant ((float) v);
1151 if (target_type == TypeManager.double_type)
1152 return new DoubleConstant ((double) v);
1154 if (expr is FloatConstant){
1155 float v = ((FloatConstant) expr).Value;
1157 if (target_type == TypeManager.byte_type)
1158 return new ByteConstant ((byte) v);
1159 if (target_type == TypeManager.sbyte_type)
1160 return new SByteConstant ((sbyte) v);
1161 if (target_type == TypeManager.short_type)
1162 return new ShortConstant ((short) v);
1163 if (target_type == TypeManager.ushort_type)
1164 return new UShortConstant ((ushort) v);
1165 if (target_type == TypeManager.int32_type)
1166 return new IntConstant ((int) v);
1167 if (target_type == TypeManager.uint32_type)
1168 return new UIntConstant ((uint) v);
1169 if (target_type == TypeManager.int64_type)
1170 return new LongConstant ((long) v);
1171 if (target_type == TypeManager.uint64_type)
1172 return new ULongConstant ((ulong) v);
1173 if (target_type == TypeManager.double_type)
1174 return new DoubleConstant ((double) v);
1176 if (expr is DoubleConstant){
1177 double v = ((DoubleConstant) expr).Value;
1179 if (target_type == TypeManager.byte_type)
1180 return new ByteConstant ((byte) v);
1181 if (target_type == TypeManager.sbyte_type)
1182 return new SByteConstant ((sbyte) v);
1183 if (target_type == TypeManager.short_type)
1184 return new ShortConstant ((short) v);
1185 if (target_type == TypeManager.ushort_type)
1186 return new UShortConstant ((ushort) v);
1187 if (target_type == TypeManager.int32_type)
1188 return new IntConstant ((int) v);
1189 if (target_type == TypeManager.uint32_type)
1190 return new UIntConstant ((uint) v);
1191 if (target_type == TypeManager.int64_type)
1192 return new LongConstant ((long) v);
1193 if (target_type == TypeManager.uint64_type)
1194 return new ULongConstant ((ulong) v);
1195 if (target_type == TypeManager.float_type)
1196 return new FloatConstant ((float) v);
1202 public override Expression DoResolve (EmitContext ec)
1204 expr = expr.Resolve (ec);
1208 target_type = target_type.Resolve (ec);
1209 if (target_type == null)
1212 if (target_type.eclass != ExprClass.Type){
1213 report118 (loc, target_type, "class");
1217 type = target_type.Type;
1218 eclass = ExprClass.Value;
1223 if (expr is Constant){
1224 Expression e = TryReduce (ec, type);
1230 expr = ConvertExplicit (ec, expr, type, loc);
1234 public override void Emit (EmitContext ec)
1237 // This one will never happen
1239 throw new Exception ("Should not happen");
1244 /// Binary operators
1246 public class Binary : Expression {
1247 public enum Operator : byte {
1248 Multiply, Division, Modulus,
1249 Addition, Subtraction,
1250 LeftShift, RightShift,
1251 LessThan, GreaterThan, LessThanOrEqual, GreaterThanOrEqual,
1252 Equality, Inequality,
1261 Expression left, right;
1263 ArrayList Arguments;
1266 bool DelegateOperation;
1268 public Binary (Operator oper, Expression left, Expression right, Location loc)
1276 public Operator Oper {
1285 public Expression Left {
1294 public Expression Right {
1305 /// Returns a stringified representation of the Operator
1307 static string OperName (Operator oper)
1310 case Operator.Multiply:
1312 case Operator.Division:
1314 case Operator.Modulus:
1316 case Operator.Addition:
1318 case Operator.Subtraction:
1320 case Operator.LeftShift:
1322 case Operator.RightShift:
1324 case Operator.LessThan:
1326 case Operator.GreaterThan:
1328 case Operator.LessThanOrEqual:
1330 case Operator.GreaterThanOrEqual:
1332 case Operator.Equality:
1334 case Operator.Inequality:
1336 case Operator.BitwiseAnd:
1338 case Operator.BitwiseOr:
1340 case Operator.ExclusiveOr:
1342 case Operator.LogicalOr:
1344 case Operator.LogicalAnd:
1348 return oper.ToString ();
1351 Expression ForceConversion (EmitContext ec, Expression expr, Type target_type)
1353 if (expr.Type == target_type)
1356 return ConvertImplicit (ec, expr, target_type, new Location (-1));
1359 public static void Error_OperatorAmbiguous (Location loc, Operator oper, Type l, Type r)
1362 34, loc, "Operator `" + OperName (oper)
1363 + "' is ambiguous on operands of type `"
1364 + TypeManager.CSharpName (l) + "' "
1365 + "and `" + TypeManager.CSharpName (r)
1370 // Note that handling the case l == Decimal || r == Decimal
1371 // is taken care of by the Step 1 Operator Overload resolution.
1373 bool DoNumericPromotions (EmitContext ec, Type l, Type r)
1375 if (l == TypeManager.double_type || r == TypeManager.double_type){
1377 // If either operand is of type double, the other operand is
1378 // conveted to type double.
1380 if (r != TypeManager.double_type)
1381 right = ConvertImplicit (ec, right, TypeManager.double_type, loc);
1382 if (l != TypeManager.double_type)
1383 left = ConvertImplicit (ec, left, TypeManager.double_type, loc);
1385 type = TypeManager.double_type;
1386 } else if (l == TypeManager.float_type || r == TypeManager.float_type){
1388 // if either operand is of type float, the other operand is
1389 // converted to type float.
1391 if (r != TypeManager.double_type)
1392 right = ConvertImplicit (ec, right, TypeManager.float_type, loc);
1393 if (l != TypeManager.double_type)
1394 left = ConvertImplicit (ec, left, TypeManager.float_type, loc);
1395 type = TypeManager.float_type;
1396 } else if (l == TypeManager.uint64_type || r == TypeManager.uint64_type){
1400 // If either operand is of type ulong, the other operand is
1401 // converted to type ulong. or an error ocurrs if the other
1402 // operand is of type sbyte, short, int or long
1404 if (l == TypeManager.uint64_type){
1405 if (r != TypeManager.uint64_type){
1406 if (right is IntConstant){
1407 IntConstant ic = (IntConstant) right;
1409 e = TryImplicitIntConversion (l, ic);
1412 } else if (right is LongConstant){
1413 long ll = ((LongConstant) right).Value;
1416 right = new ULongConstant ((ulong) ll);
1418 e = ImplicitNumericConversion (ec, right, l, loc);
1425 if (left is IntConstant){
1426 e = TryImplicitIntConversion (r, (IntConstant) left);
1429 } else if (left is LongConstant){
1430 long ll = ((LongConstant) left).Value;
1433 left = new ULongConstant ((ulong) ll);
1435 e = ImplicitNumericConversion (ec, left, r, loc);
1442 if ((other == TypeManager.sbyte_type) ||
1443 (other == TypeManager.short_type) ||
1444 (other == TypeManager.int32_type) ||
1445 (other == TypeManager.int64_type))
1446 Error_OperatorAmbiguous (loc, oper, l, r);
1447 type = TypeManager.uint64_type;
1448 } else if (l == TypeManager.int64_type || r == TypeManager.int64_type){
1450 // If either operand is of type long, the other operand is converted
1453 if (l != TypeManager.int64_type)
1454 left = ConvertImplicit (ec, left, TypeManager.int64_type, loc);
1455 if (r != TypeManager.int64_type)
1456 right = ConvertImplicit (ec, right, TypeManager.int64_type, loc);
1458 type = TypeManager.int64_type;
1459 } else if (l == TypeManager.uint32_type || r == TypeManager.uint32_type){
1461 // If either operand is of type uint, and the other
1462 // operand is of type sbyte, short or int, othe operands are
1463 // converted to type long.
1467 if (l == TypeManager.uint32_type){
1468 if (right is IntConstant){
1469 IntConstant ic = (IntConstant) right;
1473 right = new UIntConstant ((uint) val);
1480 else if (r == TypeManager.uint32_type){
1481 if (left is IntConstant){
1482 IntConstant ic = (IntConstant) left;
1486 left = new UIntConstant ((uint) val);
1495 if ((other == TypeManager.sbyte_type) ||
1496 (other == TypeManager.short_type) ||
1497 (other == TypeManager.int32_type)){
1498 left = ForceConversion (ec, left, TypeManager.int64_type);
1499 right = ForceConversion (ec, right, TypeManager.int64_type);
1500 type = TypeManager.int64_type;
1503 // if either operand is of type uint, the other
1504 // operand is converd to type uint
1506 left = ForceConversion (ec, left, TypeManager.uint32_type);
1507 right = ForceConversion (ec, right, TypeManager.uint32_type);
1508 type = TypeManager.uint32_type;
1510 } else if (l == TypeManager.decimal_type || r == TypeManager.decimal_type){
1511 if (l != TypeManager.decimal_type)
1512 left = ConvertImplicit (ec, left, TypeManager.decimal_type, loc);
1513 if (r != TypeManager.decimal_type)
1514 right = ConvertImplicit (ec, right, TypeManager.decimal_type, loc);
1516 type = TypeManager.decimal_type;
1518 Expression l_tmp, r_tmp;
1520 l_tmp = ForceConversion (ec, left, TypeManager.int32_type);
1524 r_tmp = ForceConversion (ec, right, TypeManager.int32_type);
1531 type = TypeManager.int32_type;
1537 static public void Error_OperatorCannotBeApplied (Location loc, string name, Type l, Type r)
1540 "Operator " + name + " cannot be applied to operands of type `" +
1541 TypeManager.CSharpName (l) + "' and `" +
1542 TypeManager.CSharpName (r) + "'");
1547 Error_OperatorCannotBeApplied (loc, OperName (oper), left.Type, right.Type);
1550 static bool is_32_or_64 (Type t)
1552 return (t == TypeManager.int32_type || t == TypeManager.uint32_type ||
1553 t == TypeManager.int64_type || t == TypeManager.uint64_type);
1556 Expression CheckShiftArguments (EmitContext ec)
1560 Type r = right.Type;
1562 e = ForceConversion (ec, right, TypeManager.int32_type);
1569 if (((e = ConvertImplicit (ec, left, TypeManager.int32_type, loc)) != null) ||
1570 ((e = ConvertImplicit (ec, left, TypeManager.uint32_type, loc)) != null) ||
1571 ((e = ConvertImplicit (ec, left, TypeManager.int64_type, loc)) != null) ||
1572 ((e = ConvertImplicit (ec, left, TypeManager.uint64_type, loc)) != null)){
1582 Expression ResolveOperator (EmitContext ec)
1585 Type r = right.Type;
1588 // Step 1: Perform Operator Overload location
1590 Expression left_expr, right_expr;
1592 string op = "op_" + oper;
1594 MethodGroupExpr union;
1595 left_expr = MemberLookup (ec, l, op, MemberTypes.Method, AllBindingFlags, loc);
1597 right_expr = MemberLookup (
1598 ec, r, op, MemberTypes.Method, AllBindingFlags, loc);
1599 union = Invocation.MakeUnionSet (left_expr, right_expr);
1601 union = (MethodGroupExpr) left_expr;
1603 if (union != null) {
1604 Arguments = new ArrayList ();
1605 Arguments.Add (new Argument (left, Argument.AType.Expression));
1606 Arguments.Add (new Argument (right, Argument.AType.Expression));
1608 method = Invocation.OverloadResolve (ec, union, Arguments, loc);
1609 if (method != null) {
1610 MethodInfo mi = (MethodInfo) method;
1612 type = mi.ReturnType;
1621 // Step 2: Default operations on CLI native types.
1624 // Only perform numeric promotions on:
1625 // +, -, *, /, %, &, |, ^, ==, !=, <, >, <=, >=
1627 if (oper == Operator.Addition){
1629 // If any of the arguments is a string, cast to string
1631 if (l == TypeManager.string_type){
1633 if (r == TypeManager.void_type) {
1638 if (r == TypeManager.string_type){
1639 if (left is Constant && right is Constant){
1640 StringConstant ls = (StringConstant) left;
1641 StringConstant rs = (StringConstant) right;
1643 return new StringConstant (
1644 ls.Value + rs.Value);
1648 method = TypeManager.string_concat_string_string;
1651 method = TypeManager.string_concat_object_object;
1652 right = ConvertImplicit (ec, right,
1653 TypeManager.object_type, loc);
1655 type = TypeManager.string_type;
1657 Arguments = new ArrayList ();
1658 Arguments.Add (new Argument (left, Argument.AType.Expression));
1659 Arguments.Add (new Argument (right, Argument.AType.Expression));
1663 } else if (r == TypeManager.string_type){
1666 if (l == TypeManager.void_type) {
1671 method = TypeManager.string_concat_object_object;
1672 left = ConvertImplicit (ec, left, TypeManager.object_type, loc);
1673 Arguments = new ArrayList ();
1674 Arguments.Add (new Argument (left, Argument.AType.Expression));
1675 Arguments.Add (new Argument (right, Argument.AType.Expression));
1677 type = TypeManager.string_type;
1683 if (oper == Operator.Addition || oper == Operator.Subtraction) {
1684 if (l.IsSubclassOf (TypeManager.delegate_type) &&
1685 r.IsSubclassOf (TypeManager.delegate_type)) {
1687 Arguments = new ArrayList ();
1688 Arguments.Add (new Argument (left, Argument.AType.Expression));
1689 Arguments.Add (new Argument (right, Argument.AType.Expression));
1691 if (oper == Operator.Addition)
1692 method = TypeManager.delegate_combine_delegate_delegate;
1694 method = TypeManager.delegate_remove_delegate_delegate;
1696 DelegateOperation = true;
1702 // Pointer arithmetic:
1704 // T* operator + (T* x, int y);
1705 // T* operator + (T* x, uint y);
1706 // T* operator + (T* x, long y);
1707 // T* operator + (T* x, ulong y);
1709 // T* operator + (int y, T* x);
1710 // T* operator + (uint y, T *x);
1711 // T* operator + (long y, T *x);
1712 // T* operator + (ulong y, T *x);
1714 // T* operator - (T* x, int y);
1715 // T* operator - (T* x, uint y);
1716 // T* operator - (T* x, long y);
1717 // T* operator - (T* x, ulong y);
1719 // long operator - (T* x, T *y)
1722 if (r.IsPointer && oper == Operator.Subtraction){
1724 return new PointerArithmetic (
1725 false, left, right, TypeManager.int64_type);
1726 } else if (is_32_or_64 (r))
1727 return new PointerArithmetic (
1728 oper == Operator.Addition, left, right, l);
1729 } else if (r.IsPointer && is_32_or_64 (l) && oper == Operator.Addition)
1730 return new PointerArithmetic (
1731 true, right, left, r);
1735 // Enumeration operators
1737 bool lie = TypeManager.IsEnumType (l);
1738 bool rie = TypeManager.IsEnumType (r);
1743 temp = ConvertImplicit (ec, right, l, loc);
1747 temp = ConvertImplicit (ec, left, r, loc);
1754 if (oper == Operator.Equality || oper == Operator.Inequality ||
1755 oper == Operator.LessThanOrEqual || oper == Operator.LessThan ||
1756 oper == Operator.GreaterThanOrEqual || oper == Operator.GreaterThan){
1757 type = TypeManager.bool_type;
1761 if (oper == Operator.BitwiseAnd ||
1762 oper == Operator.BitwiseOr ||
1763 oper == Operator.ExclusiveOr){
1769 if (oper == Operator.LeftShift || oper == Operator.RightShift)
1770 return CheckShiftArguments (ec);
1772 if (oper == Operator.LogicalOr || oper == Operator.LogicalAnd){
1773 if (l != TypeManager.bool_type || r != TypeManager.bool_type){
1778 type = TypeManager.bool_type;
1782 if (oper == Operator.Equality || oper == Operator.Inequality){
1783 if (l == TypeManager.bool_type || r == TypeManager.bool_type){
1784 if (r != TypeManager.bool_type || l != TypeManager.bool_type){
1789 type = TypeManager.bool_type;
1794 // operator != (object a, object b)
1795 // operator == (object a, object b)
1797 // For this to be used, both arguments have to be reference-types.
1798 // Read the rationale on the spec (14.9.6)
1800 // Also, if at compile time we know that the classes do not inherit
1801 // one from the other, then we catch the error there.
1803 if (!(l.IsValueType || r.IsValueType)){
1804 type = TypeManager.bool_type;
1809 if (l.IsSubclassOf (r) || r.IsSubclassOf (l))
1813 // We are going to have to convert to an object to compare
1815 if (l != TypeManager.object_type)
1816 left = new EmptyCast (left, TypeManager.object_type);
1817 if (r != TypeManager.object_type)
1818 right = new EmptyCast (right, TypeManager.object_type);
1825 // Pointer comparison
1827 if (l.IsPointer && r.IsPointer){
1828 if (oper == Operator.Equality || oper == Operator.Inequality ||
1829 oper == Operator.LessThan || oper == Operator.LessThanOrEqual ||
1830 oper == Operator.GreaterThan || oper == Operator.GreaterThanOrEqual){
1831 type = TypeManager.bool_type;
1837 // We are dealing with numbers
1840 if (!DoNumericPromotions (ec, l, r)){
1845 if (left == null || right == null)
1849 // reload our cached types if required
1854 if (oper == Operator.BitwiseAnd ||
1855 oper == Operator.BitwiseOr ||
1856 oper == Operator.ExclusiveOr){
1858 if (!((l == TypeManager.int32_type) ||
1859 (l == TypeManager.uint32_type) ||
1860 (l == TypeManager.int64_type) ||
1861 (l == TypeManager.uint64_type)))
1869 if (oper == Operator.Equality ||
1870 oper == Operator.Inequality ||
1871 oper == Operator.LessThanOrEqual ||
1872 oper == Operator.LessThan ||
1873 oper == Operator.GreaterThanOrEqual ||
1874 oper == Operator.GreaterThan){
1875 type = TypeManager.bool_type;
1881 public override Expression DoResolve (EmitContext ec)
1883 left = left.Resolve (ec);
1884 right = right.Resolve (ec);
1886 if (left == null || right == null)
1889 if (left.Type == null)
1890 throw new Exception (
1891 "Resolve returned non null, but did not set the type! (" +
1892 left + ") at Line: " + loc.Row);
1893 if (right.Type == null)
1894 throw new Exception (
1895 "Resolve returned non null, but did not set the type! (" +
1896 right + ") at Line: "+ loc.Row);
1898 eclass = ExprClass.Value;
1900 if (left is Constant && right is Constant){
1901 Expression e = ConstantFold.BinaryFold (
1902 ec, oper, (Constant) left, (Constant) right, loc);
1907 return ResolveOperator (ec);
1910 public bool IsBranchable ()
1912 if (oper == Operator.Equality ||
1913 oper == Operator.Inequality ||
1914 oper == Operator.LessThan ||
1915 oper == Operator.GreaterThan ||
1916 oper == Operator.LessThanOrEqual ||
1917 oper == Operator.GreaterThanOrEqual){
1924 /// This entry point is used by routines that might want
1925 /// to emit a brfalse/brtrue after an expression, and instead
1926 /// they could use a more compact notation.
1928 /// Typically the code would generate l.emit/r.emit, followed
1929 /// by the comparission and then a brtrue/brfalse. The comparissions
1930 /// are sometimes inneficient (there are not as complete as the branches
1931 /// look for the hacks in Emit using double ceqs).
1933 /// So for those cases we provide EmitBranchable that can emit the
1934 /// branch with the test
1936 public void EmitBranchable (EmitContext ec, int target)
1939 bool close_target = false;
1940 ILGenerator ig = ec.ig;
1943 // short-circuit operators
1945 if (oper == Operator.LogicalAnd){
1947 ig.Emit (OpCodes.Brfalse, target);
1949 ig.Emit (OpCodes.Brfalse, target);
1950 } else if (oper == Operator.LogicalOr){
1952 ig.Emit (OpCodes.Brtrue, target);
1954 ig.Emit (OpCodes.Brfalse, target);
1961 case Operator.Equality:
1963 opcode = OpCodes.Beq_S;
1965 opcode = OpCodes.Beq;
1968 case Operator.Inequality:
1970 opcode = OpCodes.Bne_Un_S;
1972 opcode = OpCodes.Bne_Un;
1975 case Operator.LessThan:
1977 opcode = OpCodes.Blt_S;
1979 opcode = OpCodes.Blt;
1982 case Operator.GreaterThan:
1984 opcode = OpCodes.Bgt_S;
1986 opcode = OpCodes.Bgt;
1989 case Operator.LessThanOrEqual:
1991 opcode = OpCodes.Ble_S;
1993 opcode = OpCodes.Ble;
1996 case Operator.GreaterThanOrEqual:
1998 opcode = OpCodes.Bge_S;
2000 opcode = OpCodes.Ble;
2004 throw new Exception ("EmitBranchable called on non-EmitBranchable operator: "
2005 + oper.ToString ());
2008 ig.Emit (opcode, target);
2011 public override void Emit (EmitContext ec)
2013 ILGenerator ig = ec.ig;
2015 Type r = right.Type;
2018 if (method != null) {
2020 // Note that operators are static anyway
2022 if (Arguments != null)
2023 Invocation.EmitArguments (ec, method, Arguments);
2025 if (method is MethodInfo)
2026 ig.Emit (OpCodes.Call, (MethodInfo) method);
2028 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
2030 if (DelegateOperation)
2031 ig.Emit (OpCodes.Castclass, type);
2037 // Handle short-circuit operators differently
2040 if (oper == Operator.LogicalAnd){
2041 Label load_zero = ig.DefineLabel ();
2042 Label end = ig.DefineLabel ();
2045 ig.Emit (OpCodes.Brfalse, load_zero);
2047 ig.Emit (OpCodes.Br, end);
2048 ig.MarkLabel (load_zero);
2049 ig.Emit (OpCodes.Ldc_I4_0);
2052 } else if (oper == Operator.LogicalOr){
2053 Label load_one = ig.DefineLabel ();
2054 Label end = ig.DefineLabel ();
2057 ig.Emit (OpCodes.Brtrue, load_one);
2059 ig.Emit (OpCodes.Br, end);
2060 ig.MarkLabel (load_one);
2061 ig.Emit (OpCodes.Ldc_I4_1);
2070 case Operator.Multiply:
2072 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
2073 opcode = OpCodes.Mul_Ovf;
2074 else if (l==TypeManager.uint32_type || l==TypeManager.uint64_type)
2075 opcode = OpCodes.Mul_Ovf_Un;
2077 opcode = OpCodes.Mul;
2079 opcode = OpCodes.Mul;
2083 case Operator.Division:
2084 if (l == TypeManager.uint32_type || l == TypeManager.uint64_type)
2085 opcode = OpCodes.Div_Un;
2087 opcode = OpCodes.Div;
2090 case Operator.Modulus:
2091 if (l == TypeManager.uint32_type || l == TypeManager.uint64_type)
2092 opcode = OpCodes.Rem_Un;
2094 opcode = OpCodes.Rem;
2097 case Operator.Addition:
2099 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
2100 opcode = OpCodes.Add_Ovf;
2101 else if (l==TypeManager.uint32_type || l==TypeManager.uint64_type)
2102 opcode = OpCodes.Add_Ovf_Un;
2104 opcode = OpCodes.Mul;
2106 opcode = OpCodes.Add;
2109 case Operator.Subtraction:
2111 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
2112 opcode = OpCodes.Sub_Ovf;
2113 else if (l==TypeManager.uint32_type || l==TypeManager.uint64_type)
2114 opcode = OpCodes.Sub_Ovf_Un;
2116 opcode = OpCodes.Sub;
2118 opcode = OpCodes.Sub;
2121 case Operator.RightShift:
2122 opcode = OpCodes.Shr;
2125 case Operator.LeftShift:
2126 opcode = OpCodes.Shl;
2129 case Operator.Equality:
2130 opcode = OpCodes.Ceq;
2133 case Operator.Inequality:
2134 ec.ig.Emit (OpCodes.Ceq);
2135 ec.ig.Emit (OpCodes.Ldc_I4_0);
2137 opcode = OpCodes.Ceq;
2140 case Operator.LessThan:
2141 opcode = OpCodes.Clt;
2144 case Operator.GreaterThan:
2145 opcode = OpCodes.Cgt;
2148 case Operator.LessThanOrEqual:
2149 ec.ig.Emit (OpCodes.Cgt);
2150 ec.ig.Emit (OpCodes.Ldc_I4_0);
2152 opcode = OpCodes.Ceq;
2155 case Operator.GreaterThanOrEqual:
2156 ec.ig.Emit (OpCodes.Clt);
2157 ec.ig.Emit (OpCodes.Ldc_I4_1);
2159 opcode = OpCodes.Sub;
2162 case Operator.BitwiseOr:
2163 opcode = OpCodes.Or;
2166 case Operator.BitwiseAnd:
2167 opcode = OpCodes.And;
2170 case Operator.ExclusiveOr:
2171 opcode = OpCodes.Xor;
2175 throw new Exception ("This should not happen: Operator = "
2176 + oper.ToString ());
2183 public class PointerArithmetic : Expression {
2184 Expression left, right;
2188 // We assume that `l' is always a pointer
2190 public PointerArithmetic (bool is_addition, Expression l, Expression r, Type t)
2193 eclass = ExprClass.Variable;
2196 is_add = is_addition;
2199 public override Expression DoResolve (EmitContext ec)
2202 // We are born fully resolved
2207 public override void Emit (EmitContext ec)
2209 Type op_type = left.Type;
2210 ILGenerator ig = ec.ig;
2211 int size = GetTypeSize (op_type.GetElementType ());
2213 if (right.Type.IsPointer){
2215 // handle (pointer - pointer)
2219 ig.Emit (OpCodes.Sub);
2223 ig.Emit (OpCodes.Sizeof, op_type);
2225 IntLiteral.EmitInt (ig, size);
2226 ig.Emit (OpCodes.Div);
2228 ig.Emit (OpCodes.Conv_I8);
2231 // handle + and - on (pointer op int)
2234 ig.Emit (OpCodes.Conv_I);
2238 ig.Emit (OpCodes.Sizeof, op_type);
2240 IntLiteral.EmitInt (ig, size);
2241 ig.Emit (OpCodes.Mul);
2244 ig.Emit (OpCodes.Add);
2246 ig.Emit (OpCodes.Sub);
2252 /// Implements the ternary conditiona operator (?:)
2254 public class Conditional : Expression {
2255 Expression expr, trueExpr, falseExpr;
2258 public Conditional (Expression expr, Expression trueExpr, Expression falseExpr, Location l)
2261 this.trueExpr = trueExpr;
2262 this.falseExpr = falseExpr;
2266 public Expression Expr {
2272 public Expression TrueExpr {
2278 public Expression FalseExpr {
2284 public override Expression DoResolve (EmitContext ec)
2286 expr = expr.Resolve (ec);
2288 if (expr.Type != TypeManager.bool_type)
2289 expr = Expression.ConvertImplicitRequired (
2290 ec, expr, TypeManager.bool_type, loc);
2292 trueExpr = trueExpr.Resolve (ec);
2293 falseExpr = falseExpr.Resolve (ec);
2295 if (expr == null || trueExpr == null || falseExpr == null)
2298 eclass = ExprClass.Value;
2299 if (trueExpr.Type == falseExpr.Type)
2300 type = trueExpr.Type;
2303 Type true_type = trueExpr.Type;
2304 Type false_type = falseExpr.Type;
2306 if (trueExpr is NullLiteral){
2309 } else if (falseExpr is NullLiteral){
2315 // First, if an implicit conversion exists from trueExpr
2316 // to falseExpr, then the result type is of type falseExpr.Type
2318 conv = ConvertImplicit (ec, trueExpr, false_type, loc);
2321 // Check if both can convert implicitl to each other's type
2323 if (ConvertImplicit (ec, falseExpr, true_type, loc) != null){
2326 "Can not compute type of conditional expression " +
2327 "as `" + TypeManager.CSharpName (trueExpr.Type) +
2328 "' and `" + TypeManager.CSharpName (falseExpr.Type) +
2329 "' convert implicitly to each other");
2334 } else if ((conv = ConvertImplicit(ec, falseExpr, true_type,loc))!= null){
2338 Error (173, loc, "The type of the conditional expression can " +
2339 "not be computed because there is no implicit conversion" +
2340 " from `" + TypeManager.CSharpName (trueExpr.Type) + "'" +
2341 " and `" + TypeManager.CSharpName (falseExpr.Type) + "'");
2346 if (expr is BoolConstant){
2347 BoolConstant bc = (BoolConstant) expr;
2358 public override void Emit (EmitContext ec)
2360 ILGenerator ig = ec.ig;
2361 Label false_target = ig.DefineLabel ();
2362 Label end_target = ig.DefineLabel ();
2365 ig.Emit (OpCodes.Brfalse, false_target);
2367 ig.Emit (OpCodes.Br, end_target);
2368 ig.MarkLabel (false_target);
2369 falseExpr.Emit (ec);
2370 ig.MarkLabel (end_target);
2378 public class LocalVariableReference : Expression, IAssignMethod, IMemoryLocation {
2379 public readonly string Name;
2380 public readonly Block Block;
2382 VariableInfo variable_info;
2384 public LocalVariableReference (Block block, string name, Location l)
2389 eclass = ExprClass.Variable;
2392 public VariableInfo VariableInfo {
2394 if (variable_info == null)
2395 variable_info = Block.GetVariableInfo (Name);
2396 return variable_info;
2400 public override Expression DoResolve (EmitContext ec)
2402 VariableInfo vi = VariableInfo;
2404 if (Block.IsConstant (Name)) {
2405 Expression e = Block.GetConstantExpression (Name);
2411 type = vi.VariableType;
2415 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
2417 Expression e = DoResolve (ec);
2422 VariableInfo vi = VariableInfo;
2428 "cannot assign to `" + Name + "' because it is readonly");
2436 public override void Emit (EmitContext ec)
2438 VariableInfo vi = VariableInfo;
2439 ILGenerator ig = ec.ig;
2446 ig.Emit (OpCodes.Ldloc_0);
2450 ig.Emit (OpCodes.Ldloc_1);
2454 ig.Emit (OpCodes.Ldloc_2);
2458 ig.Emit (OpCodes.Ldloc_3);
2463 ig.Emit (OpCodes.Ldloc_S, (byte) idx);
2465 ig.Emit (OpCodes.Ldloc, idx);
2470 public static void Store (ILGenerator ig, int idx)
2474 ig.Emit (OpCodes.Stloc_0);
2478 ig.Emit (OpCodes.Stloc_1);
2482 ig.Emit (OpCodes.Stloc_2);
2486 ig.Emit (OpCodes.Stloc_3);
2491 ig.Emit (OpCodes.Stloc_S, (byte) idx);
2493 ig.Emit (OpCodes.Stloc, idx);
2498 public void EmitAssign (EmitContext ec, Expression source)
2500 ILGenerator ig = ec.ig;
2501 VariableInfo vi = VariableInfo;
2507 // Funny seems the code below generates optimal code for us, but
2508 // seems to take too long to generate what we need.
2509 // ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
2514 public void AddressOf (EmitContext ec, AddressOp mode)
2516 VariableInfo vi = VariableInfo;
2519 if ((mode & AddressOp.Load) != 0)
2521 if ((mode & AddressOp.Store) != 0)
2525 ec.ig.Emit (OpCodes.Ldloca_S, (byte) idx);
2527 ec.ig.Emit (OpCodes.Ldloca, idx);
2532 /// This represents a reference to a parameter in the intermediate
2535 public class ParameterReference : Expression, IAssignMethod, IMemoryLocation {
2541 public ParameterReference (Parameters pars, int idx, string name)
2546 eclass = ExprClass.Variable;
2550 // Notice that for ref/out parameters, the type exposed is not the
2551 // same type exposed externally.
2554 // externally we expose "int&"
2555 // here we expose "int".
2557 // We record this in "is_ref". This means that the type system can treat
2558 // the type as it is expected, but when we generate the code, we generate
2559 // the alternate kind of code.
2561 public override Expression DoResolve (EmitContext ec)
2563 type = pars.GetParameterInfo (ec.TypeContainer, idx, out is_ref);
2564 eclass = ExprClass.Variable;
2570 // This method is used by parameters that are references, that are
2571 // being passed as references: we only want to pass the pointer (that
2572 // is already stored in the parameter, not the address of the pointer,
2573 // and not the value of the variable).
2575 public void EmitLoad (EmitContext ec)
2577 ILGenerator ig = ec.ig;
2584 ig.Emit (OpCodes.Ldarg_S, (byte) arg_idx);
2586 ig.Emit (OpCodes.Ldarg, arg_idx);
2589 public override void Emit (EmitContext ec)
2591 ILGenerator ig = ec.ig;
2598 ig.Emit (OpCodes.Ldarg_S, (byte) arg_idx);
2600 ig.Emit (OpCodes.Ldarg, arg_idx);
2606 // If we are a reference, we loaded on the stack a pointer
2607 // Now lets load the real value
2609 LoadFromPtr (ig, type, true);
2612 public void EmitAssign (EmitContext ec, Expression source)
2614 ILGenerator ig = ec.ig;
2623 ig.Emit (OpCodes.Ldarg_S, (byte) arg_idx);
2625 ig.Emit (OpCodes.Ldarg, arg_idx);
2631 StoreFromPtr (ig, type);
2634 ig.Emit (OpCodes.Starg_S, (byte) arg_idx);
2636 ig.Emit (OpCodes.Starg, arg_idx);
2641 public void AddressOf (EmitContext ec, AddressOp mode)
2649 ec.ig.Emit (OpCodes.Ldarga_S, (byte) arg_idx);
2651 ec.ig.Emit (OpCodes.Ldarga, arg_idx);
2656 /// Used for arguments to New(), Invocation()
2658 public class Argument {
2659 public enum AType : byte {
2665 public readonly AType ArgType;
2666 public Expression expr;
2668 public Argument (Expression expr, AType type)
2671 this.ArgType = type;
2674 public Expression Expr {
2690 public Parameter.Modifier GetParameterModifier ()
2692 if (ArgType == AType.Ref || ArgType == AType.Out)
2693 return Parameter.Modifier.OUT;
2695 return Parameter.Modifier.NONE;
2698 public static string FullDesc (Argument a)
2700 return (a.ArgType == AType.Ref ? "ref " :
2701 (a.ArgType == AType.Out ? "out " : "")) +
2702 TypeManager.CSharpName (a.Expr.Type);
2705 public bool Resolve (EmitContext ec, Location loc)
2707 expr = expr.Resolve (ec);
2709 if (ArgType == AType.Expression)
2710 return expr != null;
2712 if (expr.eclass != ExprClass.Variable){
2714 // We just probe to match the CSC output
2716 if (expr.eclass == ExprClass.PropertyAccess ||
2717 expr.eclass == ExprClass.IndexerAccess){
2720 "A property or indexer can not be passed as an out or ref " +
2725 "An lvalue is required as an argument to out or ref");
2730 return expr != null;
2733 public void Emit (EmitContext ec)
2736 // Ref and Out parameters need to have their addresses taken.
2738 // ParameterReferences might already be references, so we want
2739 // to pass just the value
2741 if (ArgType == AType.Ref || ArgType == AType.Out){
2742 AddressOp mode = AddressOp.Store;
2744 if (ArgType == AType.Ref)
2745 mode |= AddressOp.Load;
2747 if (expr is ParameterReference){
2748 ParameterReference pr = (ParameterReference) expr;
2754 pr.AddressOf (ec, mode);
2757 ((IMemoryLocation)expr).AddressOf (ec, mode);
2764 /// Invocation of methods or delegates.
2766 public class Invocation : ExpressionStatement {
2767 public readonly ArrayList Arguments;
2771 MethodBase method = null;
2774 static Hashtable method_parameter_cache;
2776 static Invocation ()
2778 method_parameter_cache = new PtrHashtable ();
2782 // arguments is an ArrayList, but we do not want to typecast,
2783 // as it might be null.
2785 // FIXME: only allow expr to be a method invocation or a
2786 // delegate invocation (7.5.5)
2788 public Invocation (Expression expr, ArrayList arguments, Location l)
2791 Arguments = arguments;
2795 public Expression Expr {
2802 /// Returns the Parameters (a ParameterData interface) for the
2805 public static ParameterData GetParameterData (MethodBase mb)
2807 object pd = method_parameter_cache [mb];
2811 return (ParameterData) pd;
2814 ip = TypeManager.LookupParametersByBuilder (mb);
2816 method_parameter_cache [mb] = ip;
2818 return (ParameterData) ip;
2820 ParameterInfo [] pi = mb.GetParameters ();
2821 ReflectionParameters rp = new ReflectionParameters (pi);
2822 method_parameter_cache [mb] = rp;
2824 return (ParameterData) rp;
2829 /// Determines "better conversion" as specified in 7.4.2.3
2830 /// Returns : 1 if a->p is better
2831 /// 0 if a->q or neither is better
2833 static int BetterConversion (EmitContext ec, Argument a, Type p, Type q, Location loc)
2835 Type argument_type = a.Type;
2836 Expression argument_expr = a.Expr;
2838 if (argument_type == null)
2839 throw new Exception ("Expression of type " + a.Expr + " does not resolve its type");
2844 if (argument_type == p)
2847 if (argument_type == q)
2851 // Now probe whether an implicit constant expression conversion
2854 // An implicit constant expression conversion permits the following
2857 // * A constant-expression of type `int' can be converted to type
2858 // sbyte, byute, short, ushort, uint, ulong provided the value of
2859 // of the expression is withing the range of the destination type.
2861 // * A constant-expression of type long can be converted to type
2862 // ulong, provided the value of the constant expression is not negative
2864 // FIXME: Note that this assumes that constant folding has
2865 // taken place. We dont do constant folding yet.
2868 if (argument_expr is IntConstant){
2869 IntConstant ei = (IntConstant) argument_expr;
2870 int value = ei.Value;
2872 if (p == TypeManager.sbyte_type){
2873 if (value >= SByte.MinValue && value <= SByte.MaxValue)
2875 } else if (p == TypeManager.byte_type){
2876 if (Byte.MinValue >= 0 && value <= Byte.MaxValue)
2878 } else if (p == TypeManager.short_type){
2879 if (value >= Int16.MinValue && value <= Int16.MaxValue)
2881 } else if (p == TypeManager.ushort_type){
2882 if (value >= UInt16.MinValue && value <= UInt16.MaxValue)
2884 } else if (p == TypeManager.uint32_type){
2886 // we can optimize this case: a positive int32
2887 // always fits on a uint32
2891 } else if (p == TypeManager.uint64_type){
2893 // we can optimize this case: a positive int32
2894 // always fits on a uint64
2899 } else if (argument_type == TypeManager.int64_type && argument_expr is LongConstant){
2900 LongConstant lc = (LongConstant) argument_expr;
2902 if (p == TypeManager.uint64_type){
2909 Expression tmp = ConvertImplicitStandard (ec, argument_expr, p, loc);
2917 if (StandardConversionExists (p, q) == true &&
2918 StandardConversionExists (q, p) == false)
2921 if (p == TypeManager.sbyte_type)
2922 if (q == TypeManager.byte_type || q == TypeManager.ushort_type ||
2923 q == TypeManager.uint32_type || q == TypeManager.uint64_type)
2926 if (p == TypeManager.short_type)
2927 if (q == TypeManager.ushort_type || q == TypeManager.uint32_type ||
2928 q == TypeManager.uint64_type)
2931 if (p == TypeManager.int32_type)
2932 if (q == TypeManager.uint32_type || q == TypeManager.uint64_type)
2935 if (p == TypeManager.int64_type)
2936 if (q == TypeManager.uint64_type)
2943 /// Determines "Better function"
2946 /// and returns an integer indicating :
2947 /// 0 if candidate ain't better
2948 /// 1 if candidate is better than the current best match
2950 static int BetterFunction (EmitContext ec, ArrayList args,
2951 MethodBase candidate, MethodBase best,
2952 bool expanded_form, Location loc)
2954 ParameterData candidate_pd = GetParameterData (candidate);
2955 ParameterData best_pd;
2962 argument_count = args.Count;
2964 int cand_count = candidate_pd.Count;
2966 if (cand_count == 0 && argument_count == 0)
2969 if (candidate_pd.ParameterModifier (cand_count - 1) != Parameter.Modifier.PARAMS)
2970 if (cand_count != argument_count)
2976 if (argument_count == 0 && cand_count == 1 &&
2977 candidate_pd.ParameterModifier (cand_count - 1) == Parameter.Modifier.PARAMS)
2980 for (int j = argument_count; j > 0;) {
2983 Argument a = (Argument) args [j];
2984 Type t = candidate_pd.ParameterType (j);
2986 if (candidate_pd.ParameterModifier (j) == Parameter.Modifier.PARAMS)
2988 t = t.GetElementType ();
2990 x = BetterConversion (ec, a, t, null, loc);
3002 best_pd = GetParameterData (best);
3004 int rating1 = 0, rating2 = 0;
3006 for (int j = 0; j < argument_count; ++j) {
3009 Argument a = (Argument) args [j];
3011 Type ct = candidate_pd.ParameterType (j);
3012 Type bt = best_pd.ParameterType (j);
3014 if (candidate_pd.ParameterModifier (j) == Parameter.Modifier.PARAMS)
3016 ct = ct.GetElementType ();
3018 if (best_pd.ParameterModifier (j) == Parameter.Modifier.PARAMS)
3020 bt = bt.GetElementType ();
3022 x = BetterConversion (ec, a, ct, bt, loc);
3023 y = BetterConversion (ec, a, bt, ct, loc);
3032 if (rating1 > rating2)
3038 public static string FullMethodDesc (MethodBase mb)
3040 string ret_type = "";
3042 if (mb is MethodInfo)
3043 ret_type = TypeManager.CSharpName (((MethodInfo) mb).ReturnType);
3045 StringBuilder sb = new StringBuilder (ret_type + " " + mb.Name);
3046 ParameterData pd = GetParameterData (mb);
3048 int count = pd.Count;
3051 for (int i = count; i > 0; ) {
3054 sb.Append (pd.ParameterDesc (count - i - 1));
3060 return sb.ToString ();
3063 public static MethodGroupExpr MakeUnionSet (Expression mg1, Expression mg2)
3065 MemberInfo [] miset;
3066 MethodGroupExpr union;
3068 if (mg1 != null && mg2 != null) {
3070 MethodGroupExpr left_set = null, right_set = null;
3071 int length1 = 0, length2 = 0;
3073 left_set = (MethodGroupExpr) mg1;
3074 length1 = left_set.Methods.Length;
3076 right_set = (MethodGroupExpr) mg2;
3077 length2 = right_set.Methods.Length;
3079 ArrayList common = new ArrayList ();
3081 for (int i = 0; i < left_set.Methods.Length; i++) {
3082 for (int j = 0; j < right_set.Methods.Length; j++) {
3083 if (left_set.Methods [i] == right_set.Methods [j])
3084 common.Add (left_set.Methods [i]);
3088 miset = new MemberInfo [length1 + length2 - common.Count];
3090 left_set.Methods.CopyTo (miset, 0);
3094 for (int j = 0; j < right_set.Methods.Length; j++)
3095 if (!common.Contains (right_set.Methods [j]))
3096 miset [length1 + k++] = right_set.Methods [j];
3098 union = new MethodGroupExpr (miset);
3102 } else if (mg1 == null && mg2 != null) {
3104 MethodGroupExpr me = (MethodGroupExpr) mg2;
3106 miset = new MemberInfo [me.Methods.Length];
3107 me.Methods.CopyTo (miset, 0);
3109 union = new MethodGroupExpr (miset);
3113 } else if (mg2 == null && mg1 != null) {
3115 MethodGroupExpr me = (MethodGroupExpr) mg1;
3117 miset = new MemberInfo [me.Methods.Length];
3118 me.Methods.CopyTo (miset, 0);
3120 union = new MethodGroupExpr (miset);
3129 /// Determines is the candidate method, if a params method, is applicable
3130 /// in its expanded form to the given set of arguments
3132 static bool IsParamsMethodApplicable (ArrayList arguments, MethodBase candidate)
3136 if (arguments == null)
3139 arg_count = arguments.Count;
3141 ParameterData pd = GetParameterData (candidate);
3143 int pd_count = pd.Count;
3148 if (pd.ParameterModifier (pd_count - 1) != Parameter.Modifier.PARAMS)
3151 if (pd_count - 1 > arg_count)
3154 if (pd_count == 1 && arg_count == 0)
3158 // If we have come this far, the case which remains is when the number of parameters
3159 // is less than or equal to the argument count.
3161 for (int i = 0; i < pd_count - 1; ++i) {
3163 Argument a = (Argument) arguments [i];
3165 Parameter.Modifier a_mod = a.GetParameterModifier ();
3166 Parameter.Modifier p_mod = pd.ParameterModifier (i);
3168 if (a_mod == p_mod) {
3170 if (a_mod == Parameter.Modifier.NONE)
3171 if (!StandardConversionExists (a.Type, pd.ParameterType (i)))
3174 if (a_mod == Parameter.Modifier.REF ||
3175 a_mod == Parameter.Modifier.OUT)
3176 if (pd.ParameterType (i) != a.Type)
3183 Type element_type = pd.ParameterType (pd_count - 1).GetElementType ();
3185 for (int i = pd_count - 1; i < arg_count; i++) {
3186 Argument a = (Argument) arguments [i];
3188 if (!StandardConversionExists (a.Type, element_type))
3196 /// Determines if the candidate method is applicable (section 14.4.2.1)
3197 /// to the given set of arguments
3199 static bool IsApplicable (ArrayList arguments, MethodBase candidate)
3203 if (arguments == null)
3206 arg_count = arguments.Count;
3208 ParameterData pd = GetParameterData (candidate);
3210 int pd_count = pd.Count;
3212 if (arg_count != pd.Count)
3215 for (int i = arg_count; i > 0; ) {
3218 Argument a = (Argument) arguments [i];
3220 Parameter.Modifier a_mod = a.GetParameterModifier ();
3221 Parameter.Modifier p_mod = pd.ParameterModifier (i);
3223 if (a_mod == p_mod) {
3225 if (a_mod == Parameter.Modifier.NONE)
3226 if (!StandardConversionExists (a.Type, pd.ParameterType (i)))
3229 if (a_mod == Parameter.Modifier.REF ||
3230 a_mod == Parameter.Modifier.OUT)
3231 if (pd.ParameterType (i) != a.Type)
3243 /// Find the Applicable Function Members (7.4.2.1)
3245 /// me: Method Group expression with the members to select.
3246 /// it might contain constructors or methods (or anything
3247 /// that maps to a method).
3249 /// Arguments: ArrayList containing resolved Argument objects.
3251 /// loc: The location if we want an error to be reported, or a Null
3252 /// location for "probing" purposes.
3254 /// Returns: The MethodBase (either a ConstructorInfo or a MethodInfo)
3255 /// that is the best match of me on Arguments.
3258 public static MethodBase OverloadResolve (EmitContext ec, MethodGroupExpr me,
3259 ArrayList Arguments, Location loc)
3261 ArrayList afm = new ArrayList ();
3262 int best_match_idx = -1;
3263 MethodBase method = null;
3265 ArrayList candidates = new ArrayList ();
3267 for (int i = me.Methods.Length; i > 0; ){
3269 MethodBase candidate = me.Methods [i];
3272 // Check if candidate is applicable (section 14.4.2.1)
3273 if (!IsApplicable (Arguments, candidate))
3276 candidates.Add (candidate);
3278 x = BetterFunction (ec, Arguments, candidate, method, false, loc);
3284 method = me.Methods [best_match_idx];
3288 if (Arguments == null)
3291 argument_count = Arguments.Count;
3294 // Now we see if we can find params functions, applicable in their expanded form
3295 // since if they were applicable in their normal form, they would have been selected
3298 bool chose_params_expanded = false;
3300 if (best_match_idx == -1) {
3302 candidates = new ArrayList ();
3303 for (int i = me.Methods.Length; i > 0; ) {
3305 MethodBase candidate = me.Methods [i];
3307 if (!IsParamsMethodApplicable (Arguments, candidate))
3310 candidates.Add (candidate);
3312 int x = BetterFunction (ec, Arguments, candidate, method, true, loc);
3318 method = me.Methods [best_match_idx];
3319 chose_params_expanded = true;
3325 // Now we see if we can at least find a method with the same number of arguments
3328 int method_count = 0;
3330 if (best_match_idx == -1) {
3332 for (int i = me.Methods.Length; i > 0;) {
3334 MethodBase mb = me.Methods [i];
3335 pd = GetParameterData (mb);
3337 if (pd.Count == argument_count) {
3339 method = me.Methods [best_match_idx];
3351 // Now check that there are no ambiguities i.e the selected method
3352 // should be better than all the others
3355 for (int i = 0; i < candidates.Count; ++i) {
3356 MethodBase candidate = (MethodBase) candidates [i];
3358 if (candidate == method)
3362 // If a normal method is applicable in the sense that it has the same
3363 // number of arguments, then the expanded params method is never applicable
3364 // so we debar the params method.
3366 if (IsParamsMethodApplicable (Arguments, candidate) &&
3367 IsApplicable (Arguments, method))
3370 int x = BetterFunction (ec, Arguments, method, candidate,
3371 chose_params_expanded, loc);
3374 //Console.WriteLine ("Candidate : " + FullMethodDesc (candidate));
3375 //Console.WriteLine ("Best : " + FullMethodDesc (method));
3378 "Ambiguous call when selecting function due to implicit casts");
3383 // And now convert implicitly, each argument to the required type
3385 pd = GetParameterData (method);
3386 int pd_count = pd.Count;
3388 for (int j = 0; j < argument_count; j++) {
3389 Argument a = (Argument) Arguments [j];
3390 Expression a_expr = a.Expr;
3391 Type parameter_type = pd.ParameterType (j);
3393 if (pd.ParameterModifier (j) == Parameter.Modifier.PARAMS && chose_params_expanded)
3394 parameter_type = parameter_type.GetElementType ();
3396 if (a.Type != parameter_type){
3399 conv = ConvertImplicitStandard (ec, a_expr, parameter_type, Location.Null);
3402 if (!Location.IsNull (loc)) {
3404 "The best overloaded match for method '" +
3405 FullMethodDesc (method) +
3406 "' has some invalid arguments");
3408 "Argument " + (j+1) +
3409 ": Cannot convert from '" + Argument.FullDesc (a)
3410 + "' to '" + pd.ParameterDesc (j) + "'");
3416 // Update the argument with the implicit conversion
3421 // FIXME : For the case of params methods, we need to actually instantiate
3422 // an array and initialize it with the argument values etc etc.
3426 if (a.GetParameterModifier () != pd.ParameterModifier (j) &&
3427 pd.ParameterModifier (pd_count - 1) != Parameter.Modifier.PARAMS) {
3428 if (!Location.IsNull (loc)) {
3429 Console.WriteLine ("A:P: " + a.GetParameterModifier ());
3430 Console.WriteLine ("PP:: " + pd.ParameterModifier (j));
3431 Console.WriteLine ("PT: " + parameter_type.IsByRef);
3433 "The best overloaded match for method '" + FullMethodDesc (method)+
3434 "' has some invalid arguments");
3436 "Argument " + (j+1) +
3437 ": Cannot convert from '" + Argument.FullDesc (a)
3438 + "' to '" + pd.ParameterDesc (j) + "'");
3447 public override Expression DoResolve (EmitContext ec)
3450 // First, resolve the expression that is used to
3451 // trigger the invocation
3453 if (expr is BaseAccess)
3456 expr = expr.Resolve (ec);
3460 if (!(expr is MethodGroupExpr)) {
3461 Type expr_type = expr.Type;
3463 if (expr_type != null){
3464 bool IsDelegate = TypeManager.IsDelegateType (expr_type);
3466 return (new DelegateInvocation (
3467 this.expr, Arguments, loc)).Resolve (ec);
3471 if (!(expr is MethodGroupExpr)){
3472 report118 (loc, this.expr, "method group");
3477 // Next, evaluate all the expressions in the argument list
3479 if (Arguments != null){
3480 for (int i = Arguments.Count; i > 0;){
3482 Argument a = (Argument) Arguments [i];
3484 if (!a.Resolve (ec, loc))
3489 method = OverloadResolve (ec, (MethodGroupExpr) this.expr, Arguments, loc);
3491 if (method == null){
3493 "Could not find any applicable function for this argument list");
3497 if (method is MethodInfo)
3498 type = ((MethodInfo)method).ReturnType;
3500 if (type.IsPointer){
3507 eclass = ExprClass.Value;
3512 // Emits the list of arguments as an array
3514 static void EmitParams (EmitContext ec, int idx, ArrayList arguments)
3516 ILGenerator ig = ec.ig;
3517 int count = arguments.Count - idx;
3518 Argument a = (Argument) arguments [idx];
3519 Type t = a.expr.Type;
3520 string array_type = t.FullName + "[]";
3523 array = ig.DeclareLocal (Type.GetType (array_type));
3524 IntConstant.EmitInt (ig, count);
3525 ig.Emit (OpCodes.Newarr, t);
3526 ig.Emit (OpCodes.Stloc, array);
3528 int top = arguments.Count;
3529 for (int j = idx; j < top; j++){
3530 a = (Argument) arguments [j];
3532 ig.Emit (OpCodes.Ldloc, array);
3533 IntConstant.EmitInt (ig, j - idx);
3536 ArrayAccess.EmitStoreOpcode (ig, t);
3538 ig.Emit (OpCodes.Ldloc, array);
3542 /// Emits a list of resolved Arguments that are in the arguments
3545 /// The MethodBase argument might be null if the
3546 /// emission of the arguments is known not to contain
3547 /// a `params' field (for example in constructors or other routines
3548 /// that keep their arguments in this structure
3550 public static void EmitArguments (EmitContext ec, MethodBase mb, ArrayList arguments)
3552 ParameterData pd = null;
3555 if (arguments != null)
3556 top = arguments.Count;
3561 pd = GetParameterData (mb);
3563 for (int i = 0; i < top; i++){
3564 Argument a = (Argument) arguments [i];
3567 if (pd.ParameterModifier (i) == Parameter.Modifier.PARAMS){
3568 EmitParams (ec, i, arguments);
3578 /// is_base tells whether we want to force the use of the `call'
3579 /// opcode instead of using callvirt. Call is required to call
3580 /// a specific method, while callvirt will always use the most
3581 /// recent method in the vtable.
3583 /// is_static tells whether this is an invocation on a static method
3585 /// instance_expr is an expression that represents the instance
3586 /// it must be non-null if is_static is false.
3588 /// method is the method to invoke.
3590 /// Arguments is the list of arguments to pass to the method or constructor.
3592 public static void EmitCall (EmitContext ec, bool is_base,
3593 bool is_static, Expression instance_expr,
3594 MethodBase method, ArrayList Arguments)
3596 ILGenerator ig = ec.ig;
3597 bool struct_call = false;
3601 if (method.DeclaringType.IsValueType)
3604 // If this is ourselves, push "this"
3606 if (instance_expr == null){
3607 ig.Emit (OpCodes.Ldarg_0);
3610 // Push the instance expression
3612 if (instance_expr.Type.IsSubclassOf (TypeManager.value_type)){
3614 // Special case: calls to a function declared in a
3615 // reference-type with a value-type argument need
3616 // to have their value boxed.
3619 if (method.DeclaringType.IsValueType){
3621 // If the expression implements IMemoryLocation, then
3622 // we can optimize and use AddressOf on the
3625 // If not we have to use some temporary storage for
3627 if (instance_expr is IMemoryLocation){
3628 ((IMemoryLocation)instance_expr).
3629 AddressOf (ec, AddressOp.LoadStore);
3632 Type t = instance_expr.Type;
3634 instance_expr.Emit (ec);
3635 LocalBuilder temp = ig.DeclareLocal (t);
3636 ig.Emit (OpCodes.Stloc, temp);
3637 ig.Emit (OpCodes.Ldloca, temp);
3640 instance_expr.Emit (ec);
3641 ig.Emit (OpCodes.Box, instance_expr.Type);
3644 instance_expr.Emit (ec);
3648 if (Arguments != null)
3649 EmitArguments (ec, method, Arguments);
3651 if (is_static || struct_call || is_base){
3652 if (method is MethodInfo)
3653 ig.Emit (OpCodes.Call, (MethodInfo) method);
3655 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
3657 if (method is MethodInfo)
3658 ig.Emit (OpCodes.Callvirt, (MethodInfo) method);
3660 ig.Emit (OpCodes.Callvirt, (ConstructorInfo) method);
3664 public override void Emit (EmitContext ec)
3666 MethodGroupExpr mg = (MethodGroupExpr) this.expr;
3668 EmitCall (ec, is_base, method.IsStatic, mg.InstanceExpression, method, Arguments);
3671 public override void EmitStatement (EmitContext ec)
3676 // Pop the return value if there is one
3678 if (method is MethodInfo){
3679 if (((MethodInfo)method).ReturnType != TypeManager.void_type)
3680 ec.ig.Emit (OpCodes.Pop);
3686 /// Implements the new expression
3688 public class New : ExpressionStatement {
3689 public readonly ArrayList Arguments;
3690 public readonly string RequestedType;
3693 MethodBase method = null;
3696 // If set, the new expression is for a value_target, and
3697 // we will not leave anything on the stack.
3699 Expression value_target;
3701 public New (string requested_type, ArrayList arguments, Location l)
3703 RequestedType = requested_type;
3704 Arguments = arguments;
3708 public Expression ValueTypeVariable {
3710 return value_target;
3714 value_target = value;
3718 public override Expression DoResolve (EmitContext ec)
3720 type = RootContext.LookupType (ec.TypeContainer, RequestedType, false, loc);
3725 bool IsDelegate = TypeManager.IsDelegateType (type);
3728 return (new NewDelegate (type, Arguments, loc)).Resolve (ec);
3730 bool is_struct = false;
3731 is_struct = type.IsSubclassOf (TypeManager.value_type);
3732 eclass = ExprClass.Value;
3735 // SRE returns a match for .ctor () on structs (the object constructor),
3736 // so we have to manually ignore it.
3738 if (is_struct && Arguments == null)
3742 ml = MemberLookup (ec, type, ".ctor", MemberTypes.Constructor, AllBindingFlags, loc);
3744 if (! (ml is MethodGroupExpr)){
3746 report118 (loc, ml, "method group");
3752 if (Arguments != null){
3753 for (int i = Arguments.Count; i > 0;){
3755 Argument a = (Argument) Arguments [i];
3757 if (!a.Resolve (ec, loc))
3762 method = Invocation.OverloadResolve (ec, (MethodGroupExpr) ml,
3767 if (method == null && !is_struct) {
3769 "New invocation: Can not find a constructor for " +
3770 "this argument list");
3777 // This DoEmit can be invoked in two contexts:
3778 // * As a mechanism that will leave a value on the stack (new object)
3779 // * As one that wont (init struct)
3781 // You can control whether a value is required on the stack by passing
3782 // need_value_on_stack. The code *might* leave a value on the stack
3783 // so it must be popped manually
3785 // If we are dealing with a ValueType, we have a few
3786 // situations to deal with:
3788 // * The target is a ValueType, and we have been provided
3789 // the instance (this is easy, we are being assigned).
3791 // * The target of New is being passed as an argument,
3792 // to a boxing operation or a function that takes a
3795 // In this case, we need to create a temporary variable
3796 // that is the argument of New.
3798 // Returns whether a value is left on the stack
3800 bool DoEmit (EmitContext ec, bool need_value_on_stack)
3802 bool is_value_type = type.IsSubclassOf (TypeManager.value_type);
3803 ILGenerator ig = ec.ig;
3808 if (value_target == null)
3809 value_target = new LocalTemporary (ec, type);
3811 ml = (IMemoryLocation) value_target;
3812 ml.AddressOf (ec, AddressOp.Store);
3816 Invocation.EmitArguments (ec, method, Arguments);
3820 ig.Emit (OpCodes.Initobj, type);
3822 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
3824 if (need_value_on_stack){
3825 value_target.Emit (ec);
3830 ig.Emit (OpCodes.Newobj, (ConstructorInfo) method);
3835 public override void Emit (EmitContext ec)
3840 public override void EmitStatement (EmitContext ec)
3842 if (DoEmit (ec, false))
3843 ec.ig.Emit (OpCodes.Pop);
3848 /// Represents an array creation expression.
3852 /// There are two possible scenarios here: one is an array creation
3853 /// expression that specifies the dimensions and optionally the
3854 /// initialization data and the other which does not need dimensions
3855 /// specified but where initialization data is mandatory.
3857 public class ArrayCreation : ExpressionStatement {
3858 string RequestedType;
3860 ArrayList Initializers;
3862 ArrayList Arguments;
3864 MethodBase method = null;
3865 Type array_element_type;
3866 bool IsOneDimensional = false;
3867 bool IsBuiltinType = false;
3868 bool ExpectInitializers = false;
3871 Type underlying_type;
3873 ArrayList ArrayData;
3878 // The number of array initializers that we can handle
3879 // via the InitializeArray method - through EmitStaticInitializers
3881 int num_automatic_initializers;
3883 public ArrayCreation (string requested_type, ArrayList exprs,
3884 string rank, ArrayList initializers, Location l)
3886 RequestedType = requested_type;
3888 Initializers = initializers;
3891 Arguments = new ArrayList ();
3893 foreach (Expression e in exprs)
3894 Arguments.Add (new Argument (e, Argument.AType.Expression));
3897 public ArrayCreation (string requested_type, string rank, ArrayList initializers, Location l)
3899 RequestedType = requested_type;
3900 Initializers = initializers;
3903 Rank = rank.Substring (0, rank.LastIndexOf ("["));
3905 string tmp = rank.Substring (rank.LastIndexOf ("["));
3907 dimensions = tmp.Length - 1;
3908 ExpectInitializers = true;
3911 public static string FormArrayType (string base_type, int idx_count, string rank)
3913 StringBuilder sb = new StringBuilder (base_type);
3918 for (int i = 1; i < idx_count; i++)
3923 return sb.ToString ();
3926 public static string FormElementType (string base_type, int idx_count, string rank)
3928 StringBuilder sb = new StringBuilder (base_type);
3931 for (int i = 1; i < idx_count; i++)
3938 string val = sb.ToString ();
3940 return val.Substring (0, val.LastIndexOf ("["));
3945 Report.Error (178, loc, "Incorrectly structured array initializer");
3948 public bool CheckIndices (EmitContext ec, ArrayList probe, int idx, bool specified_dims)
3950 if (specified_dims) {
3951 Argument a = (Argument) Arguments [idx];
3953 if (!a.Resolve (ec, loc))
3956 if (!(a.Expr is Constant)) {
3957 Report.Error (150, loc, "A constant value is expected");
3961 int value = (int) ((Constant) a.Expr).GetValue ();
3963 if (value != probe.Count) {
3968 Bounds [idx] = value;
3971 foreach (object o in probe) {
3972 if (o is ArrayList) {
3973 bool ret = CheckIndices (ec, (ArrayList) o, idx + 1, specified_dims);
3977 Expression tmp = (Expression) o;
3978 tmp = tmp.Resolve (ec);
3982 // Handle initialization from vars, fields etc.
3984 Expression conv = ConvertImplicitRequired (
3985 ec, tmp, underlying_type, loc);
3990 if (conv is StringConstant)
3991 ArrayData.Add (conv);
3992 else if (conv is Constant) {
3993 ArrayData.Add (conv);
3994 num_automatic_initializers++;
3996 ArrayData.Add (conv);
4003 public void UpdateIndices (EmitContext ec)
4006 for (ArrayList probe = Initializers; probe != null;) {
4007 if (probe.Count > 0 && probe [0] is ArrayList) {
4008 Expression e = new IntConstant (probe.Count);
4009 Arguments.Add (new Argument (e, Argument.AType.Expression));
4011 Bounds [i++] = probe.Count;
4013 probe = (ArrayList) probe [0];
4016 Expression e = new IntConstant (probe.Count);
4017 Arguments.Add (new Argument (e, Argument.AType.Expression));
4019 Bounds [i++] = probe.Count;
4026 public bool ValidateInitializers (EmitContext ec)
4028 if (Initializers == null) {
4029 if (ExpectInitializers)
4035 underlying_type = RootContext.LookupType (
4036 ec.TypeContainer, RequestedType, false, loc);
4039 // We use this to store all the date values in the order in which we
4040 // will need to store them in the byte blob later
4042 ArrayData = new ArrayList ();
4043 Bounds = new Hashtable ();
4047 if (Arguments != null) {
4048 ret = CheckIndices (ec, Initializers, 0, true);
4052 Arguments = new ArrayList ();
4054 ret = CheckIndices (ec, Initializers, 0, false);
4061 if (Arguments.Count != dimensions) {
4070 public override Expression DoResolve (EmitContext ec)
4075 // First step is to validate the initializers and fill
4076 // in any missing bits
4078 if (!ValidateInitializers (ec))
4081 if (Arguments == null)
4084 arg_count = Arguments.Count;
4085 for (int i = arg_count; i > 0;){
4087 Argument a = (Argument) Arguments [i];
4089 if (!a.Resolve (ec, loc))
4094 string array_type = FormArrayType (RequestedType, arg_count, Rank);
4095 string element_type = FormElementType (RequestedType, arg_count, Rank);
4097 type = RootContext.LookupType (ec.TypeContainer, array_type, false, loc);
4099 array_element_type = RootContext.LookupType (
4100 ec.TypeContainer, element_type, false, loc);
4105 if (arg_count == 1) {
4106 IsOneDimensional = true;
4107 eclass = ExprClass.Value;
4111 IsBuiltinType = TypeManager.IsBuiltinType (type);
4113 if (IsBuiltinType) {
4117 ml = MemberLookup (ec, type, ".ctor", MemberTypes.Constructor,
4118 AllBindingFlags, loc);
4120 if (!(ml is MethodGroupExpr)){
4121 report118 (loc, ml, "method group");
4126 Report.Error (-6, loc, "New invocation: Can not find a constructor for " +
4127 "this argument list");
4131 method = Invocation.OverloadResolve (ec, (MethodGroupExpr) ml, Arguments, loc);
4133 if (method == null) {
4134 Report.Error (-6, loc, "New invocation: Can not find a constructor for " +
4135 "this argument list");
4139 eclass = ExprClass.Value;
4144 ModuleBuilder mb = RootContext.ModuleBuilder;
4146 ArrayList args = new ArrayList ();
4147 if (Arguments != null){
4148 for (int i = arg_count; i > 0;){
4150 Argument a = (Argument) Arguments [i];
4156 Type [] arg_types = null;
4159 arg_types = new Type [args.Count];
4161 args.CopyTo (arg_types, 0);
4163 method = mb.GetArrayMethod (type, ".ctor", CallingConventions.HasThis, null,
4166 if (method == null) {
4167 Report.Error (-6, loc, "New invocation: Can not find a constructor for " +
4168 "this argument list");
4172 eclass = ExprClass.Value;
4178 public static byte [] MakeByteBlob (ArrayList ArrayData, Type underlying_type, Location loc)
4183 int count = ArrayData.Count;
4185 factor = GetTypeSize (underlying_type);
4189 data = new byte [(count * factor + 4) & ~3];
4192 for (int i = 0; i < count; ++i) {
4193 object v = ArrayData [i];
4195 if (v is EnumConstant)
4196 v = ((EnumConstant) v).Child;
4198 if (v is Constant && !(v is StringConstant))
4199 v = ((Constant) v).GetValue ();
4205 if (underlying_type == TypeManager.int64_type){
4206 if (!(v is Expression)){
4207 long val = (long) v;
4209 for (int j = 0; j < factor; ++j) {
4210 data [idx + j] = (byte) (val & 0xFF);
4214 } else if (underlying_type == TypeManager.uint64_type){
4215 if (!(v is Expression)){
4216 ulong val = (ulong) v;
4218 for (int j = 0; j < factor; ++j) {
4219 data [idx + j] = (byte) (val & 0xFF);
4223 } else if (underlying_type == TypeManager.float_type) {
4224 if (!(v is Expression)){
4225 element = BitConverter.GetBytes ((float) v);
4227 for (int j = 0; j < factor; ++j)
4228 data [idx + j] = element [j];
4230 } else if (underlying_type == TypeManager.double_type) {
4231 if (!(v is Expression)){
4232 element = BitConverter.GetBytes ((double) v);
4234 for (int j = 0; j < factor; ++j)
4235 data [idx + j] = element [j];
4237 } else if (underlying_type == TypeManager.char_type){
4238 if (!(v is Expression)){
4239 int val = (int) ((char) v);
4241 data [idx] = (byte) (val & 0xff);
4242 data [idx+1] = (byte) (val >> 8);
4244 } else if (underlying_type == TypeManager.short_type){
4245 if (!(v is Expression)){
4246 int val = (int) ((short) v);
4248 data [idx] = (byte) (val & 0xff);
4249 data [idx+1] = (byte) (val >> 8);
4251 } else if (underlying_type == TypeManager.ushort_type){
4252 if (!(v is Expression)){
4253 int val = (int) ((ushort) v);
4255 data [idx] = (byte) (val & 0xff);
4256 data [idx+1] = (byte) (val >> 8);
4258 } else if (underlying_type == TypeManager.int32_type) {
4259 if (!(v is Expression)){
4262 data [idx] = (byte) (val & 0xff);
4263 data [idx+1] = (byte) ((val >> 8) & 0xff);
4264 data [idx+2] = (byte) ((val >> 16) & 0xff);
4265 data [idx+3] = (byte) (val >> 24);
4267 } else if (underlying_type == TypeManager.uint32_type) {
4268 if (!(v is Expression)){
4269 uint val = (uint) v;
4271 data [idx] = (byte) (val & 0xff);
4272 data [idx+1] = (byte) ((val >> 8) & 0xff);
4273 data [idx+2] = (byte) ((val >> 16) & 0xff);
4274 data [idx+3] = (byte) (val >> 24);
4276 } else if (underlying_type == TypeManager.sbyte_type) {
4277 if (!(v is Expression)){
4278 sbyte val = (sbyte) v;
4279 data [idx] = (byte) val;
4281 } else if (underlying_type == TypeManager.byte_type) {
4282 if (!(v is Expression)){
4283 byte val = (byte) v;
4284 data [idx] = (byte) val;
4287 throw new Exception ("Unrecognized type in MakeByteBlob");
4296 // Emits the initializers for the array
4298 void EmitStaticInitializers (EmitContext ec, bool is_expression)
4301 // First, the static data
4304 ILGenerator ig = ec.ig;
4306 byte [] data = MakeByteBlob (ArrayData, underlying_type, loc);
4309 fb = RootContext.MakeStaticData (data);
4312 ig.Emit (OpCodes.Dup);
4313 ig.Emit (OpCodes.Ldtoken, fb);
4314 ig.Emit (OpCodes.Call,
4315 TypeManager.void_initializearray_array_fieldhandle);
4320 // Emits pieces of the array that can not be computed at compile
4321 // time (variables and string locations).
4323 // This always expect the top value on the stack to be the array
4325 void EmitDynamicInitializers (EmitContext ec, bool is_expression)
4327 ILGenerator ig = ec.ig;
4328 int dims = Bounds.Count;
4329 int [] current_pos = new int [dims];
4330 int top = ArrayData.Count;
4331 LocalBuilder temp = ig.DeclareLocal (type);
4333 ig.Emit (OpCodes.Stloc, temp);
4335 MethodInfo set = null;
4339 ModuleBuilder mb = null;
4340 mb = RootContext.ModuleBuilder;
4341 args = new Type [dims + 1];
4344 for (j = 0; j < dims; j++)
4345 args [j] = TypeManager.int32_type;
4347 args [j] = array_element_type;
4349 set = mb.GetArrayMethod (
4351 CallingConventions.HasThis | CallingConventions.Standard,
4352 TypeManager.void_type, args);
4355 for (int i = 0; i < top; i++){
4357 Expression e = null;
4359 if (ArrayData [i] is Expression)
4360 e = (Expression) ArrayData [i];
4364 // Basically we do this for string literals and
4365 // other non-literal expressions
4367 if (e is StringConstant || !(e is Constant) || num_automatic_initializers <= 2) {
4369 ig.Emit (OpCodes.Ldloc, temp);
4371 for (int idx = dims; idx > 0; ) {
4373 IntConstant.EmitInt (ig, current_pos [idx]);
4379 ArrayAccess.EmitStoreOpcode (ig, array_element_type);
4381 ig.Emit (OpCodes.Call, set);
4389 for (int j = 0; j < dims; j++){
4391 if (current_pos [j] < (int) Bounds [j])
4393 current_pos [j] = 0;
4398 ig.Emit (OpCodes.Ldloc, temp);
4401 void DoEmit (EmitContext ec, bool is_statement)
4403 ILGenerator ig = ec.ig;
4405 if (IsOneDimensional) {
4406 Invocation.EmitArguments (ec, null, Arguments);
4407 ig.Emit (OpCodes.Newarr, array_element_type);
4410 Invocation.EmitArguments (ec, null, Arguments);
4413 ig.Emit (OpCodes.Newobj, (ConstructorInfo) method);
4415 ig.Emit (OpCodes.Newobj, (MethodInfo) method);
4418 if (Initializers != null){
4420 // FIXME: Set this variable correctly.
4422 bool dynamic_initializers = true;
4424 if (underlying_type != TypeManager.string_type &&
4425 underlying_type != TypeManager.object_type) {
4426 if (num_automatic_initializers > 2)
4427 EmitStaticInitializers (ec, dynamic_initializers || !is_statement);
4430 if (dynamic_initializers)
4431 EmitDynamicInitializers (ec, !is_statement);
4435 public override void Emit (EmitContext ec)
4440 public override void EmitStatement (EmitContext ec)
4448 /// Represents the `this' construct
4450 public class This : Expression, IAssignMethod, IMemoryLocation {
4453 public This (Location loc)
4458 public override Expression DoResolve (EmitContext ec)
4460 eclass = ExprClass.Variable;
4461 type = ec.TypeContainer.TypeBuilder;
4464 Report.Error (26, loc,
4465 "Keyword this not valid in static code");
4472 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
4476 if (ec.TypeContainer is Class){
4477 Report.Error (1604, loc, "Cannot assign to `this'");
4484 public override void Emit (EmitContext ec)
4486 ec.ig.Emit (OpCodes.Ldarg_0);
4489 public void EmitAssign (EmitContext ec, Expression source)
4492 ec.ig.Emit (OpCodes.Starg, 0);
4495 public void AddressOf (EmitContext ec, AddressOp mode)
4497 ec.ig.Emit (OpCodes.Ldarg_0);
4500 // FIGURE OUT WHY LDARG_S does not work
4502 // consider: struct X { int val; int P { set { val = value; }}}
4504 // Yes, this looks very bad. Look at `NOTAS' for
4506 // ec.ig.Emit (OpCodes.Ldarga_S, (byte) 0);
4511 /// Implements the typeof operator
4513 public class TypeOf : Expression {
4514 public readonly string QueriedType;
4518 public TypeOf (string queried_type, Location l)
4520 QueriedType = queried_type;
4524 public override Expression DoResolve (EmitContext ec)
4526 typearg = RootContext.LookupType (
4527 ec.TypeContainer, QueriedType, false, loc);
4529 if (typearg == null)
4532 type = TypeManager.type_type;
4533 eclass = ExprClass.Type;
4537 public override void Emit (EmitContext ec)
4539 ec.ig.Emit (OpCodes.Ldtoken, typearg);
4540 ec.ig.Emit (OpCodes.Call, TypeManager.system_type_get_type_from_handle);
4545 /// Implements the sizeof expression
4547 public class SizeOf : Expression {
4548 public readonly string QueriedType;
4552 public SizeOf (string queried_type, Location l)
4554 this.QueriedType = queried_type;
4558 public override Expression DoResolve (EmitContext ec)
4560 type_queried = RootContext.LookupType (
4561 ec.TypeContainer, QueriedType, false, loc);
4562 if (type_queried == null)
4565 type = TypeManager.int32_type;
4566 eclass = ExprClass.Value;
4570 public override void Emit (EmitContext ec)
4572 int size = GetTypeSize (type_queried);
4575 ec.ig.Emit (OpCodes.Sizeof, type_queried);
4577 IntConstant.EmitInt (ec.ig, size);
4582 /// Implements the member access expression
4584 public class MemberAccess : Expression {
4585 public readonly string Identifier;
4587 Expression member_lookup;
4590 public MemberAccess (Expression expr, string id, Location l)
4597 public Expression Expr {
4603 static void error176 (Location loc, string name)
4605 Report.Error (176, loc, "Static member `" +
4606 name + "' cannot be accessed " +
4607 "with an instance reference, qualify with a " +
4608 "type name instead");
4611 static bool IdenticalNameAndTypeName (EmitContext ec, Expression left_original, Location loc)
4613 if (left_original == null)
4616 if (!(left_original is SimpleName))
4619 SimpleName sn = (SimpleName) left_original;
4621 Type t = RootContext.LookupType (ec.TypeContainer, sn.Name, true, loc);
4628 public static Expression ResolveMemberAccess (EmitContext ec, Expression member_lookup,
4629 Expression left, Location loc,
4630 Expression left_original)
4635 if (member_lookup is MethodGroupExpr){
4636 MethodGroupExpr mg = (MethodGroupExpr) member_lookup;
4641 if (left is TypeExpr){
4642 if (!mg.RemoveInstanceMethods ()){
4643 SimpleName.Error120 (loc, mg.Methods [0].Name);
4647 return member_lookup;
4651 // Instance.MethodGroup
4653 if (IdenticalNameAndTypeName (ec, left_original, loc)){
4654 if (mg.RemoveInstanceMethods ())
4655 return member_lookup;
4658 if (!mg.RemoveStaticMethods ()){
4659 error176 (loc, mg.Methods [0].Name);
4663 mg.InstanceExpression = left;
4664 return member_lookup;
4666 if (!mg.RemoveStaticMethods ()){
4667 if (IdenticalNameAndTypeName (ec, left_original, loc)){
4668 if (!mg.RemoveInstanceMethods ()){
4669 SimpleName.Error120 (loc, mg.Methods [0].Name);
4672 return member_lookup;
4675 error176 (loc, mg.Methods [0].Name);
4679 mg.InstanceExpression = left;
4681 return member_lookup;
4685 if (member_lookup is FieldExpr){
4686 FieldExpr fe = (FieldExpr) member_lookup;
4687 FieldInfo fi = fe.FieldInfo;
4689 if (fi is FieldBuilder) {
4690 Const c = TypeManager.LookupConstant ((FieldBuilder) fi);
4693 object o = c.LookupConstantValue (ec);
4694 object real_value = ((Constant) c.Expr).GetValue ();
4696 return Constantify (real_value, fi.FieldType);
4701 Type t = fi.FieldType;
4702 Type decl_type = fi.DeclaringType;
4705 if (fi is FieldBuilder)
4706 o = TypeManager.GetValue ((FieldBuilder) fi);
4708 o = fi.GetValue (fi);
4710 if (decl_type.IsSubclassOf (TypeManager.enum_type)) {
4711 Expression enum_member = MemberLookup (
4712 ec, decl_type, "value__", MemberTypes.Field,
4713 AllBindingFlags, loc);
4715 Enum en = TypeManager.LookupEnum (decl_type);
4719 c = Constantify (o, en.UnderlyingType);
4721 c = Constantify (o, enum_member.Type);
4723 return new EnumConstant (c, decl_type);
4726 Expression exp = Constantify (o, t);
4728 if (!(left is TypeExpr)) {
4729 error176 (loc, fe.FieldInfo.Name);
4736 if (fi.FieldType.IsPointer && !ec.InUnsafe){
4741 if (left is TypeExpr){
4742 // and refers to a type name or an
4743 if (!fe.FieldInfo.IsStatic){
4744 error176 (loc, fe.FieldInfo.Name);
4747 return member_lookup;
4749 if (fe.FieldInfo.IsStatic){
4750 if (IdenticalNameAndTypeName (ec, left_original, loc))
4751 return member_lookup;
4753 error176 (loc, fe.FieldInfo.Name);
4756 fe.InstanceExpression = left;
4762 if (member_lookup is PropertyExpr){
4763 PropertyExpr pe = (PropertyExpr) member_lookup;
4765 if (left is TypeExpr){
4767 SimpleName.Error120 (loc, pe.PropertyInfo.Name);
4773 if (IdenticalNameAndTypeName (ec, left_original, loc))
4774 return member_lookup;
4775 error176 (loc, pe.PropertyInfo.Name);
4778 pe.InstanceExpression = left;
4784 if (member_lookup is EventExpr) {
4786 EventExpr ee = (EventExpr) member_lookup;
4789 // If the event is local to this class, we transform ourselves into
4793 Expression ml = MemberLookup (
4794 ec, ec.TypeContainer.TypeBuilder,
4795 ee.EventInfo.Name, MemberTypes.Event, AllBindingFlags, loc);
4798 MemberInfo mi = ec.TypeContainer.GetFieldFromEvent ((EventExpr) ml);
4802 // If this happens, then we have an event with its own
4803 // accessors and private field etc so there's no need
4804 // to transform ourselves : we should instead flag an error
4806 Assign.error70 (ee.EventInfo, loc);
4810 ml = ExprClassFromMemberInfo (ec, mi, loc);
4813 Report.Error (-200, loc, "Internal error!!");
4816 return ResolveMemberAccess (ec, ml, left, loc, left_original);
4819 if (left is TypeExpr) {
4821 SimpleName.Error120 (loc, ee.EventInfo.Name);
4829 if (IdenticalNameAndTypeName (ec, left_original, loc))
4832 error176 (loc, ee.EventInfo.Name);
4836 ee.InstanceExpression = left;
4842 if (member_lookup is TypeExpr){
4843 member_lookup.Resolve (ec);
4844 return member_lookup;
4847 Console.WriteLine ("Left is: " + left);
4848 Report.Error (-100, loc, "Support for [" + member_lookup + "] is not present yet");
4849 Environment.Exit (0);
4853 public override Expression DoResolve (EmitContext ec)
4856 // We are the sole users of ResolveWithSimpleName (ie, the only
4857 // ones that can cope with it
4859 Expression original = expr;
4860 expr = expr.ResolveWithSimpleName (ec);
4865 if (expr is SimpleName){
4866 SimpleName child_expr = (SimpleName) expr;
4868 expr = new SimpleName (child_expr.Name + "." + Identifier, loc);
4870 return expr.ResolveWithSimpleName (ec);
4874 // TODO: I mailed Ravi about this, and apparently we can get rid
4875 // of this and put it in the right place.
4877 // Handle enums here when they are in transit.
4878 // Note that we cannot afford to hit MemberLookup in this case because
4879 // it will fail to find any members at all
4882 Type expr_type = expr.Type;
4883 if ((expr is TypeExpr) && (expr_type.IsSubclassOf (TypeManager.enum_type))){
4885 Enum en = TypeManager.LookupEnum (expr_type);
4888 object value = en.LookupEnumValue (ec, Identifier, loc);
4891 Constant c = Constantify (value, en.UnderlyingType);
4892 return new EnumConstant (c, expr_type);
4897 if (expr_type.IsPointer){
4898 Report.Error (23, loc,
4899 "The `.' operator can not be applied to pointer operands (" +
4900 TypeManager.CSharpName (expr_type) + ")");
4904 member_lookup = MemberLookup (ec, expr_type, Identifier, loc);
4906 if (member_lookup == null){
4907 Report.Error (117, loc, "`" + expr_type + "' does not contain a " +
4908 "definition for `" + Identifier + "'");
4913 return ResolveMemberAccess (ec, member_lookup, expr, loc, original);
4916 public override void Emit (EmitContext ec)
4918 throw new Exception ("Should not happen");
4923 /// Implements checked expressions
4925 public class CheckedExpr : Expression {
4927 public Expression Expr;
4929 public CheckedExpr (Expression e)
4934 public override Expression DoResolve (EmitContext ec)
4936 bool last_const_check = ec.ConstantCheckState;
4938 ec.ConstantCheckState = true;
4939 Expr = Expr.Resolve (ec);
4940 ec.ConstantCheckState = last_const_check;
4945 eclass = Expr.eclass;
4950 public override void Emit (EmitContext ec)
4952 bool last_check = ec.CheckState;
4953 bool last_const_check = ec.ConstantCheckState;
4955 ec.CheckState = true;
4956 ec.ConstantCheckState = true;
4958 ec.CheckState = last_check;
4959 ec.ConstantCheckState = last_const_check;
4965 /// Implements the unchecked expression
4967 public class UnCheckedExpr : Expression {
4969 public Expression Expr;
4971 public UnCheckedExpr (Expression e)
4976 public override Expression DoResolve (EmitContext ec)
4978 bool last_const_check = ec.ConstantCheckState;
4980 ec.ConstantCheckState = false;
4981 Expr = Expr.Resolve (ec);
4982 ec.ConstantCheckState = last_const_check;
4987 eclass = Expr.eclass;
4992 public override void Emit (EmitContext ec)
4994 bool last_check = ec.CheckState;
4995 bool last_const_check = ec.ConstantCheckState;
4997 ec.CheckState = false;
4998 ec.ConstantCheckState = false;
5000 ec.CheckState = last_check;
5001 ec.ConstantCheckState = last_const_check;
5007 /// An Element Access expression.
5009 /// During semantic analysis these are transformed into
5010 /// IndexerAccess or ArrayAccess
5012 public class ElementAccess : Expression {
5013 public ArrayList Arguments;
5014 public Expression Expr;
5015 public Location loc;
5017 public ElementAccess (Expression e, ArrayList e_list, Location l)
5026 Arguments = new ArrayList ();
5027 foreach (Expression tmp in e_list)
5028 Arguments.Add (new Argument (tmp, Argument.AType.Expression));
5032 bool CommonResolve (EmitContext ec)
5034 Expr = Expr.Resolve (ec);
5039 if (Arguments == null)
5042 for (int i = Arguments.Count; i > 0;){
5044 Argument a = (Argument) Arguments [i];
5046 if (!a.Resolve (ec, loc))
5053 Expression MakePointerAccess ()
5057 if (t == TypeManager.void_ptr_type){
5060 "The array index operation is not valid for void pointers");
5063 if (Arguments.Count != 1){
5066 "A pointer must be indexed by a single value");
5069 Expression p = new PointerArithmetic (true, Expr, ((Argument)Arguments [0]).Expr, t);
5070 return new Indirection (p);
5073 public override Expression DoResolve (EmitContext ec)
5075 if (!CommonResolve (ec))
5079 // We perform some simple tests, and then to "split" the emit and store
5080 // code we create an instance of a different class, and return that.
5082 // I am experimenting with this pattern.
5086 if (t.IsSubclassOf (TypeManager.array_type))
5087 return (new ArrayAccess (this)).Resolve (ec);
5088 else if (t.IsPointer)
5089 return MakePointerAccess ();
5091 return (new IndexerAccess (this)).Resolve (ec);
5094 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
5096 if (!CommonResolve (ec))
5100 if (t.IsSubclassOf (TypeManager.array_type))
5101 return (new ArrayAccess (this)).ResolveLValue (ec, right_side);
5102 else if (t.IsPointer)
5103 return MakePointerAccess ();
5105 return (new IndexerAccess (this)).ResolveLValue (ec, right_side);
5108 public override void Emit (EmitContext ec)
5110 throw new Exception ("Should never be reached");
5115 /// Implements array access
5117 public class ArrayAccess : Expression, IAssignMethod, IMemoryLocation {
5119 // Points to our "data" repository
5123 public ArrayAccess (ElementAccess ea_data)
5126 eclass = ExprClass.Variable;
5129 public override Expression DoResolve (EmitContext ec)
5131 if (ea.Expr.eclass != ExprClass.Variable) {
5132 report118 (ea.loc, ea.Expr, "variable");
5136 Type t = ea.Expr.Type;
5137 if (t.GetArrayRank () != ea.Arguments.Count){
5138 Report.Error (22, ea.loc,
5139 "Incorrect number of indexes for array " +
5140 " expected: " + t.GetArrayRank () + " got: " +
5141 ea.Arguments.Count);
5144 type = t.GetElementType ();
5145 if (type.IsPointer && !ec.InUnsafe){
5146 UnsafeError (ea.loc);
5150 eclass = ExprClass.Variable;
5156 /// Emits the right opcode to load an object of Type `t'
5157 /// from an array of T
5159 static public void EmitLoadOpcode (ILGenerator ig, Type type)
5161 if (type == TypeManager.byte_type || type == TypeManager.bool_type)
5162 ig.Emit (OpCodes.Ldelem_I1);
5163 else if (type == TypeManager.sbyte_type)
5164 ig.Emit (OpCodes.Ldelem_U1);
5165 else if (type == TypeManager.short_type)
5166 ig.Emit (OpCodes.Ldelem_I2);
5167 else if (type == TypeManager.ushort_type)
5168 ig.Emit (OpCodes.Ldelem_U2);
5169 else if (type == TypeManager.int32_type)
5170 ig.Emit (OpCodes.Ldelem_I4);
5171 else if (type == TypeManager.uint32_type)
5172 ig.Emit (OpCodes.Ldelem_U4);
5173 else if (type == TypeManager.uint64_type)
5174 ig.Emit (OpCodes.Ldelem_I8);
5175 else if (type == TypeManager.int64_type)
5176 ig.Emit (OpCodes.Ldelem_I8);
5177 else if (type == TypeManager.float_type)
5178 ig.Emit (OpCodes.Ldelem_R4);
5179 else if (type == TypeManager.double_type)
5180 ig.Emit (OpCodes.Ldelem_R8);
5181 else if (type == TypeManager.intptr_type)
5182 ig.Emit (OpCodes.Ldelem_I);
5183 else if (type.IsValueType){
5184 ig.Emit (OpCodes.Ldelema, type);
5185 ig.Emit (OpCodes.Ldobj, type);
5187 ig.Emit (OpCodes.Ldelem_Ref);
5191 /// Emits the right opcode to store an object of Type `t'
5192 /// from an array of T.
5194 static public void EmitStoreOpcode (ILGenerator ig, Type t)
5196 if (t == TypeManager.byte_type || t == TypeManager.sbyte_type ||
5197 t == TypeManager.bool_type)
5198 ig.Emit (OpCodes.Stelem_I1);
5199 else if (t == TypeManager.short_type || t == TypeManager.ushort_type || t == TypeManager.char_type)
5200 ig.Emit (OpCodes.Stelem_I2);
5201 else if (t == TypeManager.int32_type || t == TypeManager.uint32_type)
5202 ig.Emit (OpCodes.Stelem_I4);
5203 else if (t == TypeManager.int64_type || t == TypeManager.uint64_type)
5204 ig.Emit (OpCodes.Stelem_I8);
5205 else if (t == TypeManager.float_type)
5206 ig.Emit (OpCodes.Stelem_R4);
5207 else if (t == TypeManager.double_type)
5208 ig.Emit (OpCodes.Stelem_R8);
5209 else if (t == TypeManager.intptr_type)
5210 ig.Emit (OpCodes.Stelem_I);
5211 else if (t.IsValueType)
5212 ig.Emit (OpCodes.Stobj, t);
5214 ig.Emit (OpCodes.Stelem_Ref);
5217 MethodInfo FetchGetMethod ()
5219 ModuleBuilder mb = RootContext.ModuleBuilder;
5220 Type [] args = new Type [ea.Arguments.Count];
5225 foreach (Argument a in ea.Arguments)
5226 args [i++] = a.Type;
5228 get = mb.GetArrayMethod (
5229 ea.Expr.Type, "Get",
5230 CallingConventions.HasThis |
5231 CallingConventions.Standard,
5237 MethodInfo FetchAddressMethod ()
5239 ModuleBuilder mb = RootContext.ModuleBuilder;
5240 Type [] args = new Type [ea.Arguments.Count];
5242 string ptr_type_name;
5246 ptr_type_name = type.FullName + "&";
5247 ret_type = Type.GetType (ptr_type_name);
5250 // It is a type defined by the source code we are compiling
5252 if (ret_type == null){
5253 ret_type = mb.GetType (ptr_type_name);
5256 foreach (Argument a in ea.Arguments)
5257 args [i++] = a.Type;
5259 address = mb.GetArrayMethod (
5260 ea.Expr.Type, "Address",
5261 CallingConventions.HasThis |
5262 CallingConventions.Standard,
5268 public override void Emit (EmitContext ec)
5270 int rank = ea.Expr.Type.GetArrayRank ();
5271 ILGenerator ig = ec.ig;
5275 foreach (Argument a in ea.Arguments)
5279 EmitLoadOpcode (ig, type);
5283 method = FetchGetMethod ();
5284 ig.Emit (OpCodes.Call, method);
5288 public void EmitAssign (EmitContext ec, Expression source)
5290 int rank = ea.Expr.Type.GetArrayRank ();
5291 ILGenerator ig = ec.ig;
5295 foreach (Argument a in ea.Arguments)
5298 Type t = source.Type;
5301 // The stobj opcode used by value types will need
5302 // an address on the stack, not really an array/array
5306 if (t.IsValueType && !TypeManager.IsBuiltinType (t))
5307 ig.Emit (OpCodes.Ldelema, t);
5313 EmitStoreOpcode (ig, t);
5315 ModuleBuilder mb = RootContext.ModuleBuilder;
5316 Type [] args = new Type [ea.Arguments.Count + 1];
5321 foreach (Argument a in ea.Arguments)
5322 args [i++] = a.Type;
5326 set = mb.GetArrayMethod (
5327 ea.Expr.Type, "Set",
5328 CallingConventions.HasThis |
5329 CallingConventions.Standard,
5330 TypeManager.void_type, args);
5332 ig.Emit (OpCodes.Call, set);
5336 public void AddressOf (EmitContext ec, AddressOp mode)
5338 int rank = ea.Expr.Type.GetArrayRank ();
5339 ILGenerator ig = ec.ig;
5343 foreach (Argument a in ea.Arguments)
5347 ig.Emit (OpCodes.Ldelema, type);
5349 MethodInfo address = FetchAddressMethod ();
5350 ig.Emit (OpCodes.Call, address);
5357 public ArrayList getters, setters;
5358 static Hashtable map;
5362 map = new Hashtable ();
5365 Indexers (MemberInfo [] mi)
5367 foreach (PropertyInfo property in mi){
5368 MethodInfo get, set;
5370 get = property.GetGetMethod (true);
5372 if (getters == null)
5373 getters = new ArrayList ();
5378 set = property.GetSetMethod (true);
5380 if (setters == null)
5381 setters = new ArrayList ();
5387 static public Indexers GetIndexersForType (Type t, TypeManager tm, Location loc)
5389 Indexers ix = (Indexers) map [t];
5390 string p_name = TypeManager.IndexerPropertyName (t);
5395 MemberInfo [] mi = tm.FindMembers (
5396 t, MemberTypes.Property,
5397 BindingFlags.Public | BindingFlags.Instance,
5398 Type.FilterName, p_name);
5400 if (mi == null || mi.Length == 0){
5401 Report.Error (21, loc,
5402 "Type `" + TypeManager.CSharpName (t) + "' does not have " +
5403 "any indexers defined");
5407 ix = new Indexers (mi);
5415 /// Expressions that represent an indexer call.
5417 public class IndexerAccess : Expression, IAssignMethod {
5419 // Points to our "data" repository
5422 MethodInfo get, set;
5424 ArrayList set_arguments;
5426 public IndexerAccess (ElementAccess ea_data)
5429 eclass = ExprClass.Value;
5432 public override Expression DoResolve (EmitContext ec)
5434 Type indexer_type = ea.Expr.Type;
5437 // Step 1: Query for all `Item' *properties*. Notice
5438 // that the actual methods are pointed from here.
5440 // This is a group of properties, piles of them.
5443 ilist = Indexers.GetIndexersForType (
5444 indexer_type, RootContext.TypeManager, ea.loc);
5448 // Step 2: find the proper match
5450 if (ilist != null && ilist.getters != null && ilist.getters.Count > 0)
5451 get = (MethodInfo) Invocation.OverloadResolve (
5452 ec, new MethodGroupExpr (ilist.getters), ea.Arguments, ea.loc);
5455 Report.Error (154, ea.loc,
5456 "indexer can not be used in this context, because " +
5457 "it lacks a `get' accessor");
5461 type = get.ReturnType;
5462 if (type.IsPointer && !ec.InUnsafe){
5463 UnsafeError (ea.loc);
5467 eclass = ExprClass.IndexerAccess;
5471 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
5473 Type indexer_type = ea.Expr.Type;
5474 Type right_type = right_side.Type;
5477 ilist = Indexers.GetIndexersForType (
5478 indexer_type, RootContext.TypeManager, ea.loc);
5480 if (ilist != null && ilist.setters != null && ilist.setters.Count > 0){
5481 set_arguments = (ArrayList) ea.Arguments.Clone ();
5482 set_arguments.Add (new Argument (right_side, Argument.AType.Expression));
5484 set = (MethodInfo) Invocation.OverloadResolve (
5485 ec, new MethodGroupExpr (ilist.setters), set_arguments, ea.loc);
5489 Report.Error (200, ea.loc,
5490 "indexer X.this [" + TypeManager.CSharpName (right_type) +
5491 "] lacks a `set' accessor");
5495 type = TypeManager.void_type;
5496 eclass = ExprClass.IndexerAccess;
5500 public override void Emit (EmitContext ec)
5502 Invocation.EmitCall (ec, false, false, ea.Expr, get, ea.Arguments);
5506 // source is ignored, because we already have a copy of it from the
5507 // LValue resolution and we have already constructed a pre-cached
5508 // version of the arguments (ea.set_arguments);
5510 public void EmitAssign (EmitContext ec, Expression source)
5512 Invocation.EmitCall (ec, false, false, ea.Expr, set, set_arguments);
5517 /// The base operator for method names
5519 public class BaseAccess : Expression {
5523 public BaseAccess (string member, Location l)
5525 this.member = member;
5529 public override Expression DoResolve (EmitContext ec)
5531 Expression member_lookup;
5532 Type current_type = ec.TypeContainer.TypeBuilder;
5533 Type base_type = current_type.BaseType;
5537 Report.Error (1511, loc,
5538 "Keyword base is not allowed in static method");
5542 member_lookup = MemberLookup (ec, base_type, member, loc);
5543 if (member_lookup == null)
5549 left = new TypeExpr (base_type);
5553 e = MemberAccess.ResolveMemberAccess (ec, member_lookup, left, loc, null);
5554 if (e is PropertyExpr){
5555 PropertyExpr pe = (PropertyExpr) e;
5563 public override void Emit (EmitContext ec)
5565 throw new Exception ("Should never be called");
5570 /// The base indexer operator
5572 public class BaseIndexerAccess : Expression {
5573 ArrayList Arguments;
5576 public BaseIndexerAccess (ArrayList args, Location l)
5582 public override Expression DoResolve (EmitContext ec)
5584 Type current_type = ec.TypeContainer.TypeBuilder;
5585 Type base_type = current_type.BaseType;
5586 Expression member_lookup;
5589 Report.Error (1511, loc,
5590 "Keyword base is not allowed in static method");
5594 member_lookup = MemberLookup (ec, base_type, "get_Item", MemberTypes.Method, AllBindingFlags, loc);
5595 if (member_lookup == null)
5598 return MemberAccess.ResolveMemberAccess (ec, member_lookup, ec.This, loc, null);
5601 public override void Emit (EmitContext ec)
5603 throw new Exception ("Should never be called");
5608 /// This class exists solely to pass the Type around and to be a dummy
5609 /// that can be passed to the conversion functions (this is used by
5610 /// foreach implementation to typecast the object return value from
5611 /// get_Current into the proper type. All code has been generated and
5612 /// we only care about the side effect conversions to be performed
5614 public class EmptyExpression : Expression {
5615 public EmptyExpression ()
5617 type = TypeManager.object_type;
5618 eclass = ExprClass.Value;
5621 public EmptyExpression (Type t)
5624 eclass = ExprClass.Value;
5627 public override Expression DoResolve (EmitContext ec)
5632 public override void Emit (EmitContext ec)
5634 // nothing, as we only exist to not do anything.
5638 // This is just because we might want to reuse this bad boy
5639 // instead of creating gazillions of EmptyExpressions.
5640 // (CanConvertImplicit uses it)
5642 public void SetType (Type t)
5648 public class UserCast : Expression {
5652 public UserCast (MethodInfo method, Expression source)
5654 this.method = method;
5655 this.source = source;
5656 type = method.ReturnType;
5657 eclass = ExprClass.Value;
5660 public override Expression DoResolve (EmitContext ec)
5663 // We are born fully resolved
5668 public override void Emit (EmitContext ec)
5670 ILGenerator ig = ec.ig;
5674 if (method is MethodInfo)
5675 ig.Emit (OpCodes.Call, (MethodInfo) method);
5677 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
5683 // This class is used to "construct" the type during a typecast
5684 // operation. Since the Type.GetType class in .NET can parse
5685 // the type specification, we just use this to construct the type
5686 // one bit at a time.
5688 public class ComposedCast : Expression {
5693 public ComposedCast (Expression left, string dim, Location l)
5700 public override Expression DoResolve (EmitContext ec)
5702 left = left.Resolve (ec);
5706 if (left.eclass != ExprClass.Type){
5707 report118 (loc, left, "type");
5711 type = RootContext.LookupType (
5712 ec.TypeContainer, left.Type.FullName + dim, false, loc);
5716 if (!ec.InUnsafe && type.IsPointer){
5721 eclass = ExprClass.Type;
5725 public override void Emit (EmitContext ec)
5727 throw new Exception ("This should never be called");
5732 // This class is used to represent the address of an array, used
5733 // only by the Fixed statement, this is like the C "&a [0]" construct.
5735 public class ArrayPtr : Expression {
5738 public ArrayPtr (Expression array)
5740 Type array_type = array.Type.GetElementType ();
5744 string array_ptr_type_name = array_type.FullName + "*";
5746 type = Type.GetType (array_ptr_type_name);
5748 ModuleBuilder mb = RootContext.ModuleBuilder;
5750 type = mb.GetType (array_ptr_type_name);
5753 eclass = ExprClass.Value;
5756 public override void Emit (EmitContext ec)
5758 ILGenerator ig = ec.ig;
5761 IntLiteral.EmitInt (ig, 0);
5762 ig.Emit (OpCodes.Ldelema, array.Type.GetElementType ());
5765 public override Expression DoResolve (EmitContext ec)
5768 // We are born fully resolved
5775 // Used by the fixed statement
5777 public class StringPtr : Expression {
5780 public StringPtr (LocalBuilder b)
5783 eclass = ExprClass.Value;
5784 type = TypeManager.char_ptr_type;
5787 public override Expression DoResolve (EmitContext ec)
5789 // This should never be invoked, we are born in fully
5790 // initialized state.
5795 public override void Emit (EmitContext ec)
5797 ILGenerator ig = ec.ig;
5799 ig.Emit (OpCodes.Ldloc, b);
5800 ig.Emit (OpCodes.Conv_I);
5801 ig.Emit (OpCodes.Call, TypeManager.int_get_offset_to_string_data);
5802 ig.Emit (OpCodes.Add);
5807 // Implements the `stackalloc' keyword
5809 public class StackAlloc : Expression {
5815 public StackAlloc (string type, Expression count, Location l)
5822 public override Expression DoResolve (EmitContext ec)
5824 count = count.Resolve (ec);
5828 if (count.Type != TypeManager.int32_type){
5829 count = ConvertImplicitRequired (ec, count, TypeManager.int32_type, loc);
5834 if (ec.InCatch || ec.InFinally){
5835 Report.Error (255, loc,
5836 "stackalloc can not be used in a catch or finally block");
5840 otype = RootContext.LookupType (ec.TypeContainer, t, false, loc);
5845 if (!TypeManager.VerifyUnManaged (otype, loc))
5848 string ptr_name = otype.FullName + "*";
5849 type = Type.GetType (ptr_name);
5851 ModuleBuilder mb = RootContext.ModuleBuilder;
5853 type = mb.GetType (ptr_name);
5855 eclass = ExprClass.Value;
5860 public override void Emit (EmitContext ec)
5862 int size = GetTypeSize (otype);
5863 ILGenerator ig = ec.ig;
5866 ig.Emit (OpCodes.Sizeof, otype);
5868 IntConstant.EmitInt (ig, size);
5870 ig.Emit (OpCodes.Mul);
5871 ig.Emit (OpCodes.Localloc);