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");
403 type = Type.GetType (expr.Type.ToString () + "*");
408 Error (187, loc, "No such operator '" + OperName () + "' defined for type '" +
409 TypeManager.CSharpName (expr_type) + "'");
413 public override Expression DoResolve (EmitContext ec)
415 expr = expr.Resolve (ec);
420 eclass = ExprClass.Value;
421 return ResolveOperator (ec);
424 public override void Emit (EmitContext ec)
426 ILGenerator ig = ec.ig;
427 Type expr_type = expr.Type;
430 case Operator.UnaryPlus:
431 throw new Exception ("This should be caught by Resolve");
433 case Operator.UnaryNegation:
435 ig.Emit (OpCodes.Neg);
438 case Operator.LogicalNot:
440 ig.Emit (OpCodes.Ldc_I4_0);
441 ig.Emit (OpCodes.Ceq);
444 case Operator.OnesComplement:
446 ig.Emit (OpCodes.Not);
449 case Operator.AddressOf:
450 ((IMemoryLocation)expr).AddressOf (ec);
453 case Operator.Indirection:
454 throw new Exception ("Not implemented yet");
457 throw new Exception ("This should not happen: Operator = "
463 /// This will emit the child expression for `ec' avoiding the logical
464 /// not. The parent will take care of changing brfalse/brtrue
466 public void EmitLogicalNot (EmitContext ec)
468 if (oper != Operator.LogicalNot)
469 throw new Exception ("EmitLogicalNot can only be called with !expr");
477 /// Unary Mutator expressions (pre and post ++ and --)
481 /// UnaryMutator implements ++ and -- expressions. It derives from
482 /// ExpressionStatement becuase the pre/post increment/decrement
483 /// operators can be used in a statement context.
485 /// FIXME: Idea, we could split this up in two classes, one simpler
486 /// for the common case, and one with the extra fields for more complex
487 /// classes (indexers require temporary access; overloaded require method)
489 /// Maybe we should have classes PreIncrement, PostIncrement, PreDecrement,
490 /// PostDecrement, that way we could save the `Mode' byte as well.
492 public class UnaryMutator : ExpressionStatement {
493 public enum Mode : byte {
494 PreIncrement, PreDecrement, PostIncrement, PostDecrement
500 LocalTemporary temp_storage;
503 // This is expensive for the simplest case.
507 public UnaryMutator (Mode m, Expression e, Location l)
516 return (mode == Mode.PreIncrement || mode == Mode.PostIncrement) ?
520 void error23 (Type t)
523 23, loc, "Operator " + OperName () +
524 " cannot be applied to operand of type `" +
525 TypeManager.CSharpName (t) + "'");
529 /// Returns whether an object of type `t' can be incremented
530 /// or decremented with add/sub (ie, basically whether we can
531 /// use pre-post incr-decr operations on it, but it is not a
532 /// System.Decimal, which we require operator overloading to catch)
534 static bool IsIncrementableNumber (Type t)
536 return (t == TypeManager.sbyte_type) ||
537 (t == TypeManager.byte_type) ||
538 (t == TypeManager.short_type) ||
539 (t == TypeManager.ushort_type) ||
540 (t == TypeManager.int32_type) ||
541 (t == TypeManager.uint32_type) ||
542 (t == TypeManager.int64_type) ||
543 (t == TypeManager.uint64_type) ||
544 (t == TypeManager.char_type) ||
545 (t.IsSubclassOf (TypeManager.enum_type)) ||
546 (t == TypeManager.float_type) ||
547 (t == TypeManager.double_type);
550 Expression ResolveOperator (EmitContext ec)
552 Type expr_type = expr.Type;
555 // Step 1: Perform Operator Overload location
560 if (mode == Mode.PreIncrement || mode == Mode.PostIncrement)
561 op_name = "op_Increment";
563 op_name = "op_Decrement";
565 mg = MemberLookup (ec, expr_type, op_name, loc);
567 if (mg == null && expr_type.BaseType != null)
568 mg = MemberLookup (ec, expr_type.BaseType, op_name, loc);
571 method = StaticCallExpr.MakeSimpleCall (
572 ec, (MethodGroupExpr) mg, expr, loc);
579 // The operand of the prefix/postfix increment decrement operators
580 // should be an expression that is classified as a variable,
581 // a property access or an indexer access
584 if (expr.eclass == ExprClass.Variable){
585 if (IsIncrementableNumber (expr_type) ||
586 expr_type == TypeManager.decimal_type){
589 } else if (expr.eclass == ExprClass.IndexerAccess){
590 IndexerAccess ia = (IndexerAccess) expr;
592 temp_storage = new LocalTemporary (ec, expr.Type);
594 expr = ia.ResolveLValue (ec, temp_storage);
599 } else if (expr.eclass == ExprClass.PropertyAccess){
600 PropertyExpr pe = (PropertyExpr) expr;
602 if (pe.VerifyAssignable ())
607 report118 (loc, expr, "variable, indexer or property access");
611 Error (187, loc, "No such operator '" + OperName () + "' defined for type '" +
612 TypeManager.CSharpName (expr_type) + "'");
616 public override Expression DoResolve (EmitContext ec)
618 expr = expr.Resolve (ec);
623 eclass = ExprClass.Value;
624 return ResolveOperator (ec);
629 // FIXME: We need some way of avoiding the use of temp_storage
630 // for some types of storage (parameters, local variables,
631 // static fields) and single-dimension array access.
633 void EmitCode (EmitContext ec, bool is_expr)
635 ILGenerator ig = ec.ig;
636 IAssignMethod ia = (IAssignMethod) expr;
637 Type expr_type = expr.Type;
639 if (temp_storage == null)
640 temp_storage = new LocalTemporary (ec, expr_type);
643 case Mode.PreIncrement:
644 case Mode.PreDecrement:
648 if (expr_type == TypeManager.uint64_type ||
649 expr_type == TypeManager.int64_type)
650 ig.Emit (OpCodes.Ldc_I8, 1L);
651 else if (expr_type == TypeManager.double_type)
652 ig.Emit (OpCodes.Ldc_R8, 1.0);
653 else if (expr_type == TypeManager.float_type)
654 ig.Emit (OpCodes.Ldc_R4, 1.0F);
656 ig.Emit (OpCodes.Ldc_I4_1);
658 if (mode == Mode.PreDecrement)
659 ig.Emit (OpCodes.Sub);
661 ig.Emit (OpCodes.Add);
665 temp_storage.Store (ec);
666 ia.EmitAssign (ec, temp_storage);
668 temp_storage.Emit (ec);
671 case Mode.PostIncrement:
672 case Mode.PostDecrement:
680 ig.Emit (OpCodes.Dup);
682 if (expr_type == TypeManager.uint64_type ||
683 expr_type == TypeManager.int64_type)
684 ig.Emit (OpCodes.Ldc_I8, 1L);
685 else if (expr_type == TypeManager.double_type)
686 ig.Emit (OpCodes.Ldc_R8, 1.0);
687 else if (expr_type == TypeManager.float_type)
688 ig.Emit (OpCodes.Ldc_R4, 1.0F);
690 ig.Emit (OpCodes.Ldc_I4_1);
692 if (mode == Mode.PostDecrement)
693 ig.Emit (OpCodes.Sub);
695 ig.Emit (OpCodes.Add);
700 temp_storage.Store (ec);
701 ia.EmitAssign (ec, temp_storage);
706 public override void Emit (EmitContext ec)
712 public override void EmitStatement (EmitContext ec)
714 EmitCode (ec, false);
720 /// Base class for the `Is' and `As' classes.
724 /// FIXME: Split this in two, and we get to save the `Operator' Oper
727 public abstract class Probe : Expression {
728 public readonly string ProbeType;
729 protected Expression expr;
730 protected Type probe_type;
733 public Probe (Expression expr, string probe_type, Location l)
735 ProbeType = probe_type;
740 public Expression Expr {
746 public override Expression DoResolve (EmitContext ec)
748 probe_type = RootContext.LookupType (ec.TypeContainer, ProbeType, false, loc);
750 if (probe_type == null)
753 expr = expr.Resolve (ec);
760 /// Implementation of the `is' operator.
762 public class Is : Probe {
763 public Is (Expression expr, string probe_type, Location l)
764 : base (expr, probe_type, l)
768 public override void Emit (EmitContext ec)
770 ILGenerator ig = ec.ig;
774 ig.Emit (OpCodes.Isinst, probe_type);
775 ig.Emit (OpCodes.Ldnull);
776 ig.Emit (OpCodes.Cgt_Un);
779 public override Expression DoResolve (EmitContext ec)
781 Expression e = base.DoResolve (ec);
786 type = TypeManager.bool_type;
787 eclass = ExprClass.Value;
794 /// Implementation of the `as' operator.
796 public class As : Probe {
797 public As (Expression expr, string probe_type, Location l)
798 : base (expr, probe_type, l)
802 public override void Emit (EmitContext ec)
804 ILGenerator ig = ec.ig;
807 ig.Emit (OpCodes.Isinst, probe_type);
810 public override Expression DoResolve (EmitContext ec)
812 Expression e = base.DoResolve (ec);
818 eclass = ExprClass.Value;
825 /// This represents a typecast in the source language.
827 /// FIXME: Cast expressions have an unusual set of parsing
828 /// rules, we need to figure those out.
830 public class Cast : Expression {
831 Expression target_type;
835 public Cast (Expression cast_type, Expression expr, Location loc)
837 this.target_type = cast_type;
842 public Expression TargetType {
848 public Expression Expr {
858 /// Attempts to do a compile-time folding of a constant cast.
860 Expression TryReduce (EmitContext ec, Type target_type)
862 if (expr is ByteConstant){
863 byte v = ((ByteConstant) expr).Value;
865 if (target_type == TypeManager.sbyte_type)
866 return new SByteConstant ((sbyte) v);
867 if (target_type == TypeManager.short_type)
868 return new ShortConstant ((short) v);
869 if (target_type == TypeManager.ushort_type)
870 return new UShortConstant ((ushort) v);
871 if (target_type == TypeManager.int32_type)
872 return new IntConstant ((int) v);
873 if (target_type == TypeManager.uint32_type)
874 return new UIntConstant ((uint) v);
875 if (target_type == TypeManager.int64_type)
876 return new LongConstant ((long) v);
877 if (target_type == TypeManager.uint64_type)
878 return new ULongConstant ((ulong) v);
879 if (target_type == TypeManager.float_type)
880 return new FloatConstant ((float) v);
881 if (target_type == TypeManager.double_type)
882 return new DoubleConstant ((double) v);
884 if (expr is SByteConstant){
885 sbyte v = ((SByteConstant) expr).Value;
887 if (target_type == TypeManager.byte_type)
888 return new ByteConstant ((byte) v);
889 if (target_type == TypeManager.short_type)
890 return new ShortConstant ((short) v);
891 if (target_type == TypeManager.ushort_type)
892 return new UShortConstant ((ushort) v);
893 if (target_type == TypeManager.int32_type)
894 return new IntConstant ((int) v);
895 if (target_type == TypeManager.uint32_type)
896 return new UIntConstant ((uint) v);
897 if (target_type == TypeManager.int64_type)
898 return new LongConstant ((long) v);
899 if (target_type == TypeManager.uint64_type)
900 return new ULongConstant ((ulong) v);
901 if (target_type == TypeManager.float_type)
902 return new FloatConstant ((float) v);
903 if (target_type == TypeManager.double_type)
904 return new DoubleConstant ((double) v);
906 if (expr is ShortConstant){
907 short v = ((ShortConstant) expr).Value;
909 if (target_type == TypeManager.byte_type)
910 return new ByteConstant ((byte) v);
911 if (target_type == TypeManager.sbyte_type)
912 return new SByteConstant ((sbyte) v);
913 if (target_type == TypeManager.ushort_type)
914 return new UShortConstant ((ushort) v);
915 if (target_type == TypeManager.int32_type)
916 return new IntConstant ((int) v);
917 if (target_type == TypeManager.uint32_type)
918 return new UIntConstant ((uint) v);
919 if (target_type == TypeManager.int64_type)
920 return new LongConstant ((long) v);
921 if (target_type == TypeManager.uint64_type)
922 return new ULongConstant ((ulong) v);
923 if (target_type == TypeManager.float_type)
924 return new FloatConstant ((float) v);
925 if (target_type == TypeManager.double_type)
926 return new DoubleConstant ((double) v);
928 if (expr is UShortConstant){
929 ushort v = ((UShortConstant) expr).Value;
931 if (target_type == TypeManager.byte_type)
932 return new ByteConstant ((byte) v);
933 if (target_type == TypeManager.sbyte_type)
934 return new SByteConstant ((sbyte) v);
935 if (target_type == TypeManager.short_type)
936 return new ShortConstant ((short) v);
937 if (target_type == TypeManager.int32_type)
938 return new IntConstant ((int) v);
939 if (target_type == TypeManager.uint32_type)
940 return new UIntConstant ((uint) v);
941 if (target_type == TypeManager.int64_type)
942 return new LongConstant ((long) v);
943 if (target_type == TypeManager.uint64_type)
944 return new ULongConstant ((ulong) v);
945 if (target_type == TypeManager.float_type)
946 return new FloatConstant ((float) v);
947 if (target_type == TypeManager.double_type)
948 return new DoubleConstant ((double) v);
950 if (expr is IntConstant){
951 int v = ((IntConstant) expr).Value;
953 if (target_type == TypeManager.byte_type)
954 return new ByteConstant ((byte) v);
955 if (target_type == TypeManager.sbyte_type)
956 return new SByteConstant ((sbyte) v);
957 if (target_type == TypeManager.short_type)
958 return new ShortConstant ((short) v);
959 if (target_type == TypeManager.ushort_type)
960 return new UShortConstant ((ushort) v);
961 if (target_type == TypeManager.uint32_type)
962 return new UIntConstant ((uint) v);
963 if (target_type == TypeManager.int64_type)
964 return new LongConstant ((long) v);
965 if (target_type == TypeManager.uint64_type)
966 return new ULongConstant ((ulong) v);
967 if (target_type == TypeManager.float_type)
968 return new FloatConstant ((float) v);
969 if (target_type == TypeManager.double_type)
970 return new DoubleConstant ((double) v);
972 if (expr is UIntConstant){
973 uint v = ((UIntConstant) expr).Value;
975 if (target_type == TypeManager.byte_type)
976 return new ByteConstant ((byte) v);
977 if (target_type == TypeManager.sbyte_type)
978 return new SByteConstant ((sbyte) v);
979 if (target_type == TypeManager.short_type)
980 return new ShortConstant ((short) v);
981 if (target_type == TypeManager.ushort_type)
982 return new UShortConstant ((ushort) v);
983 if (target_type == TypeManager.int32_type)
984 return new IntConstant ((int) v);
985 if (target_type == TypeManager.int64_type)
986 return new LongConstant ((long) v);
987 if (target_type == TypeManager.uint64_type)
988 return new ULongConstant ((ulong) v);
989 if (target_type == TypeManager.float_type)
990 return new FloatConstant ((float) v);
991 if (target_type == TypeManager.double_type)
992 return new DoubleConstant ((double) v);
994 if (expr is LongConstant){
995 long v = ((LongConstant) expr).Value;
997 if (target_type == TypeManager.byte_type)
998 return new ByteConstant ((byte) v);
999 if (target_type == TypeManager.sbyte_type)
1000 return new SByteConstant ((sbyte) v);
1001 if (target_type == TypeManager.short_type)
1002 return new ShortConstant ((short) v);
1003 if (target_type == TypeManager.ushort_type)
1004 return new UShortConstant ((ushort) v);
1005 if (target_type == TypeManager.int32_type)
1006 return new IntConstant ((int) v);
1007 if (target_type == TypeManager.uint32_type)
1008 return new UIntConstant ((uint) v);
1009 if (target_type == TypeManager.uint64_type)
1010 return new ULongConstant ((ulong) v);
1011 if (target_type == TypeManager.float_type)
1012 return new FloatConstant ((float) v);
1013 if (target_type == TypeManager.double_type)
1014 return new DoubleConstant ((double) v);
1016 if (expr is ULongConstant){
1017 ulong v = ((ULongConstant) expr).Value;
1019 if (target_type == TypeManager.byte_type)
1020 return new ByteConstant ((byte) v);
1021 if (target_type == TypeManager.sbyte_type)
1022 return new SByteConstant ((sbyte) v);
1023 if (target_type == TypeManager.short_type)
1024 return new ShortConstant ((short) v);
1025 if (target_type == TypeManager.ushort_type)
1026 return new UShortConstant ((ushort) v);
1027 if (target_type == TypeManager.int32_type)
1028 return new IntConstant ((int) v);
1029 if (target_type == TypeManager.uint32_type)
1030 return new UIntConstant ((uint) v);
1031 if (target_type == TypeManager.int64_type)
1032 return new LongConstant ((long) v);
1033 if (target_type == TypeManager.float_type)
1034 return new FloatConstant ((float) v);
1035 if (target_type == TypeManager.double_type)
1036 return new DoubleConstant ((double) v);
1038 if (expr is FloatConstant){
1039 float v = ((FloatConstant) expr).Value;
1041 if (target_type == TypeManager.byte_type)
1042 return new ByteConstant ((byte) v);
1043 if (target_type == TypeManager.sbyte_type)
1044 return new SByteConstant ((sbyte) v);
1045 if (target_type == TypeManager.short_type)
1046 return new ShortConstant ((short) v);
1047 if (target_type == TypeManager.ushort_type)
1048 return new UShortConstant ((ushort) v);
1049 if (target_type == TypeManager.int32_type)
1050 return new IntConstant ((int) v);
1051 if (target_type == TypeManager.uint32_type)
1052 return new UIntConstant ((uint) v);
1053 if (target_type == TypeManager.int64_type)
1054 return new LongConstant ((long) v);
1055 if (target_type == TypeManager.uint64_type)
1056 return new ULongConstant ((ulong) v);
1057 if (target_type == TypeManager.double_type)
1058 return new DoubleConstant ((double) v);
1060 if (expr is DoubleConstant){
1061 double v = ((DoubleConstant) expr).Value;
1063 if (target_type == TypeManager.byte_type)
1064 return new ByteConstant ((byte) v);
1065 if (target_type == TypeManager.sbyte_type)
1066 return new SByteConstant ((sbyte) v);
1067 if (target_type == TypeManager.short_type)
1068 return new ShortConstant ((short) v);
1069 if (target_type == TypeManager.ushort_type)
1070 return new UShortConstant ((ushort) v);
1071 if (target_type == TypeManager.int32_type)
1072 return new IntConstant ((int) v);
1073 if (target_type == TypeManager.uint32_type)
1074 return new UIntConstant ((uint) v);
1075 if (target_type == TypeManager.int64_type)
1076 return new LongConstant ((long) v);
1077 if (target_type == TypeManager.uint64_type)
1078 return new ULongConstant ((ulong) v);
1079 if (target_type == TypeManager.float_type)
1080 return new FloatConstant ((float) v);
1086 public override Expression DoResolve (EmitContext ec)
1088 expr = expr.Resolve (ec);
1092 target_type = target_type.Resolve (ec);
1093 if (target_type == null)
1096 if (target_type.eclass != ExprClass.Type){
1097 report118 (loc, target_type, "class");
1101 type = target_type.Type;
1102 eclass = ExprClass.Value;
1107 if (expr is Constant){
1108 Expression e = TryReduce (ec, type);
1114 expr = ConvertExplicit (ec, expr, type, loc);
1118 public override void Emit (EmitContext ec)
1121 // This one will never happen
1123 throw new Exception ("Should not happen");
1128 /// Binary operators
1130 public class Binary : Expression {
1131 public enum Operator : byte {
1132 Multiply, Division, Modulus,
1133 Addition, Subtraction,
1134 LeftShift, RightShift,
1135 LessThan, GreaterThan, LessThanOrEqual, GreaterThanOrEqual,
1136 Equality, Inequality,
1145 Expression left, right;
1147 ArrayList Arguments;
1150 bool DelegateOperation;
1152 public Binary (Operator oper, Expression left, Expression right, Location loc)
1160 public Operator Oper {
1169 public Expression Left {
1178 public Expression Right {
1189 /// Returns a stringified representation of the Operator
1194 case Operator.Multiply:
1196 case Operator.Division:
1198 case Operator.Modulus:
1200 case Operator.Addition:
1202 case Operator.Subtraction:
1204 case Operator.LeftShift:
1206 case Operator.RightShift:
1208 case Operator.LessThan:
1210 case Operator.GreaterThan:
1212 case Operator.LessThanOrEqual:
1214 case Operator.GreaterThanOrEqual:
1216 case Operator.Equality:
1218 case Operator.Inequality:
1220 case Operator.BitwiseAnd:
1222 case Operator.BitwiseOr:
1224 case Operator.ExclusiveOr:
1226 case Operator.LogicalOr:
1228 case Operator.LogicalAnd:
1232 return oper.ToString ();
1235 Expression ForceConversion (EmitContext ec, Expression expr, Type target_type)
1237 if (expr.Type == target_type)
1240 return ConvertImplicit (ec, expr, target_type, new Location (-1));
1244 // Note that handling the case l == Decimal || r == Decimal
1245 // is taken care of by the Step 1 Operator Overload resolution.
1247 bool DoNumericPromotions (EmitContext ec, Type l, Type r)
1249 if (l == TypeManager.double_type || r == TypeManager.double_type){
1251 // If either operand is of type double, the other operand is
1252 // conveted to type double.
1254 if (r != TypeManager.double_type)
1255 right = ConvertImplicit (ec, right, TypeManager.double_type, loc);
1256 if (l != TypeManager.double_type)
1257 left = ConvertImplicit (ec, left, TypeManager.double_type, loc);
1259 type = TypeManager.double_type;
1260 } else if (l == TypeManager.float_type || r == TypeManager.float_type){
1262 // if either operand is of type float, th eother operand is
1263 // converd to type float.
1265 if (r != TypeManager.double_type)
1266 right = ConvertImplicit (ec, right, TypeManager.float_type, loc);
1267 if (l != TypeManager.double_type)
1268 left = ConvertImplicit (ec, left, TypeManager.float_type, loc);
1269 type = TypeManager.float_type;
1270 } else if (l == TypeManager.uint64_type || r == TypeManager.uint64_type){
1274 // If either operand is of type ulong, the other operand is
1275 // converted to type ulong. or an error ocurrs if the other
1276 // operand is of type sbyte, short, int or long
1278 if (l == TypeManager.uint64_type){
1279 if (r != TypeManager.uint64_type){
1280 if (right is IntConstant){
1281 IntConstant ic = (IntConstant) right;
1283 e = TryImplicitIntConversion (l, ic);
1286 } else if (right is LongConstant){
1287 long ll = ((LongConstant) right).Value;
1290 right = new ULongConstant ((ulong) ll);
1292 e = ImplicitNumericConversion (ec, right, l, loc);
1299 if (left is IntConstant){
1300 e = TryImplicitIntConversion (r, (IntConstant) left);
1303 } else if (left is LongConstant){
1304 long ll = ((LongConstant) left).Value;
1307 left = new ULongConstant ((ulong) ll);
1309 e = ImplicitNumericConversion (ec, left, r, loc);
1316 if ((other == TypeManager.sbyte_type) ||
1317 (other == TypeManager.short_type) ||
1318 (other == TypeManager.int32_type) ||
1319 (other == TypeManager.int64_type)){
1320 string oper = OperName ();
1322 Error (34, loc, "Operator `" + OperName ()
1323 + "' is ambiguous on operands of type `"
1324 + TypeManager.CSharpName (l) + "' "
1325 + "and `" + TypeManager.CSharpName (r)
1328 type = TypeManager.uint64_type;
1329 } else if (l == TypeManager.int64_type || r == TypeManager.int64_type){
1331 // If either operand is of type long, the other operand is converted
1334 if (l != TypeManager.int64_type)
1335 left = ConvertImplicit (ec, left, TypeManager.int64_type, loc);
1336 if (r != TypeManager.int64_type)
1337 right = ConvertImplicit (ec, right, TypeManager.int64_type, loc);
1339 type = TypeManager.int64_type;
1340 } else if (l == TypeManager.uint32_type || r == TypeManager.uint32_type){
1342 // If either operand is of type uint, and the other
1343 // operand is of type sbyte, short or int, othe operands are
1344 // converted to type long.
1348 if (l == TypeManager.uint32_type){
1349 if (right is IntConstant){
1350 IntConstant ic = (IntConstant) right;
1354 right = new UIntConstant ((uint) val);
1361 else if (r == TypeManager.uint32_type){
1362 if (left is IntConstant){
1363 IntConstant ic = (IntConstant) left;
1367 left = new UIntConstant ((uint) val);
1376 if ((other == TypeManager.sbyte_type) ||
1377 (other == TypeManager.short_type) ||
1378 (other == TypeManager.int32_type)){
1379 left = ForceConversion (ec, left, TypeManager.int64_type);
1380 right = ForceConversion (ec, right, TypeManager.int64_type);
1381 type = TypeManager.int64_type;
1384 // if either operand is of type uint, the other
1385 // operand is converd to type uint
1387 left = ForceConversion (ec, left, TypeManager.uint32_type);
1388 right = ForceConversion (ec, right, TypeManager.uint32_type);
1389 type = TypeManager.uint32_type;
1391 } else if (l == TypeManager.decimal_type || r == TypeManager.decimal_type){
1392 if (l != TypeManager.decimal_type)
1393 left = ConvertImplicit (ec, left, TypeManager.decimal_type, loc);
1394 if (r != TypeManager.decimal_type)
1395 right = ConvertImplicit (ec, right, TypeManager.decimal_type, loc);
1397 type = TypeManager.decimal_type;
1399 Expression l_tmp, r_tmp;
1401 l_tmp = ForceConversion (ec, left, TypeManager.int32_type);
1405 r_tmp = ForceConversion (ec, right, TypeManager.int32_type);
1412 type = TypeManager.int32_type;
1421 "Operator " + OperName () + " cannot be applied to operands of type `" +
1422 TypeManager.CSharpName (left.Type) + "' and `" +
1423 TypeManager.CSharpName (right.Type) + "'");
1427 Expression CheckShiftArguments (EmitContext ec)
1431 Type r = right.Type;
1433 e = ForceConversion (ec, right, TypeManager.int32_type);
1440 if (((e = ConvertImplicit (ec, left, TypeManager.int32_type, loc)) != null) ||
1441 ((e = ConvertImplicit (ec, left, TypeManager.uint32_type, loc)) != null) ||
1442 ((e = ConvertImplicit (ec, left, TypeManager.int64_type, loc)) != null) ||
1443 ((e = ConvertImplicit (ec, left, TypeManager.uint64_type, loc)) != null)){
1453 Expression ResolveOperator (EmitContext ec)
1456 Type r = right.Type;
1459 // Step 1: Perform Operator Overload location
1461 Expression left_expr, right_expr;
1463 string op = "op_" + oper;
1465 left_expr = MemberLookup (ec, l, op, loc);
1466 if (left_expr == null && l.BaseType != null)
1467 left_expr = MemberLookup (ec, l.BaseType, op, loc);
1469 right_expr = MemberLookup (ec, r, op, loc);
1470 if (right_expr == null && r.BaseType != null)
1471 right_expr = MemberLookup (ec, r.BaseType, op, loc);
1473 MethodGroupExpr union = Invocation.MakeUnionSet (left_expr, right_expr);
1475 if (union != null) {
1476 Arguments = new ArrayList ();
1477 Arguments.Add (new Argument (left, Argument.AType.Expression));
1478 Arguments.Add (new Argument (right, Argument.AType.Expression));
1480 method = Invocation.OverloadResolve (ec, union, Arguments, loc);
1481 if (method != null) {
1482 MethodInfo mi = (MethodInfo) method;
1483 type = mi.ReturnType;
1492 // Step 2: Default operations on CLI native types.
1495 // Only perform numeric promotions on:
1496 // +, -, *, /, %, &, |, ^, ==, !=, <, >, <=, >=
1498 if (oper == Operator.Addition){
1500 // If any of the arguments is a string, cast to string
1502 if (l == TypeManager.string_type){
1503 if (r == TypeManager.string_type){
1504 if (left is Constant && right is Constant){
1505 StringConstant ls = (StringConstant) left;
1506 StringConstant rs = (StringConstant) right;
1508 return new StringConstant (
1509 ls.Value + rs.Value);
1513 method = TypeManager.string_concat_string_string;
1516 method = TypeManager.string_concat_object_object;
1517 right = ConvertImplicit (ec, right,
1518 TypeManager.object_type, loc);
1520 type = TypeManager.string_type;
1522 Arguments = new ArrayList ();
1523 Arguments.Add (new Argument (left, Argument.AType.Expression));
1524 Arguments.Add (new Argument (right, Argument.AType.Expression));
1528 } else if (r == TypeManager.string_type){
1530 method = TypeManager.string_concat_object_object;
1531 Arguments = new ArrayList ();
1532 Arguments.Add (new Argument (left, Argument.AType.Expression));
1533 Arguments.Add (new Argument (right, Argument.AType.Expression));
1535 left = ConvertImplicit (ec, left, TypeManager.object_type, loc);
1536 type = TypeManager.string_type;
1542 if (oper == Operator.Addition || oper == Operator.Subtraction) {
1543 if (l.IsSubclassOf (TypeManager.delegate_type) &&
1544 r.IsSubclassOf (TypeManager.delegate_type)) {
1546 Arguments = new ArrayList ();
1547 Arguments.Add (new Argument (left, Argument.AType.Expression));
1548 Arguments.Add (new Argument (right, Argument.AType.Expression));
1550 if (oper == Operator.Addition)
1551 method = TypeManager.delegate_combine_delegate_delegate;
1553 method = TypeManager.delegate_remove_delegate_delegate;
1555 DelegateOperation = true;
1562 // Enumeration operators
1564 bool lie = TypeManager.IsEnumType (l);
1565 bool rie = TypeManager.IsEnumType (r);
1570 temp = ConvertImplicit (ec, right, l, loc);
1574 temp = ConvertImplicit (ec, left, r, loc);
1581 if (oper == Operator.Equality || oper == Operator.Inequality ||
1582 oper == Operator.LessThanOrEqual || oper == Operator.LessThan ||
1583 oper == Operator.GreaterThanOrEqual || oper == Operator.GreaterThan){
1584 type = TypeManager.bool_type;
1588 if (oper == Operator.BitwiseAnd ||
1589 oper == Operator.BitwiseOr ||
1590 oper == Operator.ExclusiveOr){
1596 if (oper == Operator.LeftShift || oper == Operator.RightShift)
1597 return CheckShiftArguments (ec);
1599 if (oper == Operator.LogicalOr || oper == Operator.LogicalAnd){
1600 if (l != TypeManager.bool_type || r != TypeManager.bool_type){
1605 type = TypeManager.bool_type;
1609 if (oper == Operator.Equality || oper == Operator.Inequality){
1610 if (l == TypeManager.bool_type || r == TypeManager.bool_type){
1611 if (r != TypeManager.bool_type || l != TypeManager.bool_type){
1616 type = TypeManager.bool_type;
1621 // operator != (object a, object b)
1622 // operator == (object a, object b)
1624 // For this to be used, both arguments have to be reference-types.
1625 // Read the rationale on the spec (14.9.6)
1627 // Also, if at compile time we know that the classes do not inherit
1628 // one from the other, then we catch the error there.
1630 if (!(l.IsValueType || r.IsValueType)){
1631 type = TypeManager.bool_type;
1636 if (l.IsSubclassOf (r) || r.IsSubclassOf (l))
1640 // We are going to have to convert to an object to compare
1642 if (l != TypeManager.object_type)
1643 left = new EmptyCast (left, TypeManager.object_type);
1644 if (r != TypeManager.object_type)
1645 right = new EmptyCast (right, TypeManager.object_type);
1652 // We are dealing with numbers
1655 if (!DoNumericPromotions (ec, l, r)){
1660 if (left == null || right == null)
1664 // reload our cached types if required
1669 if (oper == Operator.BitwiseAnd ||
1670 oper == Operator.BitwiseOr ||
1671 oper == Operator.ExclusiveOr){
1673 if (!((l == TypeManager.int32_type) ||
1674 (l == TypeManager.uint32_type) ||
1675 (l == TypeManager.int64_type) ||
1676 (l == TypeManager.uint64_type)))
1684 if (oper == Operator.Equality ||
1685 oper == Operator.Inequality ||
1686 oper == Operator.LessThanOrEqual ||
1687 oper == Operator.LessThan ||
1688 oper == Operator.GreaterThanOrEqual ||
1689 oper == Operator.GreaterThan){
1690 type = TypeManager.bool_type;
1697 /// Constant expression reducer for binary operations
1699 public Expression ConstantFold (EmitContext ec)
1701 object l = ((Constant) left).GetValue ();
1702 object r = ((Constant) right).GetValue ();
1704 if (l is string && r is string)
1705 return new StringConstant ((string) l + (string) r);
1707 Type result_type = null;
1710 // Enumerator folding
1712 if (left.Type == right.Type && left is EnumConstant)
1713 result_type = left.Type;
1716 case Operator.BitwiseOr:
1717 if ((l is int) && (r is int)){
1719 int res = (int)l | (int)r;
1721 v = new IntConstant (res);
1722 if (result_type == null)
1725 return new EnumConstant (v, result_type);
1729 case Operator.BitwiseAnd:
1730 if ((l is int) && (r is int)){
1732 int res = (int)l & (int)r;
1734 v = new IntConstant (res);
1735 if (result_type == null)
1738 return new EnumConstant (v, result_type);
1746 public override Expression DoResolve (EmitContext ec)
1748 left = left.Resolve (ec);
1749 right = right.Resolve (ec);
1751 if (left == null || right == null)
1754 if (left.Type == null)
1755 throw new Exception (
1756 "Resolve returned non null, but did not set the type! (" +
1757 left + ") at Line: " + loc.Row);
1758 if (right.Type == null)
1759 throw new Exception (
1760 "Resolve returned non null, but did not set the type! (" +
1761 right + ") at Line: "+ loc.Row);
1763 eclass = ExprClass.Value;
1765 if (left is Constant && right is Constant){
1767 // This is temporary until we do the full folding
1769 Expression e = ConstantFold (ec);
1774 return ResolveOperator (ec);
1777 public bool IsBranchable ()
1779 if (oper == Operator.Equality ||
1780 oper == Operator.Inequality ||
1781 oper == Operator.LessThan ||
1782 oper == Operator.GreaterThan ||
1783 oper == Operator.LessThanOrEqual ||
1784 oper == Operator.GreaterThanOrEqual){
1791 /// This entry point is used by routines that might want
1792 /// to emit a brfalse/brtrue after an expression, and instead
1793 /// they could use a more compact notation.
1795 /// Typically the code would generate l.emit/r.emit, followed
1796 /// by the comparission and then a brtrue/brfalse. The comparissions
1797 /// are sometimes inneficient (there are not as complete as the branches
1798 /// look for the hacks in Emit using double ceqs).
1800 /// So for those cases we provide EmitBranchable that can emit the
1801 /// branch with the test
1803 public void EmitBranchable (EmitContext ec, int target)
1806 bool close_target = false;
1807 ILGenerator ig = ec.ig;
1810 // short-circuit operators
1812 if (oper == Operator.LogicalAnd){
1814 ig.Emit (OpCodes.Brfalse, target);
1816 ig.Emit (OpCodes.Brfalse, target);
1817 } else if (oper == Operator.LogicalOr){
1819 ig.Emit (OpCodes.Brtrue, target);
1821 ig.Emit (OpCodes.Brfalse, target);
1828 case Operator.Equality:
1830 opcode = OpCodes.Beq_S;
1832 opcode = OpCodes.Beq;
1835 case Operator.Inequality:
1837 opcode = OpCodes.Bne_Un_S;
1839 opcode = OpCodes.Bne_Un;
1842 case Operator.LessThan:
1844 opcode = OpCodes.Blt_S;
1846 opcode = OpCodes.Blt;
1849 case Operator.GreaterThan:
1851 opcode = OpCodes.Bgt_S;
1853 opcode = OpCodes.Bgt;
1856 case Operator.LessThanOrEqual:
1858 opcode = OpCodes.Ble_S;
1860 opcode = OpCodes.Ble;
1863 case Operator.GreaterThanOrEqual:
1865 opcode = OpCodes.Bge_S;
1867 opcode = OpCodes.Ble;
1871 throw new Exception ("EmitBranchable called on non-EmitBranchable operator: "
1872 + oper.ToString ());
1875 ig.Emit (opcode, target);
1878 public override void Emit (EmitContext ec)
1880 ILGenerator ig = ec.ig;
1882 Type r = right.Type;
1885 if (method != null) {
1887 // Note that operators are static anyway
1889 if (Arguments != null)
1890 Invocation.EmitArguments (ec, method, Arguments);
1892 if (method is MethodInfo)
1893 ig.Emit (OpCodes.Call, (MethodInfo) method);
1895 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
1897 if (DelegateOperation)
1898 ig.Emit (OpCodes.Castclass, type);
1904 // Handle short-circuit operators differently
1907 if (oper == Operator.LogicalAnd){
1908 Label load_zero = ig.DefineLabel ();
1909 Label end = ig.DefineLabel ();
1912 ig.Emit (OpCodes.Brfalse, load_zero);
1914 ig.Emit (OpCodes.Br, end);
1915 ig.MarkLabel (load_zero);
1916 ig.Emit (OpCodes.Ldc_I4_0);
1919 } else if (oper == Operator.LogicalOr){
1920 Label load_one = ig.DefineLabel ();
1921 Label end = ig.DefineLabel ();
1924 ig.Emit (OpCodes.Brtrue, load_one);
1926 ig.Emit (OpCodes.Br, end);
1927 ig.MarkLabel (load_one);
1928 ig.Emit (OpCodes.Ldc_I4_1);
1937 case Operator.Multiply:
1939 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
1940 opcode = OpCodes.Mul_Ovf;
1941 else if (l==TypeManager.uint32_type || l==TypeManager.uint64_type)
1942 opcode = OpCodes.Mul_Ovf_Un;
1944 opcode = OpCodes.Mul;
1946 opcode = OpCodes.Mul;
1950 case Operator.Division:
1951 if (l == TypeManager.uint32_type || l == TypeManager.uint64_type)
1952 opcode = OpCodes.Div_Un;
1954 opcode = OpCodes.Div;
1957 case Operator.Modulus:
1958 if (l == TypeManager.uint32_type || l == TypeManager.uint64_type)
1959 opcode = OpCodes.Rem_Un;
1961 opcode = OpCodes.Rem;
1964 case Operator.Addition:
1966 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
1967 opcode = OpCodes.Add_Ovf;
1968 else if (l==TypeManager.uint32_type || l==TypeManager.uint64_type)
1969 opcode = OpCodes.Add_Ovf_Un;
1971 opcode = OpCodes.Mul;
1973 opcode = OpCodes.Add;
1976 case Operator.Subtraction:
1978 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
1979 opcode = OpCodes.Sub_Ovf;
1980 else if (l==TypeManager.uint32_type || l==TypeManager.uint64_type)
1981 opcode = OpCodes.Sub_Ovf_Un;
1983 opcode = OpCodes.Sub;
1985 opcode = OpCodes.Sub;
1988 case Operator.RightShift:
1989 opcode = OpCodes.Shr;
1992 case Operator.LeftShift:
1993 opcode = OpCodes.Shl;
1996 case Operator.Equality:
1997 opcode = OpCodes.Ceq;
2000 case Operator.Inequality:
2001 ec.ig.Emit (OpCodes.Ceq);
2002 ec.ig.Emit (OpCodes.Ldc_I4_0);
2004 opcode = OpCodes.Ceq;
2007 case Operator.LessThan:
2008 opcode = OpCodes.Clt;
2011 case Operator.GreaterThan:
2012 opcode = OpCodes.Cgt;
2015 case Operator.LessThanOrEqual:
2016 ec.ig.Emit (OpCodes.Cgt);
2017 ec.ig.Emit (OpCodes.Ldc_I4_0);
2019 opcode = OpCodes.Ceq;
2022 case Operator.GreaterThanOrEqual:
2023 ec.ig.Emit (OpCodes.Clt);
2024 ec.ig.Emit (OpCodes.Ldc_I4_1);
2026 opcode = OpCodes.Sub;
2029 case Operator.BitwiseOr:
2030 opcode = OpCodes.Or;
2033 case Operator.BitwiseAnd:
2034 opcode = OpCodes.And;
2037 case Operator.ExclusiveOr:
2038 opcode = OpCodes.Xor;
2042 throw new Exception ("This should not happen: Operator = "
2043 + oper.ToString ());
2051 /// Implements the ternary conditiona operator (?:)
2053 public class Conditional : Expression {
2054 Expression expr, trueExpr, falseExpr;
2057 public Conditional (Expression expr, Expression trueExpr, Expression falseExpr, Location l)
2060 this.trueExpr = trueExpr;
2061 this.falseExpr = falseExpr;
2065 public Expression Expr {
2071 public Expression TrueExpr {
2077 public Expression FalseExpr {
2083 public override Expression DoResolve (EmitContext ec)
2085 expr = expr.Resolve (ec);
2087 if (expr.Type != TypeManager.bool_type)
2088 expr = Expression.ConvertImplicitRequired (
2089 ec, expr, TypeManager.bool_type, loc);
2091 trueExpr = trueExpr.Resolve (ec);
2092 falseExpr = falseExpr.Resolve (ec);
2094 if (expr == null || trueExpr == null || falseExpr == null)
2097 if (trueExpr.Type == falseExpr.Type)
2098 type = trueExpr.Type;
2103 // First, if an implicit conversion exists from trueExpr
2104 // to falseExpr, then the result type is of type falseExpr.Type
2106 conv = ConvertImplicit (ec, trueExpr, falseExpr.Type, loc);
2108 type = falseExpr.Type;
2110 } else if ((conv = ConvertImplicit(ec, falseExpr,trueExpr.Type,loc))!= null){
2111 type = trueExpr.Type;
2114 Error (173, loc, "The type of the conditional expression can " +
2115 "not be computed because there is no implicit conversion" +
2116 " from `" + TypeManager.CSharpName (trueExpr.Type) + "'" +
2117 " and `" + TypeManager.CSharpName (falseExpr.Type) + "'");
2122 if (expr is BoolConstant){
2123 BoolConstant bc = (BoolConstant) expr;
2131 eclass = ExprClass.Value;
2135 public override void Emit (EmitContext ec)
2137 ILGenerator ig = ec.ig;
2138 Label false_target = ig.DefineLabel ();
2139 Label end_target = ig.DefineLabel ();
2142 ig.Emit (OpCodes.Brfalse, false_target);
2144 ig.Emit (OpCodes.Br, end_target);
2145 ig.MarkLabel (false_target);
2146 falseExpr.Emit (ec);
2147 ig.MarkLabel (end_target);
2155 public class LocalVariableReference : Expression, IAssignMethod, IMemoryLocation {
2156 public readonly string Name;
2157 public readonly Block Block;
2159 VariableInfo variable_info;
2161 public LocalVariableReference (Block block, string name, Location l)
2166 eclass = ExprClass.Variable;
2169 public VariableInfo VariableInfo {
2171 if (variable_info == null)
2172 variable_info = Block.GetVariableInfo (Name);
2173 return variable_info;
2177 public override Expression DoResolve (EmitContext ec)
2179 VariableInfo vi = VariableInfo;
2181 if (Block.IsConstant (Name)) {
2182 Expression e = Block.GetConstantExpression (Name);
2188 if (!(e is Constant)) {
2189 Report.Error (150, loc, "A constant value is expected");
2197 type = vi.VariableType;
2201 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
2203 Expression e = DoResolve (ec);
2208 VariableInfo vi = VariableInfo;
2214 "cannot assign to `" + Name + "' because it is readonly");
2222 public override void Emit (EmitContext ec)
2224 VariableInfo vi = VariableInfo;
2225 ILGenerator ig = ec.ig;
2232 ig.Emit (OpCodes.Ldloc_0);
2236 ig.Emit (OpCodes.Ldloc_1);
2240 ig.Emit (OpCodes.Ldloc_2);
2244 ig.Emit (OpCodes.Ldloc_3);
2249 ig.Emit (OpCodes.Ldloc_S, (byte) idx);
2251 ig.Emit (OpCodes.Ldloc, idx);
2256 public static void Store (ILGenerator ig, int idx)
2260 ig.Emit (OpCodes.Stloc_0);
2264 ig.Emit (OpCodes.Stloc_1);
2268 ig.Emit (OpCodes.Stloc_2);
2272 ig.Emit (OpCodes.Stloc_3);
2277 ig.Emit (OpCodes.Stloc_S, (byte) idx);
2279 ig.Emit (OpCodes.Stloc, idx);
2284 public void EmitAssign (EmitContext ec, Expression source)
2286 ILGenerator ig = ec.ig;
2287 VariableInfo vi = VariableInfo;
2293 // Funny seems the code below generates optimal code for us, but
2294 // seems to take too long to generate what we need.
2295 // ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
2300 public void AddressOf (EmitContext ec)
2302 VariableInfo vi = VariableInfo;
2309 ec.ig.Emit (OpCodes.Ldloca_S, (byte) idx);
2311 ec.ig.Emit (OpCodes.Ldloca, idx);
2316 /// This represents a reference to a parameter in the intermediate
2319 public class ParameterReference : Expression, IAssignMethod, IMemoryLocation {
2325 public ParameterReference (Parameters pars, int idx, string name)
2330 eclass = ExprClass.Variable;
2334 // Notice that for ref/out parameters, the type exposed is not the
2335 // same type exposed externally.
2338 // externally we expose "int&"
2339 // here we expose "int".
2341 // We record this in "is_ref". This means that the type system can treat
2342 // the type as it is expected, but when we generate the code, we generate
2343 // the alternate kind of code.
2345 public override Expression DoResolve (EmitContext ec)
2347 type = pars.GetParameterInfo (ec.TypeContainer, idx, out is_ref);
2348 eclass = ExprClass.Variable;
2354 // This method is used by parameters that are references, that are
2355 // being passed as references: we only want to pass the pointer (that
2356 // is already stored in the parameter, not the address of the pointer,
2357 // and not the value of the variable).
2359 public void EmitLoad (EmitContext ec)
2361 ILGenerator ig = ec.ig;
2368 ig.Emit (OpCodes.Ldarg_S, (byte) arg_idx);
2370 ig.Emit (OpCodes.Ldarg, arg_idx);
2373 public override void Emit (EmitContext ec)
2375 ILGenerator ig = ec.ig;
2382 ig.Emit (OpCodes.Ldarg_S, (byte) arg_idx);
2384 ig.Emit (OpCodes.Ldarg, arg_idx);
2390 // If we are a reference, we loaded on the stack a pointer
2391 // Now lets load the real value
2394 if (type == TypeManager.int32_type)
2395 ig.Emit (OpCodes.Ldind_I4);
2396 else if (type == TypeManager.uint32_type)
2397 ig.Emit (OpCodes.Ldind_U4);
2398 else if (type == TypeManager.int64_type || type == TypeManager.uint64_type)
2399 ig.Emit (OpCodes.Ldind_I8);
2400 else if (type == TypeManager.char_type)
2401 ig.Emit (OpCodes.Ldind_U2);
2402 else if (type == TypeManager.short_type)
2403 ig.Emit (OpCodes.Ldind_I2);
2404 else if (type == TypeManager.ushort_type)
2405 ig.Emit (OpCodes.Ldind_U2);
2406 else if (type == TypeManager.float_type)
2407 ig.Emit (OpCodes.Ldind_R4);
2408 else if (type == TypeManager.double_type)
2409 ig.Emit (OpCodes.Ldind_R8);
2410 else if (type == TypeManager.byte_type)
2411 ig.Emit (OpCodes.Ldind_U1);
2412 else if (type == TypeManager.sbyte_type || type == TypeManager.bool_type)
2413 ig.Emit (OpCodes.Ldind_I1);
2414 else if (type == TypeManager.intptr_type)
2415 ig.Emit (OpCodes.Ldind_I);
2417 ig.Emit (OpCodes.Ldind_Ref);
2420 public void EmitAssign (EmitContext ec, Expression source)
2422 ILGenerator ig = ec.ig;
2431 ig.Emit (OpCodes.Ldarg_S, (byte) arg_idx);
2433 ig.Emit (OpCodes.Ldarg, arg_idx);
2439 if (type == TypeManager.int32_type || type == TypeManager.uint32_type)
2440 ig.Emit (OpCodes.Stind_I4);
2441 else if (type == TypeManager.int64_type || type == TypeManager.uint64_type)
2442 ig.Emit (OpCodes.Stind_I8);
2443 else if (type == TypeManager.char_type || type == TypeManager.short_type ||
2444 type == TypeManager.ushort_type)
2445 ig.Emit (OpCodes.Stind_I2);
2446 else if (type == TypeManager.float_type)
2447 ig.Emit (OpCodes.Stind_R4);
2448 else if (type == TypeManager.double_type)
2449 ig.Emit (OpCodes.Stind_R8);
2450 else if (type == TypeManager.byte_type || type == TypeManager.sbyte_type ||
2451 type == TypeManager.bool_type)
2452 ig.Emit (OpCodes.Stind_I1);
2453 else if (type == TypeManager.intptr_type)
2454 ig.Emit (OpCodes.Stind_I);
2456 ig.Emit (OpCodes.Stind_Ref);
2459 ig.Emit (OpCodes.Starg_S, (byte) arg_idx);
2461 ig.Emit (OpCodes.Starg, arg_idx);
2466 public void AddressOf (EmitContext ec)
2474 ec.ig.Emit (OpCodes.Ldarga_S, (byte) arg_idx);
2476 ec.ig.Emit (OpCodes.Ldarga, arg_idx);
2481 /// Used for arguments to New(), Invocation()
2483 public class Argument {
2484 public enum AType : byte {
2490 public readonly AType ArgType;
2491 public Expression expr;
2493 public Argument (Expression expr, AType type)
2496 this.ArgType = type;
2499 public Expression Expr {
2515 public Parameter.Modifier GetParameterModifier ()
2517 if (ArgType == AType.Ref)
2518 return Parameter.Modifier.REF;
2520 if (ArgType == AType.Out)
2521 return Parameter.Modifier.OUT;
2523 return Parameter.Modifier.NONE;
2526 public static string FullDesc (Argument a)
2528 return (a.ArgType == AType.Ref ? "ref " :
2529 (a.ArgType == AType.Out ? "out " : "")) +
2530 TypeManager.CSharpName (a.Expr.Type);
2533 public bool Resolve (EmitContext ec, Location loc)
2535 expr = expr.Resolve (ec);
2537 if (ArgType == AType.Expression)
2538 return expr != null;
2540 if (expr.eclass != ExprClass.Variable){
2541 Report.Error (206, loc,
2542 "A property or indexer can not be passed as an out or ref " +
2547 return expr != null;
2550 public void Emit (EmitContext ec)
2553 // Ref and Out parameters need to have their addresses taken.
2555 // ParameterReferences might already be references, so we want
2556 // to pass just the value
2558 if (ArgType == AType.Ref || ArgType == AType.Out){
2559 if (expr is ParameterReference){
2560 ParameterReference pr = (ParameterReference) expr;
2567 ((IMemoryLocation)expr).AddressOf (ec);
2574 /// Invocation of methods or delegates.
2576 public class Invocation : ExpressionStatement {
2577 public readonly ArrayList Arguments;
2581 MethodBase method = null;
2584 static Hashtable method_parameter_cache;
2586 static Invocation ()
2588 method_parameter_cache = new PtrHashtable ();
2592 // arguments is an ArrayList, but we do not want to typecast,
2593 // as it might be null.
2595 // FIXME: only allow expr to be a method invocation or a
2596 // delegate invocation (7.5.5)
2598 public Invocation (Expression expr, ArrayList arguments, Location l)
2601 Arguments = arguments;
2605 public Expression Expr {
2612 /// Returns the Parameters (a ParameterData interface) for the
2615 public static ParameterData GetParameterData (MethodBase mb)
2617 object pd = method_parameter_cache [mb];
2621 return (ParameterData) pd;
2624 ip = TypeManager.LookupParametersByBuilder (mb);
2626 method_parameter_cache [mb] = ip;
2628 return (ParameterData) ip;
2630 ParameterInfo [] pi = mb.GetParameters ();
2631 ReflectionParameters rp = new ReflectionParameters (pi);
2632 method_parameter_cache [mb] = rp;
2634 return (ParameterData) rp;
2639 /// Determines "better conversion" as specified in 7.4.2.3
2640 /// Returns : 1 if a->p is better
2641 /// 0 if a->q or neither is better
2643 static int BetterConversion (EmitContext ec, Argument a, Type p, Type q, Location loc)
2645 Type argument_type = a.Type;
2646 Expression argument_expr = a.Expr;
2648 if (argument_type == null)
2649 throw new Exception ("Expression of type " + a.Expr + " does not resolve its type");
2654 if (argument_type == p)
2657 if (argument_type == q)
2661 // Now probe whether an implicit constant expression conversion
2664 // An implicit constant expression conversion permits the following
2667 // * A constant-expression of type `int' can be converted to type
2668 // sbyte, byute, short, ushort, uint, ulong provided the value of
2669 // of the expression is withing the range of the destination type.
2671 // * A constant-expression of type long can be converted to type
2672 // ulong, provided the value of the constant expression is not negative
2674 // FIXME: Note that this assumes that constant folding has
2675 // taken place. We dont do constant folding yet.
2678 if (argument_expr is IntConstant){
2679 IntConstant ei = (IntConstant) argument_expr;
2680 int value = ei.Value;
2682 if (p == TypeManager.sbyte_type){
2683 if (value >= SByte.MinValue && value <= SByte.MaxValue)
2685 } else if (p == TypeManager.byte_type){
2686 if (Byte.MinValue >= 0 && value <= Byte.MaxValue)
2688 } else if (p == TypeManager.short_type){
2689 if (value >= Int16.MinValue && value <= Int16.MaxValue)
2691 } else if (p == TypeManager.ushort_type){
2692 if (value >= UInt16.MinValue && value <= UInt16.MaxValue)
2694 } else if (p == TypeManager.uint32_type){
2696 // we can optimize this case: a positive int32
2697 // always fits on a uint32
2701 } else if (p == TypeManager.uint64_type){
2703 // we can optimize this case: a positive int32
2704 // always fits on a uint64
2709 } else if (argument_type == TypeManager.int64_type && argument_expr is LongConstant){
2710 LongConstant lc = (LongConstant) argument_expr;
2712 if (p == TypeManager.uint64_type){
2722 tmp = ConvertImplicitStandard (ec, argument_expr, p, loc);
2731 if (StandardConversionExists (p, q) == true &&
2732 StandardConversionExists (q, p) == false)
2735 if (p == TypeManager.sbyte_type)
2736 if (q == TypeManager.byte_type || q == TypeManager.ushort_type ||
2737 q == TypeManager.uint32_type || q == TypeManager.uint64_type)
2740 if (p == TypeManager.short_type)
2741 if (q == TypeManager.ushort_type || q == TypeManager.uint32_type ||
2742 q == TypeManager.uint64_type)
2745 if (p == TypeManager.int32_type)
2746 if (q == TypeManager.uint32_type || q == TypeManager.uint64_type)
2749 if (p == TypeManager.int64_type)
2750 if (q == TypeManager.uint64_type)
2757 /// Determines "Better function"
2760 /// and returns an integer indicating :
2761 /// 0 if candidate ain't better
2762 /// 1 if candidate is better than the current best match
2764 static int BetterFunction (EmitContext ec, ArrayList args,
2765 MethodBase candidate, MethodBase best,
2766 bool expanded_form, Location loc)
2768 ParameterData candidate_pd = GetParameterData (candidate);
2769 ParameterData best_pd;
2776 argument_count = args.Count;
2778 if (candidate_pd.Count == 0 && argument_count == 0)
2781 if (candidate_pd.ParameterModifier (candidate_pd.Count - 1) != Parameter.Modifier.PARAMS)
2782 if (candidate_pd.Count != argument_count)
2787 for (int j = argument_count; j > 0;) {
2790 Argument a = (Argument) args [j];
2791 Type t = candidate_pd.ParameterType (j);
2793 if (candidate_pd.ParameterModifier (j) == Parameter.Modifier.PARAMS)
2795 t = t.GetElementType ();
2797 x = BetterConversion (ec, a, t, null, loc);
2809 best_pd = GetParameterData (best);
2811 int rating1 = 0, rating2 = 0;
2813 for (int j = 0; j < argument_count; ++j) {
2816 Argument a = (Argument) args [j];
2818 Type ct = candidate_pd.ParameterType (j);
2819 Type bt = best_pd.ParameterType (j);
2821 if (candidate_pd.ParameterModifier (j) == Parameter.Modifier.PARAMS)
2823 ct = ct.GetElementType ();
2825 if (best_pd.ParameterModifier (j) == Parameter.Modifier.PARAMS)
2827 bt = bt.GetElementType ();
2829 x = BetterConversion (ec, a, ct, bt, loc);
2830 y = BetterConversion (ec, a, bt, ct, loc);
2839 if (rating1 > rating2)
2845 public static string FullMethodDesc (MethodBase mb)
2847 StringBuilder sb = new StringBuilder (mb.Name);
2848 ParameterData pd = GetParameterData (mb);
2850 int count = pd.Count;
2853 for (int i = count; i > 0; ) {
2856 sb.Append (pd.ParameterDesc (count - i - 1));
2862 return sb.ToString ();
2865 public static MethodGroupExpr MakeUnionSet (Expression mg1, Expression mg2)
2867 MemberInfo [] miset;
2868 MethodGroupExpr union;
2870 if (mg1 != null && mg2 != null) {
2872 MethodGroupExpr left_set = null, right_set = null;
2873 int length1 = 0, length2 = 0;
2875 left_set = (MethodGroupExpr) mg1;
2876 length1 = left_set.Methods.Length;
2878 right_set = (MethodGroupExpr) mg2;
2879 length2 = right_set.Methods.Length;
2881 ArrayList common = new ArrayList ();
2883 for (int i = 0; i < left_set.Methods.Length; i++) {
2884 for (int j = 0; j < right_set.Methods.Length; j++) {
2885 if (left_set.Methods [i] == right_set.Methods [j])
2886 common.Add (left_set.Methods [i]);
2890 miset = new MemberInfo [length1 + length2 - common.Count];
2892 left_set.Methods.CopyTo (miset, 0);
2896 for (int j = 0; j < right_set.Methods.Length; j++)
2897 if (!common.Contains (right_set.Methods [j]))
2898 miset [length1 + k++] = right_set.Methods [j];
2900 union = new MethodGroupExpr (miset);
2904 } else if (mg1 == null && mg2 != null) {
2906 MethodGroupExpr me = (MethodGroupExpr) mg2;
2908 miset = new MemberInfo [me.Methods.Length];
2909 me.Methods.CopyTo (miset, 0);
2911 union = new MethodGroupExpr (miset);
2915 } else if (mg2 == null && mg1 != null) {
2917 MethodGroupExpr me = (MethodGroupExpr) mg1;
2919 miset = new MemberInfo [me.Methods.Length];
2920 me.Methods.CopyTo (miset, 0);
2922 union = new MethodGroupExpr (miset);
2931 /// Determines is the candidate method, if a params method, is applicable
2932 /// in its expanded form to the given set of arguments
2934 static bool IsParamsMethodApplicable (ArrayList arguments, MethodBase candidate)
2938 if (arguments == null)
2941 arg_count = arguments.Count;
2943 ParameterData pd = GetParameterData (candidate);
2945 int pd_count = pd.Count;
2950 if (pd.ParameterModifier (pd_count - 1) != Parameter.Modifier.PARAMS)
2953 if (pd_count - 1 > arg_count)
2957 // If we have come this far, the case which remains is when the number of parameters
2958 // is less than or equal to the argument count. So, we now check if the element type
2959 // of the params array is compatible with each argument type
2962 Type element_type = pd.ParameterType (pd_count - 1).GetElementType ();
2964 for (int i = pd_count - 1; i < arg_count - 1; i++) {
2965 Argument a = (Argument) arguments [i];
2967 if (!StandardConversionExists (a.Type, element_type))
2975 /// Determines if the candidate method is applicable (section 14.4.2.1)
2976 /// to the given set of arguments
2978 static bool IsApplicable (ArrayList arguments, MethodBase candidate)
2982 if (arguments == null)
2985 arg_count = arguments.Count;
2987 ParameterData pd = GetParameterData (candidate);
2989 int pd_count = pd.Count;
2991 if (arg_count != pd.Count)
2994 for (int i = arg_count; i > 0; ) {
2997 Argument a = (Argument) arguments [i];
2999 Parameter.Modifier a_mod = a.GetParameterModifier ();
3000 Parameter.Modifier p_mod = pd.ParameterModifier (i);
3002 if (a_mod == p_mod) {
3004 if (a_mod == Parameter.Modifier.NONE)
3005 if (!StandardConversionExists (a.Type, pd.ParameterType (i)))
3008 if (a_mod == Parameter.Modifier.REF ||
3009 a_mod == Parameter.Modifier.OUT)
3010 if (pd.ParameterType (i) != a.Type)
3022 /// Find the Applicable Function Members (7.4.2.1)
3024 /// me: Method Group expression with the members to select.
3025 /// it might contain constructors or methods (or anything
3026 /// that maps to a method).
3028 /// Arguments: ArrayList containing resolved Argument objects.
3030 /// loc: The location if we want an error to be reported, or a Null
3031 /// location for "probing" purposes.
3033 /// Returns: The MethodBase (either a ConstructorInfo or a MethodInfo)
3034 /// that is the best match of me on Arguments.
3037 public static MethodBase OverloadResolve (EmitContext ec, MethodGroupExpr me,
3038 ArrayList Arguments, Location loc)
3040 ArrayList afm = new ArrayList ();
3041 int best_match_idx = -1;
3042 MethodBase method = null;
3044 ArrayList candidates = new ArrayList ();
3046 for (int i = me.Methods.Length; i > 0; ){
3048 MethodBase candidate = me.Methods [i];
3051 // Check if candidate is applicable (section 14.4.2.1)
3052 if (!IsApplicable (Arguments, candidate))
3055 candidates.Add (candidate);
3057 x = BetterFunction (ec, Arguments, candidate, method, false, loc);
3063 method = me.Methods [best_match_idx];
3067 if (Arguments == null)
3070 argument_count = Arguments.Count;
3073 // Now we see if we can find params functions, applicable in their expanded form
3074 // since if they were applicable in their normal form, they would have been selected
3077 bool chose_params_expanded = false;
3079 if (best_match_idx == -1) {
3081 candidates = new ArrayList ();
3082 for (int i = me.Methods.Length; i > 0; ) {
3084 MethodBase candidate = me.Methods [i];
3086 if (!IsParamsMethodApplicable (Arguments, candidate))
3089 candidates.Add (candidate);
3091 int x = BetterFunction (ec, Arguments, candidate, method, true, loc);
3097 method = me.Methods [best_match_idx];
3098 chose_params_expanded = true;
3104 // Now we see if we can at least find a method with the same number of arguments
3107 int method_count = 0;
3109 if (best_match_idx == -1) {
3111 for (int i = me.Methods.Length; i > 0;) {
3113 MethodBase mb = me.Methods [i];
3114 pd = GetParameterData (mb);
3116 if (pd.Count == argument_count) {
3118 method = me.Methods [best_match_idx];
3130 // Now check that there are no ambiguities i.e the selected method
3131 // should be better than all the others
3134 for (int i = 0; i < candidates.Count; ++i) {
3135 MethodBase candidate = (MethodBase) candidates [i];
3137 if (candidate == method)
3141 int x = BetterFunction (ec, Arguments, method, candidate,
3142 chose_params_expanded, loc);
3145 Console.WriteLine ("Candidate : " + candidate);
3146 Console.WriteLine ("Best : " + method);
3149 "Ambiguous call when selecting function due to implicit casts");
3154 // And now convert implicitly, each argument to the required type
3156 pd = GetParameterData (method);
3157 int pd_count = pd.Count;
3159 for (int j = 0; j < argument_count; j++) {
3160 Argument a = (Argument) Arguments [j];
3161 Expression a_expr = a.Expr;
3162 Type parameter_type = pd.ParameterType (j);
3164 if (pd.ParameterModifier (j) == Parameter.Modifier.PARAMS && chose_params_expanded)
3165 parameter_type = parameter_type.GetElementType ();
3167 if (a.Type != parameter_type){
3170 conv = ConvertImplicitStandard (ec, a_expr, parameter_type, Location.Null);
3173 if (!Location.IsNull (loc)) {
3175 "The best overloaded match for method '" +
3176 FullMethodDesc (method) +
3177 "' has some invalid arguments");
3179 "Argument " + (j+1) +
3180 ": Cannot convert from '" + Argument.FullDesc (a)
3181 + "' to '" + pd.ParameterDesc (j) + "'");
3187 // Update the argument with the implicit conversion
3192 // FIXME : For the case of params methods, we need to actually instantiate
3193 // an array and initialize it with the argument values etc etc.
3197 if (a.GetParameterModifier () != pd.ParameterModifier (j) &&
3198 pd.ParameterModifier (pd_count - 1) != Parameter.Modifier.PARAMS) {
3199 if (!Location.IsNull (loc)) {
3201 "The best overloaded match for method '" + FullMethodDesc (method)+
3202 "' has some invalid arguments");
3204 "Argument " + (j+1) +
3205 ": Cannot convert from '" + Argument.FullDesc (a)
3206 + "' to '" + pd.ParameterDesc (j) + "'");
3215 public override Expression DoResolve (EmitContext ec)
3218 // First, resolve the expression that is used to
3219 // trigger the invocation
3221 if (expr is BaseAccess)
3224 expr = expr.Resolve (ec);
3228 if (!(expr is MethodGroupExpr)) {
3229 Type expr_type = expr.Type;
3231 if (expr_type != null){
3232 bool IsDelegate = TypeManager.IsDelegateType (expr_type);
3234 return (new DelegateInvocation (
3235 this.expr, Arguments, loc)).Resolve (ec);
3239 if (!(expr is MethodGroupExpr)){
3240 report118 (loc, this.expr, "method group");
3245 // Next, evaluate all the expressions in the argument list
3247 if (Arguments != null){
3248 for (int i = Arguments.Count; i > 0;){
3250 Argument a = (Argument) Arguments [i];
3252 if (!a.Resolve (ec, loc))
3257 method = OverloadResolve (ec, (MethodGroupExpr) this.expr, Arguments, loc);
3259 if (method == null){
3261 "Could not find any applicable function for this argument list");
3265 if (method is MethodInfo)
3266 type = ((MethodInfo)method).ReturnType;
3268 eclass = ExprClass.Value;
3273 // Emits the list of arguments as an array
3275 static void EmitParams (EmitContext ec, int idx, ArrayList arguments)
3277 ILGenerator ig = ec.ig;
3278 int count = arguments.Count - idx;
3279 Argument a = (Argument) arguments [idx];
3280 Type t = a.expr.Type;
3281 string array_type = t.FullName + "[]";
3284 array = ig.DeclareLocal (Type.GetType (array_type));
3285 IntConstant.EmitInt (ig, count);
3286 ig.Emit (OpCodes.Newarr, t);
3287 ig.Emit (OpCodes.Stloc, array);
3289 int top = arguments.Count;
3290 for (int j = idx; j < top; j++){
3291 a = (Argument) arguments [j];
3293 ig.Emit (OpCodes.Ldloc, array);
3294 IntConstant.EmitInt (ig, j - idx);
3297 ArrayAccess.EmitStoreOpcode (ig, t);
3299 ig.Emit (OpCodes.Ldloc, array);
3303 /// Emits a list of resolved Arguments that are in the arguments
3306 /// The MethodBase argument might be null if the
3307 /// emission of the arguments is known not to contain
3308 /// a `params' field (for example in constructors or other routines
3309 /// that keep their arguments in this structure
3311 public static void EmitArguments (EmitContext ec, MethodBase mb, ArrayList arguments)
3313 ParameterData pd = null;
3316 if (arguments != null)
3317 top = arguments.Count;
3322 pd = GetParameterData (mb);
3324 for (int i = 0; i < top; i++){
3325 Argument a = (Argument) arguments [i];
3328 if (pd.ParameterModifier (i) == Parameter.Modifier.PARAMS){
3329 EmitParams (ec, i, arguments);
3339 /// is_base tells whether we want to force the use of the `call'
3340 /// opcode instead of using callvirt. Call is required to call
3341 /// a specific method, while callvirt will always use the most
3342 /// recent method in the vtable.
3344 /// is_static tells whether this is an invocation on a static method
3346 /// instance_expr is an expression that represents the instance
3347 /// it must be non-null if is_static is false.
3349 /// method is the method to invoke.
3351 /// Arguments is the list of arguments to pass to the method or constructor.
3353 public static void EmitCall (EmitContext ec, bool is_base,
3354 bool is_static, Expression instance_expr,
3355 MethodBase method, ArrayList Arguments)
3357 ILGenerator ig = ec.ig;
3358 bool struct_call = false;
3362 if (method.DeclaringType.IsValueType)
3365 // If this is ourselves, push "this"
3367 if (instance_expr == null){
3368 ig.Emit (OpCodes.Ldarg_0);
3371 // Push the instance expression
3373 if (instance_expr.Type.IsSubclassOf (TypeManager.value_type)){
3375 // Special case: calls to a function declared in a
3376 // reference-type with a value-type argument need
3377 // to have their value boxed.
3380 if (method.DeclaringType.IsValueType){
3382 // If the expression implements IMemoryLocation, then
3383 // we can optimize and use AddressOf on the
3386 // If not we have to use some temporary storage for
3388 if (instance_expr is IMemoryLocation){
3389 ((IMemoryLocation)instance_expr).
3393 Type t = instance_expr.Type;
3395 instance_expr.Emit (ec);
3396 LocalBuilder temp = ig.DeclareLocal (t);
3397 ig.Emit (OpCodes.Stloc, temp);
3398 ig.Emit (OpCodes.Ldloca, temp);
3401 instance_expr.Emit (ec);
3402 ig.Emit (OpCodes.Box, instance_expr.Type);
3405 instance_expr.Emit (ec);
3409 if (Arguments != null)
3410 EmitArguments (ec, method, Arguments);
3412 if (method is MethodInfo){
3413 MethodInfo mi = (MethodInfo) method;
3419 if (is_static || struct_call || is_base){
3420 if (method is MethodInfo)
3421 ig.Emit (OpCodes.Call, (MethodInfo) method);
3423 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
3425 if (method is MethodInfo)
3426 ig.Emit (OpCodes.Callvirt, (MethodInfo) method);
3428 ig.Emit (OpCodes.Callvirt, (ConstructorInfo) method);
3432 public override void Emit (EmitContext ec)
3434 MethodGroupExpr mg = (MethodGroupExpr) this.expr;
3436 EmitCall (ec, is_base, method.IsStatic, mg.InstanceExpression, method, Arguments);
3439 public override void EmitStatement (EmitContext ec)
3444 // Pop the return value if there is one
3446 if (method is MethodInfo){
3447 if (((MethodInfo)method).ReturnType != TypeManager.void_type)
3448 ec.ig.Emit (OpCodes.Pop);
3454 /// Implements the new expression
3456 public class New : ExpressionStatement {
3457 public readonly ArrayList Arguments;
3458 public readonly string RequestedType;
3461 MethodBase method = null;
3464 // If set, the new expression is for a value_target, and
3465 // we will not leave anything on the stack.
3467 Expression value_target;
3469 public New (string requested_type, ArrayList arguments, Location l)
3471 RequestedType = requested_type;
3472 Arguments = arguments;
3476 public Expression ValueTypeVariable {
3478 return value_target;
3482 value_target = value;
3486 public override Expression DoResolve (EmitContext ec)
3488 type = RootContext.LookupType (ec.TypeContainer, RequestedType, false, loc);
3493 bool IsDelegate = TypeManager.IsDelegateType (type);
3496 return (new NewDelegate (type, Arguments, loc)).Resolve (ec);
3498 bool is_struct = false;
3499 is_struct = type.IsSubclassOf (TypeManager.value_type);
3500 eclass = ExprClass.Value;
3503 // SRE returns a match for .ctor () on structs (the object constructor),
3504 // so we have to manually ignore it.
3506 if (is_struct && Arguments == null)
3510 ml = MemberLookup (ec, type, ".ctor", MemberTypes.Constructor, AllBindingFlags, loc);
3512 if (! (ml is MethodGroupExpr)){
3514 report118 (loc, ml, "method group");
3520 if (Arguments != null){
3521 for (int i = Arguments.Count; i > 0;){
3523 Argument a = (Argument) Arguments [i];
3525 if (!a.Resolve (ec, loc))
3530 method = Invocation.OverloadResolve (ec, (MethodGroupExpr) ml,
3535 if (method == null && !is_struct) {
3537 "New invocation: Can not find a constructor for " +
3538 "this argument list");
3545 // This DoEmit can be invoked in two contexts:
3546 // * As a mechanism that will leave a value on the stack (new object)
3547 // * As one that wont (init struct)
3549 // You can control whether a value is required on the stack by passing
3550 // need_value_on_stack. The code *might* leave a value on the stack
3551 // so it must be popped manually
3553 // If we are dealing with a ValueType, we have a few
3554 // situations to deal with:
3556 // * The target is a ValueType, and we have been provided
3557 // the instance (this is easy, we are being assigned).
3559 // * The target of New is being passed as an argument,
3560 // to a boxing operation or a function that takes a
3563 // In this case, we need to create a temporary variable
3564 // that is the argument of New.
3566 // Returns whether a value is left on the stack
3568 bool DoEmit (EmitContext ec, bool need_value_on_stack)
3570 bool is_value_type = type.IsSubclassOf (TypeManager.value_type);
3571 ILGenerator ig = ec.ig;
3576 if (value_target == null)
3577 value_target = new LocalTemporary (ec, type);
3579 ml = (IMemoryLocation) value_target;
3584 Invocation.EmitArguments (ec, method, Arguments);
3588 ig.Emit (OpCodes.Initobj, type);
3590 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
3592 if (need_value_on_stack){
3593 value_target.Emit (ec);
3598 ig.Emit (OpCodes.Newobj, (ConstructorInfo) method);
3603 public override void Emit (EmitContext ec)
3608 public override void EmitStatement (EmitContext ec)
3610 if (DoEmit (ec, false))
3611 ec.ig.Emit (OpCodes.Pop);
3616 /// Represents an array creation expression.
3620 /// There are two possible scenarios here: one is an array creation
3621 /// expression that specifies the dimensions and optionally the
3622 /// initialization data and the other which does not need dimensions
3623 /// specified but where initialization data is mandatory.
3625 public class ArrayCreation : ExpressionStatement {
3626 string RequestedType;
3628 ArrayList Initializers;
3630 ArrayList Arguments;
3632 MethodBase method = null;
3633 Type array_element_type;
3634 bool IsOneDimensional = false;
3635 bool IsBuiltinType = false;
3636 bool ExpectInitializers = false;
3639 Type underlying_type;
3641 ArrayList ArrayData;
3646 // The number of array initializers that we can handle
3647 // via the InitializeArray method - through EmitStaticInitializers
3649 int num_automatic_initializers;
3651 public ArrayCreation (string requested_type, ArrayList exprs,
3652 string rank, ArrayList initializers, Location l)
3654 RequestedType = requested_type;
3656 Initializers = initializers;
3659 Arguments = new ArrayList ();
3661 foreach (Expression e in exprs)
3662 Arguments.Add (new Argument (e, Argument.AType.Expression));
3665 public ArrayCreation (string requested_type, string rank, ArrayList initializers, Location l)
3667 RequestedType = requested_type;
3668 Initializers = initializers;
3671 Rank = rank.Substring (0, rank.LastIndexOf ("["));
3673 string tmp = rank.Substring (rank.LastIndexOf ("["));
3675 dimensions = tmp.Length - 1;
3676 ExpectInitializers = true;
3679 public static string FormArrayType (string base_type, int idx_count, string rank)
3681 StringBuilder sb = new StringBuilder (base_type);
3686 for (int i = 1; i < idx_count; i++)
3691 return sb.ToString ();
3694 public static string FormElementType (string base_type, int idx_count, string rank)
3696 StringBuilder sb = new StringBuilder (base_type);
3699 for (int i = 1; i < idx_count; i++)
3706 string val = sb.ToString ();
3708 return val.Substring (0, val.LastIndexOf ("["));
3713 Report.Error (178, loc, "Incorrectly structured array initializer");
3716 public bool CheckIndices (EmitContext ec, ArrayList probe, int idx, bool specified_dims)
3718 if (specified_dims) {
3719 Argument a = (Argument) Arguments [idx];
3721 if (!a.Resolve (ec, loc))
3724 if (!(a.Expr is Constant)) {
3725 Report.Error (150, loc, "A constant value is expected");
3729 int value = (int) ((Constant) a.Expr).GetValue ();
3731 if (value != probe.Count) {
3736 Bounds [idx] = value;
3739 foreach (object o in probe) {
3740 if (o is ArrayList) {
3741 bool ret = CheckIndices (ec, (ArrayList) o, idx + 1, specified_dims);
3745 Expression tmp = (Expression) o;
3746 tmp = tmp.Resolve (ec);
3750 // Handle initialization from vars, fields etc.
3752 Expression conv = ConvertImplicitRequired (
3753 ec, tmp, underlying_type, loc);
3758 if (conv is StringConstant)
3759 ArrayData.Add (conv);
3760 else if (conv is Constant) {
3761 ArrayData.Add (conv);
3762 num_automatic_initializers++;
3764 ArrayData.Add (conv);
3771 public void UpdateIndices (EmitContext ec)
3774 for (ArrayList probe = Initializers; probe != null;) {
3775 if (probe.Count > 0 && probe [0] is ArrayList) {
3776 Expression e = new IntConstant (probe.Count);
3777 Arguments.Add (new Argument (e, Argument.AType.Expression));
3779 Bounds [i++] = probe.Count;
3781 probe = (ArrayList) probe [0];
3784 Expression e = new IntConstant (probe.Count);
3785 Arguments.Add (new Argument (e, Argument.AType.Expression));
3787 Bounds [i++] = probe.Count;
3794 public bool ValidateInitializers (EmitContext ec)
3796 if (Initializers == null) {
3797 if (ExpectInitializers)
3803 underlying_type = RootContext.LookupType (
3804 ec.TypeContainer, RequestedType, false, loc);
3807 // We use this to store all the date values in the order in which we
3808 // will need to store them in the byte blob later
3810 ArrayData = new ArrayList ();
3811 Bounds = new Hashtable ();
3815 if (Arguments != null) {
3816 ret = CheckIndices (ec, Initializers, 0, true);
3820 Arguments = new ArrayList ();
3822 ret = CheckIndices (ec, Initializers, 0, false);
3829 if (Arguments.Count != dimensions) {
3838 public override Expression DoResolve (EmitContext ec)
3843 // First step is to validate the initializers and fill
3844 // in any missing bits
3846 if (!ValidateInitializers (ec))
3849 if (Arguments == null)
3852 arg_count = Arguments.Count;
3853 for (int i = arg_count; i > 0;){
3855 Argument a = (Argument) Arguments [i];
3857 if (!a.Resolve (ec, loc))
3862 string array_type = FormArrayType (RequestedType, arg_count, Rank);
3863 string element_type = FormElementType (RequestedType, arg_count, Rank);
3865 type = RootContext.LookupType (ec.TypeContainer, array_type, false, loc);
3867 array_element_type = RootContext.LookupType (
3868 ec.TypeContainer, element_type, false, loc);
3873 if (arg_count == 1) {
3874 IsOneDimensional = true;
3875 eclass = ExprClass.Value;
3879 IsBuiltinType = TypeManager.IsBuiltinType (type);
3881 if (IsBuiltinType) {
3885 ml = MemberLookup (ec, type, ".ctor", MemberTypes.Constructor,
3886 AllBindingFlags, loc);
3888 if (!(ml is MethodGroupExpr)){
3889 report118 (loc, ml, "method group");
3894 Report.Error (-6, loc, "New invocation: Can not find a constructor for " +
3895 "this argument list");
3899 method = Invocation.OverloadResolve (ec, (MethodGroupExpr) ml, Arguments, loc);
3901 if (method == null) {
3902 Report.Error (-6, loc, "New invocation: Can not find a constructor for " +
3903 "this argument list");
3907 eclass = ExprClass.Value;
3912 ModuleBuilder mb = RootContext.ModuleBuilder;
3914 ArrayList args = new ArrayList ();
3915 if (Arguments != null){
3916 for (int i = arg_count; i > 0;){
3918 Argument a = (Argument) Arguments [i];
3924 Type [] arg_types = null;
3927 arg_types = new Type [args.Count];
3929 args.CopyTo (arg_types, 0);
3931 method = mb.GetArrayMethod (type, ".ctor", CallingConventions.HasThis, null,
3934 if (method == null) {
3935 Report.Error (-6, loc, "New invocation: Can not find a constructor for " +
3936 "this argument list");
3940 eclass = ExprClass.Value;
3946 public static byte [] MakeByteBlob (ArrayList ArrayData, Type underlying_type, Location loc)
3951 int count = ArrayData.Count;
3953 if (underlying_type == TypeManager.int32_type ||
3954 underlying_type == TypeManager.uint32_type ||
3955 underlying_type == TypeManager.float_type)
3957 else if (underlying_type == TypeManager.int64_type ||
3958 underlying_type == TypeManager.uint64_type ||
3959 underlying_type == TypeManager.double_type)
3961 else if (underlying_type == TypeManager.byte_type ||
3962 underlying_type == TypeManager.sbyte_type ||
3963 underlying_type == TypeManager.bool_type)
3965 else if (underlying_type == TypeManager.short_type ||
3966 underlying_type == TypeManager.char_type ||
3967 underlying_type == TypeManager.ushort_type)
3972 data = new byte [(count * factor + 4) & ~3];
3975 for (int i = 0; i < count; ++i) {
3976 object v = ArrayData [i];
3978 if (v is EnumConstant)
3979 v = ((EnumConstant) v).Child;
3981 if (v is Constant && !(v is StringConstant))
3982 v = ((Constant) v).GetValue ();
3988 if (underlying_type == TypeManager.int64_type){
3989 if (!(v is Expression)){
3990 long val = (long) v;
3992 for (int j = 0; j < factor; ++j) {
3993 data [idx + j] = (byte) (val & 0xFF);
3997 } else if (underlying_type == TypeManager.uint64_type){
3998 if (!(v is Expression)){
3999 ulong val = (ulong) v;
4001 for (int j = 0; j < factor; ++j) {
4002 data [idx + j] = (byte) (val & 0xFF);
4006 } else if (underlying_type == TypeManager.float_type) {
4010 if (!(v is Expression)){
4011 float val = (float) v;
4013 byte *ptr = (byte *) &val;
4015 for (int j = 0; j < factor; ++j)
4016 data [idx + j] = (byte) ptr [j];
4020 } else if (underlying_type == TypeManager.double_type) {
4024 if (!(v is Expression)){
4025 double val = (double) v;
4027 byte *ptr = (byte *) &val;
4029 for (int j = 0; j < factor; ++j)
4030 data [idx + j] = (byte) ptr [j];
4034 } else if (underlying_type == TypeManager.char_type){
4036 if (!(v is Expression)){
4037 int val = (int) ((char) v);
4039 data [idx] = (byte) (val & 0xff);
4040 data [idx+1] = (byte) (val >> 8);
4042 } else if (underlying_type == TypeManager.short_type){
4043 if (!(v is Expression)){
4044 int val = (int) ((short) v);
4046 data [idx] = (byte) (val & 0xff);
4047 data [idx+1] = (byte) (val >> 8);
4049 } else if (underlying_type == TypeManager.ushort_type){
4050 if (!(v is Expression)){
4051 int val = (int) ((ushort) v);
4053 data [idx] = (byte) (val & 0xff);
4054 data [idx+1] = (byte) (val >> 8);
4056 } else if (underlying_type == TypeManager.int32_type) {
4057 if (!(v is Expression)){
4060 data [idx] = (byte) (val & 0xff);
4061 data [idx+1] = (byte) ((val >> 8) & 0xff);
4062 data [idx+2] = (byte) ((val >> 16) & 0xff);
4063 data [idx+3] = (byte) (val >> 24);
4065 } else if (underlying_type == TypeManager.uint32_type) {
4066 if (!(v is Expression)){
4067 uint val = (uint) v;
4069 data [idx] = (byte) (val & 0xff);
4070 data [idx+1] = (byte) ((val >> 8) & 0xff);
4071 data [idx+2] = (byte) ((val >> 16) & 0xff);
4072 data [idx+3] = (byte) (val >> 24);
4074 } else if (underlying_type == TypeManager.sbyte_type) {
4075 if (!(v is Expression)){
4076 sbyte val = (sbyte) v;
4077 data [idx] = (byte) val;
4079 } else if (underlying_type == TypeManager.byte_type) {
4080 if (!(v is Expression)){
4081 byte val = (byte) v;
4082 data [idx] = (byte) val;
4085 throw new Exception ("Unrecognized type in MakeByteBlob");
4094 // Emits the initializers for the array
4096 void EmitStaticInitializers (EmitContext ec, bool is_expression)
4099 // First, the static data
4102 ILGenerator ig = ec.ig;
4104 byte [] data = MakeByteBlob (ArrayData, underlying_type, loc);
4107 fb = RootContext.MakeStaticData (data);
4110 ig.Emit (OpCodes.Dup);
4111 ig.Emit (OpCodes.Ldtoken, fb);
4112 ig.Emit (OpCodes.Call,
4113 TypeManager.void_initializearray_array_fieldhandle);
4118 // Emits pieces of the array that can not be computed at compile
4119 // time (variables and string locations).
4121 // This always expect the top value on the stack to be the array
4123 void EmitDynamicInitializers (EmitContext ec, bool is_expression)
4125 ILGenerator ig = ec.ig;
4126 int dims = Bounds.Count;
4127 int [] current_pos = new int [dims];
4128 int top = ArrayData.Count;
4129 LocalBuilder temp = ig.DeclareLocal (type);
4131 ig.Emit (OpCodes.Stloc, temp);
4133 MethodInfo set = null;
4137 ModuleBuilder mb = null;
4138 mb = RootContext.ModuleBuilder;
4139 args = new Type [dims + 1];
4142 for (j = 0; j < dims; j++)
4143 args [j] = TypeManager.int32_type;
4145 args [j] = array_element_type;
4147 set = mb.GetArrayMethod (
4149 CallingConventions.HasThis | CallingConventions.Standard,
4150 TypeManager.void_type, args);
4153 for (int i = 0; i < top; i++){
4155 Expression e = null;
4157 if (ArrayData [i] is Expression)
4158 e = (Expression) ArrayData [i];
4162 // Basically we do this for string literals and
4163 // other non-literal expressions
4165 if (e is StringConstant || !(e is Constant) || num_automatic_initializers <= 2) {
4167 ig.Emit (OpCodes.Ldloc, temp);
4169 for (int idx = dims; idx > 0; ) {
4171 IntConstant.EmitInt (ig, current_pos [idx]);
4177 ArrayAccess.EmitStoreOpcode (ig, array_element_type);
4179 ig.Emit (OpCodes.Call, set);
4187 for (int j = 0; j < dims; j++){
4189 if (current_pos [j] < (int) Bounds [j])
4191 current_pos [j] = 0;
4196 ig.Emit (OpCodes.Ldloc, temp);
4199 void DoEmit (EmitContext ec, bool is_statement)
4201 ILGenerator ig = ec.ig;
4203 if (IsOneDimensional) {
4204 Invocation.EmitArguments (ec, null, Arguments);
4205 ig.Emit (OpCodes.Newarr, array_element_type);
4208 Invocation.EmitArguments (ec, null, Arguments);
4211 ig.Emit (OpCodes.Newobj, (ConstructorInfo) method);
4213 ig.Emit (OpCodes.Newobj, (MethodInfo) method);
4216 if (Initializers != null){
4218 // FIXME: Set this variable correctly.
4220 bool dynamic_initializers = true;
4222 if (underlying_type != TypeManager.string_type &&
4223 underlying_type != TypeManager.object_type) {
4224 if (num_automatic_initializers > 2)
4225 EmitStaticInitializers (ec, dynamic_initializers || !is_statement);
4228 if (dynamic_initializers)
4229 EmitDynamicInitializers (ec, !is_statement);
4233 public override void Emit (EmitContext ec)
4238 public override void EmitStatement (EmitContext ec)
4246 /// Represents the `this' construct
4248 public class This : Expression, IAssignMethod, IMemoryLocation {
4251 public This (Location loc)
4256 public override Expression DoResolve (EmitContext ec)
4258 eclass = ExprClass.Variable;
4259 type = ec.TypeContainer.TypeBuilder;
4262 Report.Error (26, loc,
4263 "Keyword this not valid in static code");
4270 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
4274 if (ec.TypeContainer is Class){
4275 Report.Error (1604, loc, "Cannot assign to `this'");
4282 public override void Emit (EmitContext ec)
4284 ec.ig.Emit (OpCodes.Ldarg_0);
4287 public void EmitAssign (EmitContext ec, Expression source)
4290 ec.ig.Emit (OpCodes.Starg, 0);
4293 public void AddressOf (EmitContext ec)
4295 ec.ig.Emit (OpCodes.Ldarg_0);
4298 // FIGURE OUT WHY LDARG_S does not work
4300 // consider: struct X { int val; int P { set { val = value; }}}
4302 // Yes, this looks very bad. Look at `NOTAS' for
4304 // ec.ig.Emit (OpCodes.Ldarga_S, (byte) 0);
4309 /// Implements the typeof operator
4311 public class TypeOf : Expression {
4312 public readonly string QueriedType;
4316 public TypeOf (string queried_type, Location l)
4318 QueriedType = queried_type;
4322 public override Expression DoResolve (EmitContext ec)
4324 typearg = RootContext.LookupType (
4325 ec.TypeContainer, QueriedType, false, loc);
4327 if (typearg == null)
4330 type = TypeManager.type_type;
4331 eclass = ExprClass.Type;
4335 public override void Emit (EmitContext ec)
4337 ec.ig.Emit (OpCodes.Ldtoken, typearg);
4338 ec.ig.Emit (OpCodes.Call, TypeManager.system_type_get_type_from_handle);
4343 /// Implements the sizeof expression
4345 public class SizeOf : Expression {
4346 public readonly string QueriedType;
4348 public SizeOf (string queried_type)
4350 this.QueriedType = queried_type;
4353 public override Expression DoResolve (EmitContext ec)
4355 // FIXME: Implement;
4356 throw new Exception ("Unimplemented");
4360 public override void Emit (EmitContext ec)
4362 throw new Exception ("Implement me");
4367 /// Implements the member access expression
4369 public class MemberAccess : Expression {
4370 public readonly string Identifier;
4372 Expression member_lookup;
4375 public MemberAccess (Expression expr, string id, Location l)
4382 public Expression Expr {
4388 static void error176 (Location loc, string name)
4390 Report.Error (176, loc, "Static member `" +
4391 name + "' cannot be accessed " +
4392 "with an instance reference, qualify with a " +
4393 "type name instead");
4396 static bool IdenticalNameAndTypeName (EmitContext ec, Expression left_original, Location loc)
4398 if (left_original == null)
4401 if (!(left_original is SimpleName))
4404 SimpleName sn = (SimpleName) left_original;
4406 Type t = RootContext.LookupType (ec.TypeContainer, sn.Name, true, loc);
4413 public static Expression ResolveMemberAccess (EmitContext ec, Expression member_lookup,
4414 Expression left, Location loc,
4415 Expression left_original)
4420 if (member_lookup is MethodGroupExpr){
4421 MethodGroupExpr mg = (MethodGroupExpr) member_lookup;
4426 if (left is TypeExpr){
4427 if (!mg.RemoveInstanceMethods ()){
4428 SimpleName.Error120 (loc, mg.Methods [0].Name);
4432 return member_lookup;
4436 // Instance.MethodGroup
4438 if (!mg.RemoveStaticMethods ()){
4439 if (IdenticalNameAndTypeName (ec, left_original, loc)){
4440 if (!mg.RemoveInstanceMethods ()){
4441 SimpleName.Error120 (loc, mg.Methods [0].Name);
4444 return member_lookup;
4447 error176 (loc, mg.Methods [0].Name);
4451 mg.InstanceExpression = left;
4453 return member_lookup;
4456 if (member_lookup is FieldExpr){
4457 FieldExpr fe = (FieldExpr) member_lookup;
4458 FieldInfo fi = fe.FieldInfo;
4460 if (fi is FieldBuilder) {
4461 Const c = TypeManager.LookupConstant ((FieldBuilder) fi);
4464 object o = c.LookupConstantValue (ec);
4465 object real_value = ((Constant) c.Expr).GetValue ();
4466 return Constantify (real_value, fi.FieldType);
4471 Type t = fi.FieldType;
4472 Type decl_type = fi.DeclaringType;
4475 if (fi is FieldBuilder)
4476 o = TypeManager.GetValue ((FieldBuilder) fi);
4478 o = fi.GetValue (fi);
4480 if (decl_type.IsSubclassOf (TypeManager.enum_type)) {
4481 Expression enum_member = MemberLookup (
4482 ec, decl_type, "value__", loc);
4484 Enum en = TypeManager.LookupEnum (decl_type);
4488 c = Constantify (o, en.UnderlyingType);
4490 c = Constantify (o, enum_member.Type);
4492 return new EnumConstant (c, decl_type);
4495 Expression exp = Constantify (o, t);
4497 if (!(left is TypeExpr)) {
4498 error176 (loc, fe.FieldInfo.Name);
4505 if (left is TypeExpr){
4506 // and refers to a type name or an
4507 if (!fe.FieldInfo.IsStatic){
4508 error176 (loc, fe.FieldInfo.Name);
4511 return member_lookup;
4513 if (fe.FieldInfo.IsStatic){
4514 if (IdenticalNameAndTypeName (ec, left_original, loc))
4515 return member_lookup;
4517 error176 (loc, fe.FieldInfo.Name);
4520 fe.InstanceExpression = left;
4526 if (member_lookup is PropertyExpr){
4527 PropertyExpr pe = (PropertyExpr) member_lookup;
4529 if (left is TypeExpr){
4531 SimpleName.Error120 (loc, pe.PropertyInfo.Name);
4537 if (IdenticalNameAndTypeName (ec, left_original, loc))
4538 return member_lookup;
4539 error176 (loc, pe.PropertyInfo.Name);
4542 pe.InstanceExpression = left;
4548 if (member_lookup is EventExpr) {
4550 EventExpr ee = (EventExpr) member_lookup;
4553 // If the event is local to this class, we transform ourselves into
4557 Expression ml = MemberLookup (
4558 ec, ec.TypeContainer.TypeBuilder,
4559 ee.EventInfo.Name, MemberTypes.Event, AllBindingFlags, loc);
4562 MemberInfo mi = ec.TypeContainer.GetFieldFromEvent ((EventExpr) ml);
4566 // If this happens, then we have an event with its own
4567 // accessors and private field etc so there's no need
4568 // to transform ourselves : we should instead flag an error
4570 Assign.error70 (ee.EventInfo, loc);
4574 ml = ExprClassFromMemberInfo (ec, mi, loc);
4577 Report.Error (-200, loc, "Internal error!!");
4580 return ResolveMemberAccess (ec, ml, left, loc, left_original);
4583 if (left is TypeExpr) {
4585 SimpleName.Error120 (loc, ee.EventInfo.Name);
4593 if (IdenticalNameAndTypeName (ec, left_original, loc))
4596 error176 (loc, ee.EventInfo.Name);
4600 ee.InstanceExpression = left;
4606 if (member_lookup is TypeExpr){
4607 member_lookup.Resolve (ec);
4608 return member_lookup;
4611 Console.WriteLine ("Left is: " + left);
4612 Report.Error (-100, loc, "Support for [" + member_lookup + "] is not present yet");
4613 Environment.Exit (0);
4617 public override Expression DoResolve (EmitContext ec)
4620 // We are the sole users of ResolveWithSimpleName (ie, the only
4621 // ones that can cope with it
4623 Expression original = expr;
4624 expr = expr.ResolveWithSimpleName (ec);
4629 if (expr is SimpleName){
4630 SimpleName child_expr = (SimpleName) expr;
4632 expr = new SimpleName (child_expr.Name + "." + Identifier, loc);
4634 return expr.ResolveWithSimpleName (ec);
4638 // Handle enums here when they are in transit.
4639 // Note that we cannot afford to hit MemberLookup in this case because
4640 // it will fail to find any members at all
4643 Type expr_type = expr.Type;
4644 if ((expr is TypeExpr) && (expr_type.IsSubclassOf (TypeManager.enum_type))){
4646 Enum en = TypeManager.LookupEnum (expr_type);
4649 object value = en.LookupEnumValue (ec, Identifier, loc);
4652 Constant c = Constantify (value, en.UnderlyingType);
4653 return new EnumConstant (c, expr_type);
4658 member_lookup = MemberLookup (ec, expr_type, Identifier, loc);
4660 if (member_lookup == null)
4663 return ResolveMemberAccess (ec, member_lookup, expr, loc, original);
4666 public override void Emit (EmitContext ec)
4668 throw new Exception ("Should not happen");
4673 /// Implements checked expressions
4675 public class CheckedExpr : Expression {
4677 public Expression Expr;
4679 public CheckedExpr (Expression e)
4684 public override Expression DoResolve (EmitContext ec)
4686 Expr = Expr.Resolve (ec);
4691 eclass = Expr.eclass;
4696 public override void Emit (EmitContext ec)
4698 bool last_check = ec.CheckState;
4700 ec.CheckState = true;
4702 ec.CheckState = last_check;
4708 /// Implements the unchecked expression
4710 public class UnCheckedExpr : Expression {
4712 public Expression Expr;
4714 public UnCheckedExpr (Expression e)
4719 public override Expression DoResolve (EmitContext ec)
4721 Expr = Expr.Resolve (ec);
4726 eclass = Expr.eclass;
4731 public override void Emit (EmitContext ec)
4733 bool last_check = ec.CheckState;
4735 ec.CheckState = false;
4737 ec.CheckState = last_check;
4743 /// An Element Access expression.
4745 /// During semantic analysis these are transformed into
4746 /// IndexerAccess or ArrayAccess
4748 public class ElementAccess : Expression {
4749 public ArrayList Arguments;
4750 public Expression Expr;
4751 public Location loc;
4753 public ElementAccess (Expression e, ArrayList e_list, Location l)
4762 Arguments = new ArrayList ();
4763 foreach (Expression tmp in e_list)
4764 Arguments.Add (new Argument (tmp, Argument.AType.Expression));
4768 bool CommonResolve (EmitContext ec)
4770 Expr = Expr.Resolve (ec);
4775 if (Arguments == null)
4778 for (int i = Arguments.Count; i > 0;){
4780 Argument a = (Argument) Arguments [i];
4782 if (!a.Resolve (ec, loc))
4789 public override Expression DoResolve (EmitContext ec)
4791 if (!CommonResolve (ec))
4795 // We perform some simple tests, and then to "split" the emit and store
4796 // code we create an instance of a different class, and return that.
4798 // I am experimenting with this pattern.
4800 if (Expr.Type.IsSubclassOf (TypeManager.array_type))
4801 return (new ArrayAccess (this)).Resolve (ec);
4803 return (new IndexerAccess (this)).Resolve (ec);
4806 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
4808 if (!CommonResolve (ec))
4811 if (Expr.Type.IsSubclassOf (TypeManager.array_type))
4812 return (new ArrayAccess (this)).ResolveLValue (ec, right_side);
4814 return (new IndexerAccess (this)).ResolveLValue (ec, right_side);
4817 public override void Emit (EmitContext ec)
4819 throw new Exception ("Should never be reached");
4824 /// Implements array access
4826 public class ArrayAccess : Expression, IAssignMethod, IMemoryLocation {
4828 // Points to our "data" repository
4832 public ArrayAccess (ElementAccess ea_data)
4835 eclass = ExprClass.Variable;
4838 public override Expression DoResolve (EmitContext ec)
4840 if (ea.Expr.eclass != ExprClass.Variable) {
4841 report118 (ea.loc, ea.Expr, "variable");
4845 Type t = ea.Expr.Type;
4847 if (t.GetArrayRank () != ea.Arguments.Count){
4848 Report.Error (22, ea.loc,
4849 "Incorrect number of indexes for array " +
4850 " expected: " + t.GetArrayRank () + " got: " +
4851 ea.Arguments.Count);
4854 type = t.GetElementType ();
4855 eclass = ExprClass.Variable;
4861 /// Emits the right opcode to load an object of Type `t'
4862 /// from an array of T
4864 static public void EmitLoadOpcode (ILGenerator ig, Type type)
4866 if (type == TypeManager.byte_type || type == TypeManager.bool_type)
4867 ig.Emit (OpCodes.Ldelem_I1);
4868 else if (type == TypeManager.sbyte_type)
4869 ig.Emit (OpCodes.Ldelem_U1);
4870 else if (type == TypeManager.short_type)
4871 ig.Emit (OpCodes.Ldelem_I2);
4872 else if (type == TypeManager.ushort_type)
4873 ig.Emit (OpCodes.Ldelem_U2);
4874 else if (type == TypeManager.int32_type)
4875 ig.Emit (OpCodes.Ldelem_I4);
4876 else if (type == TypeManager.uint32_type)
4877 ig.Emit (OpCodes.Ldelem_U4);
4878 else if (type == TypeManager.uint64_type)
4879 ig.Emit (OpCodes.Ldelem_I8);
4880 else if (type == TypeManager.int64_type)
4881 ig.Emit (OpCodes.Ldelem_I8);
4882 else if (type == TypeManager.float_type)
4883 ig.Emit (OpCodes.Ldelem_R4);
4884 else if (type == TypeManager.double_type)
4885 ig.Emit (OpCodes.Ldelem_R8);
4886 else if (type == TypeManager.intptr_type)
4887 ig.Emit (OpCodes.Ldelem_I);
4888 else if (type.IsValueType){
4889 ig.Emit (OpCodes.Ldelema, type);
4890 ig.Emit (OpCodes.Ldobj, type);
4892 ig.Emit (OpCodes.Ldelem_Ref);
4896 /// Emits the right opcode to store an object of Type `t'
4897 /// from an array of T.
4899 static public void EmitStoreOpcode (ILGenerator ig, Type t)
4901 if (t == TypeManager.byte_type || t == TypeManager.sbyte_type ||
4902 t == TypeManager.bool_type)
4903 ig.Emit (OpCodes.Stelem_I1);
4904 else if (t == TypeManager.short_type || t == TypeManager.ushort_type || t == TypeManager.char_type)
4905 ig.Emit (OpCodes.Stelem_I2);
4906 else if (t == TypeManager.int32_type || t == TypeManager.uint32_type)
4907 ig.Emit (OpCodes.Stelem_I4);
4908 else if (t == TypeManager.int64_type || t == TypeManager.uint64_type)
4909 ig.Emit (OpCodes.Stelem_I8);
4910 else if (t == TypeManager.float_type)
4911 ig.Emit (OpCodes.Stelem_R4);
4912 else if (t == TypeManager.double_type)
4913 ig.Emit (OpCodes.Stelem_R8);
4914 else if (t == TypeManager.intptr_type)
4915 ig.Emit (OpCodes.Stelem_I);
4916 else if (t.IsValueType)
4917 ig.Emit (OpCodes.Stobj, t);
4919 ig.Emit (OpCodes.Stelem_Ref);
4922 MethodInfo FetchGetMethod ()
4924 ModuleBuilder mb = RootContext.ModuleBuilder;
4925 Type [] args = new Type [ea.Arguments.Count];
4930 foreach (Argument a in ea.Arguments)
4931 args [i++] = a.Type;
4933 get = mb.GetArrayMethod (
4934 ea.Expr.Type, "Get",
4935 CallingConventions.HasThis |
4936 CallingConventions.Standard,
4942 MethodInfo FetchAddressMethod ()
4944 ModuleBuilder mb = RootContext.ModuleBuilder;
4945 Type [] args = new Type [ea.Arguments.Count];
4947 string ptr_type_name;
4951 ptr_type_name = type.FullName + "&";
4952 ret_type = Type.GetType (ptr_type_name);
4955 // It is a type defined by the source code we are compiling
4957 if (ret_type == null){
4958 ret_type = mb.GetType (ptr_type_name);
4961 foreach (Argument a in ea.Arguments)
4962 args [i++] = a.Type;
4964 address = mb.GetArrayMethod (
4965 ea.Expr.Type, "Address",
4966 CallingConventions.HasThis |
4967 CallingConventions.Standard,
4973 public override void Emit (EmitContext ec)
4975 int rank = ea.Expr.Type.GetArrayRank ();
4976 ILGenerator ig = ec.ig;
4980 foreach (Argument a in ea.Arguments)
4984 EmitLoadOpcode (ig, type);
4988 method = FetchGetMethod ();
4989 ig.Emit (OpCodes.Call, method);
4993 public void EmitAssign (EmitContext ec, Expression source)
4995 int rank = ea.Expr.Type.GetArrayRank ();
4996 ILGenerator ig = ec.ig;
5000 foreach (Argument a in ea.Arguments)
5003 Type t = source.Type;
5006 // The stobj opcode used by value types will need
5007 // an address on the stack, not really an array/array
5011 if (t.IsValueType && !TypeManager.IsBuiltinType (t))
5012 ig.Emit (OpCodes.Ldelema, t);
5018 EmitStoreOpcode (ig, t);
5020 ModuleBuilder mb = RootContext.ModuleBuilder;
5021 Type [] args = new Type [ea.Arguments.Count + 1];
5026 foreach (Argument a in ea.Arguments)
5027 args [i++] = a.Type;
5031 set = mb.GetArrayMethod (
5032 ea.Expr.Type, "Set",
5033 CallingConventions.HasThis |
5034 CallingConventions.Standard,
5035 TypeManager.void_type, args);
5037 ig.Emit (OpCodes.Call, set);
5041 public void AddressOf (EmitContext ec)
5043 int rank = ea.Expr.Type.GetArrayRank ();
5044 ILGenerator ig = ec.ig;
5048 foreach (Argument a in ea.Arguments)
5052 ig.Emit (OpCodes.Ldelema, type);
5054 MethodInfo address = FetchAddressMethod ();
5055 ig.Emit (OpCodes.Call, address);
5062 public ArrayList getters, setters;
5063 static Hashtable map;
5067 map = new Hashtable ();
5070 Indexers (MemberInfo [] mi)
5072 foreach (PropertyInfo property in mi){
5073 MethodInfo get, set;
5075 get = property.GetGetMethod (true);
5077 if (getters == null)
5078 getters = new ArrayList ();
5083 set = property.GetSetMethod (true);
5085 if (setters == null)
5086 setters = new ArrayList ();
5092 static public Indexers GetIndexersForType (Type t, TypeManager tm, Location loc)
5094 Indexers ix = (Indexers) map [t];
5095 string p_name = TypeManager.IndexerPropertyName (t);
5100 MemberInfo [] mi = tm.FindMembers (
5101 t, MemberTypes.Property,
5102 BindingFlags.Public | BindingFlags.Instance,
5103 Type.FilterName, p_name);
5105 if (mi == null || mi.Length == 0){
5106 Report.Error (21, loc,
5107 "Type `" + TypeManager.CSharpName (t) + "' does not have " +
5108 "any indexers defined");
5112 ix = new Indexers (mi);
5120 /// Expressions that represent an indexer call.
5122 public class IndexerAccess : Expression, IAssignMethod {
5124 // Points to our "data" repository
5127 MethodInfo get, set;
5129 ArrayList set_arguments;
5131 public IndexerAccess (ElementAccess ea_data)
5134 eclass = ExprClass.Value;
5137 public override Expression DoResolve (EmitContext ec)
5139 Type indexer_type = ea.Expr.Type;
5142 // Step 1: Query for all `Item' *properties*. Notice
5143 // that the actual methods are pointed from here.
5145 // This is a group of properties, piles of them.
5148 ilist = Indexers.GetIndexersForType (
5149 indexer_type, RootContext.TypeManager, ea.loc);
5153 // Step 2: find the proper match
5155 if (ilist != null && ilist.getters != null && ilist.getters.Count > 0)
5156 get = (MethodInfo) Invocation.OverloadResolve (
5157 ec, new MethodGroupExpr (ilist.getters), ea.Arguments, ea.loc);
5160 Report.Error (154, ea.loc,
5161 "indexer can not be used in this context, because " +
5162 "it lacks a `get' accessor");
5166 type = get.ReturnType;
5167 eclass = ExprClass.IndexerAccess;
5171 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
5173 Type indexer_type = ea.Expr.Type;
5174 Type right_type = right_side.Type;
5177 ilist = Indexers.GetIndexersForType (
5178 indexer_type, RootContext.TypeManager, ea.loc);
5180 if (ilist != null && ilist.setters != null && ilist.setters.Count > 0){
5181 set_arguments = (ArrayList) ea.Arguments.Clone ();
5182 set_arguments.Add (new Argument (right_side, Argument.AType.Expression));
5184 set = (MethodInfo) Invocation.OverloadResolve (
5185 ec, new MethodGroupExpr (ilist.setters), set_arguments, ea.loc);
5189 Report.Error (200, ea.loc,
5190 "indexer X.this [" + TypeManager.CSharpName (right_type) +
5191 "] lacks a `set' accessor");
5195 type = TypeManager.void_type;
5196 eclass = ExprClass.IndexerAccess;
5200 public override void Emit (EmitContext ec)
5202 Invocation.EmitCall (ec, false, false, ea.Expr, get, ea.Arguments);
5206 // source is ignored, because we already have a copy of it from the
5207 // LValue resolution and we have already constructed a pre-cached
5208 // version of the arguments (ea.set_arguments);
5210 public void EmitAssign (EmitContext ec, Expression source)
5212 Invocation.EmitCall (ec, false, false, ea.Expr, set, set_arguments);
5217 /// The base operator for method names
5219 public class BaseAccess : Expression {
5223 public BaseAccess (string member, Location l)
5225 this.member = member;
5229 public override Expression DoResolve (EmitContext ec)
5231 Expression member_lookup;
5232 Type current_type = ec.TypeContainer.TypeBuilder;
5233 Type base_type = current_type.BaseType;
5236 member_lookup = MemberLookup (ec, base_type, member, loc);
5237 if (member_lookup == null)
5243 left = new TypeExpr (base_type);
5247 e = MemberAccess.ResolveMemberAccess (ec, member_lookup, left, loc, null);
5248 if (e is PropertyExpr){
5249 PropertyExpr pe = (PropertyExpr) e;
5257 public override void Emit (EmitContext ec)
5259 throw new Exception ("Should never be called");
5264 /// The base indexer operator
5266 public class BaseIndexerAccess : Expression {
5267 ArrayList Arguments;
5270 public BaseIndexerAccess (ArrayList args, Location l)
5276 public override Expression DoResolve (EmitContext ec)
5278 Type current_type = ec.TypeContainer.TypeBuilder;
5279 Type base_type = current_type.BaseType;
5280 Expression member_lookup;
5282 member_lookup = MemberLookup (ec, base_type, "get_Item", loc);
5283 if (member_lookup == null)
5286 return MemberAccess.ResolveMemberAccess (ec, member_lookup, ec.This, loc, null);
5289 public override void Emit (EmitContext ec)
5291 throw new Exception ("Should never be called");
5296 /// This class exists solely to pass the Type around and to be a dummy
5297 /// that can be passed to the conversion functions (this is used by
5298 /// foreach implementation to typecast the object return value from
5299 /// get_Current into the proper type. All code has been generated and
5300 /// we only care about the side effect conversions to be performed
5302 public class EmptyExpression : Expression {
5303 public EmptyExpression ()
5305 type = TypeManager.object_type;
5306 eclass = ExprClass.Value;
5309 public EmptyExpression (Type t)
5312 eclass = ExprClass.Value;
5315 public override Expression DoResolve (EmitContext ec)
5320 public override void Emit (EmitContext ec)
5322 // nothing, as we only exist to not do anything.
5326 // This is just because we might want to reuse this bad boy
5327 // instead of creating gazillions of EmptyExpressions.
5328 // (CanConvertImplicit uses it)
5330 public void SetType (Type t)
5336 public class UserCast : Expression {
5340 public UserCast (MethodInfo method, Expression source)
5342 this.method = method;
5343 this.source = source;
5344 type = method.ReturnType;
5345 eclass = ExprClass.Value;
5348 public override Expression DoResolve (EmitContext ec)
5351 // We are born fully resolved
5356 public override void Emit (EmitContext ec)
5358 ILGenerator ig = ec.ig;
5362 if (method is MethodInfo)
5363 ig.Emit (OpCodes.Call, (MethodInfo) method);
5365 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
5372 // This class is used to "construct" the type during a typecast
5373 // operation. Since the Type.GetType class in .NET can parse
5374 // the type specification, we just use this to construct the type
5375 // one bit at a time.
5377 public class ComposedCast : Expression {
5382 public ComposedCast (Expression left, string dim, Location l)
5389 public override Expression DoResolve (EmitContext ec)
5391 left = left.Resolve (ec);
5395 if (left.eclass != ExprClass.Type){
5396 report118 (loc, left, "type");
5400 type = RootContext.LookupType (
5401 ec.TypeContainer, left.Type.FullName + dim, false, loc);
5405 eclass = ExprClass.Type;
5409 public override void Emit (EmitContext ec)
5411 throw new Exception ("This should never be called");