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, loc);
268 if (mg == null && expr_type.BaseType != null)
269 mg = MemberLookup (ec, expr_type.BaseType, op_name, loc);
272 Expression e = StaticCallExpr.MakeSimpleCall (
273 ec, (MethodGroupExpr) mg, expr, loc);
283 // Only perform numeric promotions on:
286 if (expr_type == null)
290 // Step 2: Default operations on CLI native types.
292 if (expr is Constant)
293 return Reduce (ec, expr);
295 if (oper == Operator.LogicalNot){
296 if (expr_type != TypeManager.bool_type) {
301 type = TypeManager.bool_type;
305 if (oper == Operator.OnesComplement) {
306 if (!((expr_type == TypeManager.int32_type) ||
307 (expr_type == TypeManager.uint32_type) ||
308 (expr_type == TypeManager.int64_type) ||
309 (expr_type == TypeManager.uint64_type) ||
310 (expr_type.IsSubclassOf (TypeManager.enum_type)))){
318 if (oper == Operator.UnaryPlus) {
320 // A plus in front of something is just a no-op, so return the child.
326 // Deals with -literals
327 // int operator- (int x)
328 // long operator- (long x)
329 // float operator- (float f)
330 // double operator- (double d)
331 // decimal operator- (decimal d)
333 if (oper == Operator.UnaryNegation){
337 // perform numeric promotions to int,
341 // The following is inneficient, because we call
342 // ConvertImplicit too many times.
344 // It is also not clear if we should convert to Float
345 // or Double initially.
347 if (expr_type == TypeManager.uint32_type){
349 // FIXME: handle exception to this rule that
350 // permits the int value -2147483648 (-2^31) to
351 // bt wrote as a decimal interger literal
353 type = TypeManager.int64_type;
354 expr = ConvertImplicit (ec, expr, type, loc);
358 if (expr_type == TypeManager.uint64_type){
360 // FIXME: Handle exception of `long value'
361 // -92233720368547758087 (-2^63) to be wrote as
362 // decimal integer literal.
368 if (expr_type == TypeManager.float_type){
373 e = ConvertImplicit (ec, expr, TypeManager.int32_type, loc);
380 e = ConvertImplicit (ec, expr, TypeManager.int64_type, loc);
387 e = ConvertImplicit (ec, expr, TypeManager.double_type, loc);
398 if (oper == Operator.AddressOf){
399 if (expr.eclass != ExprClass.Variable){
400 Error (211, loc, "Cannot take the address of non-variables");
405 Error (214, loc, "Pointers may only be used in an unsafe context");
409 type = Type.GetType (expr.Type.ToString () + "*");
414 Error (187, loc, "No such operator '" + OperName () + "' defined for type '" +
415 TypeManager.CSharpName (expr_type) + "'");
419 public override Expression DoResolve (EmitContext ec)
421 expr = expr.Resolve (ec);
426 eclass = ExprClass.Value;
427 return ResolveOperator (ec);
430 public override void Emit (EmitContext ec)
432 ILGenerator ig = ec.ig;
433 Type expr_type = expr.Type;
436 case Operator.UnaryPlus:
437 throw new Exception ("This should be caught by Resolve");
439 case Operator.UnaryNegation:
441 ig.Emit (OpCodes.Neg);
444 case Operator.LogicalNot:
446 ig.Emit (OpCodes.Ldc_I4_0);
447 ig.Emit (OpCodes.Ceq);
450 case Operator.OnesComplement:
452 ig.Emit (OpCodes.Not);
455 case Operator.AddressOf:
456 ((IMemoryLocation)expr).AddressOf (ec);
459 case Operator.Indirection:
460 throw new Exception ("Not implemented yet");
463 throw new Exception ("This should not happen: Operator = "
469 /// This will emit the child expression for `ec' avoiding the logical
470 /// not. The parent will take care of changing brfalse/brtrue
472 public void EmitLogicalNot (EmitContext ec)
474 if (oper != Operator.LogicalNot)
475 throw new Exception ("EmitLogicalNot can only be called with !expr");
483 /// Unary Mutator expressions (pre and post ++ and --)
487 /// UnaryMutator implements ++ and -- expressions. It derives from
488 /// ExpressionStatement becuase the pre/post increment/decrement
489 /// operators can be used in a statement context.
491 /// FIXME: Idea, we could split this up in two classes, one simpler
492 /// for the common case, and one with the extra fields for more complex
493 /// classes (indexers require temporary access; overloaded require method)
495 /// Maybe we should have classes PreIncrement, PostIncrement, PreDecrement,
496 /// PostDecrement, that way we could save the `Mode' byte as well.
498 public class UnaryMutator : ExpressionStatement {
499 public enum Mode : byte {
500 PreIncrement, PreDecrement, PostIncrement, PostDecrement
506 LocalTemporary temp_storage;
509 // This is expensive for the simplest case.
513 public UnaryMutator (Mode m, Expression e, Location l)
522 return (mode == Mode.PreIncrement || mode == Mode.PostIncrement) ?
526 void error23 (Type t)
529 23, loc, "Operator " + OperName () +
530 " cannot be applied to operand of type `" +
531 TypeManager.CSharpName (t) + "'");
535 /// Returns whether an object of type `t' can be incremented
536 /// or decremented with add/sub (ie, basically whether we can
537 /// use pre-post incr-decr operations on it, but it is not a
538 /// System.Decimal, which we require operator overloading to catch)
540 static bool IsIncrementableNumber (Type t)
542 return (t == TypeManager.sbyte_type) ||
543 (t == TypeManager.byte_type) ||
544 (t == TypeManager.short_type) ||
545 (t == TypeManager.ushort_type) ||
546 (t == TypeManager.int32_type) ||
547 (t == TypeManager.uint32_type) ||
548 (t == TypeManager.int64_type) ||
549 (t == TypeManager.uint64_type) ||
550 (t == TypeManager.char_type) ||
551 (t.IsSubclassOf (TypeManager.enum_type)) ||
552 (t == TypeManager.float_type) ||
553 (t == TypeManager.double_type);
556 Expression ResolveOperator (EmitContext ec)
558 Type expr_type = expr.Type;
561 // Step 1: Perform Operator Overload location
566 if (mode == Mode.PreIncrement || mode == Mode.PostIncrement)
567 op_name = "op_Increment";
569 op_name = "op_Decrement";
571 mg = MemberLookup (ec, expr_type, op_name, loc);
573 if (mg == null && expr_type.BaseType != null)
574 mg = MemberLookup (ec, expr_type.BaseType, op_name, loc);
577 method = StaticCallExpr.MakeSimpleCall (
578 ec, (MethodGroupExpr) mg, expr, loc);
585 // The operand of the prefix/postfix increment decrement operators
586 // should be an expression that is classified as a variable,
587 // a property access or an indexer access
590 if (expr.eclass == ExprClass.Variable){
591 if (IsIncrementableNumber (expr_type) ||
592 expr_type == TypeManager.decimal_type){
595 } else if (expr.eclass == ExprClass.IndexerAccess){
596 IndexerAccess ia = (IndexerAccess) expr;
598 temp_storage = new LocalTemporary (ec, expr.Type);
600 expr = ia.ResolveLValue (ec, temp_storage);
605 } else if (expr.eclass == ExprClass.PropertyAccess){
606 PropertyExpr pe = (PropertyExpr) expr;
608 if (pe.VerifyAssignable ())
613 report118 (loc, expr, "variable, indexer or property access");
617 Error (187, loc, "No such operator '" + OperName () + "' defined for type '" +
618 TypeManager.CSharpName (expr_type) + "'");
622 public override Expression DoResolve (EmitContext ec)
624 expr = expr.Resolve (ec);
629 eclass = ExprClass.Value;
630 return ResolveOperator (ec);
635 // FIXME: We need some way of avoiding the use of temp_storage
636 // for some types of storage (parameters, local variables,
637 // static fields) and single-dimension array access.
639 void EmitCode (EmitContext ec, bool is_expr)
641 ILGenerator ig = ec.ig;
642 IAssignMethod ia = (IAssignMethod) expr;
643 Type expr_type = expr.Type;
645 if (temp_storage == null)
646 temp_storage = new LocalTemporary (ec, expr_type);
649 case Mode.PreIncrement:
650 case Mode.PreDecrement:
654 if (expr_type == TypeManager.uint64_type ||
655 expr_type == TypeManager.int64_type)
656 ig.Emit (OpCodes.Ldc_I8, 1L);
657 else if (expr_type == TypeManager.double_type)
658 ig.Emit (OpCodes.Ldc_R8, 1.0);
659 else if (expr_type == TypeManager.float_type)
660 ig.Emit (OpCodes.Ldc_R4, 1.0F);
662 ig.Emit (OpCodes.Ldc_I4_1);
664 if (mode == Mode.PreDecrement)
665 ig.Emit (OpCodes.Sub);
667 ig.Emit (OpCodes.Add);
671 temp_storage.Store (ec);
672 ia.EmitAssign (ec, temp_storage);
674 temp_storage.Emit (ec);
677 case Mode.PostIncrement:
678 case Mode.PostDecrement:
686 ig.Emit (OpCodes.Dup);
688 if (expr_type == TypeManager.uint64_type ||
689 expr_type == TypeManager.int64_type)
690 ig.Emit (OpCodes.Ldc_I8, 1L);
691 else if (expr_type == TypeManager.double_type)
692 ig.Emit (OpCodes.Ldc_R8, 1.0);
693 else if (expr_type == TypeManager.float_type)
694 ig.Emit (OpCodes.Ldc_R4, 1.0F);
696 ig.Emit (OpCodes.Ldc_I4_1);
698 if (mode == Mode.PostDecrement)
699 ig.Emit (OpCodes.Sub);
701 ig.Emit (OpCodes.Add);
706 temp_storage.Store (ec);
707 ia.EmitAssign (ec, temp_storage);
712 public override void Emit (EmitContext ec)
718 public override void EmitStatement (EmitContext ec)
720 EmitCode (ec, false);
726 /// Base class for the `Is' and `As' classes.
730 /// FIXME: Split this in two, and we get to save the `Operator' Oper
733 public abstract class Probe : Expression {
734 public readonly string ProbeType;
735 protected Expression expr;
736 protected Type probe_type;
739 public Probe (Expression expr, string probe_type, Location l)
741 ProbeType = probe_type;
746 public Expression Expr {
752 public override Expression DoResolve (EmitContext ec)
754 probe_type = RootContext.LookupType (ec.TypeContainer, ProbeType, false, loc);
756 if (probe_type == null)
759 expr = expr.Resolve (ec);
766 /// Implementation of the `is' operator.
768 public class Is : Probe {
769 public Is (Expression expr, string probe_type, Location l)
770 : base (expr, probe_type, l)
774 public override void Emit (EmitContext ec)
776 ILGenerator ig = ec.ig;
780 ig.Emit (OpCodes.Isinst, probe_type);
781 ig.Emit (OpCodes.Ldnull);
782 ig.Emit (OpCodes.Cgt_Un);
785 public override Expression DoResolve (EmitContext ec)
787 Expression e = base.DoResolve (ec);
792 type = TypeManager.bool_type;
793 eclass = ExprClass.Value;
800 /// Implementation of the `as' operator.
802 public class As : Probe {
803 public As (Expression expr, string probe_type, Location l)
804 : base (expr, probe_type, l)
808 public override void Emit (EmitContext ec)
810 ILGenerator ig = ec.ig;
813 ig.Emit (OpCodes.Isinst, probe_type);
816 public override Expression DoResolve (EmitContext ec)
818 Expression e = base.DoResolve (ec);
824 eclass = ExprClass.Value;
831 /// This represents a typecast in the source language.
833 /// FIXME: Cast expressions have an unusual set of parsing
834 /// rules, we need to figure those out.
836 public class Cast : Expression {
837 Expression target_type;
841 public Cast (Expression cast_type, Expression expr, Location loc)
843 this.target_type = cast_type;
848 public Expression TargetType {
854 public Expression Expr {
864 /// Attempts to do a compile-time folding of a constant cast.
866 Expression TryReduce (EmitContext ec, Type target_type)
868 if (expr is ByteConstant){
869 byte v = ((ByteConstant) expr).Value;
871 if (target_type == TypeManager.sbyte_type)
872 return new SByteConstant ((sbyte) v);
873 if (target_type == TypeManager.short_type)
874 return new ShortConstant ((short) v);
875 if (target_type == TypeManager.ushort_type)
876 return new UShortConstant ((ushort) v);
877 if (target_type == TypeManager.int32_type)
878 return new IntConstant ((int) v);
879 if (target_type == TypeManager.uint32_type)
880 return new UIntConstant ((uint) v);
881 if (target_type == TypeManager.int64_type)
882 return new LongConstant ((long) v);
883 if (target_type == TypeManager.uint64_type)
884 return new ULongConstant ((ulong) v);
885 if (target_type == TypeManager.float_type)
886 return new FloatConstant ((float) v);
887 if (target_type == TypeManager.double_type)
888 return new DoubleConstant ((double) v);
890 if (expr is SByteConstant){
891 sbyte v = ((SByteConstant) expr).Value;
893 if (target_type == TypeManager.byte_type)
894 return new ByteConstant ((byte) v);
895 if (target_type == TypeManager.short_type)
896 return new ShortConstant ((short) v);
897 if (target_type == TypeManager.ushort_type)
898 return new UShortConstant ((ushort) v);
899 if (target_type == TypeManager.int32_type)
900 return new IntConstant ((int) v);
901 if (target_type == TypeManager.uint32_type)
902 return new UIntConstant ((uint) v);
903 if (target_type == TypeManager.int64_type)
904 return new LongConstant ((long) v);
905 if (target_type == TypeManager.uint64_type)
906 return new ULongConstant ((ulong) v);
907 if (target_type == TypeManager.float_type)
908 return new FloatConstant ((float) v);
909 if (target_type == TypeManager.double_type)
910 return new DoubleConstant ((double) v);
912 if (expr is ShortConstant){
913 short v = ((ShortConstant) expr).Value;
915 if (target_type == TypeManager.byte_type)
916 return new ByteConstant ((byte) v);
917 if (target_type == TypeManager.sbyte_type)
918 return new SByteConstant ((sbyte) v);
919 if (target_type == TypeManager.ushort_type)
920 return new UShortConstant ((ushort) v);
921 if (target_type == TypeManager.int32_type)
922 return new IntConstant ((int) v);
923 if (target_type == TypeManager.uint32_type)
924 return new UIntConstant ((uint) v);
925 if (target_type == TypeManager.int64_type)
926 return new LongConstant ((long) v);
927 if (target_type == TypeManager.uint64_type)
928 return new ULongConstant ((ulong) v);
929 if (target_type == TypeManager.float_type)
930 return new FloatConstant ((float) v);
931 if (target_type == TypeManager.double_type)
932 return new DoubleConstant ((double) v);
934 if (expr is UShortConstant){
935 ushort v = ((UShortConstant) expr).Value;
937 if (target_type == TypeManager.byte_type)
938 return new ByteConstant ((byte) v);
939 if (target_type == TypeManager.sbyte_type)
940 return new SByteConstant ((sbyte) v);
941 if (target_type == TypeManager.short_type)
942 return new ShortConstant ((short) v);
943 if (target_type == TypeManager.int32_type)
944 return new IntConstant ((int) v);
945 if (target_type == TypeManager.uint32_type)
946 return new UIntConstant ((uint) v);
947 if (target_type == TypeManager.int64_type)
948 return new LongConstant ((long) v);
949 if (target_type == TypeManager.uint64_type)
950 return new ULongConstant ((ulong) v);
951 if (target_type == TypeManager.float_type)
952 return new FloatConstant ((float) v);
953 if (target_type == TypeManager.double_type)
954 return new DoubleConstant ((double) v);
956 if (expr is IntConstant){
957 int v = ((IntConstant) expr).Value;
959 if (target_type == TypeManager.byte_type)
960 return new ByteConstant ((byte) v);
961 if (target_type == TypeManager.sbyte_type)
962 return new SByteConstant ((sbyte) v);
963 if (target_type == TypeManager.short_type)
964 return new ShortConstant ((short) v);
965 if (target_type == TypeManager.ushort_type)
966 return new UShortConstant ((ushort) v);
967 if (target_type == TypeManager.uint32_type)
968 return new UIntConstant ((uint) v);
969 if (target_type == TypeManager.int64_type)
970 return new LongConstant ((long) v);
971 if (target_type == TypeManager.uint64_type)
972 return new ULongConstant ((ulong) v);
973 if (target_type == TypeManager.float_type)
974 return new FloatConstant ((float) v);
975 if (target_type == TypeManager.double_type)
976 return new DoubleConstant ((double) v);
978 if (expr is UIntConstant){
979 uint v = ((UIntConstant) expr).Value;
981 if (target_type == TypeManager.byte_type)
982 return new ByteConstant ((byte) v);
983 if (target_type == TypeManager.sbyte_type)
984 return new SByteConstant ((sbyte) v);
985 if (target_type == TypeManager.short_type)
986 return new ShortConstant ((short) v);
987 if (target_type == TypeManager.ushort_type)
988 return new UShortConstant ((ushort) v);
989 if (target_type == TypeManager.int32_type)
990 return new IntConstant ((int) v);
991 if (target_type == TypeManager.int64_type)
992 return new LongConstant ((long) v);
993 if (target_type == TypeManager.uint64_type)
994 return new ULongConstant ((ulong) v);
995 if (target_type == TypeManager.float_type)
996 return new FloatConstant ((float) v);
997 if (target_type == TypeManager.double_type)
998 return new DoubleConstant ((double) v);
1000 if (expr is LongConstant){
1001 long v = ((LongConstant) expr).Value;
1003 if (target_type == TypeManager.byte_type)
1004 return new ByteConstant ((byte) v);
1005 if (target_type == TypeManager.sbyte_type)
1006 return new SByteConstant ((sbyte) v);
1007 if (target_type == TypeManager.short_type)
1008 return new ShortConstant ((short) v);
1009 if (target_type == TypeManager.ushort_type)
1010 return new UShortConstant ((ushort) v);
1011 if (target_type == TypeManager.int32_type)
1012 return new IntConstant ((int) v);
1013 if (target_type == TypeManager.uint32_type)
1014 return new UIntConstant ((uint) v);
1015 if (target_type == TypeManager.uint64_type)
1016 return new ULongConstant ((ulong) v);
1017 if (target_type == TypeManager.float_type)
1018 return new FloatConstant ((float) v);
1019 if (target_type == TypeManager.double_type)
1020 return new DoubleConstant ((double) v);
1022 if (expr is ULongConstant){
1023 ulong v = ((ULongConstant) expr).Value;
1025 if (target_type == TypeManager.byte_type)
1026 return new ByteConstant ((byte) v);
1027 if (target_type == TypeManager.sbyte_type)
1028 return new SByteConstant ((sbyte) v);
1029 if (target_type == TypeManager.short_type)
1030 return new ShortConstant ((short) v);
1031 if (target_type == TypeManager.ushort_type)
1032 return new UShortConstant ((ushort) v);
1033 if (target_type == TypeManager.int32_type)
1034 return new IntConstant ((int) v);
1035 if (target_type == TypeManager.uint32_type)
1036 return new UIntConstant ((uint) v);
1037 if (target_type == TypeManager.int64_type)
1038 return new LongConstant ((long) v);
1039 if (target_type == TypeManager.float_type)
1040 return new FloatConstant ((float) v);
1041 if (target_type == TypeManager.double_type)
1042 return new DoubleConstant ((double) v);
1044 if (expr is FloatConstant){
1045 float v = ((FloatConstant) expr).Value;
1047 if (target_type == TypeManager.byte_type)
1048 return new ByteConstant ((byte) v);
1049 if (target_type == TypeManager.sbyte_type)
1050 return new SByteConstant ((sbyte) v);
1051 if (target_type == TypeManager.short_type)
1052 return new ShortConstant ((short) v);
1053 if (target_type == TypeManager.ushort_type)
1054 return new UShortConstant ((ushort) v);
1055 if (target_type == TypeManager.int32_type)
1056 return new IntConstant ((int) v);
1057 if (target_type == TypeManager.uint32_type)
1058 return new UIntConstant ((uint) v);
1059 if (target_type == TypeManager.int64_type)
1060 return new LongConstant ((long) v);
1061 if (target_type == TypeManager.uint64_type)
1062 return new ULongConstant ((ulong) v);
1063 if (target_type == TypeManager.double_type)
1064 return new DoubleConstant ((double) v);
1066 if (expr is DoubleConstant){
1067 double v = ((DoubleConstant) expr).Value;
1069 if (target_type == TypeManager.byte_type)
1070 return new ByteConstant ((byte) v);
1071 if (target_type == TypeManager.sbyte_type)
1072 return new SByteConstant ((sbyte) v);
1073 if (target_type == TypeManager.short_type)
1074 return new ShortConstant ((short) v);
1075 if (target_type == TypeManager.ushort_type)
1076 return new UShortConstant ((ushort) v);
1077 if (target_type == TypeManager.int32_type)
1078 return new IntConstant ((int) v);
1079 if (target_type == TypeManager.uint32_type)
1080 return new UIntConstant ((uint) v);
1081 if (target_type == TypeManager.int64_type)
1082 return new LongConstant ((long) v);
1083 if (target_type == TypeManager.uint64_type)
1084 return new ULongConstant ((ulong) v);
1085 if (target_type == TypeManager.float_type)
1086 return new FloatConstant ((float) v);
1092 public override Expression DoResolve (EmitContext ec)
1094 expr = expr.Resolve (ec);
1098 target_type = target_type.Resolve (ec);
1099 if (target_type == null)
1102 if (target_type.eclass != ExprClass.Type){
1103 report118 (loc, target_type, "class");
1107 type = target_type.Type;
1108 eclass = ExprClass.Value;
1113 if (expr is Constant){
1114 Expression e = TryReduce (ec, type);
1120 expr = ConvertExplicit (ec, expr, type, loc);
1124 public override void Emit (EmitContext ec)
1127 // This one will never happen
1129 throw new Exception ("Should not happen");
1134 /// Binary operators
1136 public class Binary : Expression {
1137 public enum Operator : byte {
1138 Multiply, Division, Modulus,
1139 Addition, Subtraction,
1140 LeftShift, RightShift,
1141 LessThan, GreaterThan, LessThanOrEqual, GreaterThanOrEqual,
1142 Equality, Inequality,
1151 Expression left, right;
1153 ArrayList Arguments;
1156 bool DelegateOperation;
1158 public Binary (Operator oper, Expression left, Expression right, Location loc)
1166 public Operator Oper {
1175 public Expression Left {
1184 public Expression Right {
1195 /// Returns a stringified representation of the Operator
1200 case Operator.Multiply:
1202 case Operator.Division:
1204 case Operator.Modulus:
1206 case Operator.Addition:
1208 case Operator.Subtraction:
1210 case Operator.LeftShift:
1212 case Operator.RightShift:
1214 case Operator.LessThan:
1216 case Operator.GreaterThan:
1218 case Operator.LessThanOrEqual:
1220 case Operator.GreaterThanOrEqual:
1222 case Operator.Equality:
1224 case Operator.Inequality:
1226 case Operator.BitwiseAnd:
1228 case Operator.BitwiseOr:
1230 case Operator.ExclusiveOr:
1232 case Operator.LogicalOr:
1234 case Operator.LogicalAnd:
1238 return oper.ToString ();
1241 Expression ForceConversion (EmitContext ec, Expression expr, Type target_type)
1243 if (expr.Type == target_type)
1246 return ConvertImplicit (ec, expr, target_type, new Location (-1));
1250 // Note that handling the case l == Decimal || r == Decimal
1251 // is taken care of by the Step 1 Operator Overload resolution.
1253 bool DoNumericPromotions (EmitContext ec, Type l, Type r)
1255 if (l == TypeManager.double_type || r == TypeManager.double_type){
1257 // If either operand is of type double, the other operand is
1258 // conveted to type double.
1260 if (r != TypeManager.double_type)
1261 right = ConvertImplicit (ec, right, TypeManager.double_type, loc);
1262 if (l != TypeManager.double_type)
1263 left = ConvertImplicit (ec, left, TypeManager.double_type, loc);
1265 type = TypeManager.double_type;
1266 } else if (l == TypeManager.float_type || r == TypeManager.float_type){
1268 // if either operand is of type float, th eother operand is
1269 // converd to type float.
1271 if (r != TypeManager.double_type)
1272 right = ConvertImplicit (ec, right, TypeManager.float_type, loc);
1273 if (l != TypeManager.double_type)
1274 left = ConvertImplicit (ec, left, TypeManager.float_type, loc);
1275 type = TypeManager.float_type;
1276 } else if (l == TypeManager.uint64_type || r == TypeManager.uint64_type){
1280 // If either operand is of type ulong, the other operand is
1281 // converted to type ulong. or an error ocurrs if the other
1282 // operand is of type sbyte, short, int or long
1284 if (l == TypeManager.uint64_type){
1285 if (r != TypeManager.uint64_type){
1286 if (right is IntConstant){
1287 IntConstant ic = (IntConstant) right;
1289 e = TryImplicitIntConversion (l, ic);
1292 } else if (right is LongConstant){
1293 long ll = ((LongConstant) right).Value;
1296 right = new ULongConstant ((ulong) ll);
1298 e = ImplicitNumericConversion (ec, right, l, loc);
1305 if (left is IntConstant){
1306 e = TryImplicitIntConversion (r, (IntConstant) left);
1309 } else if (left is LongConstant){
1310 long ll = ((LongConstant) left).Value;
1313 left = new ULongConstant ((ulong) ll);
1315 e = ImplicitNumericConversion (ec, left, r, loc);
1322 if ((other == TypeManager.sbyte_type) ||
1323 (other == TypeManager.short_type) ||
1324 (other == TypeManager.int32_type) ||
1325 (other == TypeManager.int64_type)){
1326 string oper = OperName ();
1328 Error (34, loc, "Operator `" + OperName ()
1329 + "' is ambiguous on operands of type `"
1330 + TypeManager.CSharpName (l) + "' "
1331 + "and `" + TypeManager.CSharpName (r)
1334 type = TypeManager.uint64_type;
1335 } else if (l == TypeManager.int64_type || r == TypeManager.int64_type){
1337 // If either operand is of type long, the other operand is converted
1340 if (l != TypeManager.int64_type)
1341 left = ConvertImplicit (ec, left, TypeManager.int64_type, loc);
1342 if (r != TypeManager.int64_type)
1343 right = ConvertImplicit (ec, right, TypeManager.int64_type, loc);
1345 type = TypeManager.int64_type;
1346 } else if (l == TypeManager.uint32_type || r == TypeManager.uint32_type){
1348 // If either operand is of type uint, and the other
1349 // operand is of type sbyte, short or int, othe operands are
1350 // converted to type long.
1354 if (l == TypeManager.uint32_type){
1355 if (right is IntConstant){
1356 IntConstant ic = (IntConstant) right;
1360 right = new UIntConstant ((uint) val);
1367 else if (r == TypeManager.uint32_type){
1368 if (left is IntConstant){
1369 IntConstant ic = (IntConstant) left;
1373 left = new UIntConstant ((uint) val);
1382 if ((other == TypeManager.sbyte_type) ||
1383 (other == TypeManager.short_type) ||
1384 (other == TypeManager.int32_type)){
1385 left = ForceConversion (ec, left, TypeManager.int64_type);
1386 right = ForceConversion (ec, right, TypeManager.int64_type);
1387 type = TypeManager.int64_type;
1390 // if either operand is of type uint, the other
1391 // operand is converd to type uint
1393 left = ForceConversion (ec, left, TypeManager.uint32_type);
1394 right = ForceConversion (ec, right, TypeManager.uint32_type);
1395 type = TypeManager.uint32_type;
1397 } else if (l == TypeManager.decimal_type || r == TypeManager.decimal_type){
1398 if (l != TypeManager.decimal_type)
1399 left = ConvertImplicit (ec, left, TypeManager.decimal_type, loc);
1400 if (r != TypeManager.decimal_type)
1401 right = ConvertImplicit (ec, right, TypeManager.decimal_type, loc);
1403 type = TypeManager.decimal_type;
1405 Expression l_tmp, r_tmp;
1407 l_tmp = ForceConversion (ec, left, TypeManager.int32_type);
1411 r_tmp = ForceConversion (ec, right, TypeManager.int32_type);
1418 type = TypeManager.int32_type;
1427 "Operator " + OperName () + " cannot be applied to operands of type `" +
1428 TypeManager.CSharpName (left.Type) + "' and `" +
1429 TypeManager.CSharpName (right.Type) + "'");
1433 Expression CheckShiftArguments (EmitContext ec)
1437 Type r = right.Type;
1439 e = ForceConversion (ec, right, TypeManager.int32_type);
1446 if (((e = ConvertImplicit (ec, left, TypeManager.int32_type, loc)) != null) ||
1447 ((e = ConvertImplicit (ec, left, TypeManager.uint32_type, loc)) != null) ||
1448 ((e = ConvertImplicit (ec, left, TypeManager.int64_type, loc)) != null) ||
1449 ((e = ConvertImplicit (ec, left, TypeManager.uint64_type, loc)) != null)){
1459 Expression ResolveOperator (EmitContext ec)
1462 Type r = right.Type;
1465 // Step 1: Perform Operator Overload location
1467 Expression left_expr, right_expr;
1469 string op = "op_" + oper;
1471 left_expr = MemberLookup (ec, l, op, loc);
1472 if (left_expr == null && l.BaseType != null)
1473 left_expr = MemberLookup (ec, l.BaseType, op, loc);
1475 right_expr = MemberLookup (ec, r, op, loc);
1476 if (right_expr == null && r.BaseType != null)
1477 right_expr = MemberLookup (ec, r.BaseType, op, loc);
1479 MethodGroupExpr union = Invocation.MakeUnionSet (left_expr, right_expr);
1481 if (union != null) {
1482 Arguments = new ArrayList ();
1483 Arguments.Add (new Argument (left, Argument.AType.Expression));
1484 Arguments.Add (new Argument (right, Argument.AType.Expression));
1486 method = Invocation.OverloadResolve (ec, union, Arguments, loc);
1487 if (method != null) {
1488 MethodInfo mi = (MethodInfo) method;
1489 type = mi.ReturnType;
1498 // Step 2: Default operations on CLI native types.
1501 // Only perform numeric promotions on:
1502 // +, -, *, /, %, &, |, ^, ==, !=, <, >, <=, >=
1504 if (oper == Operator.Addition){
1506 // If any of the arguments is a string, cast to string
1508 if (l == TypeManager.string_type){
1509 if (r == TypeManager.string_type){
1510 if (left is Constant && right is Constant){
1511 StringConstant ls = (StringConstant) left;
1512 StringConstant rs = (StringConstant) right;
1514 return new StringConstant (
1515 ls.Value + rs.Value);
1519 method = TypeManager.string_concat_string_string;
1522 method = TypeManager.string_concat_object_object;
1523 right = ConvertImplicit (ec, right,
1524 TypeManager.object_type, loc);
1526 type = TypeManager.string_type;
1528 Arguments = new ArrayList ();
1529 Arguments.Add (new Argument (left, Argument.AType.Expression));
1530 Arguments.Add (new Argument (right, Argument.AType.Expression));
1534 } else if (r == TypeManager.string_type){
1536 method = TypeManager.string_concat_object_object;
1537 Arguments = new ArrayList ();
1538 Arguments.Add (new Argument (left, Argument.AType.Expression));
1539 Arguments.Add (new Argument (right, Argument.AType.Expression));
1541 left = ConvertImplicit (ec, left, TypeManager.object_type, loc);
1542 type = TypeManager.string_type;
1548 if (oper == Operator.Addition || oper == Operator.Subtraction) {
1549 if (l.IsSubclassOf (TypeManager.delegate_type) &&
1550 r.IsSubclassOf (TypeManager.delegate_type)) {
1552 Arguments = new ArrayList ();
1553 Arguments.Add (new Argument (left, Argument.AType.Expression));
1554 Arguments.Add (new Argument (right, Argument.AType.Expression));
1556 if (oper == Operator.Addition)
1557 method = TypeManager.delegate_combine_delegate_delegate;
1559 method = TypeManager.delegate_remove_delegate_delegate;
1561 DelegateOperation = true;
1568 // Enumeration operators
1570 bool lie = TypeManager.IsEnumType (l);
1571 bool rie = TypeManager.IsEnumType (r);
1576 temp = ConvertImplicit (ec, right, l, loc);
1580 temp = ConvertImplicit (ec, left, r, loc);
1587 if (oper == Operator.Equality || oper == Operator.Inequality ||
1588 oper == Operator.LessThanOrEqual || oper == Operator.LessThan ||
1589 oper == Operator.GreaterThanOrEqual || oper == Operator.GreaterThan){
1590 type = TypeManager.bool_type;
1594 if (oper == Operator.BitwiseAnd ||
1595 oper == Operator.BitwiseOr ||
1596 oper == Operator.ExclusiveOr){
1602 if (oper == Operator.LeftShift || oper == Operator.RightShift)
1603 return CheckShiftArguments (ec);
1605 if (oper == Operator.LogicalOr || oper == Operator.LogicalAnd){
1606 if (l != TypeManager.bool_type || r != TypeManager.bool_type){
1611 type = TypeManager.bool_type;
1615 if (oper == Operator.Equality || oper == Operator.Inequality){
1616 if (l == TypeManager.bool_type || r == TypeManager.bool_type){
1617 if (r != TypeManager.bool_type || l != TypeManager.bool_type){
1622 type = TypeManager.bool_type;
1627 // operator != (object a, object b)
1628 // operator == (object a, object b)
1630 // For this to be used, both arguments have to be reference-types.
1631 // Read the rationale on the spec (14.9.6)
1633 // Also, if at compile time we know that the classes do not inherit
1634 // one from the other, then we catch the error there.
1636 if (!(l.IsValueType || r.IsValueType)){
1637 type = TypeManager.bool_type;
1642 if (l.IsSubclassOf (r) || r.IsSubclassOf (l))
1646 // We are going to have to convert to an object to compare
1648 if (l != TypeManager.object_type)
1649 left = new EmptyCast (left, TypeManager.object_type);
1650 if (r != TypeManager.object_type)
1651 right = new EmptyCast (right, TypeManager.object_type);
1658 // We are dealing with numbers
1661 if (!DoNumericPromotions (ec, l, r)){
1666 if (left == null || right == null)
1670 // reload our cached types if required
1675 if (oper == Operator.BitwiseAnd ||
1676 oper == Operator.BitwiseOr ||
1677 oper == Operator.ExclusiveOr){
1679 if (!((l == TypeManager.int32_type) ||
1680 (l == TypeManager.uint32_type) ||
1681 (l == TypeManager.int64_type) ||
1682 (l == TypeManager.uint64_type)))
1690 if (oper == Operator.Equality ||
1691 oper == Operator.Inequality ||
1692 oper == Operator.LessThanOrEqual ||
1693 oper == Operator.LessThan ||
1694 oper == Operator.GreaterThanOrEqual ||
1695 oper == Operator.GreaterThan){
1696 type = TypeManager.bool_type;
1703 /// Constant expression reducer for binary operations
1705 public Expression ConstantFold (EmitContext ec)
1707 object l = ((Constant) left).GetValue ();
1708 object r = ((Constant) right).GetValue ();
1710 if (l is string && r is string)
1711 return new StringConstant ((string) l + (string) r);
1713 Type result_type = null;
1716 // Enumerator folding
1718 if (left.Type == right.Type && left is EnumConstant)
1719 result_type = left.Type;
1722 case Operator.BitwiseOr:
1723 if ((l is int) && (r is int)){
1725 int res = (int)l | (int)r;
1727 v = new IntConstant (res);
1728 if (result_type == null)
1731 return new EnumConstant (v, result_type);
1735 case Operator.BitwiseAnd:
1736 if ((l is int) && (r is int)){
1738 int res = (int)l & (int)r;
1740 v = new IntConstant (res);
1741 if (result_type == null)
1744 return new EnumConstant (v, result_type);
1752 public override Expression DoResolve (EmitContext ec)
1754 left = left.Resolve (ec);
1755 right = right.Resolve (ec);
1757 if (left == null || right == null)
1760 if (left.Type == null)
1761 throw new Exception (
1762 "Resolve returned non null, but did not set the type! (" +
1763 left + ") at Line: " + loc.Row);
1764 if (right.Type == null)
1765 throw new Exception (
1766 "Resolve returned non null, but did not set the type! (" +
1767 right + ") at Line: "+ loc.Row);
1769 eclass = ExprClass.Value;
1771 if (left is Constant && right is Constant){
1773 // This is temporary until we do the full folding
1775 Expression e = ConstantFold (ec);
1780 return ResolveOperator (ec);
1783 public bool IsBranchable ()
1785 if (oper == Operator.Equality ||
1786 oper == Operator.Inequality ||
1787 oper == Operator.LessThan ||
1788 oper == Operator.GreaterThan ||
1789 oper == Operator.LessThanOrEqual ||
1790 oper == Operator.GreaterThanOrEqual){
1797 /// This entry point is used by routines that might want
1798 /// to emit a brfalse/brtrue after an expression, and instead
1799 /// they could use a more compact notation.
1801 /// Typically the code would generate l.emit/r.emit, followed
1802 /// by the comparission and then a brtrue/brfalse. The comparissions
1803 /// are sometimes inneficient (there are not as complete as the branches
1804 /// look for the hacks in Emit using double ceqs).
1806 /// So for those cases we provide EmitBranchable that can emit the
1807 /// branch with the test
1809 public void EmitBranchable (EmitContext ec, int target)
1812 bool close_target = false;
1813 ILGenerator ig = ec.ig;
1816 // short-circuit operators
1818 if (oper == Operator.LogicalAnd){
1820 ig.Emit (OpCodes.Brfalse, target);
1822 ig.Emit (OpCodes.Brfalse, target);
1823 } else if (oper == Operator.LogicalOr){
1825 ig.Emit (OpCodes.Brtrue, target);
1827 ig.Emit (OpCodes.Brfalse, target);
1834 case Operator.Equality:
1836 opcode = OpCodes.Beq_S;
1838 opcode = OpCodes.Beq;
1841 case Operator.Inequality:
1843 opcode = OpCodes.Bne_Un_S;
1845 opcode = OpCodes.Bne_Un;
1848 case Operator.LessThan:
1850 opcode = OpCodes.Blt_S;
1852 opcode = OpCodes.Blt;
1855 case Operator.GreaterThan:
1857 opcode = OpCodes.Bgt_S;
1859 opcode = OpCodes.Bgt;
1862 case Operator.LessThanOrEqual:
1864 opcode = OpCodes.Ble_S;
1866 opcode = OpCodes.Ble;
1869 case Operator.GreaterThanOrEqual:
1871 opcode = OpCodes.Bge_S;
1873 opcode = OpCodes.Ble;
1877 throw new Exception ("EmitBranchable called on non-EmitBranchable operator: "
1878 + oper.ToString ());
1881 ig.Emit (opcode, target);
1884 public override void Emit (EmitContext ec)
1886 ILGenerator ig = ec.ig;
1888 Type r = right.Type;
1891 if (method != null) {
1893 // Note that operators are static anyway
1895 if (Arguments != null)
1896 Invocation.EmitArguments (ec, method, Arguments);
1898 if (method is MethodInfo)
1899 ig.Emit (OpCodes.Call, (MethodInfo) method);
1901 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
1903 if (DelegateOperation)
1904 ig.Emit (OpCodes.Castclass, type);
1910 // Handle short-circuit operators differently
1913 if (oper == Operator.LogicalAnd){
1914 Label load_zero = ig.DefineLabel ();
1915 Label end = ig.DefineLabel ();
1918 ig.Emit (OpCodes.Brfalse, load_zero);
1920 ig.Emit (OpCodes.Br, end);
1921 ig.MarkLabel (load_zero);
1922 ig.Emit (OpCodes.Ldc_I4_0);
1925 } else if (oper == Operator.LogicalOr){
1926 Label load_one = ig.DefineLabel ();
1927 Label end = ig.DefineLabel ();
1930 ig.Emit (OpCodes.Brtrue, load_one);
1932 ig.Emit (OpCodes.Br, end);
1933 ig.MarkLabel (load_one);
1934 ig.Emit (OpCodes.Ldc_I4_1);
1943 case Operator.Multiply:
1945 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
1946 opcode = OpCodes.Mul_Ovf;
1947 else if (l==TypeManager.uint32_type || l==TypeManager.uint64_type)
1948 opcode = OpCodes.Mul_Ovf_Un;
1950 opcode = OpCodes.Mul;
1952 opcode = OpCodes.Mul;
1956 case Operator.Division:
1957 if (l == TypeManager.uint32_type || l == TypeManager.uint64_type)
1958 opcode = OpCodes.Div_Un;
1960 opcode = OpCodes.Div;
1963 case Operator.Modulus:
1964 if (l == TypeManager.uint32_type || l == TypeManager.uint64_type)
1965 opcode = OpCodes.Rem_Un;
1967 opcode = OpCodes.Rem;
1970 case Operator.Addition:
1972 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
1973 opcode = OpCodes.Add_Ovf;
1974 else if (l==TypeManager.uint32_type || l==TypeManager.uint64_type)
1975 opcode = OpCodes.Add_Ovf_Un;
1977 opcode = OpCodes.Mul;
1979 opcode = OpCodes.Add;
1982 case Operator.Subtraction:
1984 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
1985 opcode = OpCodes.Sub_Ovf;
1986 else if (l==TypeManager.uint32_type || l==TypeManager.uint64_type)
1987 opcode = OpCodes.Sub_Ovf_Un;
1989 opcode = OpCodes.Sub;
1991 opcode = OpCodes.Sub;
1994 case Operator.RightShift:
1995 opcode = OpCodes.Shr;
1998 case Operator.LeftShift:
1999 opcode = OpCodes.Shl;
2002 case Operator.Equality:
2003 opcode = OpCodes.Ceq;
2006 case Operator.Inequality:
2007 ec.ig.Emit (OpCodes.Ceq);
2008 ec.ig.Emit (OpCodes.Ldc_I4_0);
2010 opcode = OpCodes.Ceq;
2013 case Operator.LessThan:
2014 opcode = OpCodes.Clt;
2017 case Operator.GreaterThan:
2018 opcode = OpCodes.Cgt;
2021 case Operator.LessThanOrEqual:
2022 ec.ig.Emit (OpCodes.Cgt);
2023 ec.ig.Emit (OpCodes.Ldc_I4_0);
2025 opcode = OpCodes.Ceq;
2028 case Operator.GreaterThanOrEqual:
2029 ec.ig.Emit (OpCodes.Clt);
2030 ec.ig.Emit (OpCodes.Ldc_I4_1);
2032 opcode = OpCodes.Sub;
2035 case Operator.BitwiseOr:
2036 opcode = OpCodes.Or;
2039 case Operator.BitwiseAnd:
2040 opcode = OpCodes.And;
2043 case Operator.ExclusiveOr:
2044 opcode = OpCodes.Xor;
2048 throw new Exception ("This should not happen: Operator = "
2049 + oper.ToString ());
2057 /// Implements the ternary conditiona operator (?:)
2059 public class Conditional : Expression {
2060 Expression expr, trueExpr, falseExpr;
2063 public Conditional (Expression expr, Expression trueExpr, Expression falseExpr, Location l)
2066 this.trueExpr = trueExpr;
2067 this.falseExpr = falseExpr;
2071 public Expression Expr {
2077 public Expression TrueExpr {
2083 public Expression FalseExpr {
2089 public override Expression DoResolve (EmitContext ec)
2091 expr = expr.Resolve (ec);
2093 if (expr.Type != TypeManager.bool_type)
2094 expr = Expression.ConvertImplicitRequired (
2095 ec, expr, TypeManager.bool_type, loc);
2097 trueExpr = trueExpr.Resolve (ec);
2098 falseExpr = falseExpr.Resolve (ec);
2100 if (expr == null || trueExpr == null || falseExpr == null)
2103 if (trueExpr.Type == falseExpr.Type)
2104 type = trueExpr.Type;
2109 // First, if an implicit conversion exists from trueExpr
2110 // to falseExpr, then the result type is of type falseExpr.Type
2112 conv = ConvertImplicit (ec, trueExpr, falseExpr.Type, loc);
2114 type = falseExpr.Type;
2116 } else if ((conv = ConvertImplicit(ec, falseExpr,trueExpr.Type,loc))!= null){
2117 type = trueExpr.Type;
2120 Error (173, loc, "The type of the conditional expression can " +
2121 "not be computed because there is no implicit conversion" +
2122 " from `" + TypeManager.CSharpName (trueExpr.Type) + "'" +
2123 " and `" + TypeManager.CSharpName (falseExpr.Type) + "'");
2128 if (expr is BoolConstant){
2129 BoolConstant bc = (BoolConstant) expr;
2137 eclass = ExprClass.Value;
2141 public override void Emit (EmitContext ec)
2143 ILGenerator ig = ec.ig;
2144 Label false_target = ig.DefineLabel ();
2145 Label end_target = ig.DefineLabel ();
2148 ig.Emit (OpCodes.Brfalse, false_target);
2150 ig.Emit (OpCodes.Br, end_target);
2151 ig.MarkLabel (false_target);
2152 falseExpr.Emit (ec);
2153 ig.MarkLabel (end_target);
2161 public class LocalVariableReference : Expression, IAssignMethod, IMemoryLocation {
2162 public readonly string Name;
2163 public readonly Block Block;
2165 VariableInfo variable_info;
2167 public LocalVariableReference (Block block, string name, Location l)
2172 eclass = ExprClass.Variable;
2175 public VariableInfo VariableInfo {
2177 if (variable_info == null)
2178 variable_info = Block.GetVariableInfo (Name);
2179 return variable_info;
2183 public override Expression DoResolve (EmitContext ec)
2185 VariableInfo vi = VariableInfo;
2187 if (Block.IsConstant (Name)) {
2188 Expression e = Block.GetConstantExpression (Name);
2194 if (!(e is Constant)) {
2195 Report.Error (150, loc, "A constant value is expected");
2203 type = vi.VariableType;
2207 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
2209 Expression e = DoResolve (ec);
2214 VariableInfo vi = VariableInfo;
2220 "cannot assign to `" + Name + "' because it is readonly");
2228 public override void Emit (EmitContext ec)
2230 VariableInfo vi = VariableInfo;
2231 ILGenerator ig = ec.ig;
2238 ig.Emit (OpCodes.Ldloc_0);
2242 ig.Emit (OpCodes.Ldloc_1);
2246 ig.Emit (OpCodes.Ldloc_2);
2250 ig.Emit (OpCodes.Ldloc_3);
2255 ig.Emit (OpCodes.Ldloc_S, (byte) idx);
2257 ig.Emit (OpCodes.Ldloc, idx);
2262 public static void Store (ILGenerator ig, int idx)
2266 ig.Emit (OpCodes.Stloc_0);
2270 ig.Emit (OpCodes.Stloc_1);
2274 ig.Emit (OpCodes.Stloc_2);
2278 ig.Emit (OpCodes.Stloc_3);
2283 ig.Emit (OpCodes.Stloc_S, (byte) idx);
2285 ig.Emit (OpCodes.Stloc, idx);
2290 public void EmitAssign (EmitContext ec, Expression source)
2292 ILGenerator ig = ec.ig;
2293 VariableInfo vi = VariableInfo;
2299 // Funny seems the code below generates optimal code for us, but
2300 // seems to take too long to generate what we need.
2301 // ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
2306 public void AddressOf (EmitContext ec)
2308 VariableInfo vi = VariableInfo;
2315 ec.ig.Emit (OpCodes.Ldloca_S, (byte) idx);
2317 ec.ig.Emit (OpCodes.Ldloca, idx);
2322 /// This represents a reference to a parameter in the intermediate
2325 public class ParameterReference : Expression, IAssignMethod, IMemoryLocation {
2331 public ParameterReference (Parameters pars, int idx, string name)
2336 eclass = ExprClass.Variable;
2340 // Notice that for ref/out parameters, the type exposed is not the
2341 // same type exposed externally.
2344 // externally we expose "int&"
2345 // here we expose "int".
2347 // We record this in "is_ref". This means that the type system can treat
2348 // the type as it is expected, but when we generate the code, we generate
2349 // the alternate kind of code.
2351 public override Expression DoResolve (EmitContext ec)
2353 type = pars.GetParameterInfo (ec.TypeContainer, idx, out is_ref);
2354 eclass = ExprClass.Variable;
2360 // This method is used by parameters that are references, that are
2361 // being passed as references: we only want to pass the pointer (that
2362 // is already stored in the parameter, not the address of the pointer,
2363 // and not the value of the variable).
2365 public void EmitLoad (EmitContext ec)
2367 ILGenerator ig = ec.ig;
2374 ig.Emit (OpCodes.Ldarg_S, (byte) arg_idx);
2376 ig.Emit (OpCodes.Ldarg, arg_idx);
2379 public override void Emit (EmitContext ec)
2381 ILGenerator ig = ec.ig;
2388 ig.Emit (OpCodes.Ldarg_S, (byte) arg_idx);
2390 ig.Emit (OpCodes.Ldarg, arg_idx);
2396 // If we are a reference, we loaded on the stack a pointer
2397 // Now lets load the real value
2400 if (type == TypeManager.int32_type)
2401 ig.Emit (OpCodes.Ldind_I4);
2402 else if (type == TypeManager.uint32_type)
2403 ig.Emit (OpCodes.Ldind_U4);
2404 else if (type == TypeManager.int64_type || type == TypeManager.uint64_type)
2405 ig.Emit (OpCodes.Ldind_I8);
2406 else if (type == TypeManager.char_type)
2407 ig.Emit (OpCodes.Ldind_U2);
2408 else if (type == TypeManager.short_type)
2409 ig.Emit (OpCodes.Ldind_I2);
2410 else if (type == TypeManager.ushort_type)
2411 ig.Emit (OpCodes.Ldind_U2);
2412 else if (type == TypeManager.float_type)
2413 ig.Emit (OpCodes.Ldind_R4);
2414 else if (type == TypeManager.double_type)
2415 ig.Emit (OpCodes.Ldind_R8);
2416 else if (type == TypeManager.byte_type)
2417 ig.Emit (OpCodes.Ldind_U1);
2418 else if (type == TypeManager.sbyte_type || type == TypeManager.bool_type)
2419 ig.Emit (OpCodes.Ldind_I1);
2420 else if (type == TypeManager.intptr_type)
2421 ig.Emit (OpCodes.Ldind_I);
2423 ig.Emit (OpCodes.Ldind_Ref);
2426 public void EmitAssign (EmitContext ec, Expression source)
2428 ILGenerator ig = ec.ig;
2437 ig.Emit (OpCodes.Ldarg_S, (byte) arg_idx);
2439 ig.Emit (OpCodes.Ldarg, arg_idx);
2445 if (type == TypeManager.int32_type || type == TypeManager.uint32_type)
2446 ig.Emit (OpCodes.Stind_I4);
2447 else if (type == TypeManager.int64_type || type == TypeManager.uint64_type)
2448 ig.Emit (OpCodes.Stind_I8);
2449 else if (type == TypeManager.char_type || type == TypeManager.short_type ||
2450 type == TypeManager.ushort_type)
2451 ig.Emit (OpCodes.Stind_I2);
2452 else if (type == TypeManager.float_type)
2453 ig.Emit (OpCodes.Stind_R4);
2454 else if (type == TypeManager.double_type)
2455 ig.Emit (OpCodes.Stind_R8);
2456 else if (type == TypeManager.byte_type || type == TypeManager.sbyte_type ||
2457 type == TypeManager.bool_type)
2458 ig.Emit (OpCodes.Stind_I1);
2459 else if (type == TypeManager.intptr_type)
2460 ig.Emit (OpCodes.Stind_I);
2462 ig.Emit (OpCodes.Stind_Ref);
2465 ig.Emit (OpCodes.Starg_S, (byte) arg_idx);
2467 ig.Emit (OpCodes.Starg, arg_idx);
2472 public void AddressOf (EmitContext ec)
2480 ec.ig.Emit (OpCodes.Ldarga_S, (byte) arg_idx);
2482 ec.ig.Emit (OpCodes.Ldarga, arg_idx);
2487 /// Used for arguments to New(), Invocation()
2489 public class Argument {
2490 public enum AType : byte {
2496 public readonly AType ArgType;
2497 public Expression expr;
2499 public Argument (Expression expr, AType type)
2502 this.ArgType = type;
2505 public Expression Expr {
2521 public Parameter.Modifier GetParameterModifier ()
2523 if (ArgType == AType.Ref)
2524 return Parameter.Modifier.REF;
2526 if (ArgType == AType.Out)
2527 return Parameter.Modifier.OUT;
2529 return Parameter.Modifier.NONE;
2532 public static string FullDesc (Argument a)
2534 return (a.ArgType == AType.Ref ? "ref " :
2535 (a.ArgType == AType.Out ? "out " : "")) +
2536 TypeManager.CSharpName (a.Expr.Type);
2539 public bool Resolve (EmitContext ec, Location loc)
2541 expr = expr.Resolve (ec);
2543 if (ArgType == AType.Expression)
2544 return expr != null;
2546 if (expr.eclass != ExprClass.Variable){
2548 // We just probe to match the CSC output
2550 if (expr.eclass == ExprClass.PropertyAccess ||
2551 expr.eclass == ExprClass.IndexerAccess){
2554 "A property or indexer can not be passed as an out or ref " +
2559 "An lvalue is required as an argument to out or ref");
2564 return expr != null;
2567 public void Emit (EmitContext ec)
2570 // Ref and Out parameters need to have their addresses taken.
2572 // ParameterReferences might already be references, so we want
2573 // to pass just the value
2575 if (ArgType == AType.Ref || ArgType == AType.Out){
2576 if (expr is ParameterReference){
2577 ParameterReference pr = (ParameterReference) expr;
2584 ((IMemoryLocation)expr).AddressOf (ec);
2591 /// Invocation of methods or delegates.
2593 public class Invocation : ExpressionStatement {
2594 public readonly ArrayList Arguments;
2598 MethodBase method = null;
2601 static Hashtable method_parameter_cache;
2603 static Invocation ()
2605 method_parameter_cache = new PtrHashtable ();
2609 // arguments is an ArrayList, but we do not want to typecast,
2610 // as it might be null.
2612 // FIXME: only allow expr to be a method invocation or a
2613 // delegate invocation (7.5.5)
2615 public Invocation (Expression expr, ArrayList arguments, Location l)
2618 Arguments = arguments;
2622 public Expression Expr {
2629 /// Returns the Parameters (a ParameterData interface) for the
2632 public static ParameterData GetParameterData (MethodBase mb)
2634 object pd = method_parameter_cache [mb];
2638 return (ParameterData) pd;
2641 ip = TypeManager.LookupParametersByBuilder (mb);
2643 method_parameter_cache [mb] = ip;
2645 return (ParameterData) ip;
2647 ParameterInfo [] pi = mb.GetParameters ();
2648 ReflectionParameters rp = new ReflectionParameters (pi);
2649 method_parameter_cache [mb] = rp;
2651 return (ParameterData) rp;
2656 /// Determines "better conversion" as specified in 7.4.2.3
2657 /// Returns : 1 if a->p is better
2658 /// 0 if a->q or neither is better
2660 static int BetterConversion (EmitContext ec, Argument a, Type p, Type q, Location loc)
2662 Type argument_type = a.Type;
2663 Expression argument_expr = a.Expr;
2665 if (argument_type == null)
2666 throw new Exception ("Expression of type " + a.Expr + " does not resolve its type");
2671 if (argument_type == p)
2674 if (argument_type == q)
2678 // Now probe whether an implicit constant expression conversion
2681 // An implicit constant expression conversion permits the following
2684 // * A constant-expression of type `int' can be converted to type
2685 // sbyte, byute, short, ushort, uint, ulong provided the value of
2686 // of the expression is withing the range of the destination type.
2688 // * A constant-expression of type long can be converted to type
2689 // ulong, provided the value of the constant expression is not negative
2691 // FIXME: Note that this assumes that constant folding has
2692 // taken place. We dont do constant folding yet.
2695 if (argument_expr is IntConstant){
2696 IntConstant ei = (IntConstant) argument_expr;
2697 int value = ei.Value;
2699 if (p == TypeManager.sbyte_type){
2700 if (value >= SByte.MinValue && value <= SByte.MaxValue)
2702 } else if (p == TypeManager.byte_type){
2703 if (Byte.MinValue >= 0 && value <= Byte.MaxValue)
2705 } else if (p == TypeManager.short_type){
2706 if (value >= Int16.MinValue && value <= Int16.MaxValue)
2708 } else if (p == TypeManager.ushort_type){
2709 if (value >= UInt16.MinValue && value <= UInt16.MaxValue)
2711 } else if (p == TypeManager.uint32_type){
2713 // we can optimize this case: a positive int32
2714 // always fits on a uint32
2718 } else if (p == TypeManager.uint64_type){
2720 // we can optimize this case: a positive int32
2721 // always fits on a uint64
2726 } else if (argument_type == TypeManager.int64_type && argument_expr is LongConstant){
2727 LongConstant lc = (LongConstant) argument_expr;
2729 if (p == TypeManager.uint64_type){
2736 Expression tmp = ConvertImplicitStandard (ec, argument_expr, p, loc);
2744 if (StandardConversionExists (p, q) == true &&
2745 StandardConversionExists (q, p) == false)
2748 if (p == TypeManager.sbyte_type)
2749 if (q == TypeManager.byte_type || q == TypeManager.ushort_type ||
2750 q == TypeManager.uint32_type || q == TypeManager.uint64_type)
2753 if (p == TypeManager.short_type)
2754 if (q == TypeManager.ushort_type || q == TypeManager.uint32_type ||
2755 q == TypeManager.uint64_type)
2758 if (p == TypeManager.int32_type)
2759 if (q == TypeManager.uint32_type || q == TypeManager.uint64_type)
2762 if (p == TypeManager.int64_type)
2763 if (q == TypeManager.uint64_type)
2770 /// Determines "Better function"
2773 /// and returns an integer indicating :
2774 /// 0 if candidate ain't better
2775 /// 1 if candidate is better than the current best match
2777 static int BetterFunction (EmitContext ec, ArrayList args,
2778 MethodBase candidate, MethodBase best,
2779 bool expanded_form, Location loc)
2781 ParameterData candidate_pd = GetParameterData (candidate);
2782 ParameterData best_pd;
2789 argument_count = args.Count;
2791 if (candidate_pd.Count == 0 && argument_count == 0)
2794 if (candidate_pd.ParameterModifier (candidate_pd.Count - 1) != Parameter.Modifier.PARAMS)
2795 if (candidate_pd.Count != argument_count)
2800 for (int j = argument_count; j > 0;) {
2803 Argument a = (Argument) args [j];
2804 Type t = candidate_pd.ParameterType (j);
2806 if (candidate_pd.ParameterModifier (j) == Parameter.Modifier.PARAMS)
2808 t = t.GetElementType ();
2810 x = BetterConversion (ec, a, t, null, loc);
2822 best_pd = GetParameterData (best);
2824 int rating1 = 0, rating2 = 0;
2826 for (int j = 0; j < argument_count; ++j) {
2829 Argument a = (Argument) args [j];
2831 Type ct = candidate_pd.ParameterType (j);
2832 Type bt = best_pd.ParameterType (j);
2834 if (candidate_pd.ParameterModifier (j) == Parameter.Modifier.PARAMS)
2836 ct = ct.GetElementType ();
2838 if (best_pd.ParameterModifier (j) == Parameter.Modifier.PARAMS)
2840 bt = bt.GetElementType ();
2842 x = BetterConversion (ec, a, ct, bt, loc);
2843 y = BetterConversion (ec, a, bt, ct, loc);
2852 if (rating1 > rating2)
2858 public static string FullMethodDesc (MethodBase mb)
2860 string ret_type = "";
2862 if (mb is MethodInfo)
2863 ret_type = TypeManager.CSharpName (((MethodInfo) mb).ReturnType);
2865 StringBuilder sb = new StringBuilder (ret_type + " " + mb.Name);
2866 ParameterData pd = GetParameterData (mb);
2868 int count = pd.Count;
2871 for (int i = count; i > 0; ) {
2874 sb.Append (pd.ParameterDesc (count - i - 1));
2880 return sb.ToString ();
2883 public static MethodGroupExpr MakeUnionSet (Expression mg1, Expression mg2)
2885 MemberInfo [] miset;
2886 MethodGroupExpr union;
2888 if (mg1 != null && mg2 != null) {
2890 MethodGroupExpr left_set = null, right_set = null;
2891 int length1 = 0, length2 = 0;
2893 left_set = (MethodGroupExpr) mg1;
2894 length1 = left_set.Methods.Length;
2896 right_set = (MethodGroupExpr) mg2;
2897 length2 = right_set.Methods.Length;
2899 ArrayList common = new ArrayList ();
2901 for (int i = 0; i < left_set.Methods.Length; i++) {
2902 for (int j = 0; j < right_set.Methods.Length; j++) {
2903 if (left_set.Methods [i] == right_set.Methods [j])
2904 common.Add (left_set.Methods [i]);
2908 miset = new MemberInfo [length1 + length2 - common.Count];
2910 left_set.Methods.CopyTo (miset, 0);
2914 for (int j = 0; j < right_set.Methods.Length; j++)
2915 if (!common.Contains (right_set.Methods [j]))
2916 miset [length1 + k++] = right_set.Methods [j];
2918 union = new MethodGroupExpr (miset);
2922 } else if (mg1 == null && mg2 != null) {
2924 MethodGroupExpr me = (MethodGroupExpr) mg2;
2926 miset = new MemberInfo [me.Methods.Length];
2927 me.Methods.CopyTo (miset, 0);
2929 union = new MethodGroupExpr (miset);
2933 } else if (mg2 == null && mg1 != null) {
2935 MethodGroupExpr me = (MethodGroupExpr) mg1;
2937 miset = new MemberInfo [me.Methods.Length];
2938 me.Methods.CopyTo (miset, 0);
2940 union = new MethodGroupExpr (miset);
2949 /// Determines is the candidate method, if a params method, is applicable
2950 /// in its expanded form to the given set of arguments
2952 static bool IsParamsMethodApplicable (ArrayList arguments, MethodBase candidate)
2956 if (arguments == null)
2959 arg_count = arguments.Count;
2961 ParameterData pd = GetParameterData (candidate);
2963 int pd_count = pd.Count;
2968 if (pd.ParameterModifier (pd_count - 1) != Parameter.Modifier.PARAMS)
2971 if (pd_count - 1 > arg_count)
2975 // If we have come this far, the case which remains is when the number of parameters
2976 // is less than or equal to the argument count. So, we now check if the element type
2977 // of the params array is compatible with each argument type
2980 Type element_type = pd.ParameterType (pd_count - 1).GetElementType ();
2982 for (int i = pd_count - 1; i < arg_count - 1; i++) {
2983 Argument a = (Argument) arguments [i];
2985 if (!StandardConversionExists (a.Type, element_type))
2993 /// Determines if the candidate method is applicable (section 14.4.2.1)
2994 /// to the given set of arguments
2996 static bool IsApplicable (ArrayList arguments, MethodBase candidate)
3000 if (arguments == null)
3003 arg_count = arguments.Count;
3005 ParameterData pd = GetParameterData (candidate);
3007 int pd_count = pd.Count;
3009 if (arg_count != pd.Count)
3012 for (int i = arg_count; i > 0; ) {
3015 Argument a = (Argument) arguments [i];
3017 Parameter.Modifier a_mod = a.GetParameterModifier ();
3018 Parameter.Modifier p_mod = pd.ParameterModifier (i);
3020 if (a_mod == p_mod) {
3022 if (a_mod == Parameter.Modifier.NONE)
3023 if (!StandardConversionExists (a.Type, pd.ParameterType (i)))
3026 if (a_mod == Parameter.Modifier.REF ||
3027 a_mod == Parameter.Modifier.OUT)
3028 if (pd.ParameterType (i) != a.Type)
3040 /// Find the Applicable Function Members (7.4.2.1)
3042 /// me: Method Group expression with the members to select.
3043 /// it might contain constructors or methods (or anything
3044 /// that maps to a method).
3046 /// Arguments: ArrayList containing resolved Argument objects.
3048 /// loc: The location if we want an error to be reported, or a Null
3049 /// location for "probing" purposes.
3051 /// Returns: The MethodBase (either a ConstructorInfo or a MethodInfo)
3052 /// that is the best match of me on Arguments.
3055 public static MethodBase OverloadResolve (EmitContext ec, MethodGroupExpr me,
3056 ArrayList Arguments, Location loc)
3058 ArrayList afm = new ArrayList ();
3059 int best_match_idx = -1;
3060 MethodBase method = null;
3062 ArrayList candidates = new ArrayList ();
3064 for (int i = me.Methods.Length; i > 0; ){
3066 MethodBase candidate = me.Methods [i];
3069 // Check if candidate is applicable (section 14.4.2.1)
3070 if (!IsApplicable (Arguments, candidate))
3073 candidates.Add (candidate);
3075 x = BetterFunction (ec, Arguments, candidate, method, false, loc);
3081 method = me.Methods [best_match_idx];
3085 if (Arguments == null)
3088 argument_count = Arguments.Count;
3091 // Now we see if we can find params functions, applicable in their expanded form
3092 // since if they were applicable in their normal form, they would have been selected
3095 bool chose_params_expanded = false;
3097 if (best_match_idx == -1) {
3099 candidates = new ArrayList ();
3100 for (int i = me.Methods.Length; i > 0; ) {
3102 MethodBase candidate = me.Methods [i];
3104 if (!IsParamsMethodApplicable (Arguments, candidate))
3107 candidates.Add (candidate);
3109 int x = BetterFunction (ec, Arguments, candidate, method, true, loc);
3115 method = me.Methods [best_match_idx];
3116 chose_params_expanded = true;
3122 // Now we see if we can at least find a method with the same number of arguments
3125 int method_count = 0;
3127 if (best_match_idx == -1) {
3129 for (int i = me.Methods.Length; i > 0;) {
3131 MethodBase mb = me.Methods [i];
3132 pd = GetParameterData (mb);
3134 if (pd.Count == argument_count) {
3136 method = me.Methods [best_match_idx];
3148 // Now check that there are no ambiguities i.e the selected method
3149 // should be better than all the others
3152 for (int i = 0; i < candidates.Count; ++i) {
3153 MethodBase candidate = (MethodBase) candidates [i];
3155 if (candidate == method)
3159 // If a normal method is applicable in the sense that it has the same
3160 // number of arguments, then the expanded params method is never applicable
3161 // so we debar the params method.
3163 if (IsParamsMethodApplicable (Arguments, candidate) &&
3164 IsApplicable (Arguments, method))
3167 int x = BetterFunction (ec, Arguments, method, candidate,
3168 chose_params_expanded, loc);
3171 Console.WriteLine ("Candidate : " + FullMethodDesc (candidate));
3172 Console.WriteLine ("Best : " + FullMethodDesc (method));
3175 "Ambiguous call when selecting function due to implicit casts");
3180 // And now convert implicitly, each argument to the required type
3182 pd = GetParameterData (method);
3183 int pd_count = pd.Count;
3185 for (int j = 0; j < argument_count; j++) {
3186 Argument a = (Argument) Arguments [j];
3187 Expression a_expr = a.Expr;
3188 Type parameter_type = pd.ParameterType (j);
3190 if (pd.ParameterModifier (j) == Parameter.Modifier.PARAMS && chose_params_expanded)
3191 parameter_type = parameter_type.GetElementType ();
3193 if (a.Type != parameter_type){
3196 conv = ConvertImplicitStandard (ec, a_expr, parameter_type, Location.Null);
3199 if (!Location.IsNull (loc)) {
3201 "The best overloaded match for method '" +
3202 FullMethodDesc (method) +
3203 "' has some invalid arguments");
3205 "Argument " + (j+1) +
3206 ": Cannot convert from '" + Argument.FullDesc (a)
3207 + "' to '" + pd.ParameterDesc (j) + "'");
3213 // Update the argument with the implicit conversion
3218 // FIXME : For the case of params methods, we need to actually instantiate
3219 // an array and initialize it with the argument values etc etc.
3223 if (a.GetParameterModifier () != pd.ParameterModifier (j) &&
3224 pd.ParameterModifier (pd_count - 1) != Parameter.Modifier.PARAMS) {
3225 if (!Location.IsNull (loc)) {
3227 "The best overloaded match for method '" + FullMethodDesc (method)+
3228 "' has some invalid arguments");
3230 "Argument " + (j+1) +
3231 ": Cannot convert from '" + Argument.FullDesc (a)
3232 + "' to '" + pd.ParameterDesc (j) + "'");
3241 public override Expression DoResolve (EmitContext ec)
3244 // First, resolve the expression that is used to
3245 // trigger the invocation
3247 if (expr is BaseAccess)
3250 expr = expr.Resolve (ec);
3254 if (!(expr is MethodGroupExpr)) {
3255 Type expr_type = expr.Type;
3257 if (expr_type != null){
3258 bool IsDelegate = TypeManager.IsDelegateType (expr_type);
3260 return (new DelegateInvocation (
3261 this.expr, Arguments, loc)).Resolve (ec);
3265 if (!(expr is MethodGroupExpr)){
3266 report118 (loc, this.expr, "method group");
3271 // Next, evaluate all the expressions in the argument list
3273 if (Arguments != null){
3274 for (int i = Arguments.Count; i > 0;){
3276 Argument a = (Argument) Arguments [i];
3278 if (!a.Resolve (ec, loc))
3283 method = OverloadResolve (ec, (MethodGroupExpr) this.expr, Arguments, loc);
3285 if (method == null){
3287 "Could not find any applicable function for this argument list");
3291 if (method is MethodInfo)
3292 type = ((MethodInfo)method).ReturnType;
3294 eclass = ExprClass.Value;
3299 // Emits the list of arguments as an array
3301 static void EmitParams (EmitContext ec, int idx, ArrayList arguments)
3303 ILGenerator ig = ec.ig;
3304 int count = arguments.Count - idx;
3305 Argument a = (Argument) arguments [idx];
3306 Type t = a.expr.Type;
3307 string array_type = t.FullName + "[]";
3310 array = ig.DeclareLocal (Type.GetType (array_type));
3311 IntConstant.EmitInt (ig, count);
3312 ig.Emit (OpCodes.Newarr, t);
3313 ig.Emit (OpCodes.Stloc, array);
3315 int top = arguments.Count;
3316 for (int j = idx; j < top; j++){
3317 a = (Argument) arguments [j];
3319 ig.Emit (OpCodes.Ldloc, array);
3320 IntConstant.EmitInt (ig, j - idx);
3323 ArrayAccess.EmitStoreOpcode (ig, t);
3325 ig.Emit (OpCodes.Ldloc, array);
3329 /// Emits a list of resolved Arguments that are in the arguments
3332 /// The MethodBase argument might be null if the
3333 /// emission of the arguments is known not to contain
3334 /// a `params' field (for example in constructors or other routines
3335 /// that keep their arguments in this structure
3337 public static void EmitArguments (EmitContext ec, MethodBase mb, ArrayList arguments)
3339 ParameterData pd = null;
3342 if (arguments != null)
3343 top = arguments.Count;
3348 pd = GetParameterData (mb);
3350 for (int i = 0; i < top; i++){
3351 Argument a = (Argument) arguments [i];
3354 if (pd.ParameterModifier (i) == Parameter.Modifier.PARAMS){
3355 EmitParams (ec, i, arguments);
3365 /// is_base tells whether we want to force the use of the `call'
3366 /// opcode instead of using callvirt. Call is required to call
3367 /// a specific method, while callvirt will always use the most
3368 /// recent method in the vtable.
3370 /// is_static tells whether this is an invocation on a static method
3372 /// instance_expr is an expression that represents the instance
3373 /// it must be non-null if is_static is false.
3375 /// method is the method to invoke.
3377 /// Arguments is the list of arguments to pass to the method or constructor.
3379 public static void EmitCall (EmitContext ec, bool is_base,
3380 bool is_static, Expression instance_expr,
3381 MethodBase method, ArrayList Arguments)
3383 ILGenerator ig = ec.ig;
3384 bool struct_call = false;
3388 if (method.DeclaringType.IsValueType)
3391 // If this is ourselves, push "this"
3393 if (instance_expr == null){
3394 ig.Emit (OpCodes.Ldarg_0);
3397 // Push the instance expression
3399 if (instance_expr.Type.IsSubclassOf (TypeManager.value_type)){
3401 // Special case: calls to a function declared in a
3402 // reference-type with a value-type argument need
3403 // to have their value boxed.
3406 if (method.DeclaringType.IsValueType){
3408 // If the expression implements IMemoryLocation, then
3409 // we can optimize and use AddressOf on the
3412 // If not we have to use some temporary storage for
3414 if (instance_expr is IMemoryLocation){
3415 ((IMemoryLocation)instance_expr).
3419 Type t = instance_expr.Type;
3421 instance_expr.Emit (ec);
3422 LocalBuilder temp = ig.DeclareLocal (t);
3423 ig.Emit (OpCodes.Stloc, temp);
3424 ig.Emit (OpCodes.Ldloca, temp);
3427 instance_expr.Emit (ec);
3428 ig.Emit (OpCodes.Box, instance_expr.Type);
3431 instance_expr.Emit (ec);
3435 if (Arguments != null)
3436 EmitArguments (ec, method, Arguments);
3438 if (method is MethodInfo){
3439 MethodInfo mi = (MethodInfo) method;
3445 if (is_static || struct_call || is_base){
3446 if (method is MethodInfo)
3447 ig.Emit (OpCodes.Call, (MethodInfo) method);
3449 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
3451 if (method is MethodInfo)
3452 ig.Emit (OpCodes.Callvirt, (MethodInfo) method);
3454 ig.Emit (OpCodes.Callvirt, (ConstructorInfo) method);
3458 public override void Emit (EmitContext ec)
3460 MethodGroupExpr mg = (MethodGroupExpr) this.expr;
3462 EmitCall (ec, is_base, method.IsStatic, mg.InstanceExpression, method, Arguments);
3465 public override void EmitStatement (EmitContext ec)
3470 // Pop the return value if there is one
3472 if (method is MethodInfo){
3473 if (((MethodInfo)method).ReturnType != TypeManager.void_type)
3474 ec.ig.Emit (OpCodes.Pop);
3480 /// Implements the new expression
3482 public class New : ExpressionStatement {
3483 public readonly ArrayList Arguments;
3484 public readonly string RequestedType;
3487 MethodBase method = null;
3490 // If set, the new expression is for a value_target, and
3491 // we will not leave anything on the stack.
3493 Expression value_target;
3495 public New (string requested_type, ArrayList arguments, Location l)
3497 RequestedType = requested_type;
3498 Arguments = arguments;
3502 public Expression ValueTypeVariable {
3504 return value_target;
3508 value_target = value;
3512 public override Expression DoResolve (EmitContext ec)
3514 type = RootContext.LookupType (ec.TypeContainer, RequestedType, false, loc);
3519 bool IsDelegate = TypeManager.IsDelegateType (type);
3522 return (new NewDelegate (type, Arguments, loc)).Resolve (ec);
3524 bool is_struct = false;
3525 is_struct = type.IsSubclassOf (TypeManager.value_type);
3526 eclass = ExprClass.Value;
3529 // SRE returns a match for .ctor () on structs (the object constructor),
3530 // so we have to manually ignore it.
3532 if (is_struct && Arguments == null)
3536 ml = MemberLookup (ec, type, ".ctor", MemberTypes.Constructor, AllBindingFlags, loc);
3538 if (! (ml is MethodGroupExpr)){
3540 report118 (loc, ml, "method group");
3546 if (Arguments != null){
3547 for (int i = Arguments.Count; i > 0;){
3549 Argument a = (Argument) Arguments [i];
3551 if (!a.Resolve (ec, loc))
3556 method = Invocation.OverloadResolve (ec, (MethodGroupExpr) ml,
3561 if (method == null && !is_struct) {
3563 "New invocation: Can not find a constructor for " +
3564 "this argument list");
3571 // This DoEmit can be invoked in two contexts:
3572 // * As a mechanism that will leave a value on the stack (new object)
3573 // * As one that wont (init struct)
3575 // You can control whether a value is required on the stack by passing
3576 // need_value_on_stack. The code *might* leave a value on the stack
3577 // so it must be popped manually
3579 // If we are dealing with a ValueType, we have a few
3580 // situations to deal with:
3582 // * The target is a ValueType, and we have been provided
3583 // the instance (this is easy, we are being assigned).
3585 // * The target of New is being passed as an argument,
3586 // to a boxing operation or a function that takes a
3589 // In this case, we need to create a temporary variable
3590 // that is the argument of New.
3592 // Returns whether a value is left on the stack
3594 bool DoEmit (EmitContext ec, bool need_value_on_stack)
3596 bool is_value_type = type.IsSubclassOf (TypeManager.value_type);
3597 ILGenerator ig = ec.ig;
3602 if (value_target == null)
3603 value_target = new LocalTemporary (ec, type);
3605 ml = (IMemoryLocation) value_target;
3610 Invocation.EmitArguments (ec, method, Arguments);
3614 ig.Emit (OpCodes.Initobj, type);
3616 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
3618 if (need_value_on_stack){
3619 value_target.Emit (ec);
3624 ig.Emit (OpCodes.Newobj, (ConstructorInfo) method);
3629 public override void Emit (EmitContext ec)
3634 public override void EmitStatement (EmitContext ec)
3636 if (DoEmit (ec, false))
3637 ec.ig.Emit (OpCodes.Pop);
3642 /// Represents an array creation expression.
3646 /// There are two possible scenarios here: one is an array creation
3647 /// expression that specifies the dimensions and optionally the
3648 /// initialization data and the other which does not need dimensions
3649 /// specified but where initialization data is mandatory.
3651 public class ArrayCreation : ExpressionStatement {
3652 string RequestedType;
3654 ArrayList Initializers;
3656 ArrayList Arguments;
3658 MethodBase method = null;
3659 Type array_element_type;
3660 bool IsOneDimensional = false;
3661 bool IsBuiltinType = false;
3662 bool ExpectInitializers = false;
3665 Type underlying_type;
3667 ArrayList ArrayData;
3672 // The number of array initializers that we can handle
3673 // via the InitializeArray method - through EmitStaticInitializers
3675 int num_automatic_initializers;
3677 public ArrayCreation (string requested_type, ArrayList exprs,
3678 string rank, ArrayList initializers, Location l)
3680 RequestedType = requested_type;
3682 Initializers = initializers;
3685 Arguments = new ArrayList ();
3687 foreach (Expression e in exprs)
3688 Arguments.Add (new Argument (e, Argument.AType.Expression));
3691 public ArrayCreation (string requested_type, string rank, ArrayList initializers, Location l)
3693 RequestedType = requested_type;
3694 Initializers = initializers;
3697 Rank = rank.Substring (0, rank.LastIndexOf ("["));
3699 string tmp = rank.Substring (rank.LastIndexOf ("["));
3701 dimensions = tmp.Length - 1;
3702 ExpectInitializers = true;
3705 public static string FormArrayType (string base_type, int idx_count, string rank)
3707 StringBuilder sb = new StringBuilder (base_type);
3712 for (int i = 1; i < idx_count; i++)
3717 return sb.ToString ();
3720 public static string FormElementType (string base_type, int idx_count, string rank)
3722 StringBuilder sb = new StringBuilder (base_type);
3725 for (int i = 1; i < idx_count; i++)
3732 string val = sb.ToString ();
3734 return val.Substring (0, val.LastIndexOf ("["));
3739 Report.Error (178, loc, "Incorrectly structured array initializer");
3742 public bool CheckIndices (EmitContext ec, ArrayList probe, int idx, bool specified_dims)
3744 if (specified_dims) {
3745 Argument a = (Argument) Arguments [idx];
3747 if (!a.Resolve (ec, loc))
3750 if (!(a.Expr is Constant)) {
3751 Report.Error (150, loc, "A constant value is expected");
3755 int value = (int) ((Constant) a.Expr).GetValue ();
3757 if (value != probe.Count) {
3762 Bounds [idx] = value;
3765 foreach (object o in probe) {
3766 if (o is ArrayList) {
3767 bool ret = CheckIndices (ec, (ArrayList) o, idx + 1, specified_dims);
3771 Expression tmp = (Expression) o;
3772 tmp = tmp.Resolve (ec);
3776 // Handle initialization from vars, fields etc.
3778 Expression conv = ConvertImplicitRequired (
3779 ec, tmp, underlying_type, loc);
3784 if (conv is StringConstant)
3785 ArrayData.Add (conv);
3786 else if (conv is Constant) {
3787 ArrayData.Add (conv);
3788 num_automatic_initializers++;
3790 ArrayData.Add (conv);
3797 public void UpdateIndices (EmitContext ec)
3800 for (ArrayList probe = Initializers; probe != null;) {
3801 if (probe.Count > 0 && probe [0] is ArrayList) {
3802 Expression e = new IntConstant (probe.Count);
3803 Arguments.Add (new Argument (e, Argument.AType.Expression));
3805 Bounds [i++] = probe.Count;
3807 probe = (ArrayList) probe [0];
3810 Expression e = new IntConstant (probe.Count);
3811 Arguments.Add (new Argument (e, Argument.AType.Expression));
3813 Bounds [i++] = probe.Count;
3820 public bool ValidateInitializers (EmitContext ec)
3822 if (Initializers == null) {
3823 if (ExpectInitializers)
3829 underlying_type = RootContext.LookupType (
3830 ec.TypeContainer, RequestedType, false, loc);
3833 // We use this to store all the date values in the order in which we
3834 // will need to store them in the byte blob later
3836 ArrayData = new ArrayList ();
3837 Bounds = new Hashtable ();
3841 if (Arguments != null) {
3842 ret = CheckIndices (ec, Initializers, 0, true);
3846 Arguments = new ArrayList ();
3848 ret = CheckIndices (ec, Initializers, 0, false);
3855 if (Arguments.Count != dimensions) {
3864 public override Expression DoResolve (EmitContext ec)
3869 // First step is to validate the initializers and fill
3870 // in any missing bits
3872 if (!ValidateInitializers (ec))
3875 if (Arguments == null)
3878 arg_count = Arguments.Count;
3879 for (int i = arg_count; i > 0;){
3881 Argument a = (Argument) Arguments [i];
3883 if (!a.Resolve (ec, loc))
3888 string array_type = FormArrayType (RequestedType, arg_count, Rank);
3889 string element_type = FormElementType (RequestedType, arg_count, Rank);
3891 type = RootContext.LookupType (ec.TypeContainer, array_type, false, loc);
3893 array_element_type = RootContext.LookupType (
3894 ec.TypeContainer, element_type, false, loc);
3899 if (arg_count == 1) {
3900 IsOneDimensional = true;
3901 eclass = ExprClass.Value;
3905 IsBuiltinType = TypeManager.IsBuiltinType (type);
3907 if (IsBuiltinType) {
3911 ml = MemberLookup (ec, type, ".ctor", MemberTypes.Constructor,
3912 AllBindingFlags, loc);
3914 if (!(ml is MethodGroupExpr)){
3915 report118 (loc, ml, "method group");
3920 Report.Error (-6, loc, "New invocation: Can not find a constructor for " +
3921 "this argument list");
3925 method = Invocation.OverloadResolve (ec, (MethodGroupExpr) ml, Arguments, loc);
3927 if (method == null) {
3928 Report.Error (-6, loc, "New invocation: Can not find a constructor for " +
3929 "this argument list");
3933 eclass = ExprClass.Value;
3938 ModuleBuilder mb = RootContext.ModuleBuilder;
3940 ArrayList args = new ArrayList ();
3941 if (Arguments != null){
3942 for (int i = arg_count; i > 0;){
3944 Argument a = (Argument) Arguments [i];
3950 Type [] arg_types = null;
3953 arg_types = new Type [args.Count];
3955 args.CopyTo (arg_types, 0);
3957 method = mb.GetArrayMethod (type, ".ctor", CallingConventions.HasThis, null,
3960 if (method == null) {
3961 Report.Error (-6, loc, "New invocation: Can not find a constructor for " +
3962 "this argument list");
3966 eclass = ExprClass.Value;
3972 public static byte [] MakeByteBlob (ArrayList ArrayData, Type underlying_type, Location loc)
3977 int count = ArrayData.Count;
3979 if (underlying_type == TypeManager.int32_type ||
3980 underlying_type == TypeManager.uint32_type ||
3981 underlying_type == TypeManager.float_type)
3983 else if (underlying_type == TypeManager.int64_type ||
3984 underlying_type == TypeManager.uint64_type ||
3985 underlying_type == TypeManager.double_type)
3987 else if (underlying_type == TypeManager.byte_type ||
3988 underlying_type == TypeManager.sbyte_type ||
3989 underlying_type == TypeManager.bool_type)
3991 else if (underlying_type == TypeManager.short_type ||
3992 underlying_type == TypeManager.char_type ||
3993 underlying_type == TypeManager.ushort_type)
3998 data = new byte [(count * factor + 4) & ~3];
4001 for (int i = 0; i < count; ++i) {
4002 object v = ArrayData [i];
4004 if (v is EnumConstant)
4005 v = ((EnumConstant) v).Child;
4007 if (v is Constant && !(v is StringConstant))
4008 v = ((Constant) v).GetValue ();
4014 if (underlying_type == TypeManager.int64_type){
4015 if (!(v is Expression)){
4016 long val = (long) v;
4018 for (int j = 0; j < factor; ++j) {
4019 data [idx + j] = (byte) (val & 0xFF);
4023 } else if (underlying_type == TypeManager.uint64_type){
4024 if (!(v is Expression)){
4025 ulong val = (ulong) v;
4027 for (int j = 0; j < factor; ++j) {
4028 data [idx + j] = (byte) (val & 0xFF);
4032 } else if (underlying_type == TypeManager.float_type) {
4036 if (!(v is Expression)){
4037 float val = (float) v;
4039 byte *ptr = (byte *) &val;
4041 for (int j = 0; j < factor; ++j)
4042 data [idx + j] = (byte) ptr [j];
4046 } else if (underlying_type == TypeManager.double_type) {
4050 if (!(v is Expression)){
4051 double val = (double) v;
4053 byte *ptr = (byte *) &val;
4055 for (int j = 0; j < factor; ++j)
4056 data [idx + j] = (byte) ptr [j];
4060 } else if (underlying_type == TypeManager.char_type){
4062 if (!(v is Expression)){
4063 int val = (int) ((char) v);
4065 data [idx] = (byte) (val & 0xff);
4066 data [idx+1] = (byte) (val >> 8);
4068 } else if (underlying_type == TypeManager.short_type){
4069 if (!(v is Expression)){
4070 int val = (int) ((short) v);
4072 data [idx] = (byte) (val & 0xff);
4073 data [idx+1] = (byte) (val >> 8);
4075 } else if (underlying_type == TypeManager.ushort_type){
4076 if (!(v is Expression)){
4077 int val = (int) ((ushort) v);
4079 data [idx] = (byte) (val & 0xff);
4080 data [idx+1] = (byte) (val >> 8);
4082 } else if (underlying_type == TypeManager.int32_type) {
4083 if (!(v is Expression)){
4086 data [idx] = (byte) (val & 0xff);
4087 data [idx+1] = (byte) ((val >> 8) & 0xff);
4088 data [idx+2] = (byte) ((val >> 16) & 0xff);
4089 data [idx+3] = (byte) (val >> 24);
4091 } else if (underlying_type == TypeManager.uint32_type) {
4092 if (!(v is Expression)){
4093 uint val = (uint) v;
4095 data [idx] = (byte) (val & 0xff);
4096 data [idx+1] = (byte) ((val >> 8) & 0xff);
4097 data [idx+2] = (byte) ((val >> 16) & 0xff);
4098 data [idx+3] = (byte) (val >> 24);
4100 } else if (underlying_type == TypeManager.sbyte_type) {
4101 if (!(v is Expression)){
4102 sbyte val = (sbyte) v;
4103 data [idx] = (byte) val;
4105 } else if (underlying_type == TypeManager.byte_type) {
4106 if (!(v is Expression)){
4107 byte val = (byte) v;
4108 data [idx] = (byte) val;
4111 throw new Exception ("Unrecognized type in MakeByteBlob");
4120 // Emits the initializers for the array
4122 void EmitStaticInitializers (EmitContext ec, bool is_expression)
4125 // First, the static data
4128 ILGenerator ig = ec.ig;
4130 byte [] data = MakeByteBlob (ArrayData, underlying_type, loc);
4133 fb = RootContext.MakeStaticData (data);
4136 ig.Emit (OpCodes.Dup);
4137 ig.Emit (OpCodes.Ldtoken, fb);
4138 ig.Emit (OpCodes.Call,
4139 TypeManager.void_initializearray_array_fieldhandle);
4144 // Emits pieces of the array that can not be computed at compile
4145 // time (variables and string locations).
4147 // This always expect the top value on the stack to be the array
4149 void EmitDynamicInitializers (EmitContext ec, bool is_expression)
4151 ILGenerator ig = ec.ig;
4152 int dims = Bounds.Count;
4153 int [] current_pos = new int [dims];
4154 int top = ArrayData.Count;
4155 LocalBuilder temp = ig.DeclareLocal (type);
4157 ig.Emit (OpCodes.Stloc, temp);
4159 MethodInfo set = null;
4163 ModuleBuilder mb = null;
4164 mb = RootContext.ModuleBuilder;
4165 args = new Type [dims + 1];
4168 for (j = 0; j < dims; j++)
4169 args [j] = TypeManager.int32_type;
4171 args [j] = array_element_type;
4173 set = mb.GetArrayMethod (
4175 CallingConventions.HasThis | CallingConventions.Standard,
4176 TypeManager.void_type, args);
4179 for (int i = 0; i < top; i++){
4181 Expression e = null;
4183 if (ArrayData [i] is Expression)
4184 e = (Expression) ArrayData [i];
4188 // Basically we do this for string literals and
4189 // other non-literal expressions
4191 if (e is StringConstant || !(e is Constant) || num_automatic_initializers <= 2) {
4193 ig.Emit (OpCodes.Ldloc, temp);
4195 for (int idx = dims; idx > 0; ) {
4197 IntConstant.EmitInt (ig, current_pos [idx]);
4203 ArrayAccess.EmitStoreOpcode (ig, array_element_type);
4205 ig.Emit (OpCodes.Call, set);
4213 for (int j = 0; j < dims; j++){
4215 if (current_pos [j] < (int) Bounds [j])
4217 current_pos [j] = 0;
4222 ig.Emit (OpCodes.Ldloc, temp);
4225 void DoEmit (EmitContext ec, bool is_statement)
4227 ILGenerator ig = ec.ig;
4229 if (IsOneDimensional) {
4230 Invocation.EmitArguments (ec, null, Arguments);
4231 ig.Emit (OpCodes.Newarr, array_element_type);
4234 Invocation.EmitArguments (ec, null, Arguments);
4237 ig.Emit (OpCodes.Newobj, (ConstructorInfo) method);
4239 ig.Emit (OpCodes.Newobj, (MethodInfo) method);
4242 if (Initializers != null){
4244 // FIXME: Set this variable correctly.
4246 bool dynamic_initializers = true;
4248 if (underlying_type != TypeManager.string_type &&
4249 underlying_type != TypeManager.object_type) {
4250 if (num_automatic_initializers > 2)
4251 EmitStaticInitializers (ec, dynamic_initializers || !is_statement);
4254 if (dynamic_initializers)
4255 EmitDynamicInitializers (ec, !is_statement);
4259 public override void Emit (EmitContext ec)
4264 public override void EmitStatement (EmitContext ec)
4272 /// Represents the `this' construct
4274 public class This : Expression, IAssignMethod, IMemoryLocation {
4277 public This (Location loc)
4282 public override Expression DoResolve (EmitContext ec)
4284 eclass = ExprClass.Variable;
4285 type = ec.TypeContainer.TypeBuilder;
4288 Report.Error (26, loc,
4289 "Keyword this not valid in static code");
4296 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
4300 if (ec.TypeContainer is Class){
4301 Report.Error (1604, loc, "Cannot assign to `this'");
4308 public override void Emit (EmitContext ec)
4310 ec.ig.Emit (OpCodes.Ldarg_0);
4313 public void EmitAssign (EmitContext ec, Expression source)
4316 ec.ig.Emit (OpCodes.Starg, 0);
4319 public void AddressOf (EmitContext ec)
4321 ec.ig.Emit (OpCodes.Ldarg_0);
4324 // FIGURE OUT WHY LDARG_S does not work
4326 // consider: struct X { int val; int P { set { val = value; }}}
4328 // Yes, this looks very bad. Look at `NOTAS' for
4330 // ec.ig.Emit (OpCodes.Ldarga_S, (byte) 0);
4335 /// Implements the typeof operator
4337 public class TypeOf : Expression {
4338 public readonly string QueriedType;
4342 public TypeOf (string queried_type, Location l)
4344 QueriedType = queried_type;
4348 public override Expression DoResolve (EmitContext ec)
4350 typearg = RootContext.LookupType (
4351 ec.TypeContainer, QueriedType, false, loc);
4353 if (typearg == null)
4356 type = TypeManager.type_type;
4357 eclass = ExprClass.Type;
4361 public override void Emit (EmitContext ec)
4363 ec.ig.Emit (OpCodes.Ldtoken, typearg);
4364 ec.ig.Emit (OpCodes.Call, TypeManager.system_type_get_type_from_handle);
4369 /// Implements the sizeof expression
4371 public class SizeOf : Expression {
4372 public readonly string QueriedType;
4374 public SizeOf (string queried_type)
4376 this.QueriedType = queried_type;
4379 public override Expression DoResolve (EmitContext ec)
4381 // FIXME: Implement;
4382 throw new Exception ("Unimplemented");
4386 public override void Emit (EmitContext ec)
4388 throw new Exception ("Implement me");
4393 /// Implements the member access expression
4395 public class MemberAccess : Expression {
4396 public readonly string Identifier;
4398 Expression member_lookup;
4401 public MemberAccess (Expression expr, string id, Location l)
4408 public Expression Expr {
4414 static void error176 (Location loc, string name)
4416 Report.Error (176, loc, "Static member `" +
4417 name + "' cannot be accessed " +
4418 "with an instance reference, qualify with a " +
4419 "type name instead");
4422 static bool IdenticalNameAndTypeName (EmitContext ec, Expression left_original, Location loc)
4424 if (left_original == null)
4427 if (!(left_original is SimpleName))
4430 SimpleName sn = (SimpleName) left_original;
4432 Type t = RootContext.LookupType (ec.TypeContainer, sn.Name, true, loc);
4439 public static Expression ResolveMemberAccess (EmitContext ec, Expression member_lookup,
4440 Expression left, Location loc,
4441 Expression left_original)
4446 if (member_lookup is MethodGroupExpr){
4447 MethodGroupExpr mg = (MethodGroupExpr) member_lookup;
4452 if (left is TypeExpr){
4453 if (!mg.RemoveInstanceMethods ()){
4454 SimpleName.Error120 (loc, mg.Methods [0].Name);
4458 return member_lookup;
4462 // Instance.MethodGroup
4464 if (!mg.RemoveStaticMethods ()){
4465 if (IdenticalNameAndTypeName (ec, left_original, loc)){
4466 if (!mg.RemoveInstanceMethods ()){
4467 SimpleName.Error120 (loc, mg.Methods [0].Name);
4470 return member_lookup;
4473 error176 (loc, mg.Methods [0].Name);
4477 mg.InstanceExpression = left;
4479 return member_lookup;
4482 if (member_lookup is FieldExpr){
4483 FieldExpr fe = (FieldExpr) member_lookup;
4484 FieldInfo fi = fe.FieldInfo;
4486 if (fi is FieldBuilder) {
4487 Const c = TypeManager.LookupConstant ((FieldBuilder) fi);
4490 object o = c.LookupConstantValue (ec);
4491 object real_value = ((Constant) c.Expr).GetValue ();
4492 return Constantify (real_value, fi.FieldType);
4497 Type t = fi.FieldType;
4498 Type decl_type = fi.DeclaringType;
4501 if (fi is FieldBuilder)
4502 o = TypeManager.GetValue ((FieldBuilder) fi);
4504 o = fi.GetValue (fi);
4506 if (decl_type.IsSubclassOf (TypeManager.enum_type)) {
4507 Expression enum_member = MemberLookup (
4508 ec, decl_type, "value__", loc);
4510 Enum en = TypeManager.LookupEnum (decl_type);
4514 c = Constantify (o, en.UnderlyingType);
4516 c = Constantify (o, enum_member.Type);
4518 return new EnumConstant (c, decl_type);
4521 Expression exp = Constantify (o, t);
4523 if (!(left is TypeExpr)) {
4524 error176 (loc, fe.FieldInfo.Name);
4531 if (left is TypeExpr){
4532 // and refers to a type name or an
4533 if (!fe.FieldInfo.IsStatic){
4534 error176 (loc, fe.FieldInfo.Name);
4537 return member_lookup;
4539 if (fe.FieldInfo.IsStatic){
4540 if (IdenticalNameAndTypeName (ec, left_original, loc))
4541 return member_lookup;
4543 error176 (loc, fe.FieldInfo.Name);
4546 fe.InstanceExpression = left;
4552 if (member_lookup is PropertyExpr){
4553 PropertyExpr pe = (PropertyExpr) member_lookup;
4555 if (left is TypeExpr){
4557 SimpleName.Error120 (loc, pe.PropertyInfo.Name);
4563 if (IdenticalNameAndTypeName (ec, left_original, loc))
4564 return member_lookup;
4565 error176 (loc, pe.PropertyInfo.Name);
4568 pe.InstanceExpression = left;
4574 if (member_lookup is EventExpr) {
4576 EventExpr ee = (EventExpr) member_lookup;
4579 // If the event is local to this class, we transform ourselves into
4583 Expression ml = MemberLookup (
4584 ec, ec.TypeContainer.TypeBuilder,
4585 ee.EventInfo.Name, MemberTypes.Event, AllBindingFlags, loc);
4588 MemberInfo mi = ec.TypeContainer.GetFieldFromEvent ((EventExpr) ml);
4592 // If this happens, then we have an event with its own
4593 // accessors and private field etc so there's no need
4594 // to transform ourselves : we should instead flag an error
4596 Assign.error70 (ee.EventInfo, loc);
4600 ml = ExprClassFromMemberInfo (ec, mi, loc);
4603 Report.Error (-200, loc, "Internal error!!");
4606 return ResolveMemberAccess (ec, ml, left, loc, left_original);
4609 if (left is TypeExpr) {
4611 SimpleName.Error120 (loc, ee.EventInfo.Name);
4619 if (IdenticalNameAndTypeName (ec, left_original, loc))
4622 error176 (loc, ee.EventInfo.Name);
4626 ee.InstanceExpression = left;
4632 if (member_lookup is TypeExpr){
4633 member_lookup.Resolve (ec);
4634 return member_lookup;
4637 Console.WriteLine ("Left is: " + left);
4638 Report.Error (-100, loc, "Support for [" + member_lookup + "] is not present yet");
4639 Environment.Exit (0);
4643 public override Expression DoResolve (EmitContext ec)
4646 // We are the sole users of ResolveWithSimpleName (ie, the only
4647 // ones that can cope with it
4649 Expression original = expr;
4650 expr = expr.ResolveWithSimpleName (ec);
4655 if (expr is SimpleName){
4656 SimpleName child_expr = (SimpleName) expr;
4658 expr = new SimpleName (child_expr.Name + "." + Identifier, loc);
4660 return expr.ResolveWithSimpleName (ec);
4664 // Handle enums here when they are in transit.
4665 // Note that we cannot afford to hit MemberLookup in this case because
4666 // it will fail to find any members at all
4669 Type expr_type = expr.Type;
4670 if ((expr is TypeExpr) && (expr_type.IsSubclassOf (TypeManager.enum_type))){
4672 Enum en = TypeManager.LookupEnum (expr_type);
4675 object value = en.LookupEnumValue (ec, Identifier, loc);
4678 Constant c = Constantify (value, en.UnderlyingType);
4679 return new EnumConstant (c, expr_type);
4684 member_lookup = MemberLookup (ec, expr_type, Identifier, loc);
4686 if (member_lookup == null)
4689 return ResolveMemberAccess (ec, member_lookup, expr, loc, original);
4692 public override void Emit (EmitContext ec)
4694 throw new Exception ("Should not happen");
4699 /// Implements checked expressions
4701 public class CheckedExpr : Expression {
4703 public Expression Expr;
4705 public CheckedExpr (Expression e)
4710 public override Expression DoResolve (EmitContext ec)
4712 Expr = Expr.Resolve (ec);
4717 eclass = Expr.eclass;
4722 public override void Emit (EmitContext ec)
4724 bool last_check = ec.CheckState;
4726 ec.CheckState = true;
4728 ec.CheckState = last_check;
4734 /// Implements the unchecked expression
4736 public class UnCheckedExpr : Expression {
4738 public Expression Expr;
4740 public UnCheckedExpr (Expression e)
4745 public override Expression DoResolve (EmitContext ec)
4747 Expr = Expr.Resolve (ec);
4752 eclass = Expr.eclass;
4757 public override void Emit (EmitContext ec)
4759 bool last_check = ec.CheckState;
4761 ec.CheckState = false;
4763 ec.CheckState = last_check;
4769 /// An Element Access expression.
4771 /// During semantic analysis these are transformed into
4772 /// IndexerAccess or ArrayAccess
4774 public class ElementAccess : Expression {
4775 public ArrayList Arguments;
4776 public Expression Expr;
4777 public Location loc;
4779 public ElementAccess (Expression e, ArrayList e_list, Location l)
4788 Arguments = new ArrayList ();
4789 foreach (Expression tmp in e_list)
4790 Arguments.Add (new Argument (tmp, Argument.AType.Expression));
4794 bool CommonResolve (EmitContext ec)
4796 Expr = Expr.Resolve (ec);
4801 if (Arguments == null)
4804 for (int i = Arguments.Count; i > 0;){
4806 Argument a = (Argument) Arguments [i];
4808 if (!a.Resolve (ec, loc))
4815 public override Expression DoResolve (EmitContext ec)
4817 if (!CommonResolve (ec))
4821 // We perform some simple tests, and then to "split" the emit and store
4822 // code we create an instance of a different class, and return that.
4824 // I am experimenting with this pattern.
4826 if (Expr.Type.IsSubclassOf (TypeManager.array_type))
4827 return (new ArrayAccess (this)).Resolve (ec);
4829 return (new IndexerAccess (this)).Resolve (ec);
4832 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
4834 if (!CommonResolve (ec))
4837 if (Expr.Type.IsSubclassOf (TypeManager.array_type))
4838 return (new ArrayAccess (this)).ResolveLValue (ec, right_side);
4840 return (new IndexerAccess (this)).ResolveLValue (ec, right_side);
4843 public override void Emit (EmitContext ec)
4845 throw new Exception ("Should never be reached");
4850 /// Implements array access
4852 public class ArrayAccess : Expression, IAssignMethod, IMemoryLocation {
4854 // Points to our "data" repository
4858 public ArrayAccess (ElementAccess ea_data)
4861 eclass = ExprClass.Variable;
4864 public override Expression DoResolve (EmitContext ec)
4866 if (ea.Expr.eclass != ExprClass.Variable) {
4867 report118 (ea.loc, ea.Expr, "variable");
4871 Type t = ea.Expr.Type;
4873 if (t.GetArrayRank () != ea.Arguments.Count){
4874 Report.Error (22, ea.loc,
4875 "Incorrect number of indexes for array " +
4876 " expected: " + t.GetArrayRank () + " got: " +
4877 ea.Arguments.Count);
4880 type = t.GetElementType ();
4881 eclass = ExprClass.Variable;
4887 /// Emits the right opcode to load an object of Type `t'
4888 /// from an array of T
4890 static public void EmitLoadOpcode (ILGenerator ig, Type type)
4892 if (type == TypeManager.byte_type || type == TypeManager.bool_type)
4893 ig.Emit (OpCodes.Ldelem_I1);
4894 else if (type == TypeManager.sbyte_type)
4895 ig.Emit (OpCodes.Ldelem_U1);
4896 else if (type == TypeManager.short_type)
4897 ig.Emit (OpCodes.Ldelem_I2);
4898 else if (type == TypeManager.ushort_type)
4899 ig.Emit (OpCodes.Ldelem_U2);
4900 else if (type == TypeManager.int32_type)
4901 ig.Emit (OpCodes.Ldelem_I4);
4902 else if (type == TypeManager.uint32_type)
4903 ig.Emit (OpCodes.Ldelem_U4);
4904 else if (type == TypeManager.uint64_type)
4905 ig.Emit (OpCodes.Ldelem_I8);
4906 else if (type == TypeManager.int64_type)
4907 ig.Emit (OpCodes.Ldelem_I8);
4908 else if (type == TypeManager.float_type)
4909 ig.Emit (OpCodes.Ldelem_R4);
4910 else if (type == TypeManager.double_type)
4911 ig.Emit (OpCodes.Ldelem_R8);
4912 else if (type == TypeManager.intptr_type)
4913 ig.Emit (OpCodes.Ldelem_I);
4914 else if (type.IsValueType){
4915 ig.Emit (OpCodes.Ldelema, type);
4916 ig.Emit (OpCodes.Ldobj, type);
4918 ig.Emit (OpCodes.Ldelem_Ref);
4922 /// Emits the right opcode to store an object of Type `t'
4923 /// from an array of T.
4925 static public void EmitStoreOpcode (ILGenerator ig, Type t)
4927 if (t == TypeManager.byte_type || t == TypeManager.sbyte_type ||
4928 t == TypeManager.bool_type)
4929 ig.Emit (OpCodes.Stelem_I1);
4930 else if (t == TypeManager.short_type || t == TypeManager.ushort_type || t == TypeManager.char_type)
4931 ig.Emit (OpCodes.Stelem_I2);
4932 else if (t == TypeManager.int32_type || t == TypeManager.uint32_type)
4933 ig.Emit (OpCodes.Stelem_I4);
4934 else if (t == TypeManager.int64_type || t == TypeManager.uint64_type)
4935 ig.Emit (OpCodes.Stelem_I8);
4936 else if (t == TypeManager.float_type)
4937 ig.Emit (OpCodes.Stelem_R4);
4938 else if (t == TypeManager.double_type)
4939 ig.Emit (OpCodes.Stelem_R8);
4940 else if (t == TypeManager.intptr_type)
4941 ig.Emit (OpCodes.Stelem_I);
4942 else if (t.IsValueType)
4943 ig.Emit (OpCodes.Stobj, t);
4945 ig.Emit (OpCodes.Stelem_Ref);
4948 MethodInfo FetchGetMethod ()
4950 ModuleBuilder mb = RootContext.ModuleBuilder;
4951 Type [] args = new Type [ea.Arguments.Count];
4956 foreach (Argument a in ea.Arguments)
4957 args [i++] = a.Type;
4959 get = mb.GetArrayMethod (
4960 ea.Expr.Type, "Get",
4961 CallingConventions.HasThis |
4962 CallingConventions.Standard,
4968 MethodInfo FetchAddressMethod ()
4970 ModuleBuilder mb = RootContext.ModuleBuilder;
4971 Type [] args = new Type [ea.Arguments.Count];
4973 string ptr_type_name;
4977 ptr_type_name = type.FullName + "&";
4978 ret_type = Type.GetType (ptr_type_name);
4981 // It is a type defined by the source code we are compiling
4983 if (ret_type == null){
4984 ret_type = mb.GetType (ptr_type_name);
4987 foreach (Argument a in ea.Arguments)
4988 args [i++] = a.Type;
4990 address = mb.GetArrayMethod (
4991 ea.Expr.Type, "Address",
4992 CallingConventions.HasThis |
4993 CallingConventions.Standard,
4999 public override void Emit (EmitContext ec)
5001 int rank = ea.Expr.Type.GetArrayRank ();
5002 ILGenerator ig = ec.ig;
5006 foreach (Argument a in ea.Arguments)
5010 EmitLoadOpcode (ig, type);
5014 method = FetchGetMethod ();
5015 ig.Emit (OpCodes.Call, method);
5019 public void EmitAssign (EmitContext ec, Expression source)
5021 int rank = ea.Expr.Type.GetArrayRank ();
5022 ILGenerator ig = ec.ig;
5026 foreach (Argument a in ea.Arguments)
5029 Type t = source.Type;
5032 // The stobj opcode used by value types will need
5033 // an address on the stack, not really an array/array
5037 if (t.IsValueType && !TypeManager.IsBuiltinType (t))
5038 ig.Emit (OpCodes.Ldelema, t);
5044 EmitStoreOpcode (ig, t);
5046 ModuleBuilder mb = RootContext.ModuleBuilder;
5047 Type [] args = new Type [ea.Arguments.Count + 1];
5052 foreach (Argument a in ea.Arguments)
5053 args [i++] = a.Type;
5057 set = mb.GetArrayMethod (
5058 ea.Expr.Type, "Set",
5059 CallingConventions.HasThis |
5060 CallingConventions.Standard,
5061 TypeManager.void_type, args);
5063 ig.Emit (OpCodes.Call, set);
5067 public void AddressOf (EmitContext ec)
5069 int rank = ea.Expr.Type.GetArrayRank ();
5070 ILGenerator ig = ec.ig;
5074 foreach (Argument a in ea.Arguments)
5078 ig.Emit (OpCodes.Ldelema, type);
5080 MethodInfo address = FetchAddressMethod ();
5081 ig.Emit (OpCodes.Call, address);
5088 public ArrayList getters, setters;
5089 static Hashtable map;
5093 map = new Hashtable ();
5096 Indexers (MemberInfo [] mi)
5098 foreach (PropertyInfo property in mi){
5099 MethodInfo get, set;
5101 get = property.GetGetMethod (true);
5103 if (getters == null)
5104 getters = new ArrayList ();
5109 set = property.GetSetMethod (true);
5111 if (setters == null)
5112 setters = new ArrayList ();
5118 static public Indexers GetIndexersForType (Type t, TypeManager tm, Location loc)
5120 Indexers ix = (Indexers) map [t];
5121 string p_name = TypeManager.IndexerPropertyName (t);
5126 MemberInfo [] mi = tm.FindMembers (
5127 t, MemberTypes.Property,
5128 BindingFlags.Public | BindingFlags.Instance,
5129 Type.FilterName, p_name);
5131 if (mi == null || mi.Length == 0){
5132 Report.Error (21, loc,
5133 "Type `" + TypeManager.CSharpName (t) + "' does not have " +
5134 "any indexers defined");
5138 ix = new Indexers (mi);
5146 /// Expressions that represent an indexer call.
5148 public class IndexerAccess : Expression, IAssignMethod {
5150 // Points to our "data" repository
5153 MethodInfo get, set;
5155 ArrayList set_arguments;
5157 public IndexerAccess (ElementAccess ea_data)
5160 eclass = ExprClass.Value;
5163 public override Expression DoResolve (EmitContext ec)
5165 Type indexer_type = ea.Expr.Type;
5168 // Step 1: Query for all `Item' *properties*. Notice
5169 // that the actual methods are pointed from here.
5171 // This is a group of properties, piles of them.
5174 ilist = Indexers.GetIndexersForType (
5175 indexer_type, RootContext.TypeManager, ea.loc);
5179 // Step 2: find the proper match
5181 if (ilist != null && ilist.getters != null && ilist.getters.Count > 0)
5182 get = (MethodInfo) Invocation.OverloadResolve (
5183 ec, new MethodGroupExpr (ilist.getters), ea.Arguments, ea.loc);
5186 Report.Error (154, ea.loc,
5187 "indexer can not be used in this context, because " +
5188 "it lacks a `get' accessor");
5192 type = get.ReturnType;
5193 eclass = ExprClass.IndexerAccess;
5197 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
5199 Type indexer_type = ea.Expr.Type;
5200 Type right_type = right_side.Type;
5203 ilist = Indexers.GetIndexersForType (
5204 indexer_type, RootContext.TypeManager, ea.loc);
5206 if (ilist != null && ilist.setters != null && ilist.setters.Count > 0){
5207 set_arguments = (ArrayList) ea.Arguments.Clone ();
5208 set_arguments.Add (new Argument (right_side, Argument.AType.Expression));
5210 set = (MethodInfo) Invocation.OverloadResolve (
5211 ec, new MethodGroupExpr (ilist.setters), set_arguments, ea.loc);
5215 Report.Error (200, ea.loc,
5216 "indexer X.this [" + TypeManager.CSharpName (right_type) +
5217 "] lacks a `set' accessor");
5221 type = TypeManager.void_type;
5222 eclass = ExprClass.IndexerAccess;
5226 public override void Emit (EmitContext ec)
5228 Invocation.EmitCall (ec, false, false, ea.Expr, get, ea.Arguments);
5232 // source is ignored, because we already have a copy of it from the
5233 // LValue resolution and we have already constructed a pre-cached
5234 // version of the arguments (ea.set_arguments);
5236 public void EmitAssign (EmitContext ec, Expression source)
5238 Invocation.EmitCall (ec, false, false, ea.Expr, set, set_arguments);
5243 /// The base operator for method names
5245 public class BaseAccess : Expression {
5249 public BaseAccess (string member, Location l)
5251 this.member = member;
5255 public override Expression DoResolve (EmitContext ec)
5257 Expression member_lookup;
5258 Type current_type = ec.TypeContainer.TypeBuilder;
5259 Type base_type = current_type.BaseType;
5263 Report.Error (1511, loc,
5264 "Keyword base is not allowed in static method");
5268 member_lookup = MemberLookup (ec, base_type, member, loc);
5269 if (member_lookup == null)
5275 left = new TypeExpr (base_type);
5279 e = MemberAccess.ResolveMemberAccess (ec, member_lookup, left, loc, null);
5280 if (e is PropertyExpr){
5281 PropertyExpr pe = (PropertyExpr) e;
5289 public override void Emit (EmitContext ec)
5291 throw new Exception ("Should never be called");
5296 /// The base indexer operator
5298 public class BaseIndexerAccess : Expression {
5299 ArrayList Arguments;
5302 public BaseIndexerAccess (ArrayList args, Location l)
5308 public override Expression DoResolve (EmitContext ec)
5310 Type current_type = ec.TypeContainer.TypeBuilder;
5311 Type base_type = current_type.BaseType;
5312 Expression member_lookup;
5315 Report.Error (1511, loc,
5316 "Keyword base is not allowed in static method");
5320 member_lookup = MemberLookup (ec, base_type, "get_Item", loc);
5321 if (member_lookup == null)
5324 return MemberAccess.ResolveMemberAccess (ec, member_lookup, ec.This, loc, null);
5327 public override void Emit (EmitContext ec)
5329 throw new Exception ("Should never be called");
5334 /// This class exists solely to pass the Type around and to be a dummy
5335 /// that can be passed to the conversion functions (this is used by
5336 /// foreach implementation to typecast the object return value from
5337 /// get_Current into the proper type. All code has been generated and
5338 /// we only care about the side effect conversions to be performed
5340 public class EmptyExpression : Expression {
5341 public EmptyExpression ()
5343 type = TypeManager.object_type;
5344 eclass = ExprClass.Value;
5347 public EmptyExpression (Type t)
5350 eclass = ExprClass.Value;
5353 public override Expression DoResolve (EmitContext ec)
5358 public override void Emit (EmitContext ec)
5360 // nothing, as we only exist to not do anything.
5364 // This is just because we might want to reuse this bad boy
5365 // instead of creating gazillions of EmptyExpressions.
5366 // (CanConvertImplicit uses it)
5368 public void SetType (Type t)
5374 public class UserCast : Expression {
5378 public UserCast (MethodInfo method, Expression source)
5380 this.method = method;
5381 this.source = source;
5382 type = method.ReturnType;
5383 eclass = ExprClass.Value;
5386 public override Expression DoResolve (EmitContext ec)
5389 // We are born fully resolved
5394 public override void Emit (EmitContext ec)
5396 ILGenerator ig = ec.ig;
5400 if (method is MethodInfo)
5401 ig.Emit (OpCodes.Call, (MethodInfo) method);
5403 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
5410 // This class is used to "construct" the type during a typecast
5411 // operation. Since the Type.GetType class in .NET can parse
5412 // the type specification, we just use this to construct the type
5413 // one bit at a time.
5415 public class ComposedCast : Expression {
5420 public ComposedCast (Expression left, string dim, Location l)
5427 public override Expression DoResolve (EmitContext ec)
5429 left = left.Resolve (ec);
5433 if (left.eclass != ExprClass.Type){
5434 report118 (loc, left, "type");
5438 type = RootContext.LookupType (
5439 ec.TypeContainer, left.Type.FullName + dim, false, loc);
5443 eclass = ExprClass.Type;
5447 public override void Emit (EmitContext ec)
5449 throw new Exception ("This should never be called");