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 ());
713 // FIXME: We need some way of avoiding the use of temp_storage
714 // for some types of storage (parameters, local variables,
715 // static fields) and single-dimension array access.
717 void EmitCode (EmitContext ec, bool is_expr)
719 ILGenerator ig = ec.ig;
720 IAssignMethod ia = (IAssignMethod) expr;
721 Type expr_type = expr.Type;
723 if (temp_storage == null)
724 temp_storage = new LocalTemporary (ec, expr_type);
727 case Mode.PreIncrement:
728 case Mode.PreDecrement:
732 if (expr_type == TypeManager.uint64_type ||
733 expr_type == TypeManager.int64_type)
734 ig.Emit (OpCodes.Ldc_I8, 1L);
735 else if (expr_type == TypeManager.double_type)
736 ig.Emit (OpCodes.Ldc_R8, 1.0);
737 else if (expr_type == TypeManager.float_type)
738 ig.Emit (OpCodes.Ldc_R4, 1.0F);
739 else if (expr_type.IsPointer){
740 int n = PtrTypeSize (expr_type);
743 ig.Emit (OpCodes.Sizeof, expr_type);
745 IntConstant.EmitInt (ig, n);
747 ig.Emit (OpCodes.Ldc_I4_1);
750 // Select the opcode based on the check state (then the type)
751 // and the actual operation
754 if (expr_type == TypeManager.int32_type ||
755 expr_type == TypeManager.int64_type){
756 if (mode == Mode.PreDecrement)
757 ig.Emit (OpCodes.Sub_Ovf);
759 ig.Emit (OpCodes.Add_Ovf);
760 } else if (expr_type == TypeManager.uint32_type ||
761 expr_type == TypeManager.uint64_type){
762 if (mode == Mode.PreDecrement)
763 ig.Emit (OpCodes.Sub_Ovf_Un);
765 ig.Emit (OpCodes.Add_Ovf_Un);
767 if (mode == Mode.PreDecrement)
768 ig.Emit (OpCodes.Sub_Ovf);
770 ig.Emit (OpCodes.Add_Ovf);
773 if (mode == Mode.PreDecrement)
774 ig.Emit (OpCodes.Sub);
776 ig.Emit (OpCodes.Add);
781 temp_storage.Store (ec);
782 ia.EmitAssign (ec, temp_storage);
784 temp_storage.Emit (ec);
787 case Mode.PostIncrement:
788 case Mode.PostDecrement:
796 ig.Emit (OpCodes.Dup);
798 if (expr_type == TypeManager.uint64_type ||
799 expr_type == TypeManager.int64_type)
800 ig.Emit (OpCodes.Ldc_I8, 1L);
801 else if (expr_type == TypeManager.double_type)
802 ig.Emit (OpCodes.Ldc_R8, 1.0);
803 else if (expr_type == TypeManager.float_type)
804 ig.Emit (OpCodes.Ldc_R4, 1.0F);
805 else if (expr_type.IsPointer){
806 int n = PtrTypeSize (expr_type);
809 ig.Emit (OpCodes.Sizeof, expr_type);
811 IntConstant.EmitInt (ig, n);
813 ig.Emit (OpCodes.Ldc_I4_1);
816 if (expr_type == TypeManager.int32_type ||
817 expr_type == TypeManager.int64_type){
818 if (mode == Mode.PostDecrement)
819 ig.Emit (OpCodes.Sub_Ovf);
821 ig.Emit (OpCodes.Add_Ovf);
822 } else if (expr_type == TypeManager.uint32_type ||
823 expr_type == TypeManager.uint64_type){
824 if (mode == Mode.PostDecrement)
825 ig.Emit (OpCodes.Sub_Ovf_Un);
827 ig.Emit (OpCodes.Add_Ovf_Un);
829 if (mode == Mode.PostDecrement)
830 ig.Emit (OpCodes.Sub_Ovf);
832 ig.Emit (OpCodes.Add_Ovf);
835 if (mode == Mode.PostDecrement)
836 ig.Emit (OpCodes.Sub);
838 ig.Emit (OpCodes.Add);
844 temp_storage.Store (ec);
845 ia.EmitAssign (ec, temp_storage);
850 public override void Emit (EmitContext ec)
856 public override void EmitStatement (EmitContext ec)
858 EmitCode (ec, false);
864 /// Base class for the `Is' and `As' classes.
868 /// FIXME: Split this in two, and we get to save the `Operator' Oper
871 public abstract class Probe : Expression {
872 public readonly string ProbeType;
873 protected Expression expr;
874 protected Type probe_type;
875 protected Location loc;
877 public Probe (Expression expr, string probe_type, Location l)
879 ProbeType = probe_type;
884 public Expression Expr {
890 public override Expression DoResolve (EmitContext ec)
892 probe_type = RootContext.LookupType (ec.DeclSpace, ProbeType, false, loc);
894 if (probe_type == null)
897 expr = expr.Resolve (ec);
904 /// Implementation of the `is' operator.
906 public class Is : Probe {
907 public Is (Expression expr, string probe_type, Location l)
908 : base (expr, probe_type, l)
912 public override void Emit (EmitContext ec)
914 ILGenerator ig = ec.ig;
918 ig.Emit (OpCodes.Isinst, probe_type);
919 ig.Emit (OpCodes.Ldnull);
920 ig.Emit (OpCodes.Cgt_Un);
923 public override Expression DoResolve (EmitContext ec)
925 Expression e = base.DoResolve (ec);
930 if (RootContext.WarningLevel >= 1){
931 if (expr.Type == probe_type || expr.Type.IsSubclassOf (probe_type)){
934 "The expression is always of type `" +
935 TypeManager.CSharpName (probe_type) + "'");
938 if (expr.Type != probe_type && !probe_type.IsSubclassOf (expr.Type)){
939 if (!(probe_type.IsInterface || expr.Type.IsInterface))
942 "The expression is never of type `" +
943 TypeManager.CSharpName (probe_type) + "'");
947 type = TypeManager.bool_type;
948 eclass = ExprClass.Value;
955 /// Implementation of the `as' operator.
957 public class As : Probe {
958 public As (Expression expr, string probe_type, Location l)
959 : base (expr, probe_type, l)
963 public override void Emit (EmitContext ec)
965 ILGenerator ig = ec.ig;
968 ig.Emit (OpCodes.Isinst, probe_type);
971 public override Expression DoResolve (EmitContext ec)
973 Expression e = base.DoResolve (ec);
979 eclass = ExprClass.Value;
986 /// This represents a typecast in the source language.
988 /// FIXME: Cast expressions have an unusual set of parsing
989 /// rules, we need to figure those out.
991 public class Cast : Expression {
992 Expression target_type;
996 public Cast (Expression cast_type, Expression expr, Location loc)
998 this.target_type = cast_type;
1003 public Expression TargetType {
1009 public Expression Expr {
1019 /// Attempts to do a compile-time folding of a constant cast.
1021 Expression TryReduce (EmitContext ec, Type target_type)
1023 if (expr is ByteConstant){
1024 byte v = ((ByteConstant) expr).Value;
1026 if (target_type == TypeManager.sbyte_type)
1027 return new SByteConstant ((sbyte) v);
1028 if (target_type == TypeManager.short_type)
1029 return new ShortConstant ((short) v);
1030 if (target_type == TypeManager.ushort_type)
1031 return new UShortConstant ((ushort) v);
1032 if (target_type == TypeManager.int32_type)
1033 return new IntConstant ((int) v);
1034 if (target_type == TypeManager.uint32_type)
1035 return new UIntConstant ((uint) v);
1036 if (target_type == TypeManager.int64_type)
1037 return new LongConstant ((long) v);
1038 if (target_type == TypeManager.uint64_type)
1039 return new ULongConstant ((ulong) v);
1040 if (target_type == TypeManager.float_type)
1041 return new FloatConstant ((float) v);
1042 if (target_type == TypeManager.double_type)
1043 return new DoubleConstant ((double) v);
1045 if (expr is SByteConstant){
1046 sbyte v = ((SByteConstant) expr).Value;
1048 if (target_type == TypeManager.byte_type)
1049 return new ByteConstant ((byte) v);
1050 if (target_type == TypeManager.short_type)
1051 return new ShortConstant ((short) v);
1052 if (target_type == TypeManager.ushort_type)
1053 return new UShortConstant ((ushort) v);
1054 if (target_type == TypeManager.int32_type)
1055 return new IntConstant ((int) v);
1056 if (target_type == TypeManager.uint32_type)
1057 return new UIntConstant ((uint) v);
1058 if (target_type == TypeManager.int64_type)
1059 return new LongConstant ((long) v);
1060 if (target_type == TypeManager.uint64_type)
1061 return new ULongConstant ((ulong) v);
1062 if (target_type == TypeManager.float_type)
1063 return new FloatConstant ((float) v);
1064 if (target_type == TypeManager.double_type)
1065 return new DoubleConstant ((double) v);
1067 if (expr is ShortConstant){
1068 short v = ((ShortConstant) expr).Value;
1070 if (target_type == TypeManager.byte_type)
1071 return new ByteConstant ((byte) v);
1072 if (target_type == TypeManager.sbyte_type)
1073 return new SByteConstant ((sbyte) v);
1074 if (target_type == TypeManager.ushort_type)
1075 return new UShortConstant ((ushort) v);
1076 if (target_type == TypeManager.int32_type)
1077 return new IntConstant ((int) v);
1078 if (target_type == TypeManager.uint32_type)
1079 return new UIntConstant ((uint) v);
1080 if (target_type == TypeManager.int64_type)
1081 return new LongConstant ((long) v);
1082 if (target_type == TypeManager.uint64_type)
1083 return new ULongConstant ((ulong) v);
1084 if (target_type == TypeManager.float_type)
1085 return new FloatConstant ((float) v);
1086 if (target_type == TypeManager.double_type)
1087 return new DoubleConstant ((double) v);
1089 if (expr is UShortConstant){
1090 ushort v = ((UShortConstant) expr).Value;
1092 if (target_type == TypeManager.byte_type)
1093 return new ByteConstant ((byte) v);
1094 if (target_type == TypeManager.sbyte_type)
1095 return new SByteConstant ((sbyte) v);
1096 if (target_type == TypeManager.short_type)
1097 return new ShortConstant ((short) v);
1098 if (target_type == TypeManager.int32_type)
1099 return new IntConstant ((int) v);
1100 if (target_type == TypeManager.uint32_type)
1101 return new UIntConstant ((uint) v);
1102 if (target_type == TypeManager.int64_type)
1103 return new LongConstant ((long) v);
1104 if (target_type == TypeManager.uint64_type)
1105 return new ULongConstant ((ulong) v);
1106 if (target_type == TypeManager.float_type)
1107 return new FloatConstant ((float) v);
1108 if (target_type == TypeManager.double_type)
1109 return new DoubleConstant ((double) v);
1111 if (expr is IntConstant){
1112 int v = ((IntConstant) expr).Value;
1114 if (target_type == TypeManager.byte_type)
1115 return new ByteConstant ((byte) v);
1116 if (target_type == TypeManager.sbyte_type)
1117 return new SByteConstant ((sbyte) v);
1118 if (target_type == TypeManager.short_type)
1119 return new ShortConstant ((short) v);
1120 if (target_type == TypeManager.ushort_type)
1121 return new UShortConstant ((ushort) v);
1122 if (target_type == TypeManager.uint32_type)
1123 return new UIntConstant ((uint) v);
1124 if (target_type == TypeManager.int64_type)
1125 return new LongConstant ((long) v);
1126 if (target_type == TypeManager.uint64_type)
1127 return new ULongConstant ((ulong) v);
1128 if (target_type == TypeManager.float_type)
1129 return new FloatConstant ((float) v);
1130 if (target_type == TypeManager.double_type)
1131 return new DoubleConstant ((double) v);
1133 if (expr is UIntConstant){
1134 uint v = ((UIntConstant) expr).Value;
1136 if (target_type == TypeManager.byte_type)
1137 return new ByteConstant ((byte) v);
1138 if (target_type == TypeManager.sbyte_type)
1139 return new SByteConstant ((sbyte) v);
1140 if (target_type == TypeManager.short_type)
1141 return new ShortConstant ((short) v);
1142 if (target_type == TypeManager.ushort_type)
1143 return new UShortConstant ((ushort) v);
1144 if (target_type == TypeManager.int32_type)
1145 return new IntConstant ((int) v);
1146 if (target_type == TypeManager.int64_type)
1147 return new LongConstant ((long) v);
1148 if (target_type == TypeManager.uint64_type)
1149 return new ULongConstant ((ulong) v);
1150 if (target_type == TypeManager.float_type)
1151 return new FloatConstant ((float) v);
1152 if (target_type == TypeManager.double_type)
1153 return new DoubleConstant ((double) v);
1155 if (expr is LongConstant){
1156 long v = ((LongConstant) expr).Value;
1158 if (target_type == TypeManager.byte_type)
1159 return new ByteConstant ((byte) v);
1160 if (target_type == TypeManager.sbyte_type)
1161 return new SByteConstant ((sbyte) v);
1162 if (target_type == TypeManager.short_type)
1163 return new ShortConstant ((short) v);
1164 if (target_type == TypeManager.ushort_type)
1165 return new UShortConstant ((ushort) v);
1166 if (target_type == TypeManager.int32_type)
1167 return new IntConstant ((int) v);
1168 if (target_type == TypeManager.uint32_type)
1169 return new UIntConstant ((uint) v);
1170 if (target_type == TypeManager.uint64_type)
1171 return new ULongConstant ((ulong) v);
1172 if (target_type == TypeManager.float_type)
1173 return new FloatConstant ((float) v);
1174 if (target_type == TypeManager.double_type)
1175 return new DoubleConstant ((double) v);
1177 if (expr is ULongConstant){
1178 ulong v = ((ULongConstant) expr).Value;
1180 if (target_type == TypeManager.byte_type)
1181 return new ByteConstant ((byte) v);
1182 if (target_type == TypeManager.sbyte_type)
1183 return new SByteConstant ((sbyte) v);
1184 if (target_type == TypeManager.short_type)
1185 return new ShortConstant ((short) v);
1186 if (target_type == TypeManager.ushort_type)
1187 return new UShortConstant ((ushort) v);
1188 if (target_type == TypeManager.int32_type)
1189 return new IntConstant ((int) v);
1190 if (target_type == TypeManager.uint32_type)
1191 return new UIntConstant ((uint) v);
1192 if (target_type == TypeManager.int64_type)
1193 return new LongConstant ((long) v);
1194 if (target_type == TypeManager.float_type)
1195 return new FloatConstant ((float) v);
1196 if (target_type == TypeManager.double_type)
1197 return new DoubleConstant ((double) v);
1199 if (expr is FloatConstant){
1200 float v = ((FloatConstant) expr).Value;
1202 if (target_type == TypeManager.byte_type)
1203 return new ByteConstant ((byte) v);
1204 if (target_type == TypeManager.sbyte_type)
1205 return new SByteConstant ((sbyte) v);
1206 if (target_type == TypeManager.short_type)
1207 return new ShortConstant ((short) v);
1208 if (target_type == TypeManager.ushort_type)
1209 return new UShortConstant ((ushort) v);
1210 if (target_type == TypeManager.int32_type)
1211 return new IntConstant ((int) v);
1212 if (target_type == TypeManager.uint32_type)
1213 return new UIntConstant ((uint) v);
1214 if (target_type == TypeManager.int64_type)
1215 return new LongConstant ((long) v);
1216 if (target_type == TypeManager.uint64_type)
1217 return new ULongConstant ((ulong) v);
1218 if (target_type == TypeManager.double_type)
1219 return new DoubleConstant ((double) v);
1221 if (expr is DoubleConstant){
1222 double v = ((DoubleConstant) expr).Value;
1224 if (target_type == TypeManager.byte_type)
1225 return new ByteConstant ((byte) v);
1226 if (target_type == TypeManager.sbyte_type)
1227 return new SByteConstant ((sbyte) v);
1228 if (target_type == TypeManager.short_type)
1229 return new ShortConstant ((short) v);
1230 if (target_type == TypeManager.ushort_type)
1231 return new UShortConstant ((ushort) v);
1232 if (target_type == TypeManager.int32_type)
1233 return new IntConstant ((int) v);
1234 if (target_type == TypeManager.uint32_type)
1235 return new UIntConstant ((uint) v);
1236 if (target_type == TypeManager.int64_type)
1237 return new LongConstant ((long) v);
1238 if (target_type == TypeManager.uint64_type)
1239 return new ULongConstant ((ulong) v);
1240 if (target_type == TypeManager.float_type)
1241 return new FloatConstant ((float) v);
1247 public override Expression DoResolve (EmitContext ec)
1249 expr = expr.Resolve (ec);
1253 bool old_state = ec.OnlyLookupTypes;
1254 ec.OnlyLookupTypes = true;
1255 target_type = target_type.Resolve (ec);
1256 ec.OnlyLookupTypes = old_state;
1258 if (target_type == null){
1259 Report.Error (-10, loc, "Can not resolve type");
1263 if (target_type.eclass != ExprClass.Type){
1264 report118 (loc, target_type, "class");
1268 type = target_type.Type;
1269 eclass = ExprClass.Value;
1274 if (expr is Constant){
1275 Expression e = TryReduce (ec, type);
1281 expr = ConvertExplicit (ec, expr, type, loc);
1285 public override void Emit (EmitContext ec)
1288 // This one will never happen
1290 throw new Exception ("Should not happen");
1295 /// Binary operators
1297 public class Binary : Expression {
1298 public enum Operator : byte {
1299 Multiply, Division, Modulus,
1300 Addition, Subtraction,
1301 LeftShift, RightShift,
1302 LessThan, GreaterThan, LessThanOrEqual, GreaterThanOrEqual,
1303 Equality, Inequality,
1312 Expression left, right;
1314 ArrayList Arguments;
1317 bool DelegateOperation;
1319 public Binary (Operator oper, Expression left, Expression right, Location loc)
1327 public Operator Oper {
1336 public Expression Left {
1345 public Expression Right {
1356 /// Returns a stringified representation of the Operator
1358 static string OperName (Operator oper)
1361 case Operator.Multiply:
1363 case Operator.Division:
1365 case Operator.Modulus:
1367 case Operator.Addition:
1369 case Operator.Subtraction:
1371 case Operator.LeftShift:
1373 case Operator.RightShift:
1375 case Operator.LessThan:
1377 case Operator.GreaterThan:
1379 case Operator.LessThanOrEqual:
1381 case Operator.GreaterThanOrEqual:
1383 case Operator.Equality:
1385 case Operator.Inequality:
1387 case Operator.BitwiseAnd:
1389 case Operator.BitwiseOr:
1391 case Operator.ExclusiveOr:
1393 case Operator.LogicalOr:
1395 case Operator.LogicalAnd:
1399 return oper.ToString ();
1402 Expression ForceConversion (EmitContext ec, Expression expr, Type target_type)
1404 if (expr.Type == target_type)
1407 return ConvertImplicit (ec, expr, target_type, new Location (-1));
1410 public static void Error_OperatorAmbiguous (Location loc, Operator oper, Type l, Type r)
1413 34, loc, "Operator `" + OperName (oper)
1414 + "' is ambiguous on operands of type `"
1415 + TypeManager.CSharpName (l) + "' "
1416 + "and `" + TypeManager.CSharpName (r)
1421 // Note that handling the case l == Decimal || r == Decimal
1422 // is taken care of by the Step 1 Operator Overload resolution.
1424 bool DoNumericPromotions (EmitContext ec, Type l, Type r)
1426 if (l == TypeManager.double_type || r == TypeManager.double_type){
1428 // If either operand is of type double, the other operand is
1429 // conveted to type double.
1431 if (r != TypeManager.double_type)
1432 right = ConvertImplicit (ec, right, TypeManager.double_type, loc);
1433 if (l != TypeManager.double_type)
1434 left = ConvertImplicit (ec, left, TypeManager.double_type, loc);
1436 type = TypeManager.double_type;
1437 } else if (l == TypeManager.float_type || r == TypeManager.float_type){
1439 // if either operand is of type float, the other operand is
1440 // converted to type float.
1442 if (r != TypeManager.double_type)
1443 right = ConvertImplicit (ec, right, TypeManager.float_type, loc);
1444 if (l != TypeManager.double_type)
1445 left = ConvertImplicit (ec, left, TypeManager.float_type, loc);
1446 type = TypeManager.float_type;
1447 } else if (l == TypeManager.uint64_type || r == TypeManager.uint64_type){
1451 // If either operand is of type ulong, the other operand is
1452 // converted to type ulong. or an error ocurrs if the other
1453 // operand is of type sbyte, short, int or long
1455 if (l == TypeManager.uint64_type){
1456 if (r != TypeManager.uint64_type){
1457 if (right is IntConstant){
1458 IntConstant ic = (IntConstant) right;
1460 e = TryImplicitIntConversion (l, ic);
1463 } else if (right is LongConstant){
1464 long ll = ((LongConstant) right).Value;
1467 right = new ULongConstant ((ulong) ll);
1469 e = ImplicitNumericConversion (ec, right, l, loc);
1476 if (left is IntConstant){
1477 e = TryImplicitIntConversion (r, (IntConstant) left);
1480 } else if (left is LongConstant){
1481 long ll = ((LongConstant) left).Value;
1484 left = new ULongConstant ((ulong) ll);
1486 e = ImplicitNumericConversion (ec, left, r, loc);
1493 if ((other == TypeManager.sbyte_type) ||
1494 (other == TypeManager.short_type) ||
1495 (other == TypeManager.int32_type) ||
1496 (other == TypeManager.int64_type))
1497 Error_OperatorAmbiguous (loc, oper, l, r);
1498 type = TypeManager.uint64_type;
1499 } else if (l == TypeManager.int64_type || r == TypeManager.int64_type){
1501 // If either operand is of type long, the other operand is converted
1504 if (l != TypeManager.int64_type)
1505 left = ConvertImplicit (ec, left, TypeManager.int64_type, loc);
1506 if (r != TypeManager.int64_type)
1507 right = ConvertImplicit (ec, right, TypeManager.int64_type, loc);
1509 type = TypeManager.int64_type;
1510 } else if (l == TypeManager.uint32_type || r == TypeManager.uint32_type){
1512 // If either operand is of type uint, and the other
1513 // operand is of type sbyte, short or int, othe operands are
1514 // converted to type long.
1518 if (l == TypeManager.uint32_type){
1519 if (right is IntConstant){
1520 IntConstant ic = (IntConstant) right;
1524 right = new UIntConstant ((uint) val);
1531 else if (r == TypeManager.uint32_type){
1532 if (left is IntConstant){
1533 IntConstant ic = (IntConstant) left;
1537 left = new UIntConstant ((uint) val);
1546 if ((other == TypeManager.sbyte_type) ||
1547 (other == TypeManager.short_type) ||
1548 (other == TypeManager.int32_type)){
1549 left = ForceConversion (ec, left, TypeManager.int64_type);
1550 right = ForceConversion (ec, right, TypeManager.int64_type);
1551 type = TypeManager.int64_type;
1554 // if either operand is of type uint, the other
1555 // operand is converd to type uint
1557 left = ForceConversion (ec, left, TypeManager.uint32_type);
1558 right = ForceConversion (ec, right, TypeManager.uint32_type);
1559 type = TypeManager.uint32_type;
1561 } else if (l == TypeManager.decimal_type || r == TypeManager.decimal_type){
1562 if (l != TypeManager.decimal_type)
1563 left = ConvertImplicit (ec, left, TypeManager.decimal_type, loc);
1564 if (r != TypeManager.decimal_type)
1565 right = ConvertImplicit (ec, right, TypeManager.decimal_type, loc);
1567 type = TypeManager.decimal_type;
1569 Expression l_tmp, r_tmp;
1571 l_tmp = ForceConversion (ec, left, TypeManager.int32_type);
1575 r_tmp = ForceConversion (ec, right, TypeManager.int32_type);
1582 type = TypeManager.int32_type;
1588 static public void Error_OperatorCannotBeApplied (Location loc, string name, Type l, Type r)
1591 "Operator " + name + " cannot be applied to operands of type `" +
1592 TypeManager.CSharpName (l) + "' and `" +
1593 TypeManager.CSharpName (r) + "'");
1598 Error_OperatorCannotBeApplied (loc, OperName (oper), left.Type, right.Type);
1601 static bool is_32_or_64 (Type t)
1603 return (t == TypeManager.int32_type || t == TypeManager.uint32_type ||
1604 t == TypeManager.int64_type || t == TypeManager.uint64_type);
1607 Expression CheckShiftArguments (EmitContext ec)
1611 Type r = right.Type;
1613 e = ForceConversion (ec, right, TypeManager.int32_type);
1620 if (((e = ConvertImplicit (ec, left, TypeManager.int32_type, loc)) != null) ||
1621 ((e = ConvertImplicit (ec, left, TypeManager.uint32_type, loc)) != null) ||
1622 ((e = ConvertImplicit (ec, left, TypeManager.int64_type, loc)) != null) ||
1623 ((e = ConvertImplicit (ec, left, TypeManager.uint64_type, loc)) != null)){
1633 Expression ResolveOperator (EmitContext ec)
1636 Type r = right.Type;
1639 // Step 1: Perform Operator Overload location
1641 Expression left_expr, right_expr;
1643 string op = "op_" + oper;
1645 MethodGroupExpr union;
1646 left_expr = MemberLookup (ec, l, op, MemberTypes.Method, AllBindingFlags, loc);
1648 right_expr = MemberLookup (
1649 ec, r, op, MemberTypes.Method, AllBindingFlags, loc);
1650 union = Invocation.MakeUnionSet (left_expr, right_expr);
1652 union = (MethodGroupExpr) left_expr;
1654 if (union != null) {
1655 Arguments = new ArrayList ();
1656 Arguments.Add (new Argument (left, Argument.AType.Expression));
1657 Arguments.Add (new Argument (right, Argument.AType.Expression));
1659 method = Invocation.OverloadResolve (ec, union, Arguments, loc);
1660 if (method != null) {
1661 MethodInfo mi = (MethodInfo) method;
1663 type = mi.ReturnType;
1672 // Step 2: Default operations on CLI native types.
1675 // Only perform numeric promotions on:
1676 // +, -, *, /, %, &, |, ^, ==, !=, <, >, <=, >=
1678 if (oper == Operator.Addition){
1680 // If any of the arguments is a string, cast to string
1682 if (l == TypeManager.string_type){
1684 if (r == TypeManager.void_type) {
1689 if (r == TypeManager.string_type){
1690 if (left is Constant && right is Constant){
1691 StringConstant ls = (StringConstant) left;
1692 StringConstant rs = (StringConstant) right;
1694 return new StringConstant (
1695 ls.Value + rs.Value);
1699 method = TypeManager.string_concat_string_string;
1702 method = TypeManager.string_concat_object_object;
1703 right = ConvertImplicit (ec, right,
1704 TypeManager.object_type, loc);
1706 type = TypeManager.string_type;
1708 Arguments = new ArrayList ();
1709 Arguments.Add (new Argument (left, Argument.AType.Expression));
1710 Arguments.Add (new Argument (right, Argument.AType.Expression));
1714 } else if (r == TypeManager.string_type){
1717 if (l == TypeManager.void_type) {
1722 method = TypeManager.string_concat_object_object;
1723 left = ConvertImplicit (ec, left, TypeManager.object_type, loc);
1724 Arguments = new ArrayList ();
1725 Arguments.Add (new Argument (left, Argument.AType.Expression));
1726 Arguments.Add (new Argument (right, Argument.AType.Expression));
1728 type = TypeManager.string_type;
1734 if (oper == Operator.Addition || oper == Operator.Subtraction) {
1735 if (l.IsSubclassOf (TypeManager.delegate_type) &&
1736 r.IsSubclassOf (TypeManager.delegate_type)) {
1738 Arguments = new ArrayList ();
1739 Arguments.Add (new Argument (left, Argument.AType.Expression));
1740 Arguments.Add (new Argument (right, Argument.AType.Expression));
1742 if (oper == Operator.Addition)
1743 method = TypeManager.delegate_combine_delegate_delegate;
1745 method = TypeManager.delegate_remove_delegate_delegate;
1747 DelegateOperation = true;
1753 // Pointer arithmetic:
1755 // T* operator + (T* x, int y);
1756 // T* operator + (T* x, uint y);
1757 // T* operator + (T* x, long y);
1758 // T* operator + (T* x, ulong y);
1760 // T* operator + (int y, T* x);
1761 // T* operator + (uint y, T *x);
1762 // T* operator + (long y, T *x);
1763 // T* operator + (ulong y, T *x);
1765 // T* operator - (T* x, int y);
1766 // T* operator - (T* x, uint y);
1767 // T* operator - (T* x, long y);
1768 // T* operator - (T* x, ulong y);
1770 // long operator - (T* x, T *y)
1773 if (r.IsPointer && oper == Operator.Subtraction){
1775 return new PointerArithmetic (
1776 false, left, right, TypeManager.int64_type);
1777 } else if (is_32_or_64 (r))
1778 return new PointerArithmetic (
1779 oper == Operator.Addition, left, right, l);
1780 } else if (r.IsPointer && is_32_or_64 (l) && oper == Operator.Addition)
1781 return new PointerArithmetic (
1782 true, right, left, r);
1786 // Enumeration operators
1788 bool lie = TypeManager.IsEnumType (l);
1789 bool rie = TypeManager.IsEnumType (r);
1794 temp = ConvertImplicit (ec, right, l, loc);
1798 temp = ConvertImplicit (ec, left, r, loc);
1805 if (oper == Operator.Equality || oper == Operator.Inequality ||
1806 oper == Operator.LessThanOrEqual || oper == Operator.LessThan ||
1807 oper == Operator.GreaterThanOrEqual || oper == Operator.GreaterThan){
1808 type = TypeManager.bool_type;
1812 if (oper == Operator.BitwiseAnd ||
1813 oper == Operator.BitwiseOr ||
1814 oper == Operator.ExclusiveOr){
1820 if (oper == Operator.LeftShift || oper == Operator.RightShift)
1821 return CheckShiftArguments (ec);
1823 if (oper == Operator.LogicalOr || oper == Operator.LogicalAnd){
1824 if (l != TypeManager.bool_type || r != TypeManager.bool_type){
1829 type = TypeManager.bool_type;
1833 if (oper == Operator.Equality || oper == Operator.Inequality){
1834 if (l == TypeManager.bool_type || r == TypeManager.bool_type){
1835 if (r != TypeManager.bool_type || l != TypeManager.bool_type){
1840 type = TypeManager.bool_type;
1845 // operator != (object a, object b)
1846 // operator == (object a, object b)
1848 // For this to be used, both arguments have to be reference-types.
1849 // Read the rationale on the spec (14.9.6)
1851 // Also, if at compile time we know that the classes do not inherit
1852 // one from the other, then we catch the error there.
1854 if (!(l.IsValueType || r.IsValueType)){
1855 type = TypeManager.bool_type;
1860 if (l.IsSubclassOf (r) || r.IsSubclassOf (l))
1864 // We are going to have to convert to an object to compare
1866 if (l != TypeManager.object_type)
1867 left = new EmptyCast (left, TypeManager.object_type);
1868 if (r != TypeManager.object_type)
1869 right = new EmptyCast (right, TypeManager.object_type);
1876 // Pointer comparison
1878 if (l.IsPointer && r.IsPointer){
1879 if (oper == Operator.Equality || oper == Operator.Inequality ||
1880 oper == Operator.LessThan || oper == Operator.LessThanOrEqual ||
1881 oper == Operator.GreaterThan || oper == Operator.GreaterThanOrEqual){
1882 type = TypeManager.bool_type;
1888 // We are dealing with numbers
1891 if (!DoNumericPromotions (ec, l, r)){
1896 if (left == null || right == null)
1900 // reload our cached types if required
1905 if (oper == Operator.BitwiseAnd ||
1906 oper == Operator.BitwiseOr ||
1907 oper == Operator.ExclusiveOr){
1909 if (!((l == TypeManager.int32_type) ||
1910 (l == TypeManager.uint32_type) ||
1911 (l == TypeManager.int64_type) ||
1912 (l == TypeManager.uint64_type)))
1920 if (oper == Operator.Equality ||
1921 oper == Operator.Inequality ||
1922 oper == Operator.LessThanOrEqual ||
1923 oper == Operator.LessThan ||
1924 oper == Operator.GreaterThanOrEqual ||
1925 oper == Operator.GreaterThan){
1926 type = TypeManager.bool_type;
1932 public override Expression DoResolve (EmitContext ec)
1934 left = left.Resolve (ec);
1935 right = right.Resolve (ec);
1937 if (left == null || right == null)
1940 if (left.Type == null)
1941 throw new Exception (
1942 "Resolve returned non null, but did not set the type! (" +
1943 left + ") at Line: " + loc.Row);
1944 if (right.Type == null)
1945 throw new Exception (
1946 "Resolve returned non null, but did not set the type! (" +
1947 right + ") at Line: "+ loc.Row);
1949 eclass = ExprClass.Value;
1951 if (left is Constant && right is Constant){
1952 Expression e = ConstantFold.BinaryFold (
1953 ec, oper, (Constant) left, (Constant) right, loc);
1958 return ResolveOperator (ec);
1961 public bool IsBranchable ()
1963 if (oper == Operator.Equality ||
1964 oper == Operator.Inequality ||
1965 oper == Operator.LessThan ||
1966 oper == Operator.GreaterThan ||
1967 oper == Operator.LessThanOrEqual ||
1968 oper == Operator.GreaterThanOrEqual){
1975 /// This entry point is used by routines that might want
1976 /// to emit a brfalse/brtrue after an expression, and instead
1977 /// they could use a more compact notation.
1979 /// Typically the code would generate l.emit/r.emit, followed
1980 /// by the comparission and then a brtrue/brfalse. The comparissions
1981 /// are sometimes inneficient (there are not as complete as the branches
1982 /// look for the hacks in Emit using double ceqs).
1984 /// So for those cases we provide EmitBranchable that can emit the
1985 /// branch with the test
1987 public void EmitBranchable (EmitContext ec, int target)
1990 bool close_target = false;
1991 ILGenerator ig = ec.ig;
1994 // short-circuit operators
1996 if (oper == Operator.LogicalAnd){
1998 ig.Emit (OpCodes.Brfalse, target);
2000 ig.Emit (OpCodes.Brfalse, target);
2001 } else if (oper == Operator.LogicalOr){
2003 ig.Emit (OpCodes.Brtrue, target);
2005 ig.Emit (OpCodes.Brfalse, target);
2012 case Operator.Equality:
2014 opcode = OpCodes.Beq_S;
2016 opcode = OpCodes.Beq;
2019 case Operator.Inequality:
2021 opcode = OpCodes.Bne_Un_S;
2023 opcode = OpCodes.Bne_Un;
2026 case Operator.LessThan:
2028 opcode = OpCodes.Blt_S;
2030 opcode = OpCodes.Blt;
2033 case Operator.GreaterThan:
2035 opcode = OpCodes.Bgt_S;
2037 opcode = OpCodes.Bgt;
2040 case Operator.LessThanOrEqual:
2042 opcode = OpCodes.Ble_S;
2044 opcode = OpCodes.Ble;
2047 case Operator.GreaterThanOrEqual:
2049 opcode = OpCodes.Bge_S;
2051 opcode = OpCodes.Ble;
2055 throw new Exception ("EmitBranchable called on non-EmitBranchable operator: "
2056 + oper.ToString ());
2059 ig.Emit (opcode, target);
2062 public override void Emit (EmitContext ec)
2064 ILGenerator ig = ec.ig;
2066 Type r = right.Type;
2069 if (method != null) {
2071 // Note that operators are static anyway
2073 if (Arguments != null)
2074 Invocation.EmitArguments (ec, method, Arguments);
2076 if (method is MethodInfo)
2077 ig.Emit (OpCodes.Call, (MethodInfo) method);
2079 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
2081 if (DelegateOperation)
2082 ig.Emit (OpCodes.Castclass, type);
2088 // Handle short-circuit operators differently
2091 if (oper == Operator.LogicalAnd){
2092 Label load_zero = ig.DefineLabel ();
2093 Label end = ig.DefineLabel ();
2096 ig.Emit (OpCodes.Brfalse, load_zero);
2098 ig.Emit (OpCodes.Br, end);
2099 ig.MarkLabel (load_zero);
2100 ig.Emit (OpCodes.Ldc_I4_0);
2103 } else if (oper == Operator.LogicalOr){
2104 Label load_one = ig.DefineLabel ();
2105 Label end = ig.DefineLabel ();
2108 ig.Emit (OpCodes.Brtrue, load_one);
2110 ig.Emit (OpCodes.Br, end);
2111 ig.MarkLabel (load_one);
2112 ig.Emit (OpCodes.Ldc_I4_1);
2121 case Operator.Multiply:
2123 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
2124 opcode = OpCodes.Mul_Ovf;
2125 else if (l==TypeManager.uint32_type || l==TypeManager.uint64_type)
2126 opcode = OpCodes.Mul_Ovf_Un;
2128 opcode = OpCodes.Mul;
2130 opcode = OpCodes.Mul;
2134 case Operator.Division:
2135 if (l == TypeManager.uint32_type || l == TypeManager.uint64_type)
2136 opcode = OpCodes.Div_Un;
2138 opcode = OpCodes.Div;
2141 case Operator.Modulus:
2142 if (l == TypeManager.uint32_type || l == TypeManager.uint64_type)
2143 opcode = OpCodes.Rem_Un;
2145 opcode = OpCodes.Rem;
2148 case Operator.Addition:
2150 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
2151 opcode = OpCodes.Add_Ovf;
2152 else if (l==TypeManager.uint32_type || l==TypeManager.uint64_type)
2153 opcode = OpCodes.Add_Ovf_Un;
2155 opcode = OpCodes.Add;
2157 opcode = OpCodes.Add;
2160 case Operator.Subtraction:
2162 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
2163 opcode = OpCodes.Sub_Ovf;
2164 else if (l==TypeManager.uint32_type || l==TypeManager.uint64_type)
2165 opcode = OpCodes.Sub_Ovf_Un;
2167 opcode = OpCodes.Sub;
2169 opcode = OpCodes.Sub;
2172 case Operator.RightShift:
2173 opcode = OpCodes.Shr;
2176 case Operator.LeftShift:
2177 opcode = OpCodes.Shl;
2180 case Operator.Equality:
2181 opcode = OpCodes.Ceq;
2184 case Operator.Inequality:
2185 ec.ig.Emit (OpCodes.Ceq);
2186 ec.ig.Emit (OpCodes.Ldc_I4_0);
2188 opcode = OpCodes.Ceq;
2191 case Operator.LessThan:
2192 opcode = OpCodes.Clt;
2195 case Operator.GreaterThan:
2196 opcode = OpCodes.Cgt;
2199 case Operator.LessThanOrEqual:
2200 ec.ig.Emit (OpCodes.Cgt);
2201 ec.ig.Emit (OpCodes.Ldc_I4_0);
2203 opcode = OpCodes.Ceq;
2206 case Operator.GreaterThanOrEqual:
2207 ec.ig.Emit (OpCodes.Clt);
2208 ec.ig.Emit (OpCodes.Ldc_I4_1);
2210 opcode = OpCodes.Sub;
2213 case Operator.BitwiseOr:
2214 opcode = OpCodes.Or;
2217 case Operator.BitwiseAnd:
2218 opcode = OpCodes.And;
2221 case Operator.ExclusiveOr:
2222 opcode = OpCodes.Xor;
2226 throw new Exception ("This should not happen: Operator = "
2227 + oper.ToString ());
2234 public class PointerArithmetic : Expression {
2235 Expression left, right;
2239 // We assume that `l' is always a pointer
2241 public PointerArithmetic (bool is_addition, Expression l, Expression r, Type t)
2244 eclass = ExprClass.Variable;
2247 is_add = is_addition;
2250 public override Expression DoResolve (EmitContext ec)
2253 // We are born fully resolved
2258 public override void Emit (EmitContext ec)
2260 Type op_type = left.Type;
2261 ILGenerator ig = ec.ig;
2262 int size = GetTypeSize (op_type.GetElementType ());
2264 if (right.Type.IsPointer){
2266 // handle (pointer - pointer)
2270 ig.Emit (OpCodes.Sub);
2274 ig.Emit (OpCodes.Sizeof, op_type);
2276 IntLiteral.EmitInt (ig, size);
2277 ig.Emit (OpCodes.Div);
2279 ig.Emit (OpCodes.Conv_I8);
2282 // handle + and - on (pointer op int)
2285 ig.Emit (OpCodes.Conv_I);
2289 ig.Emit (OpCodes.Sizeof, op_type);
2291 IntLiteral.EmitInt (ig, size);
2292 ig.Emit (OpCodes.Mul);
2295 ig.Emit (OpCodes.Add);
2297 ig.Emit (OpCodes.Sub);
2303 /// Implements the ternary conditiona operator (?:)
2305 public class Conditional : Expression {
2306 Expression expr, trueExpr, falseExpr;
2309 public Conditional (Expression expr, Expression trueExpr, Expression falseExpr, Location l)
2312 this.trueExpr = trueExpr;
2313 this.falseExpr = falseExpr;
2317 public Expression Expr {
2323 public Expression TrueExpr {
2329 public Expression FalseExpr {
2335 public override Expression DoResolve (EmitContext ec)
2337 expr = expr.Resolve (ec);
2339 if (expr.Type != TypeManager.bool_type)
2340 expr = Expression.ConvertImplicitRequired (
2341 ec, expr, TypeManager.bool_type, loc);
2343 trueExpr = trueExpr.Resolve (ec);
2344 falseExpr = falseExpr.Resolve (ec);
2346 if (expr == null || trueExpr == null || falseExpr == null)
2349 eclass = ExprClass.Value;
2350 if (trueExpr.Type == falseExpr.Type)
2351 type = trueExpr.Type;
2354 Type true_type = trueExpr.Type;
2355 Type false_type = falseExpr.Type;
2357 if (trueExpr is NullLiteral){
2360 } else if (falseExpr is NullLiteral){
2366 // First, if an implicit conversion exists from trueExpr
2367 // to falseExpr, then the result type is of type falseExpr.Type
2369 conv = ConvertImplicit (ec, trueExpr, false_type, loc);
2372 // Check if both can convert implicitl to each other's type
2374 if (ConvertImplicit (ec, falseExpr, true_type, loc) != null){
2377 "Can not compute type of conditional expression " +
2378 "as `" + TypeManager.CSharpName (trueExpr.Type) +
2379 "' and `" + TypeManager.CSharpName (falseExpr.Type) +
2380 "' convert implicitly to each other");
2385 } else if ((conv = ConvertImplicit(ec, falseExpr, true_type,loc))!= null){
2389 Error (173, loc, "The type of the conditional expression can " +
2390 "not be computed because there is no implicit conversion" +
2391 " from `" + TypeManager.CSharpName (trueExpr.Type) + "'" +
2392 " and `" + TypeManager.CSharpName (falseExpr.Type) + "'");
2397 if (expr is BoolConstant){
2398 BoolConstant bc = (BoolConstant) expr;
2409 public override void Emit (EmitContext ec)
2411 ILGenerator ig = ec.ig;
2412 Label false_target = ig.DefineLabel ();
2413 Label end_target = ig.DefineLabel ();
2416 ig.Emit (OpCodes.Brfalse, false_target);
2418 ig.Emit (OpCodes.Br, end_target);
2419 ig.MarkLabel (false_target);
2420 falseExpr.Emit (ec);
2421 ig.MarkLabel (end_target);
2429 public class LocalVariableReference : Expression, IAssignMethod, IMemoryLocation {
2430 public readonly string Name;
2431 public readonly Block Block;
2433 VariableInfo variable_info;
2435 public LocalVariableReference (Block block, string name, Location l)
2440 eclass = ExprClass.Variable;
2443 public VariableInfo VariableInfo {
2445 if (variable_info == null)
2446 variable_info = Block.GetVariableInfo (Name);
2447 return variable_info;
2451 public override Expression DoResolve (EmitContext ec)
2453 VariableInfo vi = VariableInfo;
2455 if (Block.IsConstant (Name)) {
2456 Expression e = Block.GetConstantExpression (Name);
2462 type = vi.VariableType;
2466 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
2468 Expression e = DoResolve (ec);
2473 VariableInfo vi = VariableInfo;
2479 "cannot assign to `" + Name + "' because it is readonly");
2487 public override void Emit (EmitContext ec)
2489 VariableInfo vi = VariableInfo;
2490 ILGenerator ig = ec.ig;
2492 ig.Emit (OpCodes.Ldloc, vi.LocalBuilder);
2496 public void EmitAssign (EmitContext ec, Expression source)
2498 ILGenerator ig = ec.ig;
2499 VariableInfo vi = VariableInfo;
2505 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
2508 public void AddressOf (EmitContext ec, AddressOp mode)
2510 VariableInfo vi = VariableInfo;
2512 if ((mode & AddressOp.Load) != 0)
2514 if ((mode & AddressOp.Store) != 0)
2517 ec.ig.Emit (OpCodes.Ldloca, vi.LocalBuilder);
2522 /// This represents a reference to a parameter in the intermediate
2525 public class ParameterReference : Expression, IAssignMethod, IMemoryLocation {
2531 public ParameterReference (Parameters pars, int idx, string name)
2536 eclass = ExprClass.Variable;
2540 // Notice that for ref/out parameters, the type exposed is not the
2541 // same type exposed externally.
2544 // externally we expose "int&"
2545 // here we expose "int".
2547 // We record this in "is_ref". This means that the type system can treat
2548 // the type as it is expected, but when we generate the code, we generate
2549 // the alternate kind of code.
2551 public override Expression DoResolve (EmitContext ec)
2553 type = pars.GetParameterInfo (ec.DeclSpace, idx, out is_ref);
2554 eclass = ExprClass.Variable;
2560 // This method is used by parameters that are references, that are
2561 // being passed as references: we only want to pass the pointer (that
2562 // is already stored in the parameter, not the address of the pointer,
2563 // and not the value of the variable).
2565 public void EmitLoad (EmitContext ec)
2567 ILGenerator ig = ec.ig;
2574 ig.Emit (OpCodes.Ldarg_S, (byte) arg_idx);
2576 ig.Emit (OpCodes.Ldarg, arg_idx);
2579 public override void Emit (EmitContext ec)
2581 ILGenerator ig = ec.ig;
2588 ig.Emit (OpCodes.Ldarg_S, (byte) arg_idx);
2590 ig.Emit (OpCodes.Ldarg, arg_idx);
2596 // If we are a reference, we loaded on the stack a pointer
2597 // Now lets load the real value
2599 LoadFromPtr (ig, type, true);
2602 public void EmitAssign (EmitContext ec, Expression source)
2604 ILGenerator ig = ec.ig;
2613 ig.Emit (OpCodes.Ldarg_S, (byte) arg_idx);
2615 ig.Emit (OpCodes.Ldarg, arg_idx);
2621 StoreFromPtr (ig, type);
2624 ig.Emit (OpCodes.Starg_S, (byte) arg_idx);
2626 ig.Emit (OpCodes.Starg, arg_idx);
2631 public void AddressOf (EmitContext ec, AddressOp mode)
2639 ec.ig.Emit (OpCodes.Ldarga_S, (byte) arg_idx);
2641 ec.ig.Emit (OpCodes.Ldarga, arg_idx);
2646 /// Used for arguments to New(), Invocation()
2648 public class Argument {
2649 public enum AType : byte {
2655 public readonly AType ArgType;
2656 public Expression expr;
2658 public Argument (Expression expr, AType type)
2661 this.ArgType = type;
2664 public Expression Expr {
2680 public Parameter.Modifier GetParameterModifier ()
2682 if (ArgType == AType.Ref || ArgType == AType.Out)
2683 return Parameter.Modifier.OUT;
2685 return Parameter.Modifier.NONE;
2688 public static string FullDesc (Argument a)
2690 return (a.ArgType == AType.Ref ? "ref " :
2691 (a.ArgType == AType.Out ? "out " : "")) +
2692 TypeManager.CSharpName (a.Expr.Type);
2695 public bool Resolve (EmitContext ec, Location loc)
2697 expr = expr.Resolve (ec);
2699 if (ArgType == AType.Expression)
2700 return expr != null;
2702 if (expr.eclass != ExprClass.Variable){
2704 // We just probe to match the CSC output
2706 if (expr.eclass == ExprClass.PropertyAccess ||
2707 expr.eclass == ExprClass.IndexerAccess){
2710 "A property or indexer can not be passed as an out or ref " +
2715 "An lvalue is required as an argument to out or ref");
2720 return expr != null;
2723 public void Emit (EmitContext ec)
2726 // Ref and Out parameters need to have their addresses taken.
2728 // ParameterReferences might already be references, so we want
2729 // to pass just the value
2731 if (ArgType == AType.Ref || ArgType == AType.Out){
2732 AddressOp mode = AddressOp.Store;
2734 if (ArgType == AType.Ref)
2735 mode |= AddressOp.Load;
2737 if (expr is ParameterReference){
2738 ParameterReference pr = (ParameterReference) expr;
2744 pr.AddressOf (ec, mode);
2747 ((IMemoryLocation)expr).AddressOf (ec, mode);
2754 /// Invocation of methods or delegates.
2756 public class Invocation : ExpressionStatement {
2757 public readonly ArrayList Arguments;
2761 MethodBase method = null;
2764 static Hashtable method_parameter_cache;
2766 static Invocation ()
2768 method_parameter_cache = new PtrHashtable ();
2772 // arguments is an ArrayList, but we do not want to typecast,
2773 // as it might be null.
2775 // FIXME: only allow expr to be a method invocation or a
2776 // delegate invocation (7.5.5)
2778 public Invocation (Expression expr, ArrayList arguments, Location l)
2781 Arguments = arguments;
2785 public Expression Expr {
2792 /// Returns the Parameters (a ParameterData interface) for the
2795 public static ParameterData GetParameterData (MethodBase mb)
2797 object pd = method_parameter_cache [mb];
2801 return (ParameterData) pd;
2804 ip = TypeManager.LookupParametersByBuilder (mb);
2806 method_parameter_cache [mb] = ip;
2808 return (ParameterData) ip;
2810 ParameterInfo [] pi = mb.GetParameters ();
2811 ReflectionParameters rp = new ReflectionParameters (pi);
2812 method_parameter_cache [mb] = rp;
2814 return (ParameterData) rp;
2819 /// Determines "better conversion" as specified in 7.4.2.3
2820 /// Returns : 1 if a->p is better
2821 /// 0 if a->q or neither is better
2823 static int BetterConversion (EmitContext ec, Argument a, Type p, Type q, Location loc)
2825 Type argument_type = a.Type;
2826 Expression argument_expr = a.Expr;
2828 if (argument_type == null)
2829 throw new Exception ("Expression of type " + a.Expr + " does not resolve its type");
2834 if (argument_type == p)
2837 if (argument_type == q)
2841 // Now probe whether an implicit constant expression conversion
2844 // An implicit constant expression conversion permits the following
2847 // * A constant-expression of type `int' can be converted to type
2848 // sbyte, byute, short, ushort, uint, ulong provided the value of
2849 // of the expression is withing the range of the destination type.
2851 // * A constant-expression of type long can be converted to type
2852 // ulong, provided the value of the constant expression is not negative
2854 // FIXME: Note that this assumes that constant folding has
2855 // taken place. We dont do constant folding yet.
2858 if (argument_expr is IntConstant){
2859 IntConstant ei = (IntConstant) argument_expr;
2860 int value = ei.Value;
2862 if (p == TypeManager.sbyte_type){
2863 if (value >= SByte.MinValue && value <= SByte.MaxValue)
2865 } else if (p == TypeManager.byte_type){
2866 if (Byte.MinValue >= 0 && value <= Byte.MaxValue)
2868 } else if (p == TypeManager.short_type){
2869 if (value >= Int16.MinValue && value <= Int16.MaxValue)
2871 } else if (p == TypeManager.ushort_type){
2872 if (value >= UInt16.MinValue && value <= UInt16.MaxValue)
2874 } else if (p == TypeManager.uint32_type){
2876 // we can optimize this case: a positive int32
2877 // always fits on a uint32
2881 } else if (p == TypeManager.uint64_type){
2883 // we can optimize this case: a positive int32
2884 // always fits on a uint64
2889 } else if (argument_type == TypeManager.int64_type && argument_expr is LongConstant){
2890 LongConstant lc = (LongConstant) argument_expr;
2892 if (p == TypeManager.uint64_type){
2899 Expression tmp = ConvertImplicitStandard (ec, argument_expr, p, loc);
2907 Expression p_tmp = new EmptyExpression (p);
2908 Expression q_tmp = new EmptyExpression (q);
2910 if (StandardConversionExists (p_tmp, q) == true &&
2911 StandardConversionExists (q_tmp, p) == false)
2914 if (p == TypeManager.sbyte_type)
2915 if (q == TypeManager.byte_type || q == TypeManager.ushort_type ||
2916 q == TypeManager.uint32_type || q == TypeManager.uint64_type)
2919 if (p == TypeManager.short_type)
2920 if (q == TypeManager.ushort_type || q == TypeManager.uint32_type ||
2921 q == TypeManager.uint64_type)
2924 if (p == TypeManager.int32_type)
2925 if (q == TypeManager.uint32_type || q == TypeManager.uint64_type)
2928 if (p == TypeManager.int64_type)
2929 if (q == TypeManager.uint64_type)
2936 /// Determines "Better function"
2939 /// and returns an integer indicating :
2940 /// 0 if candidate ain't better
2941 /// 1 if candidate is better than the current best match
2943 static int BetterFunction (EmitContext ec, ArrayList args,
2944 MethodBase candidate, MethodBase best,
2945 bool expanded_form, Location loc)
2947 ParameterData candidate_pd = GetParameterData (candidate);
2948 ParameterData best_pd;
2955 argument_count = args.Count;
2957 int cand_count = candidate_pd.Count;
2959 if (cand_count == 0 && argument_count == 0)
2962 if (candidate_pd.ParameterModifier (cand_count - 1) != Parameter.Modifier.PARAMS)
2963 if (cand_count != argument_count)
2969 if (argument_count == 0 && cand_count == 1 &&
2970 candidate_pd.ParameterModifier (cand_count - 1) == Parameter.Modifier.PARAMS)
2973 for (int j = argument_count; j > 0;) {
2976 Argument a = (Argument) args [j];
2977 Type t = candidate_pd.ParameterType (j);
2979 if (candidate_pd.ParameterModifier (j) == Parameter.Modifier.PARAMS)
2981 t = t.GetElementType ();
2983 x = BetterConversion (ec, a, t, null, loc);
2995 best_pd = GetParameterData (best);
2997 int rating1 = 0, rating2 = 0;
2999 for (int j = 0; j < argument_count; ++j) {
3002 Argument a = (Argument) args [j];
3004 Type ct = candidate_pd.ParameterType (j);
3005 Type bt = best_pd.ParameterType (j);
3007 if (candidate_pd.ParameterModifier (j) == Parameter.Modifier.PARAMS)
3009 ct = ct.GetElementType ();
3011 if (best_pd.ParameterModifier (j) == Parameter.Modifier.PARAMS)
3013 bt = bt.GetElementType ();
3015 x = BetterConversion (ec, a, ct, bt, loc);
3016 y = BetterConversion (ec, a, bt, ct, loc);
3025 if (rating1 > rating2)
3031 public static string FullMethodDesc (MethodBase mb)
3033 string ret_type = "";
3035 if (mb is MethodInfo)
3036 ret_type = TypeManager.CSharpName (((MethodInfo) mb).ReturnType);
3038 StringBuilder sb = new StringBuilder (ret_type + " " + mb.Name);
3039 ParameterData pd = GetParameterData (mb);
3041 int count = pd.Count;
3044 for (int i = count; i > 0; ) {
3047 sb.Append (pd.ParameterDesc (count - i - 1));
3053 return sb.ToString ();
3056 public static MethodGroupExpr MakeUnionSet (Expression mg1, Expression mg2)
3058 MemberInfo [] miset;
3059 MethodGroupExpr union;
3061 if (mg1 != null && mg2 != null) {
3063 MethodGroupExpr left_set = null, right_set = null;
3064 int length1 = 0, length2 = 0;
3066 left_set = (MethodGroupExpr) mg1;
3067 length1 = left_set.Methods.Length;
3069 right_set = (MethodGroupExpr) mg2;
3070 length2 = right_set.Methods.Length;
3072 ArrayList common = new ArrayList ();
3074 for (int i = 0; i < left_set.Methods.Length; i++) {
3075 for (int j = 0; j < right_set.Methods.Length; j++) {
3076 if (left_set.Methods [i] == right_set.Methods [j])
3077 common.Add (left_set.Methods [i]);
3081 miset = new MemberInfo [length1 + length2 - common.Count];
3083 left_set.Methods.CopyTo (miset, 0);
3087 for (int j = 0; j < right_set.Methods.Length; j++)
3088 if (!common.Contains (right_set.Methods [j]))
3089 miset [length1 + k++] = right_set.Methods [j];
3091 union = new MethodGroupExpr (miset);
3095 } else if (mg1 == null && mg2 != null) {
3097 MethodGroupExpr me = (MethodGroupExpr) mg2;
3099 miset = new MemberInfo [me.Methods.Length];
3100 me.Methods.CopyTo (miset, 0);
3102 union = new MethodGroupExpr (miset);
3106 } else if (mg2 == null && mg1 != null) {
3108 MethodGroupExpr me = (MethodGroupExpr) mg1;
3110 miset = new MemberInfo [me.Methods.Length];
3111 me.Methods.CopyTo (miset, 0);
3113 union = new MethodGroupExpr (miset);
3122 /// Determines is the candidate method, if a params method, is applicable
3123 /// in its expanded form to the given set of arguments
3125 static bool IsParamsMethodApplicable (ArrayList arguments, MethodBase candidate)
3129 if (arguments == null)
3132 arg_count = arguments.Count;
3134 ParameterData pd = GetParameterData (candidate);
3136 int pd_count = pd.Count;
3141 if (pd.ParameterModifier (pd_count - 1) != Parameter.Modifier.PARAMS)
3144 if (pd_count - 1 > arg_count)
3147 if (pd_count == 1 && arg_count == 0)
3151 // If we have come this far, the case which remains is when the number of parameters
3152 // is less than or equal to the argument count.
3154 for (int i = 0; i < pd_count - 1; ++i) {
3156 Argument a = (Argument) arguments [i];
3158 Parameter.Modifier a_mod = a.GetParameterModifier ();
3159 Parameter.Modifier p_mod = pd.ParameterModifier (i);
3161 if (a_mod == p_mod) {
3163 if (a_mod == Parameter.Modifier.NONE)
3164 if (!StandardConversionExists (a.Expr, pd.ParameterType (i)))
3167 if (a_mod == Parameter.Modifier.REF ||
3168 a_mod == Parameter.Modifier.OUT)
3169 if (pd.ParameterType (i) != a.Type)
3176 Type element_type = pd.ParameterType (pd_count - 1).GetElementType ();
3178 for (int i = pd_count - 1; i < arg_count; i++) {
3179 Argument a = (Argument) arguments [i];
3181 if (!StandardConversionExists (a.Expr, element_type))
3189 /// Determines if the candidate method is applicable (section 14.4.2.1)
3190 /// to the given set of arguments
3192 static bool IsApplicable (ArrayList arguments, MethodBase candidate)
3196 if (arguments == null)
3199 arg_count = arguments.Count;
3201 ParameterData pd = GetParameterData (candidate);
3203 int pd_count = pd.Count;
3205 if (arg_count != pd.Count)
3208 for (int i = arg_count; i > 0; ) {
3211 Argument a = (Argument) arguments [i];
3213 Parameter.Modifier a_mod = a.GetParameterModifier ();
3214 Parameter.Modifier p_mod = pd.ParameterModifier (i);
3216 if (a_mod == p_mod) {
3218 if (a_mod == Parameter.Modifier.NONE)
3219 if (!StandardConversionExists (a.Expr, pd.ParameterType (i)))
3222 if (a_mod == Parameter.Modifier.REF ||
3223 a_mod == Parameter.Modifier.OUT)
3224 if (pd.ParameterType (i) != a.Type)
3236 /// Find the Applicable Function Members (7.4.2.1)
3238 /// me: Method Group expression with the members to select.
3239 /// it might contain constructors or methods (or anything
3240 /// that maps to a method).
3242 /// Arguments: ArrayList containing resolved Argument objects.
3244 /// loc: The location if we want an error to be reported, or a Null
3245 /// location for "probing" purposes.
3247 /// Returns: The MethodBase (either a ConstructorInfo or a MethodInfo)
3248 /// that is the best match of me on Arguments.
3251 public static MethodBase OverloadResolve (EmitContext ec, MethodGroupExpr me,
3252 ArrayList Arguments, Location loc)
3254 ArrayList afm = new ArrayList ();
3255 int best_match_idx = -1;
3256 MethodBase method = null;
3258 ArrayList candidates = new ArrayList ();
3260 for (int i = me.Methods.Length; i > 0; ){
3262 MethodBase candidate = me.Methods [i];
3265 // Check if candidate is applicable (section 14.4.2.1)
3266 if (!IsApplicable (Arguments, candidate))
3269 candidates.Add (candidate);
3271 x = BetterFunction (ec, Arguments, candidate, method, false, loc);
3277 method = me.Methods [best_match_idx];
3281 if (Arguments == null)
3284 argument_count = Arguments.Count;
3287 // Now we see if we can find params functions, applicable in their expanded form
3288 // since if they were applicable in their normal form, they would have been selected
3291 bool chose_params_expanded = false;
3293 if (best_match_idx == -1) {
3295 candidates = new ArrayList ();
3296 for (int i = me.Methods.Length; i > 0; ) {
3298 MethodBase candidate = me.Methods [i];
3300 if (!IsParamsMethodApplicable (Arguments, candidate))
3303 candidates.Add (candidate);
3305 int x = BetterFunction (ec, Arguments, candidate, method, true, loc);
3311 method = me.Methods [best_match_idx];
3312 chose_params_expanded = true;
3318 // Now we see if we can at least find a method with the same number of arguments
3321 int method_count = 0;
3323 if (best_match_idx == -1) {
3325 for (int i = me.Methods.Length; i > 0;) {
3327 MethodBase mb = me.Methods [i];
3328 pd = GetParameterData (mb);
3330 if (pd.Count == argument_count) {
3332 method = me.Methods [best_match_idx];
3343 // Now check that there are no ambiguities i.e the selected method
3344 // should be better than all the others
3347 for (int i = 0; i < candidates.Count; ++i) {
3348 MethodBase candidate = (MethodBase) candidates [i];
3350 if (candidate == method)
3354 // If a normal method is applicable in the sense that it has the same
3355 // number of arguments, then the expanded params method is never applicable
3356 // so we debar the params method.
3358 if (IsParamsMethodApplicable (Arguments, candidate) &&
3359 IsApplicable (Arguments, method))
3362 int x = BetterFunction (ec, Arguments, method, candidate,
3363 chose_params_expanded, loc);
3366 //Console.WriteLine ("Candidate : " + FullMethodDesc (candidate));
3367 //Console.WriteLine ("Best : " + FullMethodDesc (method));
3370 "Ambiguous call when selecting function due to implicit casts");
3375 // And now convert implicitly, each argument to the required type
3377 pd = GetParameterData (method);
3378 int pd_count = pd.Count;
3380 for (int j = 0; j < argument_count; j++) {
3381 Argument a = (Argument) Arguments [j];
3382 Expression a_expr = a.Expr;
3383 Type parameter_type = pd.ParameterType (j);
3385 if (pd.ParameterModifier (j) == Parameter.Modifier.PARAMS && chose_params_expanded)
3386 parameter_type = parameter_type.GetElementType ();
3388 if (a.Type != parameter_type){
3391 conv = ConvertImplicitStandard (ec, a_expr, parameter_type, loc);
3394 if (!Location.IsNull (loc)) {
3396 "The best overloaded match for method '" +
3397 FullMethodDesc (method) +
3398 "' has some invalid arguments");
3400 "Argument " + (j+1) +
3401 ": Cannot convert from '" + Argument.FullDesc (a)
3402 + "' to '" + pd.ParameterDesc (j) + "'");
3408 // Update the argument with the implicit conversion
3413 // FIXME : For the case of params methods, we need to actually instantiate
3414 // an array and initialize it with the argument values etc etc.
3418 if (a.GetParameterModifier () != pd.ParameterModifier (j) &&
3419 pd.ParameterModifier (pd_count - 1) != Parameter.Modifier.PARAMS) {
3420 if (!Location.IsNull (loc)) {
3421 Console.WriteLine ("A:P: " + a.GetParameterModifier ());
3422 Console.WriteLine ("PP:: " + pd.ParameterModifier (j));
3423 Console.WriteLine ("PT: " + parameter_type.IsByRef);
3425 "The best overloaded match for method '" + FullMethodDesc (method)+
3426 "' has some invalid arguments");
3428 "Argument " + (j+1) +
3429 ": Cannot convert from '" + Argument.FullDesc (a)
3430 + "' to '" + pd.ParameterDesc (j) + "'");
3439 public override Expression DoResolve (EmitContext ec)
3442 // First, resolve the expression that is used to
3443 // trigger the invocation
3445 if (expr is BaseAccess)
3448 expr = expr.Resolve (ec);
3452 if (!(expr is MethodGroupExpr)) {
3453 Type expr_type = expr.Type;
3455 if (expr_type != null){
3456 bool IsDelegate = TypeManager.IsDelegateType (expr_type);
3458 return (new DelegateInvocation (
3459 this.expr, Arguments, loc)).Resolve (ec);
3463 if (!(expr is MethodGroupExpr)){
3464 report118 (loc, this.expr, "method group");
3469 // Next, evaluate all the expressions in the argument list
3471 if (Arguments != null){
3472 for (int i = Arguments.Count; i > 0;){
3474 Argument a = (Argument) Arguments [i];
3476 if (!a.Resolve (ec, loc))
3481 method = OverloadResolve (ec, (MethodGroupExpr) this.expr, Arguments, loc);
3483 if (method == null){
3485 "Could not find any applicable function for this argument list");
3489 if (method is MethodInfo)
3490 type = ((MethodInfo)method).ReturnType;
3492 if (type.IsPointer){
3499 eclass = ExprClass.Value;
3504 // Emits the list of arguments as an array
3506 static void EmitParams (EmitContext ec, int idx, ArrayList arguments)
3508 ILGenerator ig = ec.ig;
3509 int count = arguments.Count - idx;
3510 Argument a = (Argument) arguments [idx];
3511 Type t = a.expr.Type;
3512 string array_type = t.FullName + "[]";
3515 array = ig.DeclareLocal (Type.GetType (array_type));
3516 IntConstant.EmitInt (ig, count);
3517 ig.Emit (OpCodes.Newarr, t);
3518 ig.Emit (OpCodes.Stloc, array);
3520 int top = arguments.Count;
3521 for (int j = idx; j < top; j++){
3522 a = (Argument) arguments [j];
3524 ig.Emit (OpCodes.Ldloc, array);
3525 IntConstant.EmitInt (ig, j - idx);
3528 ArrayAccess.EmitStoreOpcode (ig, t);
3530 ig.Emit (OpCodes.Ldloc, array);
3534 /// Emits a list of resolved Arguments that are in the arguments
3537 /// The MethodBase argument might be null if the
3538 /// emission of the arguments is known not to contain
3539 /// a `params' field (for example in constructors or other routines
3540 /// that keep their arguments in this structure
3542 public static void EmitArguments (EmitContext ec, MethodBase mb, ArrayList arguments)
3544 ParameterData pd = null;
3547 if (arguments != null)
3548 top = arguments.Count;
3553 pd = GetParameterData (mb);
3555 for (int i = 0; i < top; i++){
3556 Argument a = (Argument) arguments [i];
3559 if (pd.ParameterModifier (i) == Parameter.Modifier.PARAMS){
3560 EmitParams (ec, i, arguments);
3570 /// is_base tells whether we want to force the use of the `call'
3571 /// opcode instead of using callvirt. Call is required to call
3572 /// a specific method, while callvirt will always use the most
3573 /// recent method in the vtable.
3575 /// is_static tells whether this is an invocation on a static method
3577 /// instance_expr is an expression that represents the instance
3578 /// it must be non-null if is_static is false.
3580 /// method is the method to invoke.
3582 /// Arguments is the list of arguments to pass to the method or constructor.
3584 public static void EmitCall (EmitContext ec, bool is_base,
3585 bool is_static, Expression instance_expr,
3586 MethodBase method, ArrayList Arguments)
3588 ILGenerator ig = ec.ig;
3589 bool struct_call = false;
3593 if (method.DeclaringType.IsValueType)
3596 // If this is ourselves, push "this"
3598 if (instance_expr == null){
3599 ig.Emit (OpCodes.Ldarg_0);
3602 // Push the instance expression
3604 if (instance_expr.Type.IsSubclassOf (TypeManager.value_type)){
3606 // Special case: calls to a function declared in a
3607 // reference-type with a value-type argument need
3608 // to have their value boxed.
3611 if (method.DeclaringType.IsValueType){
3613 // If the expression implements IMemoryLocation, then
3614 // we can optimize and use AddressOf on the
3617 // If not we have to use some temporary storage for
3619 if (instance_expr is IMemoryLocation){
3620 ((IMemoryLocation)instance_expr).
3621 AddressOf (ec, AddressOp.LoadStore);
3624 Type t = instance_expr.Type;
3626 instance_expr.Emit (ec);
3627 LocalBuilder temp = ig.DeclareLocal (t);
3628 ig.Emit (OpCodes.Stloc, temp);
3629 ig.Emit (OpCodes.Ldloca, temp);
3632 instance_expr.Emit (ec);
3633 ig.Emit (OpCodes.Box, instance_expr.Type);
3636 instance_expr.Emit (ec);
3640 if (Arguments != null)
3641 EmitArguments (ec, method, Arguments);
3643 if (is_static || struct_call || is_base){
3644 if (method is MethodInfo)
3645 ig.Emit (OpCodes.Call, (MethodInfo) method);
3647 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
3649 if (method is MethodInfo)
3650 ig.Emit (OpCodes.Callvirt, (MethodInfo) method);
3652 ig.Emit (OpCodes.Callvirt, (ConstructorInfo) method);
3656 public override void Emit (EmitContext ec)
3658 MethodGroupExpr mg = (MethodGroupExpr) this.expr;
3660 EmitCall (ec, is_base, method.IsStatic, mg.InstanceExpression, method, Arguments);
3663 public override void EmitStatement (EmitContext ec)
3668 // Pop the return value if there is one
3670 if (method is MethodInfo){
3671 if (((MethodInfo)method).ReturnType != TypeManager.void_type)
3672 ec.ig.Emit (OpCodes.Pop);
3678 /// Implements the new expression
3680 public class New : ExpressionStatement {
3681 public readonly ArrayList Arguments;
3682 public readonly string RequestedType;
3685 MethodBase method = null;
3688 // If set, the new expression is for a value_target, and
3689 // we will not leave anything on the stack.
3691 Expression value_target;
3693 public New (string requested_type, ArrayList arguments, Location l)
3695 RequestedType = requested_type;
3696 Arguments = arguments;
3700 public Expression ValueTypeVariable {
3702 return value_target;
3706 value_target = value;
3710 public override Expression DoResolve (EmitContext ec)
3712 type = RootContext.LookupType (ec.DeclSpace, RequestedType, false, loc);
3717 bool IsDelegate = TypeManager.IsDelegateType (type);
3720 return (new NewDelegate (type, Arguments, loc)).Resolve (ec);
3722 bool is_struct = false;
3723 is_struct = type.IsSubclassOf (TypeManager.value_type);
3724 eclass = ExprClass.Value;
3727 // SRE returns a match for .ctor () on structs (the object constructor),
3728 // so we have to manually ignore it.
3730 if (is_struct && Arguments == null)
3734 ml = MemberLookup (ec, type, ".ctor", MemberTypes.Constructor, AllBindingFlags, loc);
3736 if (! (ml is MethodGroupExpr)){
3738 report118 (loc, ml, "method group");
3744 if (Arguments != null){
3745 for (int i = Arguments.Count; i > 0;){
3747 Argument a = (Argument) Arguments [i];
3749 if (!a.Resolve (ec, loc))
3754 method = Invocation.OverloadResolve (ec, (MethodGroupExpr) ml,
3759 if (method == null && !is_struct) {
3761 "New invocation: Can not find a constructor for " +
3762 "this argument list");
3769 // This DoEmit can be invoked in two contexts:
3770 // * As a mechanism that will leave a value on the stack (new object)
3771 // * As one that wont (init struct)
3773 // You can control whether a value is required on the stack by passing
3774 // need_value_on_stack. The code *might* leave a value on the stack
3775 // so it must be popped manually
3777 // If we are dealing with a ValueType, we have a few
3778 // situations to deal with:
3780 // * The target is a ValueType, and we have been provided
3781 // the instance (this is easy, we are being assigned).
3783 // * The target of New is being passed as an argument,
3784 // to a boxing operation or a function that takes a
3787 // In this case, we need to create a temporary variable
3788 // that is the argument of New.
3790 // Returns whether a value is left on the stack
3792 bool DoEmit (EmitContext ec, bool need_value_on_stack)
3794 bool is_value_type = type.IsSubclassOf (TypeManager.value_type);
3795 ILGenerator ig = ec.ig;
3800 if (value_target == null)
3801 value_target = new LocalTemporary (ec, type);
3803 ml = (IMemoryLocation) value_target;
3804 ml.AddressOf (ec, AddressOp.Store);
3808 Invocation.EmitArguments (ec, method, Arguments);
3812 ig.Emit (OpCodes.Initobj, type);
3814 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
3816 if (need_value_on_stack){
3817 value_target.Emit (ec);
3822 ig.Emit (OpCodes.Newobj, (ConstructorInfo) method);
3827 public override void Emit (EmitContext ec)
3832 public override void EmitStatement (EmitContext ec)
3834 if (DoEmit (ec, false))
3835 ec.ig.Emit (OpCodes.Pop);
3840 /// Represents an array creation expression.
3844 /// There are two possible scenarios here: one is an array creation
3845 /// expression that specifies the dimensions and optionally the
3846 /// initialization data and the other which does not need dimensions
3847 /// specified but where initialization data is mandatory.
3849 public class ArrayCreation : ExpressionStatement {
3850 string RequestedType;
3852 ArrayList Initializers;
3856 // The list of Argument types.
3857 // This is used to constrcut the `newarray' or constructor signature
3859 ArrayList Arguments;
3861 MethodBase method = null;
3862 Type array_element_type;
3863 bool IsOneDimensional = false;
3864 bool IsBuiltinType = false;
3865 bool ExpectInitializers = false;
3868 Type underlying_type;
3870 ArrayList ArrayData;
3875 // The number of array initializers that we can handle
3876 // via the InitializeArray method - through EmitStaticInitializers
3878 int num_automatic_initializers;
3880 public ArrayCreation (string requested_type, ArrayList exprs,
3881 string rank, ArrayList initializers, Location l)
3883 RequestedType = requested_type;
3885 Initializers = initializers;
3888 Arguments = new ArrayList ();
3890 foreach (Expression e in exprs)
3891 Arguments.Add (new Argument (e, Argument.AType.Expression));
3894 public ArrayCreation (string requested_type, string rank, ArrayList initializers, Location l)
3896 RequestedType = requested_type;
3897 Initializers = initializers;
3900 Rank = rank.Substring (0, rank.LastIndexOf ("["));
3902 string tmp = rank.Substring (rank.LastIndexOf ("["));
3904 dimensions = tmp.Length - 1;
3905 ExpectInitializers = true;
3908 public static string FormArrayType (string base_type, int idx_count, string rank)
3910 StringBuilder sb = new StringBuilder (base_type);
3915 for (int i = 1; i < idx_count; i++)
3920 return sb.ToString ();
3923 public static string FormElementType (string base_type, int idx_count, string rank)
3925 StringBuilder sb = new StringBuilder (base_type);
3928 for (int i = 1; i < idx_count; i++)
3935 string val = sb.ToString ();
3937 return val.Substring (0, val.LastIndexOf ("["));
3942 Report.Error (178, loc, "Incorrectly structured array initializer");
3945 public bool CheckIndices (EmitContext ec, ArrayList probe, int idx, bool specified_dims)
3947 if (specified_dims) {
3948 Argument a = (Argument) Arguments [idx];
3950 if (!a.Resolve (ec, loc))
3953 if (!(a.Expr is Constant)) {
3954 Report.Error (150, loc, "A constant value is expected");
3958 int value = (int) ((Constant) a.Expr).GetValue ();
3960 if (value != probe.Count) {
3965 Bounds [idx] = value;
3968 foreach (object o in probe) {
3969 if (o is ArrayList) {
3970 bool ret = CheckIndices (ec, (ArrayList) o, idx + 1, specified_dims);
3974 Expression tmp = (Expression) o;
3975 tmp = tmp.Resolve (ec);
3979 // Handle initialization from vars, fields etc.
3981 Expression conv = ConvertImplicitRequired (
3982 ec, tmp, underlying_type, loc);
3987 if (conv is StringConstant)
3988 ArrayData.Add (conv);
3989 else if (conv is Constant) {
3990 ArrayData.Add (conv);
3991 num_automatic_initializers++;
3993 ArrayData.Add (conv);
4000 public void UpdateIndices (EmitContext ec)
4003 for (ArrayList probe = Initializers; probe != null;) {
4004 if (probe.Count > 0 && probe [0] is ArrayList) {
4005 Expression e = new IntConstant (probe.Count);
4006 Arguments.Add (new Argument (e, Argument.AType.Expression));
4008 Bounds [i++] = probe.Count;
4010 probe = (ArrayList) probe [0];
4013 Expression e = new IntConstant (probe.Count);
4014 Arguments.Add (new Argument (e, Argument.AType.Expression));
4016 Bounds [i++] = probe.Count;
4023 public bool ValidateInitializers (EmitContext ec)
4025 if (Initializers == null) {
4026 if (ExpectInitializers)
4032 underlying_type = RootContext.LookupType (
4033 ec.DeclSpace, RequestedType, false, loc);
4036 // We use this to store all the date values in the order in which we
4037 // will need to store them in the byte blob later
4039 ArrayData = new ArrayList ();
4040 Bounds = new Hashtable ();
4044 if (Arguments != null) {
4045 ret = CheckIndices (ec, Initializers, 0, true);
4049 Arguments = new ArrayList ();
4051 ret = CheckIndices (ec, Initializers, 0, false);
4058 if (Arguments.Count != dimensions) {
4067 public override Expression DoResolve (EmitContext ec)
4072 // First step is to validate the initializers and fill
4073 // in any missing bits
4075 if (!ValidateInitializers (ec))
4078 if (Arguments == null)
4081 arg_count = Arguments.Count;
4082 for (int i = 0; i < arg_count; i++){
4083 Argument a = (Argument) Arguments [i];
4085 if (!a.Resolve (ec, loc))
4089 // Now, convert that to an integer
4091 Expression real_arg;
4092 bool old_checked = ec.CheckState;
4093 ec.CheckState = true;
4095 real_arg = ConvertExplicit (
4096 ec, a.expr, TypeManager.uint32_type, loc);
4097 ec.CheckState = old_checked;
4098 if (real_arg == null)
4105 string array_type = FormArrayType (RequestedType, arg_count, Rank);
4106 string element_type = FormElementType (RequestedType, arg_count, Rank);
4108 type = RootContext.LookupType (ec.DeclSpace, array_type, false, loc);
4110 array_element_type = RootContext.LookupType (
4111 ec.DeclSpace, element_type, false, loc);
4116 if (arg_count == 1) {
4117 IsOneDimensional = true;
4118 eclass = ExprClass.Value;
4122 IsBuiltinType = TypeManager.IsBuiltinType (type);
4124 if (IsBuiltinType) {
4128 ml = MemberLookup (ec, type, ".ctor", MemberTypes.Constructor,
4129 AllBindingFlags, loc);
4131 if (!(ml is MethodGroupExpr)){
4132 report118 (loc, ml, "method group");
4137 Report.Error (-6, loc, "New invocation: Can not find a constructor for " +
4138 "this argument list");
4142 method = Invocation.OverloadResolve (ec, (MethodGroupExpr) ml, Arguments, loc);
4144 if (method == null) {
4145 Report.Error (-6, loc, "New invocation: Can not find a constructor for " +
4146 "this argument list");
4150 eclass = ExprClass.Value;
4155 ModuleBuilder mb = RootContext.ModuleBuilder;
4157 ArrayList args = new ArrayList ();
4158 if (Arguments != null){
4159 for (int i = arg_count; i > 0;){
4161 Argument a = (Argument) Arguments [i];
4163 args.Add (TypeManager.int32_type);
4167 Type [] arg_types = null;
4170 arg_types = new Type [args.Count];
4172 args.CopyTo (arg_types, 0);
4174 method = mb.GetArrayMethod (type, ".ctor", CallingConventions.HasThis, null,
4177 if (method == null) {
4178 Report.Error (-6, loc, "New invocation: Can not find a constructor for " +
4179 "this argument list");
4183 eclass = ExprClass.Value;
4189 public static byte [] MakeByteBlob (ArrayList ArrayData, Type underlying_type, Location loc)
4194 int count = ArrayData.Count;
4196 factor = GetTypeSize (underlying_type);
4200 data = new byte [(count * factor + 4) & ~3];
4203 for (int i = 0; i < count; ++i) {
4204 object v = ArrayData [i];
4206 if (v is EnumConstant)
4207 v = ((EnumConstant) v).Child;
4209 if (v is Constant && !(v is StringConstant))
4210 v = ((Constant) v).GetValue ();
4216 if (underlying_type == TypeManager.int64_type){
4217 if (!(v is Expression)){
4218 long val = (long) v;
4220 for (int j = 0; j < factor; ++j) {
4221 data [idx + j] = (byte) (val & 0xFF);
4225 } else if (underlying_type == TypeManager.uint64_type){
4226 if (!(v is Expression)){
4227 ulong val = (ulong) v;
4229 for (int j = 0; j < factor; ++j) {
4230 data [idx + j] = (byte) (val & 0xFF);
4234 } else if (underlying_type == TypeManager.float_type) {
4235 if (!(v is Expression)){
4236 element = BitConverter.GetBytes ((float) v);
4238 for (int j = 0; j < factor; ++j)
4239 data [idx + j] = element [j];
4241 } else if (underlying_type == TypeManager.double_type) {
4242 if (!(v is Expression)){
4243 element = BitConverter.GetBytes ((double) v);
4245 for (int j = 0; j < factor; ++j)
4246 data [idx + j] = element [j];
4248 } else if (underlying_type == TypeManager.char_type){
4249 if (!(v is Expression)){
4250 int val = (int) ((char) v);
4252 data [idx] = (byte) (val & 0xff);
4253 data [idx+1] = (byte) (val >> 8);
4255 } else if (underlying_type == TypeManager.short_type){
4256 if (!(v is Expression)){
4257 int val = (int) ((short) v);
4259 data [idx] = (byte) (val & 0xff);
4260 data [idx+1] = (byte) (val >> 8);
4262 } else if (underlying_type == TypeManager.ushort_type){
4263 if (!(v is Expression)){
4264 int val = (int) ((ushort) v);
4266 data [idx] = (byte) (val & 0xff);
4267 data [idx+1] = (byte) (val >> 8);
4269 } else if (underlying_type == TypeManager.int32_type) {
4270 if (!(v is Expression)){
4273 data [idx] = (byte) (val & 0xff);
4274 data [idx+1] = (byte) ((val >> 8) & 0xff);
4275 data [idx+2] = (byte) ((val >> 16) & 0xff);
4276 data [idx+3] = (byte) (val >> 24);
4278 } else if (underlying_type == TypeManager.uint32_type) {
4279 if (!(v is Expression)){
4280 uint val = (uint) v;
4282 data [idx] = (byte) (val & 0xff);
4283 data [idx+1] = (byte) ((val >> 8) & 0xff);
4284 data [idx+2] = (byte) ((val >> 16) & 0xff);
4285 data [idx+3] = (byte) (val >> 24);
4287 } else if (underlying_type == TypeManager.sbyte_type) {
4288 if (!(v is Expression)){
4289 sbyte val = (sbyte) v;
4290 data [idx] = (byte) val;
4292 } else if (underlying_type == TypeManager.byte_type) {
4293 if (!(v is Expression)){
4294 byte val = (byte) v;
4295 data [idx] = (byte) val;
4298 throw new Exception ("Unrecognized type in MakeByteBlob");
4307 // Emits the initializers for the array
4309 void EmitStaticInitializers (EmitContext ec, bool is_expression)
4312 // First, the static data
4315 ILGenerator ig = ec.ig;
4317 byte [] data = MakeByteBlob (ArrayData, underlying_type, loc);
4320 fb = RootContext.MakeStaticData (data);
4323 ig.Emit (OpCodes.Dup);
4324 ig.Emit (OpCodes.Ldtoken, fb);
4325 ig.Emit (OpCodes.Call,
4326 TypeManager.void_initializearray_array_fieldhandle);
4331 // Emits pieces of the array that can not be computed at compile
4332 // time (variables and string locations).
4334 // This always expect the top value on the stack to be the array
4336 void EmitDynamicInitializers (EmitContext ec, bool is_expression)
4338 ILGenerator ig = ec.ig;
4339 int dims = Bounds.Count;
4340 int [] current_pos = new int [dims];
4341 int top = ArrayData.Count;
4342 LocalBuilder temp = ig.DeclareLocal (type);
4344 ig.Emit (OpCodes.Stloc, temp);
4346 MethodInfo set = null;
4350 ModuleBuilder mb = null;
4351 mb = RootContext.ModuleBuilder;
4352 args = new Type [dims + 1];
4355 for (j = 0; j < dims; j++)
4356 args [j] = TypeManager.int32_type;
4358 args [j] = array_element_type;
4360 set = mb.GetArrayMethod (
4362 CallingConventions.HasThis | CallingConventions.Standard,
4363 TypeManager.void_type, args);
4366 for (int i = 0; i < top; i++){
4368 Expression e = null;
4370 if (ArrayData [i] is Expression)
4371 e = (Expression) ArrayData [i];
4375 // Basically we do this for string literals and
4376 // other non-literal expressions
4378 if (e is StringConstant || !(e is Constant) || num_automatic_initializers <= 2) {
4380 ig.Emit (OpCodes.Ldloc, temp);
4382 for (int idx = dims; idx > 0; ) {
4384 IntConstant.EmitInt (ig, current_pos [idx]);
4390 ArrayAccess.EmitStoreOpcode (ig, array_element_type);
4392 ig.Emit (OpCodes.Call, set);
4400 for (int j = 0; j < dims; j++){
4402 if (current_pos [j] < (int) Bounds [j])
4404 current_pos [j] = 0;
4409 ig.Emit (OpCodes.Ldloc, temp);
4412 void EmitArrayArguments (EmitContext ec)
4414 foreach (Argument a in Arguments)
4418 void DoEmit (EmitContext ec, bool is_statement)
4420 ILGenerator ig = ec.ig;
4422 EmitArrayArguments (ec);
4423 if (IsOneDimensional)
4424 ig.Emit (OpCodes.Newarr, array_element_type);
4427 ig.Emit (OpCodes.Newobj, (ConstructorInfo) method);
4429 ig.Emit (OpCodes.Newobj, (MethodInfo) method);
4432 if (Initializers != null){
4434 // FIXME: Set this variable correctly.
4436 bool dynamic_initializers = true;
4438 if (underlying_type != TypeManager.string_type &&
4439 underlying_type != TypeManager.object_type) {
4440 if (num_automatic_initializers > 2)
4441 EmitStaticInitializers (ec, dynamic_initializers || !is_statement);
4444 if (dynamic_initializers)
4445 EmitDynamicInitializers (ec, !is_statement);
4449 public override void Emit (EmitContext ec)
4454 public override void EmitStatement (EmitContext ec)
4462 /// Represents the `this' construct
4464 public class This : Expression, IAssignMethod, IMemoryLocation {
4467 public This (Location loc)
4472 public override Expression DoResolve (EmitContext ec)
4474 eclass = ExprClass.Variable;
4475 type = ec.TypeContainer.TypeBuilder;
4478 Report.Error (26, loc,
4479 "Keyword this not valid in static code");
4486 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
4490 if (ec.TypeContainer is Class){
4491 Report.Error (1604, loc, "Cannot assign to `this'");
4498 public override void Emit (EmitContext ec)
4500 ec.ig.Emit (OpCodes.Ldarg_0);
4503 public void EmitAssign (EmitContext ec, Expression source)
4506 ec.ig.Emit (OpCodes.Starg, 0);
4509 public void AddressOf (EmitContext ec, AddressOp mode)
4511 ec.ig.Emit (OpCodes.Ldarg_0);
4514 // FIGURE OUT WHY LDARG_S does not work
4516 // consider: struct X { int val; int P { set { val = value; }}}
4518 // Yes, this looks very bad. Look at `NOTAS' for
4520 // ec.ig.Emit (OpCodes.Ldarga_S, (byte) 0);
4525 /// Implements the typeof operator
4527 public class TypeOf : Expression {
4528 public readonly string QueriedType;
4532 public TypeOf (string queried_type, Location l)
4534 QueriedType = queried_type;
4538 public override Expression DoResolve (EmitContext ec)
4540 typearg = RootContext.LookupType (
4541 ec.DeclSpace, QueriedType, false, loc);
4543 if (typearg == null)
4546 type = TypeManager.type_type;
4547 eclass = ExprClass.Type;
4551 public override void Emit (EmitContext ec)
4553 ec.ig.Emit (OpCodes.Ldtoken, typearg);
4554 ec.ig.Emit (OpCodes.Call, TypeManager.system_type_get_type_from_handle);
4559 /// Implements the sizeof expression
4561 public class SizeOf : Expression {
4562 public readonly string QueriedType;
4566 public SizeOf (string queried_type, Location l)
4568 this.QueriedType = queried_type;
4572 public override Expression DoResolve (EmitContext ec)
4574 type_queried = RootContext.LookupType (
4575 ec.DeclSpace, QueriedType, false, loc);
4576 if (type_queried == null)
4579 type = TypeManager.int32_type;
4580 eclass = ExprClass.Value;
4584 public override void Emit (EmitContext ec)
4586 int size = GetTypeSize (type_queried);
4589 ec.ig.Emit (OpCodes.Sizeof, type_queried);
4591 IntConstant.EmitInt (ec.ig, size);
4596 /// Implements the member access expression
4598 public class MemberAccess : Expression {
4599 public readonly string Identifier;
4601 Expression member_lookup;
4604 public MemberAccess (Expression expr, string id, Location l)
4611 public Expression Expr {
4617 static void error176 (Location loc, string name)
4619 Report.Error (176, loc, "Static member `" +
4620 name + "' cannot be accessed " +
4621 "with an instance reference, qualify with a " +
4622 "type name instead");
4625 static bool IdenticalNameAndTypeName (EmitContext ec, Expression left_original, Location loc)
4627 if (left_original == null)
4630 if (!(left_original is SimpleName))
4633 SimpleName sn = (SimpleName) left_original;
4635 Type t = RootContext.LookupType (ec.DeclSpace, sn.Name, true, loc);
4642 public static Expression ResolveMemberAccess (EmitContext ec, Expression member_lookup,
4643 Expression left, Location loc,
4644 Expression left_original)
4649 if (member_lookup is MethodGroupExpr){
4650 MethodGroupExpr mg = (MethodGroupExpr) member_lookup;
4655 if (left is TypeExpr){
4656 if (!mg.RemoveInstanceMethods ()){
4657 SimpleName.Error120 (loc, mg.Methods [0].Name);
4661 return member_lookup;
4665 // Instance.MethodGroup
4667 if (IdenticalNameAndTypeName (ec, left_original, loc)){
4668 if (mg.RemoveInstanceMethods ())
4669 return member_lookup;
4672 if (!mg.RemoveStaticMethods ()){
4673 error176 (loc, mg.Methods [0].Name);
4677 mg.InstanceExpression = left;
4678 return member_lookup;
4680 if (!mg.RemoveStaticMethods ()){
4681 if (IdenticalNameAndTypeName (ec, left_original, loc)){
4682 if (!mg.RemoveInstanceMethods ()){
4683 SimpleName.Error120 (loc, mg.Methods [0].Name);
4686 return member_lookup;
4689 error176 (loc, mg.Methods [0].Name);
4693 mg.InstanceExpression = left;
4695 return member_lookup;
4699 if (member_lookup is FieldExpr){
4700 FieldExpr fe = (FieldExpr) member_lookup;
4701 FieldInfo fi = fe.FieldInfo;
4703 if (fi is FieldBuilder) {
4704 Const c = TypeManager.LookupConstant ((FieldBuilder) fi);
4707 object o = c.LookupConstantValue (ec);
4708 object real_value = ((Constant) c.Expr).GetValue ();
4710 return Constantify (real_value, fi.FieldType);
4715 Type t = fi.FieldType;
4716 Type decl_type = fi.DeclaringType;
4719 if (fi is FieldBuilder)
4720 o = TypeManager.GetValue ((FieldBuilder) fi);
4722 o = fi.GetValue (fi);
4724 if (decl_type.IsSubclassOf (TypeManager.enum_type)) {
4725 Expression enum_member = MemberLookup (
4726 ec, decl_type, "value__", MemberTypes.Field,
4727 AllBindingFlags, loc);
4729 Enum en = TypeManager.LookupEnum (decl_type);
4733 c = Constantify (o, en.UnderlyingType);
4735 c = Constantify (o, enum_member.Type);
4737 return new EnumConstant (c, decl_type);
4740 Expression exp = Constantify (o, t);
4742 if (!(left is TypeExpr)) {
4743 error176 (loc, fe.FieldInfo.Name);
4750 if (fi.FieldType.IsPointer && !ec.InUnsafe){
4755 if (left is TypeExpr){
4756 // and refers to a type name or an
4757 if (!fe.FieldInfo.IsStatic){
4758 error176 (loc, fe.FieldInfo.Name);
4761 return member_lookup;
4763 if (fe.FieldInfo.IsStatic){
4764 if (IdenticalNameAndTypeName (ec, left_original, loc))
4765 return member_lookup;
4767 error176 (loc, fe.FieldInfo.Name);
4770 fe.InstanceExpression = left;
4776 if (member_lookup is PropertyExpr){
4777 PropertyExpr pe = (PropertyExpr) member_lookup;
4779 if (left is TypeExpr){
4781 SimpleName.Error120 (loc, pe.PropertyInfo.Name);
4787 if (IdenticalNameAndTypeName (ec, left_original, loc))
4788 return member_lookup;
4789 error176 (loc, pe.PropertyInfo.Name);
4792 pe.InstanceExpression = left;
4798 if (member_lookup is EventExpr) {
4800 EventExpr ee = (EventExpr) member_lookup;
4803 // If the event is local to this class, we transform ourselves into
4807 Expression ml = MemberLookup (
4808 ec, ec.TypeContainer.TypeBuilder,
4809 ee.EventInfo.Name, MemberTypes.Event, AllBindingFlags, loc);
4812 MemberInfo mi = ec.TypeContainer.GetFieldFromEvent ((EventExpr) ml);
4816 // If this happens, then we have an event with its own
4817 // accessors and private field etc so there's no need
4818 // to transform ourselves : we should instead flag an error
4820 Assign.error70 (ee.EventInfo, loc);
4824 ml = ExprClassFromMemberInfo (ec, mi, loc);
4827 Report.Error (-200, loc, "Internal error!!");
4830 return ResolveMemberAccess (ec, ml, left, loc, left_original);
4833 if (left is TypeExpr) {
4835 SimpleName.Error120 (loc, ee.EventInfo.Name);
4843 if (IdenticalNameAndTypeName (ec, left_original, loc))
4846 error176 (loc, ee.EventInfo.Name);
4850 ee.InstanceExpression = left;
4856 if (member_lookup is TypeExpr){
4857 member_lookup.Resolve (ec);
4858 return member_lookup;
4861 Console.WriteLine ("Left is: " + left);
4862 Report.Error (-100, loc, "Support for [" + member_lookup + "] is not present yet");
4863 Environment.Exit (0);
4867 public override Expression DoResolve (EmitContext ec)
4870 // We are the sole users of ResolveWithSimpleName (ie, the only
4871 // ones that can cope with it
4873 Expression original = expr;
4874 expr = expr.ResolveWithSimpleName (ec);
4879 if (expr is SimpleName){
4880 SimpleName child_expr = (SimpleName) expr;
4882 expr = new SimpleName (child_expr.Name + "." + Identifier, loc);
4884 return expr.ResolveWithSimpleName (ec);
4888 // TODO: I mailed Ravi about this, and apparently we can get rid
4889 // of this and put it in the right place.
4891 // Handle enums here when they are in transit.
4892 // Note that we cannot afford to hit MemberLookup in this case because
4893 // it will fail to find any members at all
4896 Type expr_type = expr.Type;
4897 if ((expr is TypeExpr) && (expr_type.IsSubclassOf (TypeManager.enum_type))){
4899 Enum en = TypeManager.LookupEnum (expr_type);
4902 object value = en.LookupEnumValue (ec, Identifier, loc);
4905 Constant c = Constantify (value, en.UnderlyingType);
4906 return new EnumConstant (c, expr_type);
4911 if (expr_type.IsPointer){
4912 Report.Error (23, loc,
4913 "The `.' operator can not be applied to pointer operands (" +
4914 TypeManager.CSharpName (expr_type) + ")");
4918 member_lookup = MemberLookup (ec, expr_type, Identifier, loc);
4920 if (member_lookup == null){
4921 Report.Error (117, loc, "`" + expr_type + "' does not contain a " +
4922 "definition for `" + Identifier + "'");
4927 return ResolveMemberAccess (ec, member_lookup, expr, loc, original);
4930 public override void Emit (EmitContext ec)
4932 throw new Exception ("Should not happen");
4937 /// Implements checked expressions
4939 public class CheckedExpr : Expression {
4941 public Expression Expr;
4943 public CheckedExpr (Expression e)
4948 public override Expression DoResolve (EmitContext ec)
4950 bool last_const_check = ec.ConstantCheckState;
4952 ec.ConstantCheckState = true;
4953 Expr = Expr.Resolve (ec);
4954 ec.ConstantCheckState = last_const_check;
4959 eclass = Expr.eclass;
4964 public override void Emit (EmitContext ec)
4966 bool last_check = ec.CheckState;
4967 bool last_const_check = ec.ConstantCheckState;
4969 ec.CheckState = true;
4970 ec.ConstantCheckState = true;
4972 ec.CheckState = last_check;
4973 ec.ConstantCheckState = last_const_check;
4979 /// Implements the unchecked expression
4981 public class UnCheckedExpr : Expression {
4983 public Expression Expr;
4985 public UnCheckedExpr (Expression e)
4990 public override Expression DoResolve (EmitContext ec)
4992 bool last_const_check = ec.ConstantCheckState;
4994 ec.ConstantCheckState = false;
4995 Expr = Expr.Resolve (ec);
4996 ec.ConstantCheckState = last_const_check;
5001 eclass = Expr.eclass;
5006 public override void Emit (EmitContext ec)
5008 bool last_check = ec.CheckState;
5009 bool last_const_check = ec.ConstantCheckState;
5011 ec.CheckState = false;
5012 ec.ConstantCheckState = false;
5014 ec.CheckState = last_check;
5015 ec.ConstantCheckState = last_const_check;
5021 /// An Element Access expression.
5023 /// During semantic analysis these are transformed into
5024 /// IndexerAccess or ArrayAccess
5026 public class ElementAccess : Expression {
5027 public ArrayList Arguments;
5028 public Expression Expr;
5029 public Location loc;
5031 public ElementAccess (Expression e, ArrayList e_list, Location l)
5040 Arguments = new ArrayList ();
5041 foreach (Expression tmp in e_list)
5042 Arguments.Add (new Argument (tmp, Argument.AType.Expression));
5046 bool CommonResolve (EmitContext ec)
5048 Expr = Expr.Resolve (ec);
5053 if (Arguments == null)
5056 for (int i = Arguments.Count; i > 0;){
5058 Argument a = (Argument) Arguments [i];
5060 if (!a.Resolve (ec, loc))
5067 Expression MakePointerAccess ()
5071 if (t == TypeManager.void_ptr_type){
5074 "The array index operation is not valid for void pointers");
5077 if (Arguments.Count != 1){
5080 "A pointer must be indexed by a single value");
5083 Expression p = new PointerArithmetic (true, Expr, ((Argument)Arguments [0]).Expr, t);
5084 return new Indirection (p);
5087 public override Expression DoResolve (EmitContext ec)
5089 if (!CommonResolve (ec))
5093 // We perform some simple tests, and then to "split" the emit and store
5094 // code we create an instance of a different class, and return that.
5096 // I am experimenting with this pattern.
5100 if (t.IsSubclassOf (TypeManager.array_type))
5101 return (new ArrayAccess (this)).Resolve (ec);
5102 else if (t.IsPointer)
5103 return MakePointerAccess ();
5105 return (new IndexerAccess (this)).Resolve (ec);
5108 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
5110 if (!CommonResolve (ec))
5114 if (t.IsSubclassOf (TypeManager.array_type))
5115 return (new ArrayAccess (this)).ResolveLValue (ec, right_side);
5116 else if (t.IsPointer)
5117 return MakePointerAccess ();
5119 return (new IndexerAccess (this)).ResolveLValue (ec, right_side);
5122 public override void Emit (EmitContext ec)
5124 throw new Exception ("Should never be reached");
5129 /// Implements array access
5131 public class ArrayAccess : Expression, IAssignMethod, IMemoryLocation {
5133 // Points to our "data" repository
5137 public ArrayAccess (ElementAccess ea_data)
5140 eclass = ExprClass.Variable;
5143 public override Expression DoResolve (EmitContext ec)
5145 if (ea.Expr.eclass != ExprClass.Variable) {
5146 report118 (ea.loc, ea.Expr, "variable");
5150 Type t = ea.Expr.Type;
5151 if (t.GetArrayRank () != ea.Arguments.Count){
5152 Report.Error (22, ea.loc,
5153 "Incorrect number of indexes for array " +
5154 " expected: " + t.GetArrayRank () + " got: " +
5155 ea.Arguments.Count);
5158 type = t.GetElementType ();
5159 if (type.IsPointer && !ec.InUnsafe){
5160 UnsafeError (ea.loc);
5164 eclass = ExprClass.Variable;
5170 /// Emits the right opcode to load an object of Type `t'
5171 /// from an array of T
5173 static public void EmitLoadOpcode (ILGenerator ig, Type type)
5175 if (type == TypeManager.byte_type || type == TypeManager.bool_type)
5176 ig.Emit (OpCodes.Ldelem_I1);
5177 else if (type == TypeManager.sbyte_type)
5178 ig.Emit (OpCodes.Ldelem_U1);
5179 else if (type == TypeManager.short_type)
5180 ig.Emit (OpCodes.Ldelem_I2);
5181 else if (type == TypeManager.ushort_type)
5182 ig.Emit (OpCodes.Ldelem_U2);
5183 else if (type == TypeManager.int32_type)
5184 ig.Emit (OpCodes.Ldelem_I4);
5185 else if (type == TypeManager.uint32_type)
5186 ig.Emit (OpCodes.Ldelem_U4);
5187 else if (type == TypeManager.uint64_type)
5188 ig.Emit (OpCodes.Ldelem_I8);
5189 else if (type == TypeManager.int64_type)
5190 ig.Emit (OpCodes.Ldelem_I8);
5191 else if (type == TypeManager.float_type)
5192 ig.Emit (OpCodes.Ldelem_R4);
5193 else if (type == TypeManager.double_type)
5194 ig.Emit (OpCodes.Ldelem_R8);
5195 else if (type == TypeManager.intptr_type)
5196 ig.Emit (OpCodes.Ldelem_I);
5197 else if (type.IsValueType){
5198 ig.Emit (OpCodes.Ldelema, type);
5199 ig.Emit (OpCodes.Ldobj, type);
5201 ig.Emit (OpCodes.Ldelem_Ref);
5205 /// Emits the right opcode to store an object of Type `t'
5206 /// from an array of T.
5208 static public void EmitStoreOpcode (ILGenerator ig, Type t)
5210 if (t == TypeManager.byte_type || t == TypeManager.sbyte_type ||
5211 t == TypeManager.bool_type)
5212 ig.Emit (OpCodes.Stelem_I1);
5213 else if (t == TypeManager.short_type || t == TypeManager.ushort_type || t == TypeManager.char_type)
5214 ig.Emit (OpCodes.Stelem_I2);
5215 else if (t == TypeManager.int32_type || t == TypeManager.uint32_type)
5216 ig.Emit (OpCodes.Stelem_I4);
5217 else if (t == TypeManager.int64_type || t == TypeManager.uint64_type)
5218 ig.Emit (OpCodes.Stelem_I8);
5219 else if (t == TypeManager.float_type)
5220 ig.Emit (OpCodes.Stelem_R4);
5221 else if (t == TypeManager.double_type)
5222 ig.Emit (OpCodes.Stelem_R8);
5223 else if (t == TypeManager.intptr_type)
5224 ig.Emit (OpCodes.Stelem_I);
5225 else if (t.IsValueType)
5226 ig.Emit (OpCodes.Stobj, t);
5228 ig.Emit (OpCodes.Stelem_Ref);
5231 MethodInfo FetchGetMethod ()
5233 ModuleBuilder mb = RootContext.ModuleBuilder;
5234 int arg_count = ea.Arguments.Count;
5235 Type [] args = new Type [arg_count];
5238 for (int i = 0; i < arg_count; i++){
5239 //args [i++] = a.Type;
5240 args [i] = TypeManager.int32_type;
5243 get = mb.GetArrayMethod (
5244 ea.Expr.Type, "Get",
5245 CallingConventions.HasThis |
5246 CallingConventions.Standard,
5252 MethodInfo FetchAddressMethod ()
5254 ModuleBuilder mb = RootContext.ModuleBuilder;
5255 int arg_count = ea.Arguments.Count;
5256 Type [] args = new Type [arg_count];
5258 string ptr_type_name;
5261 ptr_type_name = type.FullName + "&";
5262 ret_type = Type.GetType (ptr_type_name);
5265 // It is a type defined by the source code we are compiling
5267 if (ret_type == null){
5268 ret_type = mb.GetType (ptr_type_name);
5271 for (int i = 0; i < arg_count; i++){
5272 //args [i++] = a.Type;
5273 args [i] = TypeManager.int32_type;
5276 address = mb.GetArrayMethod (
5277 ea.Expr.Type, "Address",
5278 CallingConventions.HasThis |
5279 CallingConventions.Standard,
5285 public override void Emit (EmitContext ec)
5287 int rank = ea.Expr.Type.GetArrayRank ();
5288 ILGenerator ig = ec.ig;
5292 foreach (Argument a in ea.Arguments)
5296 EmitLoadOpcode (ig, type);
5300 method = FetchGetMethod ();
5301 ig.Emit (OpCodes.Call, method);
5305 public void EmitAssign (EmitContext ec, Expression source)
5307 int rank = ea.Expr.Type.GetArrayRank ();
5308 ILGenerator ig = ec.ig;
5312 foreach (Argument a in ea.Arguments)
5315 Type t = source.Type;
5318 // The stobj opcode used by value types will need
5319 // an address on the stack, not really an array/array
5323 if (t.IsValueType && !TypeManager.IsBuiltinType (t))
5324 ig.Emit (OpCodes.Ldelema, t);
5330 EmitStoreOpcode (ig, t);
5332 ModuleBuilder mb = RootContext.ModuleBuilder;
5333 int arg_count = ea.Arguments.Count;
5334 Type [] args = new Type [arg_count + 1];
5337 for (int i = 0; i < arg_count; i++){
5338 //args [i++] = a.Type;
5339 args [i] = TypeManager.int32_type;
5342 args [arg_count] = type;
5344 set = mb.GetArrayMethod (
5345 ea.Expr.Type, "Set",
5346 CallingConventions.HasThis |
5347 CallingConventions.Standard,
5348 TypeManager.void_type, args);
5350 ig.Emit (OpCodes.Call, set);
5354 public void AddressOf (EmitContext ec, AddressOp mode)
5356 int rank = ea.Expr.Type.GetArrayRank ();
5357 ILGenerator ig = ec.ig;
5361 foreach (Argument a in ea.Arguments)
5365 ig.Emit (OpCodes.Ldelema, type);
5367 MethodInfo address = FetchAddressMethod ();
5368 ig.Emit (OpCodes.Call, address);
5375 public ArrayList getters, setters;
5376 static Hashtable map;
5380 map = new Hashtable ();
5383 Indexers (MemberInfo [] mi)
5385 foreach (PropertyInfo property in mi){
5386 MethodInfo get, set;
5388 get = property.GetGetMethod (true);
5390 if (getters == null)
5391 getters = new ArrayList ();
5396 set = property.GetSetMethod (true);
5398 if (setters == null)
5399 setters = new ArrayList ();
5405 static public Indexers GetIndexersForType (Type t, TypeManager tm, Location loc)
5407 Indexers ix = (Indexers) map [t];
5408 string p_name = TypeManager.IndexerPropertyName (t);
5413 MemberInfo [] mi = tm.FindMembers (
5414 t, MemberTypes.Property,
5415 BindingFlags.Public | BindingFlags.Instance,
5416 Type.FilterName, p_name);
5418 if (mi == null || mi.Length == 0){
5419 Report.Error (21, loc,
5420 "Type `" + TypeManager.CSharpName (t) + "' does not have " +
5421 "any indexers defined");
5425 ix = new Indexers (mi);
5433 /// Expressions that represent an indexer call.
5435 public class IndexerAccess : Expression, IAssignMethod {
5437 // Points to our "data" repository
5440 MethodInfo get, set;
5442 ArrayList set_arguments;
5444 public IndexerAccess (ElementAccess ea_data)
5447 eclass = ExprClass.Value;
5450 public override Expression DoResolve (EmitContext ec)
5452 Type indexer_type = ea.Expr.Type;
5455 // Step 1: Query for all `Item' *properties*. Notice
5456 // that the actual methods are pointed from here.
5458 // This is a group of properties, piles of them.
5461 ilist = Indexers.GetIndexersForType (
5462 indexer_type, RootContext.TypeManager, ea.loc);
5466 // Step 2: find the proper match
5468 if (ilist != null && ilist.getters != null && ilist.getters.Count > 0)
5469 get = (MethodInfo) Invocation.OverloadResolve (
5470 ec, new MethodGroupExpr (ilist.getters), ea.Arguments, ea.loc);
5473 Report.Error (154, ea.loc,
5474 "indexer can not be used in this context, because " +
5475 "it lacks a `get' accessor");
5479 type = get.ReturnType;
5480 if (type.IsPointer && !ec.InUnsafe){
5481 UnsafeError (ea.loc);
5485 eclass = ExprClass.IndexerAccess;
5489 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
5491 Type indexer_type = ea.Expr.Type;
5492 Type right_type = right_side.Type;
5495 ilist = Indexers.GetIndexersForType (
5496 indexer_type, RootContext.TypeManager, ea.loc);
5498 if (ilist != null && ilist.setters != null && ilist.setters.Count > 0){
5499 set_arguments = (ArrayList) ea.Arguments.Clone ();
5500 set_arguments.Add (new Argument (right_side, Argument.AType.Expression));
5502 set = (MethodInfo) Invocation.OverloadResolve (
5503 ec, new MethodGroupExpr (ilist.setters), set_arguments, ea.loc);
5507 Report.Error (200, ea.loc,
5508 "indexer X.this [" + TypeManager.CSharpName (right_type) +
5509 "] lacks a `set' accessor");
5513 type = TypeManager.void_type;
5514 eclass = ExprClass.IndexerAccess;
5518 public override void Emit (EmitContext ec)
5520 Invocation.EmitCall (ec, false, false, ea.Expr, get, ea.Arguments);
5524 // source is ignored, because we already have a copy of it from the
5525 // LValue resolution and we have already constructed a pre-cached
5526 // version of the arguments (ea.set_arguments);
5528 public void EmitAssign (EmitContext ec, Expression source)
5530 Invocation.EmitCall (ec, false, false, ea.Expr, set, set_arguments);
5535 /// The base operator for method names
5537 public class BaseAccess : Expression {
5541 public BaseAccess (string member, Location l)
5543 this.member = member;
5547 public override Expression DoResolve (EmitContext ec)
5549 Expression member_lookup;
5550 Type current_type = ec.TypeContainer.TypeBuilder;
5551 Type base_type = current_type.BaseType;
5555 Report.Error (1511, loc,
5556 "Keyword base is not allowed in static method");
5560 member_lookup = MemberLookup (ec, base_type, member, loc);
5561 if (member_lookup == null)
5567 left = new TypeExpr (base_type);
5571 e = MemberAccess.ResolveMemberAccess (ec, member_lookup, left, loc, null);
5572 if (e is PropertyExpr){
5573 PropertyExpr pe = (PropertyExpr) e;
5581 public override void Emit (EmitContext ec)
5583 throw new Exception ("Should never be called");
5588 /// The base indexer operator
5590 public class BaseIndexerAccess : Expression {
5591 ArrayList Arguments;
5594 public BaseIndexerAccess (ArrayList args, Location l)
5600 public override Expression DoResolve (EmitContext ec)
5602 Type current_type = ec.TypeContainer.TypeBuilder;
5603 Type base_type = current_type.BaseType;
5604 Expression member_lookup;
5607 Report.Error (1511, loc,
5608 "Keyword base is not allowed in static method");
5612 member_lookup = MemberLookup (ec, base_type, "get_Item", MemberTypes.Method, AllBindingFlags, loc);
5613 if (member_lookup == null)
5616 return MemberAccess.ResolveMemberAccess (ec, member_lookup, ec.This, loc, null);
5619 public override void Emit (EmitContext ec)
5621 throw new Exception ("Should never be called");
5626 /// This class exists solely to pass the Type around and to be a dummy
5627 /// that can be passed to the conversion functions (this is used by
5628 /// foreach implementation to typecast the object return value from
5629 /// get_Current into the proper type. All code has been generated and
5630 /// we only care about the side effect conversions to be performed
5632 public class EmptyExpression : Expression {
5633 public EmptyExpression ()
5635 type = TypeManager.object_type;
5636 eclass = ExprClass.Value;
5639 public EmptyExpression (Type t)
5642 eclass = ExprClass.Value;
5645 public override Expression DoResolve (EmitContext ec)
5650 public override void Emit (EmitContext ec)
5652 // nothing, as we only exist to not do anything.
5656 // This is just because we might want to reuse this bad boy
5657 // instead of creating gazillions of EmptyExpressions.
5658 // (CanConvertImplicit uses it)
5660 public void SetType (Type t)
5666 public class UserCast : Expression {
5670 public UserCast (MethodInfo method, Expression source)
5672 this.method = method;
5673 this.source = source;
5674 type = method.ReturnType;
5675 eclass = ExprClass.Value;
5678 public override Expression DoResolve (EmitContext ec)
5681 // We are born fully resolved
5686 public override void Emit (EmitContext ec)
5688 ILGenerator ig = ec.ig;
5692 if (method is MethodInfo)
5693 ig.Emit (OpCodes.Call, (MethodInfo) method);
5695 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
5701 // This class is used to "construct" the type during a typecast
5702 // operation. Since the Type.GetType class in .NET can parse
5703 // the type specification, we just use this to construct the type
5704 // one bit at a time.
5706 public class ComposedCast : Expression {
5711 public ComposedCast (Expression left, string dim, Location l)
5718 public override Expression DoResolve (EmitContext ec)
5720 left = left.Resolve (ec);
5724 if (left.eclass != ExprClass.Type){
5725 report118 (loc, left, "type");
5729 type = RootContext.LookupType (
5730 ec.DeclSpace, left.Type.FullName + dim, false, loc);
5734 if (!ec.InUnsafe && type.IsPointer){
5739 eclass = ExprClass.Type;
5743 public override void Emit (EmitContext ec)
5745 throw new Exception ("This should never be called");
5750 // This class is used to represent the address of an array, used
5751 // only by the Fixed statement, this is like the C "&a [0]" construct.
5753 public class ArrayPtr : Expression {
5756 public ArrayPtr (Expression array)
5758 Type array_type = array.Type.GetElementType ();
5762 string array_ptr_type_name = array_type.FullName + "*";
5764 type = Type.GetType (array_ptr_type_name);
5766 ModuleBuilder mb = RootContext.ModuleBuilder;
5768 type = mb.GetType (array_ptr_type_name);
5771 eclass = ExprClass.Value;
5774 public override void Emit (EmitContext ec)
5776 ILGenerator ig = ec.ig;
5779 IntLiteral.EmitInt (ig, 0);
5780 ig.Emit (OpCodes.Ldelema, array.Type.GetElementType ());
5783 public override Expression DoResolve (EmitContext ec)
5786 // We are born fully resolved
5793 // Used by the fixed statement
5795 public class StringPtr : Expression {
5798 public StringPtr (LocalBuilder b)
5801 eclass = ExprClass.Value;
5802 type = TypeManager.char_ptr_type;
5805 public override Expression DoResolve (EmitContext ec)
5807 // This should never be invoked, we are born in fully
5808 // initialized state.
5813 public override void Emit (EmitContext ec)
5815 ILGenerator ig = ec.ig;
5817 ig.Emit (OpCodes.Ldloc, b);
5818 ig.Emit (OpCodes.Conv_I);
5819 ig.Emit (OpCodes.Call, TypeManager.int_get_offset_to_string_data);
5820 ig.Emit (OpCodes.Add);
5825 // Implements the `stackalloc' keyword
5827 public class StackAlloc : Expression {
5833 public StackAlloc (string type, Expression count, Location l)
5840 public override Expression DoResolve (EmitContext ec)
5842 count = count.Resolve (ec);
5846 if (count.Type != TypeManager.int32_type){
5847 count = ConvertImplicitRequired (ec, count, TypeManager.int32_type, loc);
5852 if (ec.InCatch || ec.InFinally){
5853 Report.Error (255, loc,
5854 "stackalloc can not be used in a catch or finally block");
5858 otype = RootContext.LookupType (ec.DeclSpace, t, false, loc);
5863 if (!TypeManager.VerifyUnManaged (otype, loc))
5866 string ptr_name = otype.FullName + "*";
5867 type = Type.GetType (ptr_name);
5869 ModuleBuilder mb = RootContext.ModuleBuilder;
5871 type = mb.GetType (ptr_name);
5873 eclass = ExprClass.Value;
5878 public override void Emit (EmitContext ec)
5880 int size = GetTypeSize (otype);
5881 ILGenerator ig = ec.ig;
5884 ig.Emit (OpCodes.Sizeof, otype);
5886 IntConstant.EmitInt (ig, size);
5888 ig.Emit (OpCodes.Mul);
5889 ig.Emit (OpCodes.Localloc);