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
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 () +
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);
247 throw new Exception (
248 "FIXME: Implement constant OnesComplement of:" +
251 throw new Exception ("Can not constant fold");
254 Expression ResolveOperator (EmitContext ec)
256 Type expr_type = expr.Type;
259 // Step 1: Perform Operator Overload location
264 op_name = oper_names [(int) oper];
266 mg = MemberLookup (ec, expr_type, op_name, MemberTypes.Method, AllBindingFlags, loc);
269 Expression e = StaticCallExpr.MakeSimpleCall (
270 ec, (MethodGroupExpr) mg, expr, loc);
280 // Only perform numeric promotions on:
283 if (expr_type == null)
287 // Step 2: Default operations on CLI native types.
289 if (expr is Constant)
290 return Reduce (ec, expr);
292 if (oper == Operator.LogicalNot){
293 if (expr_type != TypeManager.bool_type) {
298 type = TypeManager.bool_type;
302 if (oper == Operator.OnesComplement) {
303 if (!((expr_type == TypeManager.int32_type) ||
304 (expr_type == TypeManager.uint32_type) ||
305 (expr_type == TypeManager.int64_type) ||
306 (expr_type == TypeManager.uint64_type) ||
307 (expr_type.IsSubclassOf (TypeManager.enum_type)))){
315 if (oper == Operator.UnaryPlus) {
317 // A plus in front of something is just a no-op, so return the child.
323 // Deals with -literals
324 // int operator- (int x)
325 // long operator- (long x)
326 // float operator- (float f)
327 // double operator- (double d)
328 // decimal operator- (decimal d)
330 if (oper == Operator.UnaryNegation){
334 // perform numeric promotions to int,
338 // The following is inneficient, because we call
339 // ConvertImplicit too many times.
341 // It is also not clear if we should convert to Float
342 // or Double initially.
344 if (expr_type == TypeManager.uint32_type){
346 // FIXME: handle exception to this rule that
347 // permits the int value -2147483648 (-2^31) to
348 // bt wrote as a decimal interger literal
350 type = TypeManager.int64_type;
351 expr = ConvertImplicit (ec, expr, type, loc);
355 if (expr_type == TypeManager.uint64_type){
357 // FIXME: Handle exception of `long value'
358 // -92233720368547758087 (-2^63) to be wrote as
359 // decimal integer literal.
365 if (expr_type == TypeManager.float_type){
370 e = ConvertImplicit (ec, expr, TypeManager.int32_type, loc);
377 e = ConvertImplicit (ec, expr, TypeManager.int64_type, loc);
384 e = ConvertImplicit (ec, expr, TypeManager.double_type, loc);
395 if (oper == Operator.AddressOf){
396 if (expr.eclass != ExprClass.Variable){
397 Error (211, loc, "Cannot take the address of non-variables");
406 if (!TypeManager.VerifyUnManaged (expr.Type, loc)){
411 // This construct is needed because dynamic types
412 // are not known by Type.GetType, so we have to try then to use
413 // ModuleBuilder.GetType.
415 string ptr_type_name = expr.Type.FullName + "*";
416 type = Type.GetType (ptr_type_name);
418 type = RootContext.ModuleBuilder.GetType (ptr_type_name);
423 if (oper == Operator.Indirection){
429 if (!expr_type.IsPointer){
432 "The * or -> operator can only be applied to pointers");
437 // We create an Indirection expression, because
438 // it can implement the IMemoryLocation.
440 return new Indirection (expr);
443 Error (187, loc, "No such operator '" + OperName () + "' defined for type '" +
444 TypeManager.CSharpName (expr_type) + "'");
448 public override Expression DoResolve (EmitContext ec)
450 expr = expr.Resolve (ec);
455 eclass = ExprClass.Value;
456 return ResolveOperator (ec);
459 public override void Emit (EmitContext ec)
461 ILGenerator ig = ec.ig;
462 Type expr_type = expr.Type;
465 case Operator.UnaryPlus:
466 throw new Exception ("This should be caught by Resolve");
468 case Operator.UnaryNegation:
470 ig.Emit (OpCodes.Neg);
473 case Operator.LogicalNot:
475 ig.Emit (OpCodes.Ldc_I4_0);
476 ig.Emit (OpCodes.Ceq);
479 case Operator.OnesComplement:
481 ig.Emit (OpCodes.Not);
484 case Operator.AddressOf:
485 ((IMemoryLocation)expr).AddressOf (ec);
489 throw new Exception ("This should not happen: Operator = "
495 /// This will emit the child expression for `ec' avoiding the logical
496 /// not. The parent will take care of changing brfalse/brtrue
498 public void EmitLogicalNot (EmitContext ec)
500 if (oper != Operator.LogicalNot)
501 throw new Exception ("EmitLogicalNot can only be called with !expr");
506 public override string ToString ()
508 return "Unary (" + oper + ", " + expr + ")";
514 // Unary operators are turned into Indirection expressions
515 // after semantic analysis (this is so we can take the address
516 // of an indirection).
518 public class Indirection : Expression, IMemoryLocation, IAssignMethod {
521 public Indirection (Expression expr)
524 this.type = expr.Type.GetElementType ();
525 eclass = ExprClass.Variable;
528 public override void Emit (EmitContext ec)
531 LoadFromPtr (ec.ig, Type, false);
534 public void EmitAssign (EmitContext ec, Expression source)
538 StoreFromPtr (ec.ig, type);
541 public void AddressOf (EmitContext ec)
546 public override Expression DoResolve (EmitContext ec)
549 // Born fully resolved
556 /// Unary Mutator expressions (pre and post ++ and --)
560 /// UnaryMutator implements ++ and -- expressions. It derives from
561 /// ExpressionStatement becuase the pre/post increment/decrement
562 /// operators can be used in a statement context.
564 /// FIXME: Idea, we could split this up in two classes, one simpler
565 /// for the common case, and one with the extra fields for more complex
566 /// classes (indexers require temporary access; overloaded require method)
568 /// Maybe we should have classes PreIncrement, PostIncrement, PreDecrement,
569 /// PostDecrement, that way we could save the `Mode' byte as well.
571 public class UnaryMutator : ExpressionStatement {
572 public enum Mode : byte {
573 PreIncrement, PreDecrement, PostIncrement, PostDecrement
579 LocalTemporary temp_storage;
582 // This is expensive for the simplest case.
586 public UnaryMutator (Mode m, Expression e, Location l)
595 return (mode == Mode.PreIncrement || mode == Mode.PostIncrement) ?
599 void error23 (Type t)
602 23, loc, "Operator " + OperName () +
603 " cannot be applied to operand of type `" +
604 TypeManager.CSharpName (t) + "'");
608 /// Returns whether an object of type `t' can be incremented
609 /// or decremented with add/sub (ie, basically whether we can
610 /// use pre-post incr-decr operations on it, but it is not a
611 /// System.Decimal, which we require operator overloading to catch)
613 static bool IsIncrementableNumber (Type t)
615 return (t == TypeManager.sbyte_type) ||
616 (t == TypeManager.byte_type) ||
617 (t == TypeManager.short_type) ||
618 (t == TypeManager.ushort_type) ||
619 (t == TypeManager.int32_type) ||
620 (t == TypeManager.uint32_type) ||
621 (t == TypeManager.int64_type) ||
622 (t == TypeManager.uint64_type) ||
623 (t == TypeManager.char_type) ||
624 (t.IsSubclassOf (TypeManager.enum_type)) ||
625 (t == TypeManager.float_type) ||
626 (t == TypeManager.double_type) ||
627 (t.IsPointer && t != TypeManager.void_ptr_type);
630 Expression ResolveOperator (EmitContext ec)
632 Type expr_type = expr.Type;
635 // Step 1: Perform Operator Overload location
640 if (mode == Mode.PreIncrement || mode == Mode.PostIncrement)
641 op_name = "op_Increment";
643 op_name = "op_Decrement";
645 mg = MemberLookup (ec, expr_type, op_name, MemberTypes.Method, AllBindingFlags, loc);
647 if (mg == null && expr_type.BaseType != null)
648 mg = MemberLookup (ec, expr_type.BaseType, op_name,
649 MemberTypes.Method, AllBindingFlags, loc);
652 method = StaticCallExpr.MakeSimpleCall (
653 ec, (MethodGroupExpr) mg, expr, loc);
660 // The operand of the prefix/postfix increment decrement operators
661 // should be an expression that is classified as a variable,
662 // a property access or an indexer access
665 if (expr.eclass == ExprClass.Variable){
666 if (IsIncrementableNumber (expr_type) ||
667 expr_type == TypeManager.decimal_type){
670 } else if (expr.eclass == ExprClass.IndexerAccess){
671 IndexerAccess ia = (IndexerAccess) expr;
673 temp_storage = new LocalTemporary (ec, expr.Type);
675 expr = ia.ResolveLValue (ec, temp_storage);
680 } else if (expr.eclass == ExprClass.PropertyAccess){
681 PropertyExpr pe = (PropertyExpr) expr;
683 if (pe.VerifyAssignable ())
688 report118 (loc, expr, "variable, indexer or property access");
692 Error (187, loc, "No such operator '" + OperName () + "' defined for type '" +
693 TypeManager.CSharpName (expr_type) + "'");
697 public override Expression DoResolve (EmitContext ec)
699 expr = expr.Resolve (ec);
704 eclass = ExprClass.Value;
705 return ResolveOperator (ec);
708 static int PtrTypeSize (Type t)
710 return GetTypeSize (t.GetElementType ());
715 // FIXME: We need some way of avoiding the use of temp_storage
716 // for some types of storage (parameters, local variables,
717 // static fields) and single-dimension array access.
719 void EmitCode (EmitContext ec, bool is_expr)
721 ILGenerator ig = ec.ig;
722 IAssignMethod ia = (IAssignMethod) expr;
723 Type expr_type = expr.Type;
725 if (temp_storage == null)
726 temp_storage = new LocalTemporary (ec, expr_type);
729 case Mode.PreIncrement:
730 case Mode.PreDecrement:
734 if (expr_type == TypeManager.uint64_type ||
735 expr_type == TypeManager.int64_type)
736 ig.Emit (OpCodes.Ldc_I8, 1L);
737 else if (expr_type == TypeManager.double_type)
738 ig.Emit (OpCodes.Ldc_R8, 1.0);
739 else if (expr_type == TypeManager.float_type)
740 ig.Emit (OpCodes.Ldc_R4, 1.0F);
741 else if (expr_type.IsPointer){
742 int n = PtrTypeSize (expr_type);
745 ig.Emit (OpCodes.Sizeof, expr_type);
747 IntConstant.EmitInt (ig, n);
749 ig.Emit (OpCodes.Ldc_I4_1);
751 if (mode == Mode.PreDecrement)
752 ig.Emit (OpCodes.Sub);
754 ig.Emit (OpCodes.Add);
758 temp_storage.Store (ec);
759 ia.EmitAssign (ec, temp_storage);
761 temp_storage.Emit (ec);
764 case Mode.PostIncrement:
765 case Mode.PostDecrement:
773 ig.Emit (OpCodes.Dup);
775 if (expr_type == TypeManager.uint64_type ||
776 expr_type == TypeManager.int64_type)
777 ig.Emit (OpCodes.Ldc_I8, 1L);
778 else if (expr_type == TypeManager.double_type)
779 ig.Emit (OpCodes.Ldc_R8, 1.0);
780 else if (expr_type == TypeManager.float_type)
781 ig.Emit (OpCodes.Ldc_R4, 1.0F);
782 else if (expr_type.IsPointer){
783 int n = PtrTypeSize (expr_type);
786 ig.Emit (OpCodes.Sizeof, expr_type);
788 IntConstant.EmitInt (ig, n);
790 ig.Emit (OpCodes.Ldc_I4_1);
792 if (mode == Mode.PostDecrement)
793 ig.Emit (OpCodes.Sub);
795 ig.Emit (OpCodes.Add);
800 temp_storage.Store (ec);
801 ia.EmitAssign (ec, temp_storage);
806 public override void Emit (EmitContext ec)
812 public override void EmitStatement (EmitContext ec)
814 EmitCode (ec, false);
820 /// Base class for the `Is' and `As' classes.
824 /// FIXME: Split this in two, and we get to save the `Operator' Oper
827 public abstract class Probe : Expression {
828 public readonly string ProbeType;
829 protected Expression expr;
830 protected Type probe_type;
831 protected Location loc;
833 public Probe (Expression expr, string probe_type, Location l)
835 ProbeType = probe_type;
840 public Expression Expr {
846 public override Expression DoResolve (EmitContext ec)
848 probe_type = RootContext.LookupType (ec.TypeContainer, ProbeType, false, loc);
850 if (probe_type == null)
853 expr = expr.Resolve (ec);
860 /// Implementation of the `is' operator.
862 public class Is : Probe {
863 public Is (Expression expr, string probe_type, Location l)
864 : base (expr, probe_type, l)
868 public override void Emit (EmitContext ec)
870 ILGenerator ig = ec.ig;
874 ig.Emit (OpCodes.Isinst, probe_type);
875 ig.Emit (OpCodes.Ldnull);
876 ig.Emit (OpCodes.Cgt_Un);
879 public override Expression DoResolve (EmitContext ec)
881 Expression e = base.DoResolve (ec);
886 if (RootContext.WarningLevel >= 1){
887 if (expr.Type == probe_type || expr.Type.IsSubclassOf (probe_type)){
890 "The expression is always of type `" +
891 TypeManager.CSharpName (probe_type) + "'");
894 if (expr.Type != probe_type && !probe_type.IsSubclassOf (expr.Type)){
895 if (!probe_type.IsInterface)
898 "The expression is never of type `" +
899 TypeManager.CSharpName (probe_type) + "'");
903 type = TypeManager.bool_type;
904 eclass = ExprClass.Value;
911 /// Implementation of the `as' operator.
913 public class As : Probe {
914 public As (Expression expr, string probe_type, Location l)
915 : base (expr, probe_type, l)
919 public override void Emit (EmitContext ec)
921 ILGenerator ig = ec.ig;
924 ig.Emit (OpCodes.Isinst, probe_type);
927 public override Expression DoResolve (EmitContext ec)
929 Expression e = base.DoResolve (ec);
935 eclass = ExprClass.Value;
942 /// This represents a typecast in the source language.
944 /// FIXME: Cast expressions have an unusual set of parsing
945 /// rules, we need to figure those out.
947 public class Cast : Expression {
948 Expression target_type;
952 public Cast (Expression cast_type, Expression expr, Location loc)
954 this.target_type = cast_type;
959 public Expression TargetType {
965 public Expression Expr {
975 /// Attempts to do a compile-time folding of a constant cast.
977 Expression TryReduce (EmitContext ec, Type target_type)
979 if (expr is ByteConstant){
980 byte v = ((ByteConstant) expr).Value;
982 if (target_type == TypeManager.sbyte_type)
983 return new SByteConstant ((sbyte) v);
984 if (target_type == TypeManager.short_type)
985 return new ShortConstant ((short) v);
986 if (target_type == TypeManager.ushort_type)
987 return new UShortConstant ((ushort) v);
988 if (target_type == TypeManager.int32_type)
989 return new IntConstant ((int) v);
990 if (target_type == TypeManager.uint32_type)
991 return new UIntConstant ((uint) v);
992 if (target_type == TypeManager.int64_type)
993 return new LongConstant ((long) v);
994 if (target_type == TypeManager.uint64_type)
995 return new ULongConstant ((ulong) v);
996 if (target_type == TypeManager.float_type)
997 return new FloatConstant ((float) v);
998 if (target_type == TypeManager.double_type)
999 return new DoubleConstant ((double) v);
1001 if (expr is SByteConstant){
1002 sbyte v = ((SByteConstant) expr).Value;
1004 if (target_type == TypeManager.byte_type)
1005 return new ByteConstant ((byte) v);
1006 if (target_type == TypeManager.short_type)
1007 return new ShortConstant ((short) v);
1008 if (target_type == TypeManager.ushort_type)
1009 return new UShortConstant ((ushort) v);
1010 if (target_type == TypeManager.int32_type)
1011 return new IntConstant ((int) v);
1012 if (target_type == TypeManager.uint32_type)
1013 return new UIntConstant ((uint) v);
1014 if (target_type == TypeManager.int64_type)
1015 return new LongConstant ((long) v);
1016 if (target_type == TypeManager.uint64_type)
1017 return new ULongConstant ((ulong) v);
1018 if (target_type == TypeManager.float_type)
1019 return new FloatConstant ((float) v);
1020 if (target_type == TypeManager.double_type)
1021 return new DoubleConstant ((double) v);
1023 if (expr is ShortConstant){
1024 short v = ((ShortConstant) expr).Value;
1026 if (target_type == TypeManager.byte_type)
1027 return new ByteConstant ((byte) v);
1028 if (target_type == TypeManager.sbyte_type)
1029 return new SByteConstant ((sbyte) 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 UShortConstant){
1046 ushort v = ((UShortConstant) expr).Value;
1048 if (target_type == TypeManager.byte_type)
1049 return new ByteConstant ((byte) v);
1050 if (target_type == TypeManager.sbyte_type)
1051 return new SByteConstant ((sbyte) v);
1052 if (target_type == TypeManager.short_type)
1053 return new ShortConstant ((short) 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 IntConstant){
1068 int v = ((IntConstant) 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.short_type)
1075 return new ShortConstant ((short) v);
1076 if (target_type == TypeManager.ushort_type)
1077 return new UShortConstant ((ushort) 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 UIntConstant){
1090 uint v = ((UIntConstant) 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.ushort_type)
1099 return new UShortConstant ((ushort) v);
1100 if (target_type == TypeManager.int32_type)
1101 return new IntConstant ((int) 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 LongConstant){
1112 long v = ((LongConstant) 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.int32_type)
1123 return new IntConstant ((int) v);
1124 if (target_type == TypeManager.uint32_type)
1125 return new UIntConstant ((uint) 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 ULongConstant){
1134 ulong v = ((ULongConstant) 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.uint32_type)
1147 return new UIntConstant ((uint) v);
1148 if (target_type == TypeManager.int64_type)
1149 return new LongConstant ((long) 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 FloatConstant){
1156 float v = ((FloatConstant) 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.int64_type)
1171 return new LongConstant ((long) v);
1172 if (target_type == TypeManager.uint64_type)
1173 return new ULongConstant ((ulong) v);
1174 if (target_type == TypeManager.double_type)
1175 return new DoubleConstant ((double) v);
1177 if (expr is DoubleConstant){
1178 double v = ((DoubleConstant) 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.uint64_type)
1195 return new ULongConstant ((ulong) v);
1196 if (target_type == TypeManager.float_type)
1197 return new FloatConstant ((float) v);
1203 public override Expression DoResolve (EmitContext ec)
1205 expr = expr.Resolve (ec);
1209 target_type = target_type.Resolve (ec);
1210 if (target_type == null)
1213 if (target_type.eclass != ExprClass.Type){
1214 report118 (loc, target_type, "class");
1218 type = target_type.Type;
1219 eclass = ExprClass.Value;
1224 if (expr is Constant){
1225 Expression e = TryReduce (ec, type);
1231 expr = ConvertExplicit (ec, expr, type, loc);
1235 public override void Emit (EmitContext ec)
1238 // This one will never happen
1240 throw new Exception ("Should not happen");
1245 /// Binary operators
1247 public class Binary : Expression {
1248 public enum Operator : byte {
1249 Multiply, Division, Modulus,
1250 Addition, Subtraction,
1251 LeftShift, RightShift,
1252 LessThan, GreaterThan, LessThanOrEqual, GreaterThanOrEqual,
1253 Equality, Inequality,
1262 Expression left, right;
1264 ArrayList Arguments;
1267 bool DelegateOperation;
1269 public Binary (Operator oper, Expression left, Expression right, Location loc)
1277 public Operator Oper {
1286 public Expression Left {
1295 public Expression Right {
1306 /// Returns a stringified representation of the Operator
1311 case Operator.Multiply:
1313 case Operator.Division:
1315 case Operator.Modulus:
1317 case Operator.Addition:
1319 case Operator.Subtraction:
1321 case Operator.LeftShift:
1323 case Operator.RightShift:
1325 case Operator.LessThan:
1327 case Operator.GreaterThan:
1329 case Operator.LessThanOrEqual:
1331 case Operator.GreaterThanOrEqual:
1333 case Operator.Equality:
1335 case Operator.Inequality:
1337 case Operator.BitwiseAnd:
1339 case Operator.BitwiseOr:
1341 case Operator.ExclusiveOr:
1343 case Operator.LogicalOr:
1345 case Operator.LogicalAnd:
1349 return oper.ToString ();
1352 Expression ForceConversion (EmitContext ec, Expression expr, Type target_type)
1354 if (expr.Type == target_type)
1357 return ConvertImplicit (ec, expr, target_type, new Location (-1));
1361 // Note that handling the case l == Decimal || r == Decimal
1362 // is taken care of by the Step 1 Operator Overload resolution.
1364 bool DoNumericPromotions (EmitContext ec, Type l, Type r)
1366 if (l == TypeManager.double_type || r == TypeManager.double_type){
1368 // If either operand is of type double, the other operand is
1369 // conveted to type double.
1371 if (r != TypeManager.double_type)
1372 right = ConvertImplicit (ec, right, TypeManager.double_type, loc);
1373 if (l != TypeManager.double_type)
1374 left = ConvertImplicit (ec, left, TypeManager.double_type, loc);
1376 type = TypeManager.double_type;
1377 } else if (l == TypeManager.float_type || r == TypeManager.float_type){
1379 // if either operand is of type float, th eother operand is
1380 // converd to type float.
1382 if (r != TypeManager.double_type)
1383 right = ConvertImplicit (ec, right, TypeManager.float_type, loc);
1384 if (l != TypeManager.double_type)
1385 left = ConvertImplicit (ec, left, TypeManager.float_type, loc);
1386 type = TypeManager.float_type;
1387 } else if (l == TypeManager.uint64_type || r == TypeManager.uint64_type){
1391 // If either operand is of type ulong, the other operand is
1392 // converted to type ulong. or an error ocurrs if the other
1393 // operand is of type sbyte, short, int or long
1395 if (l == TypeManager.uint64_type){
1396 if (r != TypeManager.uint64_type){
1397 if (right is IntConstant){
1398 IntConstant ic = (IntConstant) right;
1400 e = TryImplicitIntConversion (l, ic);
1403 } else if (right is LongConstant){
1404 long ll = ((LongConstant) right).Value;
1407 right = new ULongConstant ((ulong) ll);
1409 e = ImplicitNumericConversion (ec, right, l, loc);
1416 if (left is IntConstant){
1417 e = TryImplicitIntConversion (r, (IntConstant) left);
1420 } else if (left is LongConstant){
1421 long ll = ((LongConstant) left).Value;
1424 left = new ULongConstant ((ulong) ll);
1426 e = ImplicitNumericConversion (ec, left, r, loc);
1433 if ((other == TypeManager.sbyte_type) ||
1434 (other == TypeManager.short_type) ||
1435 (other == TypeManager.int32_type) ||
1436 (other == TypeManager.int64_type)){
1437 string oper = OperName ();
1439 Error (34, loc, "Operator `" + OperName ()
1440 + "' is ambiguous on operands of type `"
1441 + TypeManager.CSharpName (l) + "' "
1442 + "and `" + TypeManager.CSharpName (r)
1445 type = TypeManager.uint64_type;
1446 } else if (l == TypeManager.int64_type || r == TypeManager.int64_type){
1448 // If either operand is of type long, the other operand is converted
1451 if (l != TypeManager.int64_type)
1452 left = ConvertImplicit (ec, left, TypeManager.int64_type, loc);
1453 if (r != TypeManager.int64_type)
1454 right = ConvertImplicit (ec, right, TypeManager.int64_type, loc);
1456 type = TypeManager.int64_type;
1457 } else if (l == TypeManager.uint32_type || r == TypeManager.uint32_type){
1459 // If either operand is of type uint, and the other
1460 // operand is of type sbyte, short or int, othe operands are
1461 // converted to type long.
1465 if (l == TypeManager.uint32_type){
1466 if (right is IntConstant){
1467 IntConstant ic = (IntConstant) right;
1471 right = new UIntConstant ((uint) val);
1478 else if (r == TypeManager.uint32_type){
1479 if (left is IntConstant){
1480 IntConstant ic = (IntConstant) left;
1484 left = new UIntConstant ((uint) val);
1493 if ((other == TypeManager.sbyte_type) ||
1494 (other == TypeManager.short_type) ||
1495 (other == TypeManager.int32_type)){
1496 left = ForceConversion (ec, left, TypeManager.int64_type);
1497 right = ForceConversion (ec, right, TypeManager.int64_type);
1498 type = TypeManager.int64_type;
1501 // if either operand is of type uint, the other
1502 // operand is converd to type uint
1504 left = ForceConversion (ec, left, TypeManager.uint32_type);
1505 right = ForceConversion (ec, right, TypeManager.uint32_type);
1506 type = TypeManager.uint32_type;
1508 } else if (l == TypeManager.decimal_type || r == TypeManager.decimal_type){
1509 if (l != TypeManager.decimal_type)
1510 left = ConvertImplicit (ec, left, TypeManager.decimal_type, loc);
1511 if (r != TypeManager.decimal_type)
1512 right = ConvertImplicit (ec, right, TypeManager.decimal_type, loc);
1514 type = TypeManager.decimal_type;
1516 Expression l_tmp, r_tmp;
1518 l_tmp = ForceConversion (ec, left, TypeManager.int32_type);
1522 r_tmp = ForceConversion (ec, right, TypeManager.int32_type);
1529 type = TypeManager.int32_type;
1538 "Operator " + OperName () + " cannot be applied to operands of type `" +
1539 TypeManager.CSharpName (left.Type) + "' and `" +
1540 TypeManager.CSharpName (right.Type) + "'");
1544 static bool is_32_or_64 (Type t)
1546 return (t == TypeManager.int32_type || t == TypeManager.uint32_type ||
1547 t == TypeManager.int64_type || t == TypeManager.uint64_type);
1550 Expression CheckShiftArguments (EmitContext ec)
1554 Type r = right.Type;
1556 e = ForceConversion (ec, right, TypeManager.int32_type);
1563 if (((e = ConvertImplicit (ec, left, TypeManager.int32_type, loc)) != null) ||
1564 ((e = ConvertImplicit (ec, left, TypeManager.uint32_type, loc)) != null) ||
1565 ((e = ConvertImplicit (ec, left, TypeManager.int64_type, loc)) != null) ||
1566 ((e = ConvertImplicit (ec, left, TypeManager.uint64_type, loc)) != null)){
1576 Expression ResolveOperator (EmitContext ec)
1579 Type r = right.Type;
1582 // Step 1: Perform Operator Overload location
1584 Expression left_expr, right_expr;
1586 string op = "op_" + oper;
1588 MethodGroupExpr union;
1589 left_expr = MemberLookup (ec, l, op, MemberTypes.Method, AllBindingFlags, loc);
1591 right_expr = MemberLookup (
1592 ec, r, op, MemberTypes.Method, AllBindingFlags, loc);
1593 union = Invocation.MakeUnionSet (left_expr, right_expr);
1595 union = (MethodGroupExpr) left_expr;
1597 if (union != null) {
1598 Arguments = new ArrayList ();
1599 Arguments.Add (new Argument (left, Argument.AType.Expression));
1600 Arguments.Add (new Argument (right, Argument.AType.Expression));
1602 method = Invocation.OverloadResolve (ec, union, Arguments, loc);
1603 if (method != null) {
1604 MethodInfo mi = (MethodInfo) method;
1605 type = mi.ReturnType;
1614 // Step 2: Default operations on CLI native types.
1617 // Only perform numeric promotions on:
1618 // +, -, *, /, %, &, |, ^, ==, !=, <, >, <=, >=
1620 if (oper == Operator.Addition){
1622 // If any of the arguments is a string, cast to string
1624 if (l == TypeManager.string_type){
1626 if (r == TypeManager.void_type) {
1631 if (r == TypeManager.string_type){
1632 if (left is Constant && right is Constant){
1633 StringConstant ls = (StringConstant) left;
1634 StringConstant rs = (StringConstant) right;
1636 return new StringConstant (
1637 ls.Value + rs.Value);
1641 method = TypeManager.string_concat_string_string;
1644 method = TypeManager.string_concat_object_object;
1645 right = ConvertImplicit (ec, right,
1646 TypeManager.object_type, loc);
1648 type = TypeManager.string_type;
1650 Arguments = new ArrayList ();
1651 Arguments.Add (new Argument (left, Argument.AType.Expression));
1652 Arguments.Add (new Argument (right, Argument.AType.Expression));
1656 } else if (r == TypeManager.string_type){
1659 if (l == TypeManager.void_type) {
1664 method = TypeManager.string_concat_object_object;
1665 Arguments = new ArrayList ();
1666 Arguments.Add (new Argument (left, Argument.AType.Expression));
1667 Arguments.Add (new Argument (right, Argument.AType.Expression));
1669 left = ConvertImplicit (ec, left, TypeManager.object_type, loc);
1670 type = TypeManager.string_type;
1676 if (oper == Operator.Addition || oper == Operator.Subtraction) {
1677 if (l.IsSubclassOf (TypeManager.delegate_type) &&
1678 r.IsSubclassOf (TypeManager.delegate_type)) {
1680 Arguments = new ArrayList ();
1681 Arguments.Add (new Argument (left, Argument.AType.Expression));
1682 Arguments.Add (new Argument (right, Argument.AType.Expression));
1684 if (oper == Operator.Addition)
1685 method = TypeManager.delegate_combine_delegate_delegate;
1687 method = TypeManager.delegate_remove_delegate_delegate;
1689 DelegateOperation = true;
1695 // Pointer arithmetic:
1697 // T* operator + (T* x, int y);
1698 // T* operator + (T* x, uint y);
1699 // T* operator + (T* x, long y);
1700 // T* operator + (T* x, ulong y);
1702 // T* operator + (int y, T* x);
1703 // T* operator + (uint y, T *x);
1704 // T* operator + (long y, T *x);
1705 // T* operator + (ulong y, T *x);
1707 // T* operator - (T* x, int y);
1708 // T* operator - (T* x, uint y);
1709 // T* operator - (T* x, long y);
1710 // T* operator - (T* x, ulong y);
1712 // long operator - (T* x, T *y)
1715 if (r.IsPointer && oper == Operator.Subtraction){
1717 return new PointerArithmetic (
1718 false, left, right, TypeManager.int64_type);
1719 } else if (is_32_or_64 (r))
1720 return new PointerArithmetic (
1721 oper == Operator.Addition, left, right, l);
1722 } else if (r.IsPointer && is_32_or_64 (l) && oper == Operator.Addition)
1723 return new PointerArithmetic (
1724 true, right, left, r);
1728 // Enumeration operators
1730 bool lie = TypeManager.IsEnumType (l);
1731 bool rie = TypeManager.IsEnumType (r);
1736 temp = ConvertImplicit (ec, right, l, loc);
1740 temp = ConvertImplicit (ec, left, r, loc);
1747 if (oper == Operator.Equality || oper == Operator.Inequality ||
1748 oper == Operator.LessThanOrEqual || oper == Operator.LessThan ||
1749 oper == Operator.GreaterThanOrEqual || oper == Operator.GreaterThan){
1750 type = TypeManager.bool_type;
1754 if (oper == Operator.BitwiseAnd ||
1755 oper == Operator.BitwiseOr ||
1756 oper == Operator.ExclusiveOr){
1762 if (oper == Operator.LeftShift || oper == Operator.RightShift)
1763 return CheckShiftArguments (ec);
1765 if (oper == Operator.LogicalOr || oper == Operator.LogicalAnd){
1766 if (l != TypeManager.bool_type || r != TypeManager.bool_type){
1771 type = TypeManager.bool_type;
1775 if (oper == Operator.Equality || oper == Operator.Inequality){
1776 if (l == TypeManager.bool_type || r == TypeManager.bool_type){
1777 if (r != TypeManager.bool_type || l != TypeManager.bool_type){
1782 type = TypeManager.bool_type;
1787 // operator != (object a, object b)
1788 // operator == (object a, object b)
1790 // For this to be used, both arguments have to be reference-types.
1791 // Read the rationale on the spec (14.9.6)
1793 // Also, if at compile time we know that the classes do not inherit
1794 // one from the other, then we catch the error there.
1796 if (!(l.IsValueType || r.IsValueType)){
1797 type = TypeManager.bool_type;
1802 if (l.IsSubclassOf (r) || r.IsSubclassOf (l))
1806 // We are going to have to convert to an object to compare
1808 if (l != TypeManager.object_type)
1809 left = new EmptyCast (left, TypeManager.object_type);
1810 if (r != TypeManager.object_type)
1811 right = new EmptyCast (right, TypeManager.object_type);
1818 // Pointer comparison
1820 if (l.IsPointer && r.IsPointer){
1821 if (oper == Operator.Equality || oper == Operator.Inequality ||
1822 oper == Operator.LessThan || oper == Operator.LessThanOrEqual ||
1823 oper == Operator.GreaterThan || oper == Operator.GreaterThanOrEqual){
1824 type = TypeManager.bool_type;
1830 // We are dealing with numbers
1833 if (!DoNumericPromotions (ec, l, r)){
1838 if (left == null || right == null)
1842 // reload our cached types if required
1847 if (oper == Operator.BitwiseAnd ||
1848 oper == Operator.BitwiseOr ||
1849 oper == Operator.ExclusiveOr){
1851 if (!((l == TypeManager.int32_type) ||
1852 (l == TypeManager.uint32_type) ||
1853 (l == TypeManager.int64_type) ||
1854 (l == TypeManager.uint64_type)))
1862 if (oper == Operator.Equality ||
1863 oper == Operator.Inequality ||
1864 oper == Operator.LessThanOrEqual ||
1865 oper == Operator.LessThan ||
1866 oper == Operator.GreaterThanOrEqual ||
1867 oper == Operator.GreaterThan){
1868 type = TypeManager.bool_type;
1875 /// Constant expression reducer for binary operations
1877 public Expression ConstantFold (EmitContext ec)
1879 object l = ((Constant) left).GetValue ();
1880 object r = ((Constant) right).GetValue ();
1882 if (l is string && r is string)
1883 return new StringConstant ((string) l + (string) r);
1885 Type result_type = null;
1888 // Enumerator folding
1890 if (left.Type == right.Type && left is EnumConstant)
1891 result_type = left.Type;
1894 case Operator.BitwiseOr:
1895 if ((l is int) && (r is int)){
1897 int res = (int)l | (int)r;
1899 v = new IntConstant (res);
1900 if (result_type == null)
1903 return new EnumConstant (v, result_type);
1907 case Operator.BitwiseAnd:
1908 if ((l is int) && (r is int)){
1910 int res = (int)l & (int)r;
1912 v = new IntConstant (res);
1913 if (result_type == null)
1916 return new EnumConstant (v, result_type);
1924 public override Expression DoResolve (EmitContext ec)
1926 left = left.Resolve (ec);
1927 right = right.Resolve (ec);
1929 if (left == null || right == null)
1932 if (left.Type == null)
1933 throw new Exception (
1934 "Resolve returned non null, but did not set the type! (" +
1935 left + ") at Line: " + loc.Row);
1936 if (right.Type == null)
1937 throw new Exception (
1938 "Resolve returned non null, but did not set the type! (" +
1939 right + ") at Line: "+ loc.Row);
1941 eclass = ExprClass.Value;
1943 if (left is Constant && right is Constant){
1945 // This is temporary until we do the full folding
1947 Expression e = ConstantFold (ec);
1952 return ResolveOperator (ec);
1955 public bool IsBranchable ()
1957 if (oper == Operator.Equality ||
1958 oper == Operator.Inequality ||
1959 oper == Operator.LessThan ||
1960 oper == Operator.GreaterThan ||
1961 oper == Operator.LessThanOrEqual ||
1962 oper == Operator.GreaterThanOrEqual){
1969 /// This entry point is used by routines that might want
1970 /// to emit a brfalse/brtrue after an expression, and instead
1971 /// they could use a more compact notation.
1973 /// Typically the code would generate l.emit/r.emit, followed
1974 /// by the comparission and then a brtrue/brfalse. The comparissions
1975 /// are sometimes inneficient (there are not as complete as the branches
1976 /// look for the hacks in Emit using double ceqs).
1978 /// So for those cases we provide EmitBranchable that can emit the
1979 /// branch with the test
1981 public void EmitBranchable (EmitContext ec, int target)
1984 bool close_target = false;
1985 ILGenerator ig = ec.ig;
1988 // short-circuit operators
1990 if (oper == Operator.LogicalAnd){
1992 ig.Emit (OpCodes.Brfalse, target);
1994 ig.Emit (OpCodes.Brfalse, target);
1995 } else if (oper == Operator.LogicalOr){
1997 ig.Emit (OpCodes.Brtrue, target);
1999 ig.Emit (OpCodes.Brfalse, target);
2006 case Operator.Equality:
2008 opcode = OpCodes.Beq_S;
2010 opcode = OpCodes.Beq;
2013 case Operator.Inequality:
2015 opcode = OpCodes.Bne_Un_S;
2017 opcode = OpCodes.Bne_Un;
2020 case Operator.LessThan:
2022 opcode = OpCodes.Blt_S;
2024 opcode = OpCodes.Blt;
2027 case Operator.GreaterThan:
2029 opcode = OpCodes.Bgt_S;
2031 opcode = OpCodes.Bgt;
2034 case Operator.LessThanOrEqual:
2036 opcode = OpCodes.Ble_S;
2038 opcode = OpCodes.Ble;
2041 case Operator.GreaterThanOrEqual:
2043 opcode = OpCodes.Bge_S;
2045 opcode = OpCodes.Ble;
2049 throw new Exception ("EmitBranchable called on non-EmitBranchable operator: "
2050 + oper.ToString ());
2053 ig.Emit (opcode, target);
2056 public override void Emit (EmitContext ec)
2058 ILGenerator ig = ec.ig;
2060 Type r = right.Type;
2063 if (method != null) {
2065 // Note that operators are static anyway
2067 if (Arguments != null)
2068 Invocation.EmitArguments (ec, method, Arguments);
2070 if (method is MethodInfo)
2071 ig.Emit (OpCodes.Call, (MethodInfo) method);
2073 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
2075 if (DelegateOperation)
2076 ig.Emit (OpCodes.Castclass, type);
2082 // Handle short-circuit operators differently
2085 if (oper == Operator.LogicalAnd){
2086 Label load_zero = ig.DefineLabel ();
2087 Label end = ig.DefineLabel ();
2090 ig.Emit (OpCodes.Brfalse, load_zero);
2092 ig.Emit (OpCodes.Br, end);
2093 ig.MarkLabel (load_zero);
2094 ig.Emit (OpCodes.Ldc_I4_0);
2097 } else if (oper == Operator.LogicalOr){
2098 Label load_one = ig.DefineLabel ();
2099 Label end = ig.DefineLabel ();
2102 ig.Emit (OpCodes.Brtrue, load_one);
2104 ig.Emit (OpCodes.Br, end);
2105 ig.MarkLabel (load_one);
2106 ig.Emit (OpCodes.Ldc_I4_1);
2115 case Operator.Multiply:
2117 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
2118 opcode = OpCodes.Mul_Ovf;
2119 else if (l==TypeManager.uint32_type || l==TypeManager.uint64_type)
2120 opcode = OpCodes.Mul_Ovf_Un;
2122 opcode = OpCodes.Mul;
2124 opcode = OpCodes.Mul;
2128 case Operator.Division:
2129 if (l == TypeManager.uint32_type || l == TypeManager.uint64_type)
2130 opcode = OpCodes.Div_Un;
2132 opcode = OpCodes.Div;
2135 case Operator.Modulus:
2136 if (l == TypeManager.uint32_type || l == TypeManager.uint64_type)
2137 opcode = OpCodes.Rem_Un;
2139 opcode = OpCodes.Rem;
2142 case Operator.Addition:
2144 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
2145 opcode = OpCodes.Add_Ovf;
2146 else if (l==TypeManager.uint32_type || l==TypeManager.uint64_type)
2147 opcode = OpCodes.Add_Ovf_Un;
2149 opcode = OpCodes.Mul;
2151 opcode = OpCodes.Add;
2154 case Operator.Subtraction:
2156 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
2157 opcode = OpCodes.Sub_Ovf;
2158 else if (l==TypeManager.uint32_type || l==TypeManager.uint64_type)
2159 opcode = OpCodes.Sub_Ovf_Un;
2161 opcode = OpCodes.Sub;
2163 opcode = OpCodes.Sub;
2166 case Operator.RightShift:
2167 opcode = OpCodes.Shr;
2170 case Operator.LeftShift:
2171 opcode = OpCodes.Shl;
2174 case Operator.Equality:
2175 opcode = OpCodes.Ceq;
2178 case Operator.Inequality:
2179 ec.ig.Emit (OpCodes.Ceq);
2180 ec.ig.Emit (OpCodes.Ldc_I4_0);
2182 opcode = OpCodes.Ceq;
2185 case Operator.LessThan:
2186 opcode = OpCodes.Clt;
2189 case Operator.GreaterThan:
2190 opcode = OpCodes.Cgt;
2193 case Operator.LessThanOrEqual:
2194 ec.ig.Emit (OpCodes.Cgt);
2195 ec.ig.Emit (OpCodes.Ldc_I4_0);
2197 opcode = OpCodes.Ceq;
2200 case Operator.GreaterThanOrEqual:
2201 ec.ig.Emit (OpCodes.Clt);
2202 ec.ig.Emit (OpCodes.Ldc_I4_1);
2204 opcode = OpCodes.Sub;
2207 case Operator.BitwiseOr:
2208 opcode = OpCodes.Or;
2211 case Operator.BitwiseAnd:
2212 opcode = OpCodes.And;
2215 case Operator.ExclusiveOr:
2216 opcode = OpCodes.Xor;
2220 throw new Exception ("This should not happen: Operator = "
2221 + oper.ToString ());
2228 public class PointerArithmetic : Expression {
2229 Expression left, right;
2233 // We assume that `l' is always a pointer
2235 public PointerArithmetic (bool is_addition, Expression l, Expression r, Type t)
2238 eclass = ExprClass.Variable;
2241 is_add = is_addition;
2244 public override Expression DoResolve (EmitContext ec)
2247 // We are born fully resolved
2252 public override void Emit (EmitContext ec)
2254 Type op_type = left.Type;
2255 ILGenerator ig = ec.ig;
2256 int size = GetTypeSize (op_type.GetElementType ());
2258 if (right.Type.IsPointer){
2260 // handle (pointer - pointer)
2264 ig.Emit (OpCodes.Sub);
2268 ig.Emit (OpCodes.Sizeof, op_type);
2270 IntLiteral.EmitInt (ig, size);
2271 ig.Emit (OpCodes.Div);
2273 ig.Emit (OpCodes.Conv_I8);
2276 // handle + and - on (pointer op int)
2279 ig.Emit (OpCodes.Conv_I);
2283 ig.Emit (OpCodes.Sizeof, op_type);
2285 IntLiteral.EmitInt (ig, size);
2286 ig.Emit (OpCodes.Mul);
2289 ig.Emit (OpCodes.Add);
2291 ig.Emit (OpCodes.Sub);
2297 /// Implements the ternary conditiona operator (?:)
2299 public class Conditional : Expression {
2300 Expression expr, trueExpr, falseExpr;
2303 public Conditional (Expression expr, Expression trueExpr, Expression falseExpr, Location l)
2306 this.trueExpr = trueExpr;
2307 this.falseExpr = falseExpr;
2311 public Expression Expr {
2317 public Expression TrueExpr {
2323 public Expression FalseExpr {
2329 public override Expression DoResolve (EmitContext ec)
2331 expr = expr.Resolve (ec);
2333 if (expr.Type != TypeManager.bool_type)
2334 expr = Expression.ConvertImplicitRequired (
2335 ec, expr, TypeManager.bool_type, loc);
2337 trueExpr = trueExpr.Resolve (ec);
2338 falseExpr = falseExpr.Resolve (ec);
2340 if (expr == null || trueExpr == null || falseExpr == null)
2343 if (trueExpr.Type == falseExpr.Type)
2344 type = trueExpr.Type;
2349 // First, if an implicit conversion exists from trueExpr
2350 // to falseExpr, then the result type is of type falseExpr.Type
2352 conv = ConvertImplicit (ec, trueExpr, falseExpr.Type, loc);
2355 // Check if both can convert implicitl to each other's type
2357 if (ConvertImplicit (ec, falseExpr, trueExpr.Type, loc) != null){
2360 "Can not compute type of conditional expression " +
2361 "as `" + TypeManager.CSharpName (trueExpr.Type) +
2362 "' and `" + TypeManager.CSharpName (falseExpr.Type) +
2363 "' convert implicitly to each other");
2366 type = falseExpr.Type;
2368 } else if ((conv = ConvertImplicit(ec, falseExpr,trueExpr.Type,loc))!= null){
2369 type = trueExpr.Type;
2372 Error (173, loc, "The type of the conditional expression can " +
2373 "not be computed because there is no implicit conversion" +
2374 " from `" + TypeManager.CSharpName (trueExpr.Type) + "'" +
2375 " and `" + TypeManager.CSharpName (falseExpr.Type) + "'");
2380 if (expr is BoolConstant){
2381 BoolConstant bc = (BoolConstant) expr;
2389 eclass = ExprClass.Value;
2393 public override void Emit (EmitContext ec)
2395 ILGenerator ig = ec.ig;
2396 Label false_target = ig.DefineLabel ();
2397 Label end_target = ig.DefineLabel ();
2400 ig.Emit (OpCodes.Brfalse, false_target);
2402 ig.Emit (OpCodes.Br, end_target);
2403 ig.MarkLabel (false_target);
2404 falseExpr.Emit (ec);
2405 ig.MarkLabel (end_target);
2413 public class LocalVariableReference : Expression, IAssignMethod, IMemoryLocation {
2414 public readonly string Name;
2415 public readonly Block Block;
2417 VariableInfo variable_info;
2419 public LocalVariableReference (Block block, string name, Location l)
2424 eclass = ExprClass.Variable;
2427 public VariableInfo VariableInfo {
2429 if (variable_info == null)
2430 variable_info = Block.GetVariableInfo (Name);
2431 return variable_info;
2435 public override Expression DoResolve (EmitContext ec)
2437 VariableInfo vi = VariableInfo;
2439 if (Block.IsConstant (Name)) {
2440 Expression e = Block.GetConstantExpression (Name);
2446 type = vi.VariableType;
2450 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
2452 Expression e = DoResolve (ec);
2457 VariableInfo vi = VariableInfo;
2463 "cannot assign to `" + Name + "' because it is readonly");
2471 public override void Emit (EmitContext ec)
2473 VariableInfo vi = VariableInfo;
2474 ILGenerator ig = ec.ig;
2481 ig.Emit (OpCodes.Ldloc_0);
2485 ig.Emit (OpCodes.Ldloc_1);
2489 ig.Emit (OpCodes.Ldloc_2);
2493 ig.Emit (OpCodes.Ldloc_3);
2498 ig.Emit (OpCodes.Ldloc_S, (byte) idx);
2500 ig.Emit (OpCodes.Ldloc, idx);
2505 public static void Store (ILGenerator ig, int idx)
2509 ig.Emit (OpCodes.Stloc_0);
2513 ig.Emit (OpCodes.Stloc_1);
2517 ig.Emit (OpCodes.Stloc_2);
2521 ig.Emit (OpCodes.Stloc_3);
2526 ig.Emit (OpCodes.Stloc_S, (byte) idx);
2528 ig.Emit (OpCodes.Stloc, idx);
2533 public void EmitAssign (EmitContext ec, Expression source)
2535 ILGenerator ig = ec.ig;
2536 VariableInfo vi = VariableInfo;
2542 // Funny seems the code below generates optimal code for us, but
2543 // seems to take too long to generate what we need.
2544 // ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
2549 public void AddressOf (EmitContext ec)
2551 VariableInfo vi = VariableInfo;
2558 ec.ig.Emit (OpCodes.Ldloca_S, (byte) idx);
2560 ec.ig.Emit (OpCodes.Ldloca, idx);
2565 /// This represents a reference to a parameter in the intermediate
2568 public class ParameterReference : Expression, IAssignMethod, IMemoryLocation {
2574 public ParameterReference (Parameters pars, int idx, string name)
2579 eclass = ExprClass.Variable;
2583 // Notice that for ref/out parameters, the type exposed is not the
2584 // same type exposed externally.
2587 // externally we expose "int&"
2588 // here we expose "int".
2590 // We record this in "is_ref". This means that the type system can treat
2591 // the type as it is expected, but when we generate the code, we generate
2592 // the alternate kind of code.
2594 public override Expression DoResolve (EmitContext ec)
2596 type = pars.GetParameterInfo (ec.TypeContainer, idx, out is_ref);
2597 eclass = ExprClass.Variable;
2603 // This method is used by parameters that are references, that are
2604 // being passed as references: we only want to pass the pointer (that
2605 // is already stored in the parameter, not the address of the pointer,
2606 // and not the value of the variable).
2608 public void EmitLoad (EmitContext ec)
2610 ILGenerator ig = ec.ig;
2617 ig.Emit (OpCodes.Ldarg_S, (byte) arg_idx);
2619 ig.Emit (OpCodes.Ldarg, arg_idx);
2622 public override void Emit (EmitContext ec)
2624 ILGenerator ig = ec.ig;
2631 ig.Emit (OpCodes.Ldarg_S, (byte) arg_idx);
2633 ig.Emit (OpCodes.Ldarg, arg_idx);
2639 // If we are a reference, we loaded on the stack a pointer
2640 // Now lets load the real value
2642 LoadFromPtr (ig, type, true);
2645 public void EmitAssign (EmitContext ec, Expression source)
2647 ILGenerator ig = ec.ig;
2656 ig.Emit (OpCodes.Ldarg_S, (byte) arg_idx);
2658 ig.Emit (OpCodes.Ldarg, arg_idx);
2664 StoreFromPtr (ig, type);
2667 ig.Emit (OpCodes.Starg_S, (byte) arg_idx);
2669 ig.Emit (OpCodes.Starg, arg_idx);
2674 public void AddressOf (EmitContext ec)
2682 ec.ig.Emit (OpCodes.Ldarga_S, (byte) arg_idx);
2684 ec.ig.Emit (OpCodes.Ldarga, arg_idx);
2689 /// Used for arguments to New(), Invocation()
2691 public class Argument {
2692 public enum AType : byte {
2698 public readonly AType ArgType;
2699 public Expression expr;
2701 public Argument (Expression expr, AType type)
2704 this.ArgType = type;
2707 public Expression Expr {
2723 public Parameter.Modifier GetParameterModifier ()
2725 if (ArgType == AType.Ref || ArgType == AType.Out)
2726 return Parameter.Modifier.OUT;
2728 return Parameter.Modifier.NONE;
2731 public static string FullDesc (Argument a)
2733 return (a.ArgType == AType.Ref ? "ref " :
2734 (a.ArgType == AType.Out ? "out " : "")) +
2735 TypeManager.CSharpName (a.Expr.Type);
2738 public bool Resolve (EmitContext ec, Location loc)
2740 expr = expr.Resolve (ec);
2742 if (ArgType == AType.Expression)
2743 return expr != null;
2745 if (expr.eclass != ExprClass.Variable){
2747 // We just probe to match the CSC output
2749 if (expr.eclass == ExprClass.PropertyAccess ||
2750 expr.eclass == ExprClass.IndexerAccess){
2753 "A property or indexer can not be passed as an out or ref " +
2758 "An lvalue is required as an argument to out or ref");
2763 return expr != null;
2766 public void Emit (EmitContext ec)
2769 // Ref and Out parameters need to have their addresses taken.
2771 // ParameterReferences might already be references, so we want
2772 // to pass just the value
2774 if (ArgType == AType.Ref || ArgType == AType.Out){
2775 if (expr is ParameterReference){
2776 ParameterReference pr = (ParameterReference) expr;
2783 ((IMemoryLocation)expr).AddressOf (ec);
2790 /// Invocation of methods or delegates.
2792 public class Invocation : ExpressionStatement {
2793 public readonly ArrayList Arguments;
2797 MethodBase method = null;
2800 static Hashtable method_parameter_cache;
2802 static Invocation ()
2804 method_parameter_cache = new PtrHashtable ();
2808 // arguments is an ArrayList, but we do not want to typecast,
2809 // as it might be null.
2811 // FIXME: only allow expr to be a method invocation or a
2812 // delegate invocation (7.5.5)
2814 public Invocation (Expression expr, ArrayList arguments, Location l)
2817 Arguments = arguments;
2821 public Expression Expr {
2828 /// Returns the Parameters (a ParameterData interface) for the
2831 public static ParameterData GetParameterData (MethodBase mb)
2833 object pd = method_parameter_cache [mb];
2837 return (ParameterData) pd;
2840 ip = TypeManager.LookupParametersByBuilder (mb);
2842 method_parameter_cache [mb] = ip;
2844 return (ParameterData) ip;
2846 ParameterInfo [] pi = mb.GetParameters ();
2847 ReflectionParameters rp = new ReflectionParameters (pi);
2848 method_parameter_cache [mb] = rp;
2850 return (ParameterData) rp;
2855 /// Determines "better conversion" as specified in 7.4.2.3
2856 /// Returns : 1 if a->p is better
2857 /// 0 if a->q or neither is better
2859 static int BetterConversion (EmitContext ec, Argument a, Type p, Type q, Location loc)
2861 Type argument_type = a.Type;
2862 Expression argument_expr = a.Expr;
2864 if (argument_type == null)
2865 throw new Exception ("Expression of type " + a.Expr + " does not resolve its type");
2870 if (argument_type == p)
2873 if (argument_type == q)
2877 // Now probe whether an implicit constant expression conversion
2880 // An implicit constant expression conversion permits the following
2883 // * A constant-expression of type `int' can be converted to type
2884 // sbyte, byute, short, ushort, uint, ulong provided the value of
2885 // of the expression is withing the range of the destination type.
2887 // * A constant-expression of type long can be converted to type
2888 // ulong, provided the value of the constant expression is not negative
2890 // FIXME: Note that this assumes that constant folding has
2891 // taken place. We dont do constant folding yet.
2894 if (argument_expr is IntConstant){
2895 IntConstant ei = (IntConstant) argument_expr;
2896 int value = ei.Value;
2898 if (p == TypeManager.sbyte_type){
2899 if (value >= SByte.MinValue && value <= SByte.MaxValue)
2901 } else if (p == TypeManager.byte_type){
2902 if (Byte.MinValue >= 0 && value <= Byte.MaxValue)
2904 } else if (p == TypeManager.short_type){
2905 if (value >= Int16.MinValue && value <= Int16.MaxValue)
2907 } else if (p == TypeManager.ushort_type){
2908 if (value >= UInt16.MinValue && value <= UInt16.MaxValue)
2910 } else if (p == TypeManager.uint32_type){
2912 // we can optimize this case: a positive int32
2913 // always fits on a uint32
2917 } else if (p == TypeManager.uint64_type){
2919 // we can optimize this case: a positive int32
2920 // always fits on a uint64
2925 } else if (argument_type == TypeManager.int64_type && argument_expr is LongConstant){
2926 LongConstant lc = (LongConstant) argument_expr;
2928 if (p == TypeManager.uint64_type){
2935 Expression tmp = ConvertImplicitStandard (ec, argument_expr, p, loc);
2943 if (StandardConversionExists (p, q) == true &&
2944 StandardConversionExists (q, p) == false)
2947 if (p == TypeManager.sbyte_type)
2948 if (q == TypeManager.byte_type || q == TypeManager.ushort_type ||
2949 q == TypeManager.uint32_type || q == TypeManager.uint64_type)
2952 if (p == TypeManager.short_type)
2953 if (q == TypeManager.ushort_type || q == TypeManager.uint32_type ||
2954 q == TypeManager.uint64_type)
2957 if (p == TypeManager.int32_type)
2958 if (q == TypeManager.uint32_type || q == TypeManager.uint64_type)
2961 if (p == TypeManager.int64_type)
2962 if (q == TypeManager.uint64_type)
2969 /// Determines "Better function"
2972 /// and returns an integer indicating :
2973 /// 0 if candidate ain't better
2974 /// 1 if candidate is better than the current best match
2976 static int BetterFunction (EmitContext ec, ArrayList args,
2977 MethodBase candidate, MethodBase best,
2978 bool expanded_form, Location loc)
2980 ParameterData candidate_pd = GetParameterData (candidate);
2981 ParameterData best_pd;
2988 argument_count = args.Count;
2990 if (candidate_pd.Count == 0 && argument_count == 0)
2993 if (candidate_pd.ParameterModifier (candidate_pd.Count - 1) != Parameter.Modifier.PARAMS)
2994 if (candidate_pd.Count != argument_count)
2999 for (int j = argument_count; j > 0;) {
3002 Argument a = (Argument) args [j];
3003 Type t = candidate_pd.ParameterType (j);
3005 if (candidate_pd.ParameterModifier (j) == Parameter.Modifier.PARAMS)
3007 t = t.GetElementType ();
3009 x = BetterConversion (ec, a, t, null, loc);
3021 best_pd = GetParameterData (best);
3023 int rating1 = 0, rating2 = 0;
3025 for (int j = 0; j < argument_count; ++j) {
3028 Argument a = (Argument) args [j];
3030 Type ct = candidate_pd.ParameterType (j);
3031 Type bt = best_pd.ParameterType (j);
3033 if (candidate_pd.ParameterModifier (j) == Parameter.Modifier.PARAMS)
3035 ct = ct.GetElementType ();
3037 if (best_pd.ParameterModifier (j) == Parameter.Modifier.PARAMS)
3039 bt = bt.GetElementType ();
3041 x = BetterConversion (ec, a, ct, bt, loc);
3042 y = BetterConversion (ec, a, bt, ct, loc);
3051 if (rating1 > rating2)
3057 public static string FullMethodDesc (MethodBase mb)
3059 string ret_type = "";
3061 if (mb is MethodInfo)
3062 ret_type = TypeManager.CSharpName (((MethodInfo) mb).ReturnType);
3064 StringBuilder sb = new StringBuilder (ret_type + " " + mb.Name);
3065 ParameterData pd = GetParameterData (mb);
3067 int count = pd.Count;
3070 for (int i = count; i > 0; ) {
3073 sb.Append (pd.ParameterDesc (count - i - 1));
3079 return sb.ToString ();
3082 public static MethodGroupExpr MakeUnionSet (Expression mg1, Expression mg2)
3084 MemberInfo [] miset;
3085 MethodGroupExpr union;
3087 if (mg1 != null && mg2 != null) {
3089 MethodGroupExpr left_set = null, right_set = null;
3090 int length1 = 0, length2 = 0;
3092 left_set = (MethodGroupExpr) mg1;
3093 length1 = left_set.Methods.Length;
3095 right_set = (MethodGroupExpr) mg2;
3096 length2 = right_set.Methods.Length;
3098 ArrayList common = new ArrayList ();
3100 for (int i = 0; i < left_set.Methods.Length; i++) {
3101 for (int j = 0; j < right_set.Methods.Length; j++) {
3102 if (left_set.Methods [i] == right_set.Methods [j])
3103 common.Add (left_set.Methods [i]);
3107 miset = new MemberInfo [length1 + length2 - common.Count];
3109 left_set.Methods.CopyTo (miset, 0);
3113 for (int j = 0; j < right_set.Methods.Length; j++)
3114 if (!common.Contains (right_set.Methods [j]))
3115 miset [length1 + k++] = right_set.Methods [j];
3117 union = new MethodGroupExpr (miset);
3121 } else if (mg1 == null && mg2 != null) {
3123 MethodGroupExpr me = (MethodGroupExpr) mg2;
3125 miset = new MemberInfo [me.Methods.Length];
3126 me.Methods.CopyTo (miset, 0);
3128 union = new MethodGroupExpr (miset);
3132 } else if (mg2 == null && mg1 != null) {
3134 MethodGroupExpr me = (MethodGroupExpr) mg1;
3136 miset = new MemberInfo [me.Methods.Length];
3137 me.Methods.CopyTo (miset, 0);
3139 union = new MethodGroupExpr (miset);
3148 /// Determines is the candidate method, if a params method, is applicable
3149 /// in its expanded form to the given set of arguments
3151 static bool IsParamsMethodApplicable (ArrayList arguments, MethodBase candidate)
3155 if (arguments == null)
3158 arg_count = arguments.Count;
3160 ParameterData pd = GetParameterData (candidate);
3162 int pd_count = pd.Count;
3167 if (pd.ParameterModifier (pd_count - 1) != Parameter.Modifier.PARAMS)
3170 if (pd_count - 1 > arg_count)
3174 // If we have come this far, the case which remains is when the number of parameters
3175 // is less than or equal to the argument count.
3177 for (int i = 0; i < pd_count - 1; ++i) {
3179 Argument a = (Argument) arguments [i];
3181 Parameter.Modifier a_mod = a.GetParameterModifier ();
3182 Parameter.Modifier p_mod = pd.ParameterModifier (i);
3184 if (a_mod == p_mod) {
3186 if (a_mod == Parameter.Modifier.NONE)
3187 if (!StandardConversionExists (a.Type, pd.ParameterType (i)))
3190 if (a_mod == Parameter.Modifier.REF ||
3191 a_mod == Parameter.Modifier.OUT)
3192 if (pd.ParameterType (i) != a.Type)
3199 Type element_type = pd.ParameterType (pd_count - 1).GetElementType ();
3201 for (int i = pd_count - 1; i < arg_count; i++) {
3202 Argument a = (Argument) arguments [i];
3204 if (!StandardConversionExists (a.Type, element_type))
3212 /// Determines if the candidate method is applicable (section 14.4.2.1)
3213 /// to the given set of arguments
3215 static bool IsApplicable (ArrayList arguments, MethodBase candidate)
3219 if (arguments == null)
3222 arg_count = arguments.Count;
3224 ParameterData pd = GetParameterData (candidate);
3226 int pd_count = pd.Count;
3228 if (arg_count != pd.Count)
3231 for (int i = arg_count; i > 0; ) {
3234 Argument a = (Argument) arguments [i];
3236 Parameter.Modifier a_mod = a.GetParameterModifier ();
3237 Parameter.Modifier p_mod = pd.ParameterModifier (i);
3239 if (a_mod == p_mod) {
3241 if (a_mod == Parameter.Modifier.NONE)
3242 if (!StandardConversionExists (a.Type, pd.ParameterType (i)))
3245 if (a_mod == Parameter.Modifier.REF ||
3246 a_mod == Parameter.Modifier.OUT)
3247 if (pd.ParameterType (i) != a.Type)
3259 /// Find the Applicable Function Members (7.4.2.1)
3261 /// me: Method Group expression with the members to select.
3262 /// it might contain constructors or methods (or anything
3263 /// that maps to a method).
3265 /// Arguments: ArrayList containing resolved Argument objects.
3267 /// loc: The location if we want an error to be reported, or a Null
3268 /// location for "probing" purposes.
3270 /// Returns: The MethodBase (either a ConstructorInfo or a MethodInfo)
3271 /// that is the best match of me on Arguments.
3274 public static MethodBase OverloadResolve (EmitContext ec, MethodGroupExpr me,
3275 ArrayList Arguments, Location loc)
3277 ArrayList afm = new ArrayList ();
3278 int best_match_idx = -1;
3279 MethodBase method = null;
3281 ArrayList candidates = new ArrayList ();
3283 for (int i = me.Methods.Length; i > 0; ){
3285 MethodBase candidate = me.Methods [i];
3288 // Check if candidate is applicable (section 14.4.2.1)
3289 if (!IsApplicable (Arguments, candidate))
3292 candidates.Add (candidate);
3294 x = BetterFunction (ec, Arguments, candidate, method, false, loc);
3300 method = me.Methods [best_match_idx];
3304 if (Arguments == null)
3307 argument_count = Arguments.Count;
3310 // Now we see if we can find params functions, applicable in their expanded form
3311 // since if they were applicable in their normal form, they would have been selected
3314 bool chose_params_expanded = false;
3316 if (best_match_idx == -1) {
3318 candidates = new ArrayList ();
3319 for (int i = me.Methods.Length; i > 0; ) {
3321 MethodBase candidate = me.Methods [i];
3323 if (!IsParamsMethodApplicable (Arguments, candidate))
3326 candidates.Add (candidate);
3328 int x = BetterFunction (ec, Arguments, candidate, method, true, loc);
3334 method = me.Methods [best_match_idx];
3335 chose_params_expanded = true;
3341 // Now we see if we can at least find a method with the same number of arguments
3344 int method_count = 0;
3346 if (best_match_idx == -1) {
3348 for (int i = me.Methods.Length; i > 0;) {
3350 MethodBase mb = me.Methods [i];
3351 pd = GetParameterData (mb);
3353 if (pd.Count == argument_count) {
3355 method = me.Methods [best_match_idx];
3367 // Now check that there are no ambiguities i.e the selected method
3368 // should be better than all the others
3371 for (int i = 0; i < candidates.Count; ++i) {
3372 MethodBase candidate = (MethodBase) candidates [i];
3374 if (candidate == method)
3378 // If a normal method is applicable in the sense that it has the same
3379 // number of arguments, then the expanded params method is never applicable
3380 // so we debar the params method.
3382 //if (IsParamsMethodApplicable (Arguments, candidate) &&
3383 // IsApplicable (Arguments, method))
3386 int x = BetterFunction (ec, Arguments, method, candidate,
3387 chose_params_expanded, loc);
3390 //Console.WriteLine ("Candidate : " + FullMethodDesc (candidate));
3391 //Console.WriteLine ("Best : " + FullMethodDesc (method));
3394 "Ambiguous call when selecting function due to implicit casts");
3399 // And now convert implicitly, each argument to the required type
3401 pd = GetParameterData (method);
3402 int pd_count = pd.Count;
3404 for (int j = 0; j < argument_count; j++) {
3405 Argument a = (Argument) Arguments [j];
3406 Expression a_expr = a.Expr;
3407 Type parameter_type = pd.ParameterType (j);
3409 if (pd.ParameterModifier (j) == Parameter.Modifier.PARAMS && chose_params_expanded)
3410 parameter_type = parameter_type.GetElementType ();
3412 if (a.Type != parameter_type){
3415 conv = ConvertImplicitStandard (ec, a_expr, parameter_type, Location.Null);
3418 if (!Location.IsNull (loc)) {
3420 "The best overloaded match for method '" +
3421 FullMethodDesc (method) +
3422 "' has some invalid arguments");
3424 "Argument " + (j+1) +
3425 ": Cannot convert from '" + Argument.FullDesc (a)
3426 + "' to '" + pd.ParameterDesc (j) + "'");
3432 // Update the argument with the implicit conversion
3437 // FIXME : For the case of params methods, we need to actually instantiate
3438 // an array and initialize it with the argument values etc etc.
3442 if (a.GetParameterModifier () != pd.ParameterModifier (j) &&
3443 pd.ParameterModifier (pd_count - 1) != Parameter.Modifier.PARAMS) {
3444 if (!Location.IsNull (loc)) {
3445 Console.WriteLine ("A:P: " + a.GetParameterModifier ());
3446 Console.WriteLine ("PP:: " + pd.ParameterModifier (j));
3447 Console.WriteLine ("PT: " + parameter_type.IsByRef);
3449 "The best overloaded match for method '" + FullMethodDesc (method)+
3450 "' has some invalid arguments");
3452 "Argument " + (j+1) +
3453 ": Cannot convert from '" + Argument.FullDesc (a)
3454 + "' to '" + pd.ParameterDesc (j) + "'");
3463 public override Expression DoResolve (EmitContext ec)
3466 // First, resolve the expression that is used to
3467 // trigger the invocation
3469 if (expr is BaseAccess)
3472 expr = expr.Resolve (ec);
3476 if (!(expr is MethodGroupExpr)) {
3477 Type expr_type = expr.Type;
3479 if (expr_type != null){
3480 bool IsDelegate = TypeManager.IsDelegateType (expr_type);
3482 return (new DelegateInvocation (
3483 this.expr, Arguments, loc)).Resolve (ec);
3487 if (!(expr is MethodGroupExpr)){
3488 report118 (loc, this.expr, "method group");
3493 // Next, evaluate all the expressions in the argument list
3495 if (Arguments != null){
3496 for (int i = Arguments.Count; i > 0;){
3498 Argument a = (Argument) Arguments [i];
3500 if (!a.Resolve (ec, loc))
3505 method = OverloadResolve (ec, (MethodGroupExpr) this.expr, Arguments, loc);
3507 if (method == null){
3509 "Could not find any applicable function for this argument list");
3513 if (method is MethodInfo)
3514 type = ((MethodInfo)method).ReturnType;
3516 if (type.IsPointer){
3523 eclass = ExprClass.Value;
3528 // Emits the list of arguments as an array
3530 static void EmitParams (EmitContext ec, int idx, ArrayList arguments)
3532 ILGenerator ig = ec.ig;
3533 int count = arguments.Count - idx;
3534 Argument a = (Argument) arguments [idx];
3535 Type t = a.expr.Type;
3536 string array_type = t.FullName + "[]";
3539 array = ig.DeclareLocal (Type.GetType (array_type));
3540 IntConstant.EmitInt (ig, count);
3541 ig.Emit (OpCodes.Newarr, t);
3542 ig.Emit (OpCodes.Stloc, array);
3544 int top = arguments.Count;
3545 for (int j = idx; j < top; j++){
3546 a = (Argument) arguments [j];
3548 ig.Emit (OpCodes.Ldloc, array);
3549 IntConstant.EmitInt (ig, j - idx);
3552 ArrayAccess.EmitStoreOpcode (ig, t);
3554 ig.Emit (OpCodes.Ldloc, array);
3558 /// Emits a list of resolved Arguments that are in the arguments
3561 /// The MethodBase argument might be null if the
3562 /// emission of the arguments is known not to contain
3563 /// a `params' field (for example in constructors or other routines
3564 /// that keep their arguments in this structure
3566 public static void EmitArguments (EmitContext ec, MethodBase mb, ArrayList arguments)
3568 ParameterData pd = null;
3571 if (arguments != null)
3572 top = arguments.Count;
3577 pd = GetParameterData (mb);
3579 for (int i = 0; i < top; i++){
3580 Argument a = (Argument) arguments [i];
3583 if (pd.ParameterModifier (i) == Parameter.Modifier.PARAMS){
3584 EmitParams (ec, i, arguments);
3594 /// is_base tells whether we want to force the use of the `call'
3595 /// opcode instead of using callvirt. Call is required to call
3596 /// a specific method, while callvirt will always use the most
3597 /// recent method in the vtable.
3599 /// is_static tells whether this is an invocation on a static method
3601 /// instance_expr is an expression that represents the instance
3602 /// it must be non-null if is_static is false.
3604 /// method is the method to invoke.
3606 /// Arguments is the list of arguments to pass to the method or constructor.
3608 public static void EmitCall (EmitContext ec, bool is_base,
3609 bool is_static, Expression instance_expr,
3610 MethodBase method, ArrayList Arguments)
3612 ILGenerator ig = ec.ig;
3613 bool struct_call = false;
3617 if (method.DeclaringType.IsValueType)
3620 // If this is ourselves, push "this"
3622 if (instance_expr == null){
3623 ig.Emit (OpCodes.Ldarg_0);
3626 // Push the instance expression
3628 if (instance_expr.Type.IsSubclassOf (TypeManager.value_type)){
3630 // Special case: calls to a function declared in a
3631 // reference-type with a value-type argument need
3632 // to have their value boxed.
3635 if (method.DeclaringType.IsValueType){
3637 // If the expression implements IMemoryLocation, then
3638 // we can optimize and use AddressOf on the
3641 // If not we have to use some temporary storage for
3643 if (instance_expr is IMemoryLocation){
3644 ((IMemoryLocation)instance_expr).
3648 Type t = instance_expr.Type;
3650 instance_expr.Emit (ec);
3651 LocalBuilder temp = ig.DeclareLocal (t);
3652 ig.Emit (OpCodes.Stloc, temp);
3653 ig.Emit (OpCodes.Ldloca, temp);
3656 instance_expr.Emit (ec);
3657 ig.Emit (OpCodes.Box, instance_expr.Type);
3660 instance_expr.Emit (ec);
3664 if (Arguments != null)
3665 EmitArguments (ec, method, Arguments);
3667 if (is_static || struct_call || is_base){
3668 if (method is MethodInfo)
3669 ig.Emit (OpCodes.Call, (MethodInfo) method);
3671 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
3673 if (method is MethodInfo)
3674 ig.Emit (OpCodes.Callvirt, (MethodInfo) method);
3676 ig.Emit (OpCodes.Callvirt, (ConstructorInfo) method);
3680 public override void Emit (EmitContext ec)
3682 MethodGroupExpr mg = (MethodGroupExpr) this.expr;
3684 EmitCall (ec, is_base, method.IsStatic, mg.InstanceExpression, method, Arguments);
3687 public override void EmitStatement (EmitContext ec)
3692 // Pop the return value if there is one
3694 if (method is MethodInfo){
3695 if (((MethodInfo)method).ReturnType != TypeManager.void_type)
3696 ec.ig.Emit (OpCodes.Pop);
3702 /// Implements the new expression
3704 public class New : ExpressionStatement {
3705 public readonly ArrayList Arguments;
3706 public readonly string RequestedType;
3709 MethodBase method = null;
3712 // If set, the new expression is for a value_target, and
3713 // we will not leave anything on the stack.
3715 Expression value_target;
3717 public New (string requested_type, ArrayList arguments, Location l)
3719 RequestedType = requested_type;
3720 Arguments = arguments;
3724 public Expression ValueTypeVariable {
3726 return value_target;
3730 value_target = value;
3734 public override Expression DoResolve (EmitContext ec)
3736 type = RootContext.LookupType (ec.TypeContainer, RequestedType, false, loc);
3741 bool IsDelegate = TypeManager.IsDelegateType (type);
3744 return (new NewDelegate (type, Arguments, loc)).Resolve (ec);
3746 bool is_struct = false;
3747 is_struct = type.IsSubclassOf (TypeManager.value_type);
3748 eclass = ExprClass.Value;
3751 // SRE returns a match for .ctor () on structs (the object constructor),
3752 // so we have to manually ignore it.
3754 if (is_struct && Arguments == null)
3758 ml = MemberLookup (ec, type, ".ctor", MemberTypes.Constructor, AllBindingFlags, loc);
3760 if (! (ml is MethodGroupExpr)){
3762 report118 (loc, ml, "method group");
3768 if (Arguments != null){
3769 for (int i = Arguments.Count; i > 0;){
3771 Argument a = (Argument) Arguments [i];
3773 if (!a.Resolve (ec, loc))
3778 method = Invocation.OverloadResolve (ec, (MethodGroupExpr) ml,
3783 if (method == null && !is_struct) {
3785 "New invocation: Can not find a constructor for " +
3786 "this argument list");
3793 // This DoEmit can be invoked in two contexts:
3794 // * As a mechanism that will leave a value on the stack (new object)
3795 // * As one that wont (init struct)
3797 // You can control whether a value is required on the stack by passing
3798 // need_value_on_stack. The code *might* leave a value on the stack
3799 // so it must be popped manually
3801 // If we are dealing with a ValueType, we have a few
3802 // situations to deal with:
3804 // * The target is a ValueType, and we have been provided
3805 // the instance (this is easy, we are being assigned).
3807 // * The target of New is being passed as an argument,
3808 // to a boxing operation or a function that takes a
3811 // In this case, we need to create a temporary variable
3812 // that is the argument of New.
3814 // Returns whether a value is left on the stack
3816 bool DoEmit (EmitContext ec, bool need_value_on_stack)
3818 bool is_value_type = type.IsSubclassOf (TypeManager.value_type);
3819 ILGenerator ig = ec.ig;
3824 if (value_target == null)
3825 value_target = new LocalTemporary (ec, type);
3827 ml = (IMemoryLocation) value_target;
3832 Invocation.EmitArguments (ec, method, Arguments);
3836 ig.Emit (OpCodes.Initobj, type);
3838 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
3840 if (need_value_on_stack){
3841 value_target.Emit (ec);
3846 ig.Emit (OpCodes.Newobj, (ConstructorInfo) method);
3851 public override void Emit (EmitContext ec)
3856 public override void EmitStatement (EmitContext ec)
3858 if (DoEmit (ec, false))
3859 ec.ig.Emit (OpCodes.Pop);
3864 /// Represents an array creation expression.
3868 /// There are two possible scenarios here: one is an array creation
3869 /// expression that specifies the dimensions and optionally the
3870 /// initialization data and the other which does not need dimensions
3871 /// specified but where initialization data is mandatory.
3873 public class ArrayCreation : ExpressionStatement {
3874 string RequestedType;
3876 ArrayList Initializers;
3878 ArrayList Arguments;
3880 MethodBase method = null;
3881 Type array_element_type;
3882 bool IsOneDimensional = false;
3883 bool IsBuiltinType = false;
3884 bool ExpectInitializers = false;
3887 Type underlying_type;
3889 ArrayList ArrayData;
3894 // The number of array initializers that we can handle
3895 // via the InitializeArray method - through EmitStaticInitializers
3897 int num_automatic_initializers;
3899 public ArrayCreation (string requested_type, ArrayList exprs,
3900 string rank, ArrayList initializers, Location l)
3902 RequestedType = requested_type;
3904 Initializers = initializers;
3907 Arguments = new ArrayList ();
3909 foreach (Expression e in exprs)
3910 Arguments.Add (new Argument (e, Argument.AType.Expression));
3913 public ArrayCreation (string requested_type, string rank, ArrayList initializers, Location l)
3915 RequestedType = requested_type;
3916 Initializers = initializers;
3919 Rank = rank.Substring (0, rank.LastIndexOf ("["));
3921 string tmp = rank.Substring (rank.LastIndexOf ("["));
3923 dimensions = tmp.Length - 1;
3924 ExpectInitializers = true;
3927 public static string FormArrayType (string base_type, int idx_count, string rank)
3929 StringBuilder sb = new StringBuilder (base_type);
3934 for (int i = 1; i < idx_count; i++)
3939 return sb.ToString ();
3942 public static string FormElementType (string base_type, int idx_count, string rank)
3944 StringBuilder sb = new StringBuilder (base_type);
3947 for (int i = 1; i < idx_count; i++)
3954 string val = sb.ToString ();
3956 return val.Substring (0, val.LastIndexOf ("["));
3961 Report.Error (178, loc, "Incorrectly structured array initializer");
3964 public bool CheckIndices (EmitContext ec, ArrayList probe, int idx, bool specified_dims)
3966 if (specified_dims) {
3967 Argument a = (Argument) Arguments [idx];
3969 if (!a.Resolve (ec, loc))
3972 if (!(a.Expr is Constant)) {
3973 Report.Error (150, loc, "A constant value is expected");
3977 int value = (int) ((Constant) a.Expr).GetValue ();
3979 if (value != probe.Count) {
3984 Bounds [idx] = value;
3987 foreach (object o in probe) {
3988 if (o is ArrayList) {
3989 bool ret = CheckIndices (ec, (ArrayList) o, idx + 1, specified_dims);
3993 Expression tmp = (Expression) o;
3994 tmp = tmp.Resolve (ec);
3998 // Handle initialization from vars, fields etc.
4000 Expression conv = ConvertImplicitRequired (
4001 ec, tmp, underlying_type, loc);
4006 if (conv is StringConstant)
4007 ArrayData.Add (conv);
4008 else if (conv is Constant) {
4009 ArrayData.Add (conv);
4010 num_automatic_initializers++;
4012 ArrayData.Add (conv);
4019 public void UpdateIndices (EmitContext ec)
4022 for (ArrayList probe = Initializers; probe != null;) {
4023 if (probe.Count > 0 && probe [0] is ArrayList) {
4024 Expression e = new IntConstant (probe.Count);
4025 Arguments.Add (new Argument (e, Argument.AType.Expression));
4027 Bounds [i++] = probe.Count;
4029 probe = (ArrayList) probe [0];
4032 Expression e = new IntConstant (probe.Count);
4033 Arguments.Add (new Argument (e, Argument.AType.Expression));
4035 Bounds [i++] = probe.Count;
4042 public bool ValidateInitializers (EmitContext ec)
4044 if (Initializers == null) {
4045 if (ExpectInitializers)
4051 underlying_type = RootContext.LookupType (
4052 ec.TypeContainer, RequestedType, false, loc);
4055 // We use this to store all the date values in the order in which we
4056 // will need to store them in the byte blob later
4058 ArrayData = new ArrayList ();
4059 Bounds = new Hashtable ();
4063 if (Arguments != null) {
4064 ret = CheckIndices (ec, Initializers, 0, true);
4068 Arguments = new ArrayList ();
4070 ret = CheckIndices (ec, Initializers, 0, false);
4077 if (Arguments.Count != dimensions) {
4086 public override Expression DoResolve (EmitContext ec)
4091 // First step is to validate the initializers and fill
4092 // in any missing bits
4094 if (!ValidateInitializers (ec))
4097 if (Arguments == null)
4100 arg_count = Arguments.Count;
4101 for (int i = arg_count; i > 0;){
4103 Argument a = (Argument) Arguments [i];
4105 if (!a.Resolve (ec, loc))
4110 string array_type = FormArrayType (RequestedType, arg_count, Rank);
4111 string element_type = FormElementType (RequestedType, arg_count, Rank);
4113 type = RootContext.LookupType (ec.TypeContainer, array_type, false, loc);
4115 array_element_type = RootContext.LookupType (
4116 ec.TypeContainer, element_type, false, loc);
4121 if (arg_count == 1) {
4122 IsOneDimensional = true;
4123 eclass = ExprClass.Value;
4127 IsBuiltinType = TypeManager.IsBuiltinType (type);
4129 if (IsBuiltinType) {
4133 ml = MemberLookup (ec, type, ".ctor", MemberTypes.Constructor,
4134 AllBindingFlags, loc);
4136 if (!(ml is MethodGroupExpr)){
4137 report118 (loc, ml, "method group");
4142 Report.Error (-6, loc, "New invocation: Can not find a constructor for " +
4143 "this argument list");
4147 method = Invocation.OverloadResolve (ec, (MethodGroupExpr) ml, Arguments, loc);
4149 if (method == null) {
4150 Report.Error (-6, loc, "New invocation: Can not find a constructor for " +
4151 "this argument list");
4155 eclass = ExprClass.Value;
4160 ModuleBuilder mb = RootContext.ModuleBuilder;
4162 ArrayList args = new ArrayList ();
4163 if (Arguments != null){
4164 for (int i = arg_count; i > 0;){
4166 Argument a = (Argument) Arguments [i];
4172 Type [] arg_types = null;
4175 arg_types = new Type [args.Count];
4177 args.CopyTo (arg_types, 0);
4179 method = mb.GetArrayMethod (type, ".ctor", CallingConventions.HasThis, null,
4182 if (method == null) {
4183 Report.Error (-6, loc, "New invocation: Can not find a constructor for " +
4184 "this argument list");
4188 eclass = ExprClass.Value;
4194 public static byte [] MakeByteBlob (ArrayList ArrayData, Type underlying_type, Location loc)
4199 int count = ArrayData.Count;
4201 factor = GetTypeSize (underlying_type);
4205 data = new byte [(count * factor + 4) & ~3];
4208 for (int i = 0; i < count; ++i) {
4209 object v = ArrayData [i];
4211 if (v is EnumConstant)
4212 v = ((EnumConstant) v).Child;
4214 if (v is Constant && !(v is StringConstant))
4215 v = ((Constant) v).GetValue ();
4221 if (underlying_type == TypeManager.int64_type){
4222 if (!(v is Expression)){
4223 long val = (long) v;
4225 for (int j = 0; j < factor; ++j) {
4226 data [idx + j] = (byte) (val & 0xFF);
4230 } else if (underlying_type == TypeManager.uint64_type){
4231 if (!(v is Expression)){
4232 ulong val = (ulong) v;
4234 for (int j = 0; j < factor; ++j) {
4235 data [idx + j] = (byte) (val & 0xFF);
4239 } else if (underlying_type == TypeManager.float_type) {
4241 if (!(v is Expression)){
4242 float val = (float) v;
4244 byte *ptr = (byte *) &val;
4246 for (int j = 0; j < factor; ++j)
4247 data [idx + j] = (byte) ptr [j];
4250 } else if (underlying_type == TypeManager.double_type) {
4252 if (!(v is Expression)){
4253 double val = (double) v;
4255 byte *ptr = (byte *) &val;
4257 for (int j = 0; j < factor; ++j)
4258 data [idx + j] = (byte) ptr [j];
4261 } else if (underlying_type == TypeManager.char_type){
4263 if (!(v is Expression)){
4264 int val = (int) ((char) v);
4266 data [idx] = (byte) (val & 0xff);
4267 data [idx+1] = (byte) (val >> 8);
4269 } else if (underlying_type == TypeManager.short_type){
4270 if (!(v is Expression)){
4271 int val = (int) ((short) v);
4273 data [idx] = (byte) (val & 0xff);
4274 data [idx+1] = (byte) (val >> 8);
4276 } else if (underlying_type == TypeManager.ushort_type){
4277 if (!(v is Expression)){
4278 int val = (int) ((ushort) v);
4280 data [idx] = (byte) (val & 0xff);
4281 data [idx+1] = (byte) (val >> 8);
4283 } else if (underlying_type == TypeManager.int32_type) {
4284 if (!(v is Expression)){
4287 data [idx] = (byte) (val & 0xff);
4288 data [idx+1] = (byte) ((val >> 8) & 0xff);
4289 data [idx+2] = (byte) ((val >> 16) & 0xff);
4290 data [idx+3] = (byte) (val >> 24);
4292 } else if (underlying_type == TypeManager.uint32_type) {
4293 if (!(v is Expression)){
4294 uint val = (uint) v;
4296 data [idx] = (byte) (val & 0xff);
4297 data [idx+1] = (byte) ((val >> 8) & 0xff);
4298 data [idx+2] = (byte) ((val >> 16) & 0xff);
4299 data [idx+3] = (byte) (val >> 24);
4301 } else if (underlying_type == TypeManager.sbyte_type) {
4302 if (!(v is Expression)){
4303 sbyte val = (sbyte) v;
4304 data [idx] = (byte) val;
4306 } else if (underlying_type == TypeManager.byte_type) {
4307 if (!(v is Expression)){
4308 byte val = (byte) v;
4309 data [idx] = (byte) val;
4312 throw new Exception ("Unrecognized type in MakeByteBlob");
4321 // Emits the initializers for the array
4323 void EmitStaticInitializers (EmitContext ec, bool is_expression)
4326 // First, the static data
4329 ILGenerator ig = ec.ig;
4331 byte [] data = MakeByteBlob (ArrayData, underlying_type, loc);
4334 fb = RootContext.MakeStaticData (data);
4337 ig.Emit (OpCodes.Dup);
4338 ig.Emit (OpCodes.Ldtoken, fb);
4339 ig.Emit (OpCodes.Call,
4340 TypeManager.void_initializearray_array_fieldhandle);
4345 // Emits pieces of the array that can not be computed at compile
4346 // time (variables and string locations).
4348 // This always expect the top value on the stack to be the array
4350 void EmitDynamicInitializers (EmitContext ec, bool is_expression)
4352 ILGenerator ig = ec.ig;
4353 int dims = Bounds.Count;
4354 int [] current_pos = new int [dims];
4355 int top = ArrayData.Count;
4356 LocalBuilder temp = ig.DeclareLocal (type);
4358 ig.Emit (OpCodes.Stloc, temp);
4360 MethodInfo set = null;
4364 ModuleBuilder mb = null;
4365 mb = RootContext.ModuleBuilder;
4366 args = new Type [dims + 1];
4369 for (j = 0; j < dims; j++)
4370 args [j] = TypeManager.int32_type;
4372 args [j] = array_element_type;
4374 set = mb.GetArrayMethod (
4376 CallingConventions.HasThis | CallingConventions.Standard,
4377 TypeManager.void_type, args);
4380 for (int i = 0; i < top; i++){
4382 Expression e = null;
4384 if (ArrayData [i] is Expression)
4385 e = (Expression) ArrayData [i];
4389 // Basically we do this for string literals and
4390 // other non-literal expressions
4392 if (e is StringConstant || !(e is Constant) || num_automatic_initializers <= 2) {
4394 ig.Emit (OpCodes.Ldloc, temp);
4396 for (int idx = dims; idx > 0; ) {
4398 IntConstant.EmitInt (ig, current_pos [idx]);
4404 ArrayAccess.EmitStoreOpcode (ig, array_element_type);
4406 ig.Emit (OpCodes.Call, set);
4414 for (int j = 0; j < dims; j++){
4416 if (current_pos [j] < (int) Bounds [j])
4418 current_pos [j] = 0;
4423 ig.Emit (OpCodes.Ldloc, temp);
4426 void DoEmit (EmitContext ec, bool is_statement)
4428 ILGenerator ig = ec.ig;
4430 if (IsOneDimensional) {
4431 Invocation.EmitArguments (ec, null, Arguments);
4432 ig.Emit (OpCodes.Newarr, array_element_type);
4435 Invocation.EmitArguments (ec, null, Arguments);
4438 ig.Emit (OpCodes.Newobj, (ConstructorInfo) method);
4440 ig.Emit (OpCodes.Newobj, (MethodInfo) method);
4443 if (Initializers != null){
4445 // FIXME: Set this variable correctly.
4447 bool dynamic_initializers = true;
4449 if (underlying_type != TypeManager.string_type &&
4450 underlying_type != TypeManager.object_type) {
4451 if (num_automatic_initializers > 2)
4452 EmitStaticInitializers (ec, dynamic_initializers || !is_statement);
4455 if (dynamic_initializers)
4456 EmitDynamicInitializers (ec, !is_statement);
4460 public override void Emit (EmitContext ec)
4465 public override void EmitStatement (EmitContext ec)
4473 /// Represents the `this' construct
4475 public class This : Expression, IAssignMethod, IMemoryLocation {
4478 public This (Location loc)
4483 public override Expression DoResolve (EmitContext ec)
4485 eclass = ExprClass.Variable;
4486 type = ec.TypeContainer.TypeBuilder;
4489 Report.Error (26, loc,
4490 "Keyword this not valid in static code");
4497 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
4501 if (ec.TypeContainer is Class){
4502 Report.Error (1604, loc, "Cannot assign to `this'");
4509 public override void Emit (EmitContext ec)
4511 ec.ig.Emit (OpCodes.Ldarg_0);
4514 public void EmitAssign (EmitContext ec, Expression source)
4517 ec.ig.Emit (OpCodes.Starg, 0);
4520 public void AddressOf (EmitContext ec)
4522 ec.ig.Emit (OpCodes.Ldarg_0);
4525 // FIGURE OUT WHY LDARG_S does not work
4527 // consider: struct X { int val; int P { set { val = value; }}}
4529 // Yes, this looks very bad. Look at `NOTAS' for
4531 // ec.ig.Emit (OpCodes.Ldarga_S, (byte) 0);
4536 /// Implements the typeof operator
4538 public class TypeOf : Expression {
4539 public readonly string QueriedType;
4543 public TypeOf (string queried_type, Location l)
4545 QueriedType = queried_type;
4549 public override Expression DoResolve (EmitContext ec)
4551 typearg = RootContext.LookupType (
4552 ec.TypeContainer, QueriedType, false, loc);
4554 if (typearg == null)
4557 type = TypeManager.type_type;
4558 eclass = ExprClass.Type;
4562 public override void Emit (EmitContext ec)
4564 ec.ig.Emit (OpCodes.Ldtoken, typearg);
4565 ec.ig.Emit (OpCodes.Call, TypeManager.system_type_get_type_from_handle);
4570 /// Implements the sizeof expression
4572 public class SizeOf : Expression {
4573 public readonly string QueriedType;
4577 public SizeOf (string queried_type, Location l)
4579 this.QueriedType = queried_type;
4583 public override Expression DoResolve (EmitContext ec)
4585 type_queried = RootContext.LookupType (
4586 ec.TypeContainer, QueriedType, false, loc);
4587 if (type_queried == null)
4590 type = TypeManager.int32_type;
4591 eclass = ExprClass.Value;
4595 public override void Emit (EmitContext ec)
4597 int size = GetTypeSize (type_queried);
4600 ec.ig.Emit (OpCodes.Sizeof, type_queried);
4602 IntConstant.EmitInt (ec.ig, size);
4607 /// Implements the member access expression
4609 public class MemberAccess : Expression {
4610 public readonly string Identifier;
4612 Expression member_lookup;
4615 public MemberAccess (Expression expr, string id, Location l)
4622 public Expression Expr {
4628 static void error176 (Location loc, string name)
4630 Report.Error (176, loc, "Static member `" +
4631 name + "' cannot be accessed " +
4632 "with an instance reference, qualify with a " +
4633 "type name instead");
4636 static bool IdenticalNameAndTypeName (EmitContext ec, Expression left_original, Location loc)
4638 if (left_original == null)
4641 if (!(left_original is SimpleName))
4644 SimpleName sn = (SimpleName) left_original;
4646 Type t = RootContext.LookupType (ec.TypeContainer, sn.Name, true, loc);
4653 public static Expression ResolveMemberAccess (EmitContext ec, Expression member_lookup,
4654 Expression left, Location loc,
4655 Expression left_original)
4660 if (member_lookup is MethodGroupExpr){
4661 MethodGroupExpr mg = (MethodGroupExpr) member_lookup;
4666 if (left is TypeExpr){
4667 if (!mg.RemoveInstanceMethods ()){
4668 SimpleName.Error120 (loc, mg.Methods [0].Name);
4672 return member_lookup;
4676 // Instance.MethodGroup
4678 if (IdenticalNameAndTypeName (ec, left_original, loc)){
4679 if (mg.RemoveInstanceMethods ())
4680 return member_lookup;
4683 if (!mg.RemoveStaticMethods ()){
4684 error176 (loc, mg.Methods [0].Name);
4688 mg.InstanceExpression = left;
4689 return member_lookup;
4691 if (!mg.RemoveStaticMethods ()){
4692 if (IdenticalNameAndTypeName (ec, left_original, loc)){
4693 if (!mg.RemoveInstanceMethods ()){
4694 SimpleName.Error120 (loc, mg.Methods [0].Name);
4697 return member_lookup;
4700 error176 (loc, mg.Methods [0].Name);
4704 mg.InstanceExpression = left;
4706 return member_lookup;
4710 if (member_lookup is FieldExpr){
4711 FieldExpr fe = (FieldExpr) member_lookup;
4712 FieldInfo fi = fe.FieldInfo;
4714 if (fi is FieldBuilder) {
4715 Const c = TypeManager.LookupConstant ((FieldBuilder) fi);
4718 object o = c.LookupConstantValue (ec);
4719 object real_value = ((Constant) c.Expr).GetValue ();
4721 return Constantify (real_value, fi.FieldType);
4726 Type t = fi.FieldType;
4727 Type decl_type = fi.DeclaringType;
4730 if (fi is FieldBuilder)
4731 o = TypeManager.GetValue ((FieldBuilder) fi);
4733 o = fi.GetValue (fi);
4735 if (decl_type.IsSubclassOf (TypeManager.enum_type)) {
4736 Expression enum_member = MemberLookup (
4737 ec, decl_type, "value__", MemberTypes.Field,
4738 AllBindingFlags, loc);
4740 Enum en = TypeManager.LookupEnum (decl_type);
4744 c = Constantify (o, en.UnderlyingType);
4746 c = Constantify (o, enum_member.Type);
4748 return new EnumConstant (c, decl_type);
4751 Expression exp = Constantify (o, t);
4753 if (!(left is TypeExpr)) {
4754 error176 (loc, fe.FieldInfo.Name);
4761 if (fi.FieldType.IsPointer && !ec.InUnsafe){
4766 if (left is TypeExpr){
4767 // and refers to a type name or an
4768 if (!fe.FieldInfo.IsStatic){
4769 error176 (loc, fe.FieldInfo.Name);
4772 return member_lookup;
4774 if (fe.FieldInfo.IsStatic){
4775 if (IdenticalNameAndTypeName (ec, left_original, loc))
4776 return member_lookup;
4778 error176 (loc, fe.FieldInfo.Name);
4781 fe.InstanceExpression = left;
4787 if (member_lookup is PropertyExpr){
4788 PropertyExpr pe = (PropertyExpr) member_lookup;
4790 if (left is TypeExpr){
4792 SimpleName.Error120 (loc, pe.PropertyInfo.Name);
4798 if (IdenticalNameAndTypeName (ec, left_original, loc))
4799 return member_lookup;
4800 error176 (loc, pe.PropertyInfo.Name);
4803 pe.InstanceExpression = left;
4809 if (member_lookup is EventExpr) {
4811 EventExpr ee = (EventExpr) member_lookup;
4814 // If the event is local to this class, we transform ourselves into
4818 Expression ml = MemberLookup (
4819 ec, ec.TypeContainer.TypeBuilder,
4820 ee.EventInfo.Name, MemberTypes.Event, AllBindingFlags, loc);
4823 MemberInfo mi = ec.TypeContainer.GetFieldFromEvent ((EventExpr) ml);
4827 // If this happens, then we have an event with its own
4828 // accessors and private field etc so there's no need
4829 // to transform ourselves : we should instead flag an error
4831 Assign.error70 (ee.EventInfo, loc);
4835 ml = ExprClassFromMemberInfo (ec, mi, loc);
4838 Report.Error (-200, loc, "Internal error!!");
4841 return ResolveMemberAccess (ec, ml, left, loc, left_original);
4844 if (left is TypeExpr) {
4846 SimpleName.Error120 (loc, ee.EventInfo.Name);
4854 if (IdenticalNameAndTypeName (ec, left_original, loc))
4857 error176 (loc, ee.EventInfo.Name);
4861 ee.InstanceExpression = left;
4867 if (member_lookup is TypeExpr){
4868 member_lookup.Resolve (ec);
4869 return member_lookup;
4872 Console.WriteLine ("Left is: " + left);
4873 Report.Error (-100, loc, "Support for [" + member_lookup + "] is not present yet");
4874 Environment.Exit (0);
4878 public override Expression DoResolve (EmitContext ec)
4881 // We are the sole users of ResolveWithSimpleName (ie, the only
4882 // ones that can cope with it
4884 Expression original = expr;
4885 expr = expr.ResolveWithSimpleName (ec);
4890 if (expr is SimpleName){
4891 SimpleName child_expr = (SimpleName) expr;
4893 expr = new SimpleName (child_expr.Name + "." + Identifier, loc);
4895 return expr.ResolveWithSimpleName (ec);
4899 // TODO: I mailed Ravi about this, and apparently we can get rid
4900 // of this and put it in the right place.
4902 // Handle enums here when they are in transit.
4903 // Note that we cannot afford to hit MemberLookup in this case because
4904 // it will fail to find any members at all
4907 Type expr_type = expr.Type;
4908 if ((expr is TypeExpr) && (expr_type.IsSubclassOf (TypeManager.enum_type))){
4910 Enum en = TypeManager.LookupEnum (expr_type);
4913 object value = en.LookupEnumValue (ec, Identifier, loc);
4916 Constant c = Constantify (value, en.UnderlyingType);
4917 return new EnumConstant (c, expr_type);
4922 if (expr_type.IsPointer){
4923 Report.Error (23, loc,
4924 "The `.' operator can not be applied to pointer operands (" +
4925 TypeManager.CSharpName (expr_type) + ")");
4929 member_lookup = MemberLookup (ec, expr_type, Identifier, loc);
4931 if (member_lookup == null){
4932 Report.Error (117, loc, "`" + expr_type + "' does not contain a " +
4933 "definition for `" + Identifier + "'");
4938 return ResolveMemberAccess (ec, member_lookup, expr, loc, original);
4941 public override void Emit (EmitContext ec)
4943 throw new Exception ("Should not happen");
4948 /// Implements checked expressions
4950 public class CheckedExpr : Expression {
4952 public Expression Expr;
4954 public CheckedExpr (Expression e)
4959 public override Expression DoResolve (EmitContext ec)
4961 Expr = Expr.Resolve (ec);
4966 eclass = Expr.eclass;
4971 public override void Emit (EmitContext ec)
4973 bool last_check = ec.CheckState;
4975 ec.CheckState = true;
4977 ec.CheckState = last_check;
4983 /// Implements the unchecked expression
4985 public class UnCheckedExpr : Expression {
4987 public Expression Expr;
4989 public UnCheckedExpr (Expression e)
4994 public override Expression DoResolve (EmitContext ec)
4996 Expr = Expr.Resolve (ec);
5001 eclass = Expr.eclass;
5006 public override void Emit (EmitContext ec)
5008 bool last_check = ec.CheckState;
5010 ec.CheckState = false;
5012 ec.CheckState = last_check;
5018 /// An Element Access expression.
5020 /// During semantic analysis these are transformed into
5021 /// IndexerAccess or ArrayAccess
5023 public class ElementAccess : Expression {
5024 public ArrayList Arguments;
5025 public Expression Expr;
5026 public Location loc;
5028 public ElementAccess (Expression e, ArrayList e_list, Location l)
5037 Arguments = new ArrayList ();
5038 foreach (Expression tmp in e_list)
5039 Arguments.Add (new Argument (tmp, Argument.AType.Expression));
5043 bool CommonResolve (EmitContext ec)
5045 Expr = Expr.Resolve (ec);
5050 if (Arguments == null)
5053 for (int i = Arguments.Count; i > 0;){
5055 Argument a = (Argument) Arguments [i];
5057 if (!a.Resolve (ec, loc))
5064 Expression MakePointerAccess ()
5068 if (t == TypeManager.void_ptr_type){
5071 "The array index operation is not valid for void pointers");
5074 if (Arguments.Count != 1){
5077 "A pointer must be indexed by a single value");
5080 Expression p = new PointerArithmetic (true, Expr, ((Argument)Arguments [0]).Expr, t);
5081 return new Indirection (p);
5084 public override Expression DoResolve (EmitContext ec)
5086 if (!CommonResolve (ec))
5090 // We perform some simple tests, and then to "split" the emit and store
5091 // code we create an instance of a different class, and return that.
5093 // I am experimenting with this pattern.
5097 if (t.IsSubclassOf (TypeManager.array_type))
5098 return (new ArrayAccess (this)).Resolve (ec);
5099 else if (t.IsPointer)
5100 return MakePointerAccess ();
5102 return (new IndexerAccess (this)).Resolve (ec);
5105 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
5107 if (!CommonResolve (ec))
5111 if (t.IsSubclassOf (TypeManager.array_type))
5112 return (new ArrayAccess (this)).ResolveLValue (ec, right_side);
5113 else if (t.IsPointer)
5114 return MakePointerAccess ();
5116 return (new IndexerAccess (this)).ResolveLValue (ec, right_side);
5119 public override void Emit (EmitContext ec)
5121 throw new Exception ("Should never be reached");
5126 /// Implements array access
5128 public class ArrayAccess : Expression, IAssignMethod, IMemoryLocation {
5130 // Points to our "data" repository
5134 public ArrayAccess (ElementAccess ea_data)
5137 eclass = ExprClass.Variable;
5140 public override Expression DoResolve (EmitContext ec)
5142 if (ea.Expr.eclass != ExprClass.Variable) {
5143 report118 (ea.loc, ea.Expr, "variable");
5147 Type t = ea.Expr.Type;
5148 if (t.GetArrayRank () != ea.Arguments.Count){
5149 Report.Error (22, ea.loc,
5150 "Incorrect number of indexes for array " +
5151 " expected: " + t.GetArrayRank () + " got: " +
5152 ea.Arguments.Count);
5155 type = t.GetElementType ();
5156 if (type.IsPointer && !ec.InUnsafe){
5157 UnsafeError (ea.loc);
5161 eclass = ExprClass.Variable;
5167 /// Emits the right opcode to load an object of Type `t'
5168 /// from an array of T
5170 static public void EmitLoadOpcode (ILGenerator ig, Type type)
5172 if (type == TypeManager.byte_type || type == TypeManager.bool_type)
5173 ig.Emit (OpCodes.Ldelem_I1);
5174 else if (type == TypeManager.sbyte_type)
5175 ig.Emit (OpCodes.Ldelem_U1);
5176 else if (type == TypeManager.short_type)
5177 ig.Emit (OpCodes.Ldelem_I2);
5178 else if (type == TypeManager.ushort_type)
5179 ig.Emit (OpCodes.Ldelem_U2);
5180 else if (type == TypeManager.int32_type)
5181 ig.Emit (OpCodes.Ldelem_I4);
5182 else if (type == TypeManager.uint32_type)
5183 ig.Emit (OpCodes.Ldelem_U4);
5184 else if (type == TypeManager.uint64_type)
5185 ig.Emit (OpCodes.Ldelem_I8);
5186 else if (type == TypeManager.int64_type)
5187 ig.Emit (OpCodes.Ldelem_I8);
5188 else if (type == TypeManager.float_type)
5189 ig.Emit (OpCodes.Ldelem_R4);
5190 else if (type == TypeManager.double_type)
5191 ig.Emit (OpCodes.Ldelem_R8);
5192 else if (type == TypeManager.intptr_type)
5193 ig.Emit (OpCodes.Ldelem_I);
5194 else if (type.IsValueType){
5195 ig.Emit (OpCodes.Ldelema, type);
5196 ig.Emit (OpCodes.Ldobj, type);
5198 ig.Emit (OpCodes.Ldelem_Ref);
5202 /// Emits the right opcode to store an object of Type `t'
5203 /// from an array of T.
5205 static public void EmitStoreOpcode (ILGenerator ig, Type t)
5207 if (t == TypeManager.byte_type || t == TypeManager.sbyte_type ||
5208 t == TypeManager.bool_type)
5209 ig.Emit (OpCodes.Stelem_I1);
5210 else if (t == TypeManager.short_type || t == TypeManager.ushort_type || t == TypeManager.char_type)
5211 ig.Emit (OpCodes.Stelem_I2);
5212 else if (t == TypeManager.int32_type || t == TypeManager.uint32_type)
5213 ig.Emit (OpCodes.Stelem_I4);
5214 else if (t == TypeManager.int64_type || t == TypeManager.uint64_type)
5215 ig.Emit (OpCodes.Stelem_I8);
5216 else if (t == TypeManager.float_type)
5217 ig.Emit (OpCodes.Stelem_R4);
5218 else if (t == TypeManager.double_type)
5219 ig.Emit (OpCodes.Stelem_R8);
5220 else if (t == TypeManager.intptr_type)
5221 ig.Emit (OpCodes.Stelem_I);
5222 else if (t.IsValueType)
5223 ig.Emit (OpCodes.Stobj, t);
5225 ig.Emit (OpCodes.Stelem_Ref);
5228 MethodInfo FetchGetMethod ()
5230 ModuleBuilder mb = RootContext.ModuleBuilder;
5231 Type [] args = new Type [ea.Arguments.Count];
5236 foreach (Argument a in ea.Arguments)
5237 args [i++] = a.Type;
5239 get = mb.GetArrayMethod (
5240 ea.Expr.Type, "Get",
5241 CallingConventions.HasThis |
5242 CallingConventions.Standard,
5248 MethodInfo FetchAddressMethod ()
5250 ModuleBuilder mb = RootContext.ModuleBuilder;
5251 Type [] args = new Type [ea.Arguments.Count];
5253 string ptr_type_name;
5257 ptr_type_name = type.FullName + "&";
5258 ret_type = Type.GetType (ptr_type_name);
5261 // It is a type defined by the source code we are compiling
5263 if (ret_type == null){
5264 ret_type = mb.GetType (ptr_type_name);
5267 foreach (Argument a in ea.Arguments)
5268 args [i++] = a.Type;
5270 address = mb.GetArrayMethod (
5271 ea.Expr.Type, "Address",
5272 CallingConventions.HasThis |
5273 CallingConventions.Standard,
5279 public override void Emit (EmitContext ec)
5281 int rank = ea.Expr.Type.GetArrayRank ();
5282 ILGenerator ig = ec.ig;
5286 foreach (Argument a in ea.Arguments)
5290 EmitLoadOpcode (ig, type);
5294 method = FetchGetMethod ();
5295 ig.Emit (OpCodes.Call, method);
5299 public void EmitAssign (EmitContext ec, Expression source)
5301 int rank = ea.Expr.Type.GetArrayRank ();
5302 ILGenerator ig = ec.ig;
5306 foreach (Argument a in ea.Arguments)
5309 Type t = source.Type;
5312 // The stobj opcode used by value types will need
5313 // an address on the stack, not really an array/array
5317 if (t.IsValueType && !TypeManager.IsBuiltinType (t))
5318 ig.Emit (OpCodes.Ldelema, t);
5324 EmitStoreOpcode (ig, t);
5326 ModuleBuilder mb = RootContext.ModuleBuilder;
5327 Type [] args = new Type [ea.Arguments.Count + 1];
5332 foreach (Argument a in ea.Arguments)
5333 args [i++] = a.Type;
5337 set = mb.GetArrayMethod (
5338 ea.Expr.Type, "Set",
5339 CallingConventions.HasThis |
5340 CallingConventions.Standard,
5341 TypeManager.void_type, args);
5343 ig.Emit (OpCodes.Call, set);
5347 public void AddressOf (EmitContext ec)
5349 int rank = ea.Expr.Type.GetArrayRank ();
5350 ILGenerator ig = ec.ig;
5354 foreach (Argument a in ea.Arguments)
5358 ig.Emit (OpCodes.Ldelema, type);
5360 MethodInfo address = FetchAddressMethod ();
5361 ig.Emit (OpCodes.Call, address);
5368 public ArrayList getters, setters;
5369 static Hashtable map;
5373 map = new Hashtable ();
5376 Indexers (MemberInfo [] mi)
5378 foreach (PropertyInfo property in mi){
5379 MethodInfo get, set;
5381 get = property.GetGetMethod (true);
5383 if (getters == null)
5384 getters = new ArrayList ();
5389 set = property.GetSetMethod (true);
5391 if (setters == null)
5392 setters = new ArrayList ();
5398 static public Indexers GetIndexersForType (Type t, TypeManager tm, Location loc)
5400 Indexers ix = (Indexers) map [t];
5401 string p_name = TypeManager.IndexerPropertyName (t);
5406 MemberInfo [] mi = tm.FindMembers (
5407 t, MemberTypes.Property,
5408 BindingFlags.Public | BindingFlags.Instance,
5409 Type.FilterName, p_name);
5411 if (mi == null || mi.Length == 0){
5412 Report.Error (21, loc,
5413 "Type `" + TypeManager.CSharpName (t) + "' does not have " +
5414 "any indexers defined");
5418 ix = new Indexers (mi);
5426 /// Expressions that represent an indexer call.
5428 public class IndexerAccess : Expression, IAssignMethod {
5430 // Points to our "data" repository
5433 MethodInfo get, set;
5435 ArrayList set_arguments;
5437 public IndexerAccess (ElementAccess ea_data)
5440 eclass = ExprClass.Value;
5443 public override Expression DoResolve (EmitContext ec)
5445 Type indexer_type = ea.Expr.Type;
5448 // Step 1: Query for all `Item' *properties*. Notice
5449 // that the actual methods are pointed from here.
5451 // This is a group of properties, piles of them.
5454 ilist = Indexers.GetIndexersForType (
5455 indexer_type, RootContext.TypeManager, ea.loc);
5459 // Step 2: find the proper match
5461 if (ilist != null && ilist.getters != null && ilist.getters.Count > 0)
5462 get = (MethodInfo) Invocation.OverloadResolve (
5463 ec, new MethodGroupExpr (ilist.getters), ea.Arguments, ea.loc);
5466 Report.Error (154, ea.loc,
5467 "indexer can not be used in this context, because " +
5468 "it lacks a `get' accessor");
5472 type = get.ReturnType;
5473 if (type.IsPointer && !ec.InUnsafe){
5474 UnsafeError (ea.loc);
5478 eclass = ExprClass.IndexerAccess;
5482 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
5484 Type indexer_type = ea.Expr.Type;
5485 Type right_type = right_side.Type;
5488 ilist = Indexers.GetIndexersForType (
5489 indexer_type, RootContext.TypeManager, ea.loc);
5491 if (ilist != null && ilist.setters != null && ilist.setters.Count > 0){
5492 set_arguments = (ArrayList) ea.Arguments.Clone ();
5493 set_arguments.Add (new Argument (right_side, Argument.AType.Expression));
5495 set = (MethodInfo) Invocation.OverloadResolve (
5496 ec, new MethodGroupExpr (ilist.setters), set_arguments, ea.loc);
5500 Report.Error (200, ea.loc,
5501 "indexer X.this [" + TypeManager.CSharpName (right_type) +
5502 "] lacks a `set' accessor");
5506 type = TypeManager.void_type;
5507 eclass = ExprClass.IndexerAccess;
5511 public override void Emit (EmitContext ec)
5513 Invocation.EmitCall (ec, false, false, ea.Expr, get, ea.Arguments);
5517 // source is ignored, because we already have a copy of it from the
5518 // LValue resolution and we have already constructed a pre-cached
5519 // version of the arguments (ea.set_arguments);
5521 public void EmitAssign (EmitContext ec, Expression source)
5523 Invocation.EmitCall (ec, false, false, ea.Expr, set, set_arguments);
5528 /// The base operator for method names
5530 public class BaseAccess : Expression {
5534 public BaseAccess (string member, Location l)
5536 this.member = member;
5540 public override Expression DoResolve (EmitContext ec)
5542 Expression member_lookup;
5543 Type current_type = ec.TypeContainer.TypeBuilder;
5544 Type base_type = current_type.BaseType;
5548 Report.Error (1511, loc,
5549 "Keyword base is not allowed in static method");
5553 member_lookup = MemberLookup (ec, base_type, member, loc);
5554 if (member_lookup == null)
5560 left = new TypeExpr (base_type);
5564 e = MemberAccess.ResolveMemberAccess (ec, member_lookup, left, loc, null);
5565 if (e is PropertyExpr){
5566 PropertyExpr pe = (PropertyExpr) e;
5574 public override void Emit (EmitContext ec)
5576 throw new Exception ("Should never be called");
5581 /// The base indexer operator
5583 public class BaseIndexerAccess : Expression {
5584 ArrayList Arguments;
5587 public BaseIndexerAccess (ArrayList args, Location l)
5593 public override Expression DoResolve (EmitContext ec)
5595 Type current_type = ec.TypeContainer.TypeBuilder;
5596 Type base_type = current_type.BaseType;
5597 Expression member_lookup;
5600 Report.Error (1511, loc,
5601 "Keyword base is not allowed in static method");
5605 member_lookup = MemberLookup (ec, base_type, "get_Item", MemberTypes.Method, AllBindingFlags, loc);
5606 if (member_lookup == null)
5609 return MemberAccess.ResolveMemberAccess (ec, member_lookup, ec.This, loc, null);
5612 public override void Emit (EmitContext ec)
5614 throw new Exception ("Should never be called");
5619 /// This class exists solely to pass the Type around and to be a dummy
5620 /// that can be passed to the conversion functions (this is used by
5621 /// foreach implementation to typecast the object return value from
5622 /// get_Current into the proper type. All code has been generated and
5623 /// we only care about the side effect conversions to be performed
5625 public class EmptyExpression : Expression {
5626 public EmptyExpression ()
5628 type = TypeManager.object_type;
5629 eclass = ExprClass.Value;
5632 public EmptyExpression (Type t)
5635 eclass = ExprClass.Value;
5638 public override Expression DoResolve (EmitContext ec)
5643 public override void Emit (EmitContext ec)
5645 // nothing, as we only exist to not do anything.
5649 // This is just because we might want to reuse this bad boy
5650 // instead of creating gazillions of EmptyExpressions.
5651 // (CanConvertImplicit uses it)
5653 public void SetType (Type t)
5659 public class UserCast : Expression {
5663 public UserCast (MethodInfo method, Expression source)
5665 this.method = method;
5666 this.source = source;
5667 type = method.ReturnType;
5668 eclass = ExprClass.Value;
5671 public override Expression DoResolve (EmitContext ec)
5674 // We are born fully resolved
5679 public override void Emit (EmitContext ec)
5681 ILGenerator ig = ec.ig;
5685 if (method is MethodInfo)
5686 ig.Emit (OpCodes.Call, (MethodInfo) method);
5688 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
5694 // This class is used to "construct" the type during a typecast
5695 // operation. Since the Type.GetType class in .NET can parse
5696 // the type specification, we just use this to construct the type
5697 // one bit at a time.
5699 public class ComposedCast : Expression {
5704 public ComposedCast (Expression left, string dim, Location l)
5711 public override Expression DoResolve (EmitContext ec)
5713 left = left.Resolve (ec);
5717 if (left.eclass != ExprClass.Type){
5718 report118 (loc, left, "type");
5722 type = RootContext.LookupType (
5723 ec.TypeContainer, left.Type.FullName + dim, false, loc);
5727 if (!ec.InUnsafe && type.IsPointer){
5732 eclass = ExprClass.Type;
5736 public override void Emit (EmitContext ec)
5738 throw new Exception ("This should never be called");
5743 // This class is used to represent the address of an array, used
5744 // only by the Fixed statement, this is like the C "&a [0]" construct.
5746 public class ArrayPtr : Expression {
5749 public ArrayPtr (Expression array)
5751 Type array_type = array.Type.GetElementType ();
5755 string array_ptr_type_name = array_type.FullName + "*";
5757 type = Type.GetType (array_ptr_type_name);
5759 ModuleBuilder mb = RootContext.ModuleBuilder;
5761 type = mb.GetType (array_ptr_type_name);
5764 eclass = ExprClass.Value;
5767 public override void Emit (EmitContext ec)
5769 ILGenerator ig = ec.ig;
5772 IntLiteral.EmitInt (ig, 0);
5773 ig.Emit (OpCodes.Ldelema, array.Type.GetElementType ());
5776 public override Expression DoResolve (EmitContext ec)
5779 // We are born fully resolved
5786 // Used by the fixed statement
5788 public class StringPtr : Expression {
5791 public StringPtr (LocalBuilder b)
5794 eclass = ExprClass.Value;
5795 type = TypeManager.char_ptr_type;
5798 public override Expression DoResolve (EmitContext ec)
5800 // This should never be invoked, we are born in fully
5801 // initialized state.
5806 public override void Emit (EmitContext ec)
5808 ILGenerator ig = ec.ig;
5810 ig.Emit (OpCodes.Ldloc, b);
5811 ig.Emit (OpCodes.Conv_I);
5812 ig.Emit (OpCodes.Call, TypeManager.int_get_offset_to_string_data);
5813 ig.Emit (OpCodes.Add);
5818 // Implements the `stackalloc' keyword
5820 public class StackAlloc : Expression {
5826 public StackAlloc (string type, Expression count, Location l)
5833 public override Expression DoResolve (EmitContext ec)
5835 count = count.Resolve (ec);
5839 if (count.Type != TypeManager.int32_type){
5840 count = ConvertImplicitRequired (ec, count, TypeManager.int32_type, loc);
5845 if (ec.InCatch || ec.InFinally){
5846 Report.Error (255, loc,
5847 "stackalloc can not be used in a catch or finally block");
5851 otype = RootContext.LookupType (ec.TypeContainer, t, false, loc);
5856 if (!TypeManager.VerifyUnManaged (otype, loc))
5859 string ptr_name = otype.FullName + "*";
5860 type = Type.GetType (ptr_name);
5862 ModuleBuilder mb = RootContext.ModuleBuilder;
5864 type = mb.GetType (ptr_name);
5866 eclass = ExprClass.Value;
5871 public override void Emit (EmitContext ec)
5873 int size = GetTypeSize (otype);
5874 ILGenerator ig = ec.ig;
5877 ig.Emit (OpCodes.Sizeof, otype);
5879 IntConstant.EmitInt (ig, size);
5881 ig.Emit (OpCodes.Mul);
5882 ig.Emit (OpCodes.Localloc);