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, false, loc);
268 if (mg == null && expr_type.BaseType != null)
269 mg = MemberLookup (ec, expr_type.BaseType, op_name, false, 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, false, loc);
567 if (mg == null && expr_type.BaseType != null)
568 mg = MemberLookup (ec, expr_type.BaseType, op_name, false, 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;
638 if (temp_storage == null)
639 temp_storage = new LocalTemporary (ec, expr.Type);
642 case Mode.PreIncrement:
643 case Mode.PreDecrement:
647 ig.Emit (OpCodes.Ldc_I4_1);
649 if (mode == Mode.PreDecrement)
650 ig.Emit (OpCodes.Sub);
652 ig.Emit (OpCodes.Add);
656 temp_storage.Store (ec);
657 ia.EmitAssign (ec, temp_storage);
659 temp_storage.Emit (ec);
662 case Mode.PostIncrement:
663 case Mode.PostDecrement:
671 ig.Emit (OpCodes.Dup);
673 ig.Emit (OpCodes.Ldc_I4_1);
675 if (mode == Mode.PostDecrement)
676 ig.Emit (OpCodes.Sub);
678 ig.Emit (OpCodes.Add);
683 temp_storage.Store (ec);
684 ia.EmitAssign (ec, temp_storage);
689 public override void Emit (EmitContext ec)
695 public override void EmitStatement (EmitContext ec)
697 EmitCode (ec, false);
703 /// Base class for the `Is' and `As' classes.
707 /// FIXME: Split this in two, and we get to save the `Operator' Oper
710 public abstract class Probe : Expression {
711 public readonly string ProbeType;
712 protected Expression expr;
713 protected Type probe_type;
716 public Probe (Expression expr, string probe_type, Location l)
718 ProbeType = probe_type;
723 public Expression Expr {
729 public override Expression DoResolve (EmitContext ec)
731 probe_type = RootContext.LookupType (ec.TypeContainer, ProbeType, false, loc);
733 if (probe_type == null)
736 expr = expr.Resolve (ec);
743 /// Implementation of the `is' operator.
745 public class Is : Probe {
746 public Is (Expression expr, string probe_type, Location l)
747 : base (expr, probe_type, l)
751 public override void Emit (EmitContext ec)
753 ILGenerator ig = ec.ig;
757 ig.Emit (OpCodes.Isinst, probe_type);
758 ig.Emit (OpCodes.Ldnull);
759 ig.Emit (OpCodes.Cgt_Un);
762 public override Expression DoResolve (EmitContext ec)
764 Expression e = base.DoResolve (ec);
769 type = TypeManager.bool_type;
770 eclass = ExprClass.Value;
777 /// Implementation of the `as' operator.
779 public class As : Probe {
780 public As (Expression expr, string probe_type, Location l)
781 : base (expr, probe_type, l)
785 public override void Emit (EmitContext ec)
787 ILGenerator ig = ec.ig;
790 ig.Emit (OpCodes.Isinst, probe_type);
793 public override Expression DoResolve (EmitContext ec)
795 Expression e = base.DoResolve (ec);
801 eclass = ExprClass.Value;
808 /// This represents a typecast in the source language.
810 /// FIXME: Cast expressions have an unusual set of parsing
811 /// rules, we need to figure those out.
813 public class Cast : Expression {
814 Expression target_type;
818 public Cast (Expression cast_type, Expression expr, Location loc)
820 this.target_type = cast_type;
825 public Expression TargetType {
831 public Expression Expr {
841 /// Attempts to do a compile-time folding of a constant cast.
843 Expression TryReduce (EmitContext ec, Type target_type)
845 if (expr is ByteConstant){
846 byte v = ((ByteConstant) expr).Value;
848 if (target_type == TypeManager.sbyte_type)
849 return new SByteConstant ((sbyte) v);
850 if (target_type == TypeManager.short_type)
851 return new ShortConstant ((short) v);
852 if (target_type == TypeManager.ushort_type)
853 return new UShortConstant ((ushort) v);
854 if (target_type == TypeManager.int32_type)
855 return new IntConstant ((int) v);
856 if (target_type == TypeManager.uint32_type)
857 return new UIntConstant ((uint) v);
858 if (target_type == TypeManager.int64_type)
859 return new LongConstant ((long) v);
860 if (target_type == TypeManager.uint64_type)
861 return new ULongConstant ((ulong) v);
862 if (target_type == TypeManager.float_type)
863 return new FloatConstant ((float) v);
864 if (target_type == TypeManager.double_type)
865 return new DoubleConstant ((double) v);
867 if (expr is SByteConstant){
868 sbyte v = ((SByteConstant) expr).Value;
870 if (target_type == TypeManager.byte_type)
871 return new ByteConstant ((byte) v);
872 if (target_type == TypeManager.short_type)
873 return new ShortConstant ((short) v);
874 if (target_type == TypeManager.ushort_type)
875 return new UShortConstant ((ushort) v);
876 if (target_type == TypeManager.int32_type)
877 return new IntConstant ((int) v);
878 if (target_type == TypeManager.uint32_type)
879 return new UIntConstant ((uint) v);
880 if (target_type == TypeManager.int64_type)
881 return new LongConstant ((long) v);
882 if (target_type == TypeManager.uint64_type)
883 return new ULongConstant ((ulong) v);
884 if (target_type == TypeManager.float_type)
885 return new FloatConstant ((float) v);
886 if (target_type == TypeManager.double_type)
887 return new DoubleConstant ((double) v);
889 if (expr is ShortConstant){
890 short v = ((ShortConstant) expr).Value;
892 if (target_type == TypeManager.byte_type)
893 return new ByteConstant ((byte) v);
894 if (target_type == TypeManager.sbyte_type)
895 return new SByteConstant ((sbyte) v);
896 if (target_type == TypeManager.ushort_type)
897 return new UShortConstant ((ushort) v);
898 if (target_type == TypeManager.int32_type)
899 return new IntConstant ((int) v);
900 if (target_type == TypeManager.uint32_type)
901 return new UIntConstant ((uint) v);
902 if (target_type == TypeManager.int64_type)
903 return new LongConstant ((long) v);
904 if (target_type == TypeManager.uint64_type)
905 return new ULongConstant ((ulong) v);
906 if (target_type == TypeManager.float_type)
907 return new FloatConstant ((float) v);
908 if (target_type == TypeManager.double_type)
909 return new DoubleConstant ((double) v);
911 if (expr is UShortConstant){
912 ushort v = ((UShortConstant) expr).Value;
914 if (target_type == TypeManager.byte_type)
915 return new ByteConstant ((byte) v);
916 if (target_type == TypeManager.sbyte_type)
917 return new SByteConstant ((sbyte) v);
918 if (target_type == TypeManager.short_type)
919 return new ShortConstant ((short) v);
920 if (target_type == TypeManager.int32_type)
921 return new IntConstant ((int) v);
922 if (target_type == TypeManager.uint32_type)
923 return new UIntConstant ((uint) v);
924 if (target_type == TypeManager.int64_type)
925 return new LongConstant ((long) v);
926 if (target_type == TypeManager.uint64_type)
927 return new ULongConstant ((ulong) v);
928 if (target_type == TypeManager.float_type)
929 return new FloatConstant ((float) v);
930 if (target_type == TypeManager.double_type)
931 return new DoubleConstant ((double) v);
933 if (expr is IntConstant){
934 int v = ((IntConstant) expr).Value;
936 if (target_type == TypeManager.byte_type)
937 return new ByteConstant ((byte) v);
938 if (target_type == TypeManager.sbyte_type)
939 return new SByteConstant ((sbyte) v);
940 if (target_type == TypeManager.short_type)
941 return new ShortConstant ((short) v);
942 if (target_type == TypeManager.ushort_type)
943 return new UShortConstant ((ushort) v);
944 if (target_type == TypeManager.uint32_type)
945 return new UIntConstant ((uint) v);
946 if (target_type == TypeManager.int64_type)
947 return new LongConstant ((long) v);
948 if (target_type == TypeManager.uint64_type)
949 return new ULongConstant ((ulong) v);
950 if (target_type == TypeManager.float_type)
951 return new FloatConstant ((float) v);
952 if (target_type == TypeManager.double_type)
953 return new DoubleConstant ((double) v);
955 if (expr is UIntConstant){
956 uint v = ((UIntConstant) expr).Value;
958 if (target_type == TypeManager.byte_type)
959 return new ByteConstant ((byte) v);
960 if (target_type == TypeManager.sbyte_type)
961 return new SByteConstant ((sbyte) v);
962 if (target_type == TypeManager.short_type)
963 return new ShortConstant ((short) v);
964 if (target_type == TypeManager.ushort_type)
965 return new UShortConstant ((ushort) v);
966 if (target_type == TypeManager.int32_type)
967 return new IntConstant ((int) v);
968 if (target_type == TypeManager.int64_type)
969 return new LongConstant ((long) v);
970 if (target_type == TypeManager.uint64_type)
971 return new ULongConstant ((ulong) v);
972 if (target_type == TypeManager.float_type)
973 return new FloatConstant ((float) v);
974 if (target_type == TypeManager.double_type)
975 return new DoubleConstant ((double) v);
977 if (expr is LongConstant){
978 long v = ((LongConstant) expr).Value;
980 if (target_type == TypeManager.byte_type)
981 return new ByteConstant ((byte) v);
982 if (target_type == TypeManager.sbyte_type)
983 return new SByteConstant ((sbyte) v);
984 if (target_type == TypeManager.short_type)
985 return new ShortConstant ((short) v);
986 if (target_type == TypeManager.ushort_type)
987 return new UShortConstant ((ushort) v);
988 if (target_type == TypeManager.int32_type)
989 return new IntConstant ((int) v);
990 if (target_type == TypeManager.uint32_type)
991 return new UIntConstant ((uint) v);
992 if (target_type == TypeManager.uint64_type)
993 return new ULongConstant ((ulong) v);
994 if (target_type == TypeManager.float_type)
995 return new FloatConstant ((float) v);
996 if (target_type == TypeManager.double_type)
997 return new DoubleConstant ((double) v);
999 if (expr is ULongConstant){
1000 ulong v = ((ULongConstant) expr).Value;
1002 if (target_type == TypeManager.byte_type)
1003 return new ByteConstant ((byte) v);
1004 if (target_type == TypeManager.sbyte_type)
1005 return new SByteConstant ((sbyte) v);
1006 if (target_type == TypeManager.short_type)
1007 return new ShortConstant ((short) v);
1008 if (target_type == TypeManager.ushort_type)
1009 return new UShortConstant ((ushort) v);
1010 if (target_type == TypeManager.int32_type)
1011 return new IntConstant ((int) v);
1012 if (target_type == TypeManager.uint32_type)
1013 return new UIntConstant ((uint) v);
1014 if (target_type == TypeManager.int64_type)
1015 return new LongConstant ((long) v);
1016 if (target_type == TypeManager.float_type)
1017 return new FloatConstant ((float) v);
1018 if (target_type == TypeManager.double_type)
1019 return new DoubleConstant ((double) v);
1021 if (expr is FloatConstant){
1022 float v = ((FloatConstant) expr).Value;
1024 if (target_type == TypeManager.byte_type)
1025 return new ByteConstant ((byte) v);
1026 if (target_type == TypeManager.sbyte_type)
1027 return new SByteConstant ((sbyte) v);
1028 if (target_type == TypeManager.short_type)
1029 return new ShortConstant ((short) v);
1030 if (target_type == TypeManager.ushort_type)
1031 return new UShortConstant ((ushort) v);
1032 if (target_type == TypeManager.int32_type)
1033 return new IntConstant ((int) v);
1034 if (target_type == TypeManager.uint32_type)
1035 return new UIntConstant ((uint) v);
1036 if (target_type == TypeManager.int64_type)
1037 return new LongConstant ((long) v);
1038 if (target_type == TypeManager.uint64_type)
1039 return new ULongConstant ((ulong) v);
1040 if (target_type == TypeManager.double_type)
1041 return new DoubleConstant ((double) v);
1043 if (expr is DoubleConstant){
1044 double v = ((DoubleConstant) expr).Value;
1046 if (target_type == TypeManager.byte_type)
1047 return new ByteConstant ((byte) v);
1048 if (target_type == TypeManager.sbyte_type)
1049 return new SByteConstant ((sbyte) v);
1050 if (target_type == TypeManager.short_type)
1051 return new ShortConstant ((short) v);
1052 if (target_type == TypeManager.ushort_type)
1053 return new UShortConstant ((ushort) v);
1054 if (target_type == TypeManager.int32_type)
1055 return new IntConstant ((int) v);
1056 if (target_type == TypeManager.uint32_type)
1057 return new UIntConstant ((uint) v);
1058 if (target_type == TypeManager.int64_type)
1059 return new LongConstant ((long) v);
1060 if (target_type == TypeManager.uint64_type)
1061 return new ULongConstant ((ulong) v);
1062 if (target_type == TypeManager.float_type)
1063 return new FloatConstant ((float) v);
1069 public override Expression DoResolve (EmitContext ec)
1071 expr = expr.Resolve (ec);
1075 target_type = target_type.Resolve (ec);
1076 if (target_type == null)
1079 if (target_type.eclass != ExprClass.Type){
1080 report118 (loc, target_type, "class");
1084 type = target_type.Type;
1085 eclass = ExprClass.Value;
1090 if (expr is Constant){
1091 Expression e = TryReduce (ec, type);
1097 expr = ConvertExplicit (ec, expr, type, loc);
1101 public override void Emit (EmitContext ec)
1104 // This one will never happen
1106 throw new Exception ("Should not happen");
1111 /// Binary operators
1113 public class Binary : Expression {
1114 public enum Operator : byte {
1115 Multiply, Division, Modulus,
1116 Addition, Subtraction,
1117 LeftShift, RightShift,
1118 LessThan, GreaterThan, LessThanOrEqual, GreaterThanOrEqual,
1119 Equality, Inequality,
1128 Expression left, right;
1130 ArrayList Arguments;
1133 bool DelegateOperation;
1135 public Binary (Operator oper, Expression left, Expression right, Location loc)
1143 public Operator Oper {
1152 public Expression Left {
1161 public Expression Right {
1172 /// Returns a stringified representation of the Operator
1177 case Operator.Multiply:
1179 case Operator.Division:
1181 case Operator.Modulus:
1183 case Operator.Addition:
1185 case Operator.Subtraction:
1187 case Operator.LeftShift:
1189 case Operator.RightShift:
1191 case Operator.LessThan:
1193 case Operator.GreaterThan:
1195 case Operator.LessThanOrEqual:
1197 case Operator.GreaterThanOrEqual:
1199 case Operator.Equality:
1201 case Operator.Inequality:
1203 case Operator.BitwiseAnd:
1205 case Operator.BitwiseOr:
1207 case Operator.ExclusiveOr:
1209 case Operator.LogicalOr:
1211 case Operator.LogicalAnd:
1215 return oper.ToString ();
1218 Expression ForceConversion (EmitContext ec, Expression expr, Type target_type)
1220 if (expr.Type == target_type)
1223 return ConvertImplicit (ec, expr, target_type, new Location (-1));
1227 // Note that handling the case l == Decimal || r == Decimal
1228 // is taken care of by the Step 1 Operator Overload resolution.
1230 bool DoNumericPromotions (EmitContext ec, Type l, Type r)
1232 if (l == TypeManager.double_type || r == TypeManager.double_type){
1234 // If either operand is of type double, the other operand is
1235 // conveted to type double.
1237 if (r != TypeManager.double_type)
1238 right = ConvertImplicit (ec, right, TypeManager.double_type, loc);
1239 if (l != TypeManager.double_type)
1240 left = ConvertImplicit (ec, left, TypeManager.double_type, loc);
1242 type = TypeManager.double_type;
1243 } else if (l == TypeManager.float_type || r == TypeManager.float_type){
1245 // if either operand is of type float, th eother operand is
1246 // converd to type float.
1248 if (r != TypeManager.double_type)
1249 right = ConvertImplicit (ec, right, TypeManager.float_type, loc);
1250 if (l != TypeManager.double_type)
1251 left = ConvertImplicit (ec, left, TypeManager.float_type, loc);
1252 type = TypeManager.float_type;
1253 } else if (l == TypeManager.uint64_type || r == TypeManager.uint64_type){
1257 // If either operand is of type ulong, the other operand is
1258 // converted to type ulong. or an error ocurrs if the other
1259 // operand is of type sbyte, short, int or long
1262 if (l == TypeManager.uint64_type){
1263 if (r != TypeManager.uint64_type){
1264 if (right is IntConstant){
1265 e = TryImplicitIntConversion(l, (IntConstant) right);
1268 } else if (right is LongConstant){
1269 long ll = ((LongConstant) right).Value;
1272 right = new ULongConstant ((ulong) ll);
1277 if (left is IntConstant){
1278 e = TryImplicitIntConversion (r, (IntConstant) left);
1281 } else if (left is LongConstant){
1282 long ll = ((LongConstant) left).Value;
1285 left = new ULongConstant ((ulong) ll);
1290 if ((other == TypeManager.sbyte_type) ||
1291 (other == TypeManager.short_type) ||
1292 (other == TypeManager.int32_type) ||
1293 (other == TypeManager.int64_type)){
1294 string oper = OperName ();
1296 Error (34, loc, "Operator `" + OperName ()
1297 + "' is ambiguous on operands of type `"
1298 + TypeManager.CSharpName (l) + "' "
1299 + "and `" + TypeManager.CSharpName (r)
1302 type = TypeManager.uint64_type;
1303 } else if (l == TypeManager.int64_type || r == TypeManager.int64_type){
1305 // If either operand is of type long, the other operand is converted
1308 if (l != TypeManager.int64_type)
1309 left = ConvertImplicit (ec, left, TypeManager.int64_type, loc);
1310 if (r != TypeManager.int64_type)
1311 right = ConvertImplicit (ec, right, TypeManager.int64_type, loc);
1313 type = TypeManager.int64_type;
1314 } else if (l == TypeManager.uint32_type || r == TypeManager.uint32_type){
1316 // If either operand is of type uint, and the other
1317 // operand is of type sbyte, short or int, othe operands are
1318 // converted to type long.
1322 if (l == TypeManager.uint32_type)
1324 else if (r == TypeManager.uint32_type)
1327 if ((other == TypeManager.sbyte_type) ||
1328 (other == TypeManager.short_type) ||
1329 (other == TypeManager.int32_type)){
1330 left = ForceConversion (ec, left, TypeManager.int64_type);
1331 right = ForceConversion (ec, right, TypeManager.int64_type);
1332 type = TypeManager.int64_type;
1335 // if either operand is of type uint, the other
1336 // operand is converd to type uint
1338 left = ForceConversion (ec, left, TypeManager.uint32_type);
1339 right = ForceConversion (ec, right, TypeManager.uint32_type);
1340 type = TypeManager.uint32_type;
1342 } else if (l == TypeManager.decimal_type || r == TypeManager.decimal_type){
1343 if (l != TypeManager.decimal_type)
1344 left = ConvertImplicit (ec, left, TypeManager.decimal_type, loc);
1345 if (r != TypeManager.decimal_type)
1346 right = ConvertImplicit (ec, right, TypeManager.decimal_type, loc);
1348 type = TypeManager.decimal_type;
1350 Expression l_tmp, r_tmp;
1352 l_tmp = ForceConversion (ec, left, TypeManager.int32_type);
1356 r_tmp = ForceConversion (ec, right, TypeManager.int32_type);
1363 type = TypeManager.int32_type;
1372 "Operator " + OperName () + " cannot be applied to operands of type `" +
1373 TypeManager.CSharpName (left.Type) + "' and `" +
1374 TypeManager.CSharpName (right.Type) + "'");
1378 Expression CheckShiftArguments (EmitContext ec)
1382 Type r = right.Type;
1384 e = ForceConversion (ec, right, TypeManager.int32_type);
1391 if (((e = ConvertImplicit (ec, left, TypeManager.int32_type, loc)) != null) ||
1392 ((e = ConvertImplicit (ec, left, TypeManager.uint32_type, loc)) != null) ||
1393 ((e = ConvertImplicit (ec, left, TypeManager.int64_type, loc)) != null) ||
1394 ((e = ConvertImplicit (ec, left, TypeManager.uint64_type, loc)) != null)){
1404 Expression ResolveOperator (EmitContext ec)
1407 Type r = right.Type;
1410 // Step 1: Perform Operator Overload location
1412 Expression left_expr, right_expr;
1414 string op = "op_" + oper;
1416 left_expr = MemberLookup (ec, l, op, false, loc);
1417 if (left_expr == null && l.BaseType != null)
1418 left_expr = MemberLookup (ec, l.BaseType, op, false, loc);
1420 right_expr = MemberLookup (ec, r, op, false, loc);
1421 if (right_expr == null && r.BaseType != null)
1422 right_expr = MemberLookup (ec, r.BaseType, op, false, loc);
1424 MethodGroupExpr union = Invocation.MakeUnionSet (left_expr, right_expr);
1426 if (union != null) {
1427 Arguments = new ArrayList ();
1428 Arguments.Add (new Argument (left, Argument.AType.Expression));
1429 Arguments.Add (new Argument (right, Argument.AType.Expression));
1431 method = Invocation.OverloadResolve (ec, union, Arguments, loc);
1432 if (method != null) {
1433 MethodInfo mi = (MethodInfo) method;
1434 type = mi.ReturnType;
1443 // Step 2: Default operations on CLI native types.
1446 // Only perform numeric promotions on:
1447 // +, -, *, /, %, &, |, ^, ==, !=, <, >, <=, >=
1449 if (oper == Operator.Addition){
1451 // If any of the arguments is a string, cast to string
1453 if (l == TypeManager.string_type){
1454 if (r == TypeManager.string_type){
1455 if (left is Constant && right is Constant){
1456 StringConstant ls = (StringConstant) left;
1457 StringConstant rs = (StringConstant) right;
1459 return new StringConstant (
1460 ls.Value + rs.Value);
1464 method = TypeManager.string_concat_string_string;
1467 method = TypeManager.string_concat_object_object;
1468 right = ConvertImplicit (ec, right,
1469 TypeManager.object_type, loc);
1471 type = TypeManager.string_type;
1473 Arguments = new ArrayList ();
1474 Arguments.Add (new Argument (left, Argument.AType.Expression));
1475 Arguments.Add (new Argument (right, Argument.AType.Expression));
1479 } else if (r == TypeManager.string_type){
1481 method = TypeManager.string_concat_object_object;
1482 Arguments = new ArrayList ();
1483 Arguments.Add (new Argument (left, Argument.AType.Expression));
1484 Arguments.Add (new Argument (right, Argument.AType.Expression));
1486 left = ConvertImplicit (ec, left, TypeManager.object_type, loc);
1487 type = TypeManager.string_type;
1493 if (oper == Operator.Addition || oper == Operator.Subtraction) {
1494 if (l.IsSubclassOf (TypeManager.delegate_type) &&
1495 r.IsSubclassOf (TypeManager.delegate_type)) {
1497 Arguments = new ArrayList ();
1498 Arguments.Add (new Argument (left, Argument.AType.Expression));
1499 Arguments.Add (new Argument (right, Argument.AType.Expression));
1501 if (oper == Operator.Addition)
1502 method = TypeManager.delegate_combine_delegate_delegate;
1504 method = TypeManager.delegate_remove_delegate_delegate;
1506 DelegateOperation = true;
1513 // Enumeration operators
1515 bool lie = TypeManager.IsEnumType (l);
1516 bool rie = TypeManager.IsEnumType (r);
1521 temp = ConvertImplicit (ec, right, l, loc);
1525 temp = ConvertImplicit (ec, left, r, loc);
1532 if (oper == Operator.Equality || oper == Operator.Inequality ||
1533 oper == Operator.LessThanOrEqual || oper == Operator.LessThan ||
1534 oper == Operator.GreaterThanOrEqual || oper == Operator.GreaterThan){
1535 type = TypeManager.bool_type;
1539 if (oper == Operator.BitwiseAnd ||
1540 oper == Operator.BitwiseOr ||
1541 oper == Operator.ExclusiveOr){
1547 if (oper == Operator.LeftShift || oper == Operator.RightShift)
1548 return CheckShiftArguments (ec);
1550 if (oper == Operator.LogicalOr || oper == Operator.LogicalAnd){
1551 if (l != TypeManager.bool_type || r != TypeManager.bool_type){
1556 type = TypeManager.bool_type;
1560 if (oper == Operator.Equality || oper == Operator.Inequality){
1561 if (l == TypeManager.bool_type || r == TypeManager.bool_type){
1562 if (r != TypeManager.bool_type || l != TypeManager.bool_type){
1567 type = TypeManager.bool_type;
1572 // operator != (object a, object b)
1573 // operator == (object a, object b)
1575 // For this to be used, both arguments have to be reference-types.
1576 // Read the rationale on the spec (14.9.6)
1578 // Also, if at compile time we know that the classes do not inherit
1579 // one from the other, then we catch the error there.
1581 if (!(l.IsValueType || r.IsValueType)){
1582 type = TypeManager.bool_type;
1587 if (l.IsSubclassOf (r) || r.IsSubclassOf (l))
1591 // We are going to have to convert to an object to compare
1593 if (l != TypeManager.object_type)
1594 left = new EmptyCast (left, TypeManager.object_type);
1595 if (r != TypeManager.object_type)
1596 right = new EmptyCast (right, TypeManager.object_type);
1603 // We are dealing with numbers
1606 if (!DoNumericPromotions (ec, l, r)){
1611 if (left == null || right == null)
1615 // reload our cached types if required
1620 if (oper == Operator.BitwiseAnd ||
1621 oper == Operator.BitwiseOr ||
1622 oper == Operator.ExclusiveOr){
1624 if (!((l == TypeManager.int32_type) ||
1625 (l == TypeManager.uint32_type) ||
1626 (l == TypeManager.int64_type) ||
1627 (l == TypeManager.uint64_type)))
1635 if (oper == Operator.Equality ||
1636 oper == Operator.Inequality ||
1637 oper == Operator.LessThanOrEqual ||
1638 oper == Operator.LessThan ||
1639 oper == Operator.GreaterThanOrEqual ||
1640 oper == Operator.GreaterThan){
1641 type = TypeManager.bool_type;
1648 /// Constant expression reducer for binary operations
1650 public Expression ConstantFold (EmitContext ec)
1652 object l = ((Constant) left).GetValue ();
1653 object r = ((Constant) right).GetValue ();
1655 if (l is string && r is string)
1656 return new StringConstant ((string) l + (string) r);
1658 Type result_type = null;
1661 // Enumerator folding
1663 if (left.Type == right.Type && left is EnumConstant)
1664 result_type = left.Type;
1667 case Operator.BitwiseOr:
1668 if ((l is int) && (r is int)){
1670 int res = (int)l | (int)r;
1672 v = new IntConstant (res);
1673 if (result_type == null)
1676 return new EnumConstant (v, result_type);
1680 case Operator.BitwiseAnd:
1681 if ((l is int) && (r is int)){
1683 int res = (int)l & (int)r;
1685 v = new IntConstant (res);
1686 if (result_type == null)
1689 return new EnumConstant (v, result_type);
1697 public override Expression DoResolve (EmitContext ec)
1699 left = left.Resolve (ec);
1700 right = right.Resolve (ec);
1702 if (left == null || right == null)
1705 if (left.Type == null)
1706 throw new Exception (
1707 "Resolve returned non null, but did not set the type! (" +
1708 left + ") at Line: " + loc.Row);
1709 if (right.Type == null)
1710 throw new Exception (
1711 "Resolve returned non null, but did not set the type! (" +
1712 right + ") at Line: "+ loc.Row);
1714 eclass = ExprClass.Value;
1716 if (left is Constant && right is Constant){
1718 // This is temporary until we do the full folding
1720 Expression e = ConstantFold (ec);
1725 return ResolveOperator (ec);
1728 public bool IsBranchable ()
1730 if (oper == Operator.Equality ||
1731 oper == Operator.Inequality ||
1732 oper == Operator.LessThan ||
1733 oper == Operator.GreaterThan ||
1734 oper == Operator.LessThanOrEqual ||
1735 oper == Operator.GreaterThanOrEqual){
1742 /// This entry point is used by routines that might want
1743 /// to emit a brfalse/brtrue after an expression, and instead
1744 /// they could use a more compact notation.
1746 /// Typically the code would generate l.emit/r.emit, followed
1747 /// by the comparission and then a brtrue/brfalse. The comparissions
1748 /// are sometimes inneficient (there are not as complete as the branches
1749 /// look for the hacks in Emit using double ceqs).
1751 /// So for those cases we provide EmitBranchable that can emit the
1752 /// branch with the test
1754 public void EmitBranchable (EmitContext ec, int target)
1757 bool close_target = false;
1758 ILGenerator ig = ec.ig;
1761 // short-circuit operators
1763 if (oper == Operator.LogicalAnd){
1765 ig.Emit (OpCodes.Brfalse, target);
1767 ig.Emit (OpCodes.Brfalse, target);
1768 } else if (oper == Operator.LogicalOr){
1770 ig.Emit (OpCodes.Brtrue, target);
1772 ig.Emit (OpCodes.Brfalse, target);
1779 case Operator.Equality:
1781 opcode = OpCodes.Beq_S;
1783 opcode = OpCodes.Beq;
1786 case Operator.Inequality:
1788 opcode = OpCodes.Bne_Un_S;
1790 opcode = OpCodes.Bne_Un;
1793 case Operator.LessThan:
1795 opcode = OpCodes.Blt_S;
1797 opcode = OpCodes.Blt;
1800 case Operator.GreaterThan:
1802 opcode = OpCodes.Bgt_S;
1804 opcode = OpCodes.Bgt;
1807 case Operator.LessThanOrEqual:
1809 opcode = OpCodes.Ble_S;
1811 opcode = OpCodes.Ble;
1814 case Operator.GreaterThanOrEqual:
1816 opcode = OpCodes.Bge_S;
1818 opcode = OpCodes.Ble;
1822 throw new Exception ("EmitBranchable called on non-EmitBranchable operator: "
1823 + oper.ToString ());
1826 ig.Emit (opcode, target);
1829 public override void Emit (EmitContext ec)
1831 ILGenerator ig = ec.ig;
1833 Type r = right.Type;
1836 if (method != null) {
1838 // Note that operators are static anyway
1840 if (Arguments != null)
1841 Invocation.EmitArguments (ec, method, Arguments);
1843 if (method is MethodInfo)
1844 ig.Emit (OpCodes.Call, (MethodInfo) method);
1846 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
1848 if (DelegateOperation)
1849 ig.Emit (OpCodes.Castclass, type);
1855 // Handle short-circuit operators differently
1858 if (oper == Operator.LogicalAnd){
1859 Label load_zero = ig.DefineLabel ();
1860 Label end = ig.DefineLabel ();
1863 ig.Emit (OpCodes.Brfalse, load_zero);
1865 ig.Emit (OpCodes.Br, end);
1866 ig.MarkLabel (load_zero);
1867 ig.Emit (OpCodes.Ldc_I4_0);
1870 } else if (oper == Operator.LogicalOr){
1871 Label load_one = ig.DefineLabel ();
1872 Label end = ig.DefineLabel ();
1875 ig.Emit (OpCodes.Brtrue, load_one);
1877 ig.Emit (OpCodes.Br, end);
1878 ig.MarkLabel (load_one);
1879 ig.Emit (OpCodes.Ldc_I4_1);
1888 case Operator.Multiply:
1890 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
1891 opcode = OpCodes.Mul_Ovf;
1892 else if (l==TypeManager.uint32_type || l==TypeManager.uint64_type)
1893 opcode = OpCodes.Mul_Ovf_Un;
1895 opcode = OpCodes.Mul;
1897 opcode = OpCodes.Mul;
1901 case Operator.Division:
1902 if (l == TypeManager.uint32_type || l == TypeManager.uint64_type)
1903 opcode = OpCodes.Div_Un;
1905 opcode = OpCodes.Div;
1908 case Operator.Modulus:
1909 if (l == TypeManager.uint32_type || l == TypeManager.uint64_type)
1910 opcode = OpCodes.Rem_Un;
1912 opcode = OpCodes.Rem;
1915 case Operator.Addition:
1917 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
1918 opcode = OpCodes.Add_Ovf;
1919 else if (l==TypeManager.uint32_type || l==TypeManager.uint64_type)
1920 opcode = OpCodes.Add_Ovf_Un;
1922 opcode = OpCodes.Mul;
1924 opcode = OpCodes.Add;
1927 case Operator.Subtraction:
1929 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
1930 opcode = OpCodes.Sub_Ovf;
1931 else if (l==TypeManager.uint32_type || l==TypeManager.uint64_type)
1932 opcode = OpCodes.Sub_Ovf_Un;
1934 opcode = OpCodes.Sub;
1936 opcode = OpCodes.Sub;
1939 case Operator.RightShift:
1940 opcode = OpCodes.Shr;
1943 case Operator.LeftShift:
1944 opcode = OpCodes.Shl;
1947 case Operator.Equality:
1948 opcode = OpCodes.Ceq;
1951 case Operator.Inequality:
1952 ec.ig.Emit (OpCodes.Ceq);
1953 ec.ig.Emit (OpCodes.Ldc_I4_0);
1955 opcode = OpCodes.Ceq;
1958 case Operator.LessThan:
1959 opcode = OpCodes.Clt;
1962 case Operator.GreaterThan:
1963 opcode = OpCodes.Cgt;
1966 case Operator.LessThanOrEqual:
1967 ec.ig.Emit (OpCodes.Cgt);
1968 ec.ig.Emit (OpCodes.Ldc_I4_0);
1970 opcode = OpCodes.Ceq;
1973 case Operator.GreaterThanOrEqual:
1974 ec.ig.Emit (OpCodes.Clt);
1975 ec.ig.Emit (OpCodes.Ldc_I4_1);
1977 opcode = OpCodes.Sub;
1980 case Operator.BitwiseOr:
1981 opcode = OpCodes.Or;
1984 case Operator.BitwiseAnd:
1985 opcode = OpCodes.And;
1988 case Operator.ExclusiveOr:
1989 opcode = OpCodes.Xor;
1993 throw new Exception ("This should not happen: Operator = "
1994 + oper.ToString ());
2002 /// Implements the ternary conditiona operator (?:)
2004 public class Conditional : Expression {
2005 Expression expr, trueExpr, falseExpr;
2008 public Conditional (Expression expr, Expression trueExpr, Expression falseExpr, Location l)
2011 this.trueExpr = trueExpr;
2012 this.falseExpr = falseExpr;
2016 public Expression Expr {
2022 public Expression TrueExpr {
2028 public Expression FalseExpr {
2034 public override Expression DoResolve (EmitContext ec)
2036 expr = expr.Resolve (ec);
2038 if (expr.Type != TypeManager.bool_type)
2039 expr = Expression.ConvertImplicitRequired (
2040 ec, expr, TypeManager.bool_type, loc);
2042 trueExpr = trueExpr.Resolve (ec);
2043 falseExpr = falseExpr.Resolve (ec);
2045 if (expr == null || trueExpr == null || falseExpr == null)
2048 if (trueExpr.Type == falseExpr.Type)
2049 type = trueExpr.Type;
2054 // First, if an implicit conversion exists from trueExpr
2055 // to falseExpr, then the result type is of type falseExpr.Type
2057 conv = ConvertImplicit (ec, trueExpr, falseExpr.Type, loc);
2059 type = falseExpr.Type;
2061 } else if ((conv = ConvertImplicit(ec, falseExpr,trueExpr.Type,loc))!= null){
2062 type = trueExpr.Type;
2065 Error (173, loc, "The type of the conditional expression can " +
2066 "not be computed because there is no implicit conversion" +
2067 " from `" + TypeManager.CSharpName (trueExpr.Type) + "'" +
2068 " and `" + TypeManager.CSharpName (falseExpr.Type) + "'");
2073 if (expr is BoolConstant){
2074 BoolConstant bc = (BoolConstant) expr;
2082 eclass = ExprClass.Value;
2086 public override void Emit (EmitContext ec)
2088 ILGenerator ig = ec.ig;
2089 Label false_target = ig.DefineLabel ();
2090 Label end_target = ig.DefineLabel ();
2093 ig.Emit (OpCodes.Brfalse, false_target);
2095 ig.Emit (OpCodes.Br, end_target);
2096 ig.MarkLabel (false_target);
2097 falseExpr.Emit (ec);
2098 ig.MarkLabel (end_target);
2106 public class LocalVariableReference : Expression, IAssignMethod, IMemoryLocation {
2107 public readonly string Name;
2108 public readonly Block Block;
2110 VariableInfo variable_info;
2112 public LocalVariableReference (Block block, string name, Location l)
2117 eclass = ExprClass.Variable;
2120 public VariableInfo VariableInfo {
2122 if (variable_info == null)
2123 variable_info = Block.GetVariableInfo (Name);
2124 return variable_info;
2128 public override Expression DoResolve (EmitContext ec)
2130 VariableInfo vi = VariableInfo;
2132 if (Block.IsConstant (Name)) {
2133 Expression e = Block.GetConstantExpression (Name);
2139 if (!(e is Constant)) {
2140 Report.Error (150, loc, "A constant value is expected");
2148 type = vi.VariableType;
2152 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
2154 Expression e = DoResolve (ec);
2159 VariableInfo vi = VariableInfo;
2165 "cannot assign to `" + Name + "' because it is readonly");
2173 public override void Emit (EmitContext ec)
2175 VariableInfo vi = VariableInfo;
2176 ILGenerator ig = ec.ig;
2183 ig.Emit (OpCodes.Ldloc_0);
2187 ig.Emit (OpCodes.Ldloc_1);
2191 ig.Emit (OpCodes.Ldloc_2);
2195 ig.Emit (OpCodes.Ldloc_3);
2200 ig.Emit (OpCodes.Ldloc_S, (byte) idx);
2202 ig.Emit (OpCodes.Ldloc, idx);
2207 public static void Store (ILGenerator ig, int idx)
2211 ig.Emit (OpCodes.Stloc_0);
2215 ig.Emit (OpCodes.Stloc_1);
2219 ig.Emit (OpCodes.Stloc_2);
2223 ig.Emit (OpCodes.Stloc_3);
2228 ig.Emit (OpCodes.Stloc_S, (byte) idx);
2230 ig.Emit (OpCodes.Stloc, idx);
2235 public void EmitAssign (EmitContext ec, Expression source)
2237 ILGenerator ig = ec.ig;
2238 VariableInfo vi = VariableInfo;
2244 // Funny seems the code below generates optimal code for us, but
2245 // seems to take too long to generate what we need.
2246 // ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
2251 public void AddressOf (EmitContext ec)
2253 VariableInfo vi = VariableInfo;
2260 ec.ig.Emit (OpCodes.Ldloca_S, (byte) idx);
2262 ec.ig.Emit (OpCodes.Ldloca, idx);
2267 /// This represents a reference to a parameter in the intermediate
2270 public class ParameterReference : Expression, IAssignMethod, IMemoryLocation {
2276 public ParameterReference (Parameters pars, int idx, string name)
2281 eclass = ExprClass.Variable;
2285 // Notice that for ref/out parameters, the type exposed is not the
2286 // same type exposed externally.
2289 // externally we expose "int&"
2290 // here we expose "int".
2292 // We record this in "is_ref". This means that the type system can treat
2293 // the type as it is expected, but when we generate the code, we generate
2294 // the alternate kind of code.
2296 public override Expression DoResolve (EmitContext ec)
2298 type = pars.GetParameterInfo (ec.TypeContainer, idx, out is_ref);
2299 eclass = ExprClass.Variable;
2304 public override void Emit (EmitContext ec)
2306 ILGenerator ig = ec.ig;
2313 ig.Emit (OpCodes.Ldarg_S, (byte) arg_idx);
2315 ig.Emit (OpCodes.Ldarg, arg_idx);
2321 // If we are a reference, we loaded on the stack a pointer
2322 // Now lets load the real value
2325 if (type == TypeManager.int32_type)
2326 ig.Emit (OpCodes.Ldind_I4);
2327 else if (type == TypeManager.uint32_type)
2328 ig.Emit (OpCodes.Ldind_U4);
2329 else if (type == TypeManager.int64_type || type == TypeManager.uint64_type)
2330 ig.Emit (OpCodes.Ldind_I8);
2331 else if (type == TypeManager.char_type)
2332 ig.Emit (OpCodes.Ldind_U2);
2333 else if (type == TypeManager.short_type)
2334 ig.Emit (OpCodes.Ldind_I2);
2335 else if (type == TypeManager.ushort_type)
2336 ig.Emit (OpCodes.Ldind_U2);
2337 else if (type == TypeManager.float_type)
2338 ig.Emit (OpCodes.Ldind_R4);
2339 else if (type == TypeManager.double_type)
2340 ig.Emit (OpCodes.Ldind_R8);
2341 else if (type == TypeManager.byte_type)
2342 ig.Emit (OpCodes.Ldind_U1);
2343 else if (type == TypeManager.sbyte_type)
2344 ig.Emit (OpCodes.Ldind_I1);
2345 else if (type == TypeManager.intptr_type)
2346 ig.Emit (OpCodes.Ldind_I);
2348 ig.Emit (OpCodes.Ldind_Ref);
2351 public void EmitAssign (EmitContext ec, Expression source)
2353 ILGenerator ig = ec.ig;
2362 ig.Emit (OpCodes.Ldarg_S, (byte) arg_idx);
2364 ig.Emit (OpCodes.Ldarg, arg_idx);
2370 if (type == TypeManager.int32_type || type == TypeManager.uint32_type)
2371 ig.Emit (OpCodes.Stind_I4);
2372 else if (type == TypeManager.int64_type || type == TypeManager.uint64_type)
2373 ig.Emit (OpCodes.Stind_I8);
2374 else if (type == TypeManager.char_type || type == TypeManager.short_type ||
2375 type == TypeManager.ushort_type)
2376 ig.Emit (OpCodes.Stind_I2);
2377 else if (type == TypeManager.float_type)
2378 ig.Emit (OpCodes.Stind_R4);
2379 else if (type == TypeManager.double_type)
2380 ig.Emit (OpCodes.Stind_R8);
2381 else if (type == TypeManager.byte_type || type == TypeManager.sbyte_type)
2382 ig.Emit (OpCodes.Stind_I1);
2383 else if (type == TypeManager.intptr_type)
2384 ig.Emit (OpCodes.Stind_I);
2386 ig.Emit (OpCodes.Stind_Ref);
2389 ig.Emit (OpCodes.Starg_S, (byte) arg_idx);
2391 ig.Emit (OpCodes.Starg, arg_idx);
2396 public void AddressOf (EmitContext ec)
2404 ec.ig.Emit (OpCodes.Ldarga_S, (byte) arg_idx);
2406 ec.ig.Emit (OpCodes.Ldarga, arg_idx);
2411 /// Used for arguments to New(), Invocation()
2413 public class Argument {
2414 public enum AType : byte {
2420 public readonly AType ArgType;
2421 public Expression expr;
2423 public Argument (Expression expr, AType type)
2426 this.ArgType = type;
2429 public Expression Expr {
2445 public Parameter.Modifier GetParameterModifier ()
2447 if (ArgType == AType.Ref)
2448 return Parameter.Modifier.REF;
2450 if (ArgType == AType.Out)
2451 return Parameter.Modifier.OUT;
2453 return Parameter.Modifier.NONE;
2456 public static string FullDesc (Argument a)
2458 return (a.ArgType == AType.Ref ? "ref " :
2459 (a.ArgType == AType.Out ? "out " : "")) +
2460 TypeManager.CSharpName (a.Expr.Type);
2463 public bool Resolve (EmitContext ec, Location loc)
2465 expr = expr.Resolve (ec);
2467 if (ArgType == AType.Expression)
2468 return expr != null;
2470 if (expr.eclass != ExprClass.Variable){
2471 Report.Error (206, loc,
2472 "A property or indexer can not be passed as an out or ref " +
2477 return expr != null;
2480 public void Emit (EmitContext ec)
2482 if (ArgType == AType.Ref || ArgType == AType.Out)
2483 ((IMemoryLocation)expr).AddressOf (ec);
2490 /// Invocation of methods or delegates.
2492 public class Invocation : ExpressionStatement {
2493 public readonly ArrayList Arguments;
2497 MethodBase method = null;
2499 static Hashtable method_parameter_cache;
2501 static Invocation ()
2503 method_parameter_cache = new PtrHashtable ();
2507 // arguments is an ArrayList, but we do not want to typecast,
2508 // as it might be null.
2510 // FIXME: only allow expr to be a method invocation or a
2511 // delegate invocation (7.5.5)
2513 public Invocation (Expression expr, ArrayList arguments, Location l)
2516 Arguments = arguments;
2520 public Expression Expr {
2527 /// Returns the Parameters (a ParameterData interface) for the
2530 public static ParameterData GetParameterData (MethodBase mb)
2532 object pd = method_parameter_cache [mb];
2536 return (ParameterData) pd;
2539 ip = TypeManager.LookupParametersByBuilder (mb);
2541 method_parameter_cache [mb] = ip;
2543 return (ParameterData) ip;
2545 ParameterInfo [] pi = mb.GetParameters ();
2546 ReflectionParameters rp = new ReflectionParameters (pi);
2547 method_parameter_cache [mb] = rp;
2549 return (ParameterData) rp;
2554 /// Tells whether a user defined conversion from Type `from' to
2555 /// Type `to' exists.
2557 /// FIXME: we could implement a cache here.
2559 static bool ConversionExists (EmitContext ec, Type from, Type to, Location loc)
2561 // Locate user-defined implicit operators
2565 mg = MemberLookup (ec, to, "op_Implicit", false, loc);
2568 MethodGroupExpr me = (MethodGroupExpr) mg;
2570 for (int i = me.Methods.Length; i > 0;) {
2572 MethodBase mb = me.Methods [i];
2573 ParameterData pd = GetParameterData (mb);
2575 if (from == pd.ParameterType (0))
2580 mg = MemberLookup (ec, from, "op_Implicit", false, loc);
2583 MethodGroupExpr me = (MethodGroupExpr) mg;
2585 for (int i = me.Methods.Length; i > 0;) {
2587 MethodBase mb = me.Methods [i];
2588 MethodInfo mi = (MethodInfo) mb;
2590 if (mi.ReturnType == to)
2599 /// Determines "better conversion" as specified in 7.4.2.3
2600 /// Returns : 1 if a->p is better
2601 /// 0 if a->q or neither is better
2603 static int BetterConversion (EmitContext ec, Argument a, Type p, Type q, bool use_standard,
2606 Type argument_type = a.Type;
2607 Expression argument_expr = a.Expr;
2609 if (argument_type == null)
2610 throw new Exception ("Expression of type " + a.Expr + " does not resolve its type");
2615 if (argument_type == p)
2618 if (argument_type == q)
2622 // Now probe whether an implicit constant expression conversion
2625 // An implicit constant expression conversion permits the following
2628 // * A constant-expression of type `int' can be converted to type
2629 // sbyte, byute, short, ushort, uint, ulong provided the value of
2630 // of the expression is withing the range of the destination type.
2632 // * A constant-expression of type long can be converted to type
2633 // ulong, provided the value of the constant expression is not negative
2635 // FIXME: Note that this assumes that constant folding has
2636 // taken place. We dont do constant folding yet.
2639 if (argument_expr is IntConstant){
2640 IntConstant ei = (IntConstant) argument_expr;
2641 int value = ei.Value;
2643 if (p == TypeManager.sbyte_type){
2644 if (value >= SByte.MinValue && value <= SByte.MaxValue)
2646 } else if (p == TypeManager.byte_type){
2647 if (Byte.MinValue >= 0 && value <= Byte.MaxValue)
2649 } else if (p == TypeManager.short_type){
2650 if (value >= Int16.MinValue && value <= Int16.MaxValue)
2652 } else if (p == TypeManager.ushort_type){
2653 if (value >= UInt16.MinValue && value <= UInt16.MaxValue)
2655 } else if (p == TypeManager.uint32_type){
2657 // we can optimize this case: a positive int32
2658 // always fits on a uint32
2662 } else if (p == TypeManager.uint64_type){
2664 // we can optimize this case: a positive int32
2665 // always fits on a uint64
2670 } else if (argument_type == TypeManager.int64_type && argument_expr is LongConstant){
2671 LongConstant lc = (LongConstant) argument_expr;
2673 if (p == TypeManager.uint64_type){
2684 tmp = ConvertImplicitStandard (ec, argument_expr, p, loc);
2686 tmp = ConvertImplicit (ec, argument_expr, p, loc);
2695 if (ConversionExists (ec, p, q, loc) == true &&
2696 ConversionExists (ec, q, p, loc) == false)
2699 if (p == TypeManager.sbyte_type)
2700 if (q == TypeManager.byte_type || q == TypeManager.ushort_type ||
2701 q == TypeManager.uint32_type || q == TypeManager.uint64_type)
2704 if (p == TypeManager.short_type)
2705 if (q == TypeManager.ushort_type || q == TypeManager.uint32_type ||
2706 q == TypeManager.uint64_type)
2709 if (p == TypeManager.int32_type)
2710 if (q == TypeManager.uint32_type || q == TypeManager.uint64_type)
2713 if (p == TypeManager.int64_type)
2714 if (q == TypeManager.uint64_type)
2721 /// Determines "Better function"
2724 /// and returns an integer indicating :
2725 /// 0 if candidate ain't better
2726 /// 1 if candidate is better than the current best match
2728 static int BetterFunction (EmitContext ec, ArrayList args,
2729 MethodBase candidate, MethodBase best,
2730 bool use_standard, Location loc)
2732 ParameterData candidate_pd = GetParameterData (candidate);
2733 ParameterData best_pd;
2740 argument_count = args.Count;
2742 if (candidate_pd.Count == 0 && argument_count == 0)
2745 if (candidate_pd.ParameterModifier (candidate_pd.Count - 1) != Parameter.Modifier.PARAMS)
2746 if (candidate_pd.Count != argument_count)
2751 for (int j = argument_count; j > 0;) {
2754 Argument a = (Argument) args [j];
2756 x = BetterConversion (ec, a, candidate_pd.ParameterType (j), null,
2769 best_pd = GetParameterData (best);
2771 int rating1 = 0, rating2 = 0;
2773 for (int j = 0; j < argument_count; ++j) {
2776 Argument a = (Argument) args [j];
2778 x = BetterConversion (ec, a, candidate_pd.ParameterType (j),
2779 best_pd.ParameterType (j), use_standard, loc);
2780 y = BetterConversion (ec, a, best_pd.ParameterType (j),
2781 candidate_pd.ParameterType (j), use_standard, loc);
2788 if (rating1 > rating2)
2794 public static string FullMethodDesc (MethodBase mb)
2796 StringBuilder sb = new StringBuilder (mb.Name);
2797 ParameterData pd = GetParameterData (mb);
2799 int count = pd.Count;
2802 for (int i = count; i > 0; ) {
2805 sb.Append (pd.ParameterDesc (count - i - 1));
2811 return sb.ToString ();
2814 public static MethodGroupExpr MakeUnionSet (Expression mg1, Expression mg2)
2816 MemberInfo [] miset;
2817 MethodGroupExpr union;
2819 if (mg1 != null && mg2 != null) {
2821 MethodGroupExpr left_set = null, right_set = null;
2822 int length1 = 0, length2 = 0;
2824 left_set = (MethodGroupExpr) mg1;
2825 length1 = left_set.Methods.Length;
2827 right_set = (MethodGroupExpr) mg2;
2828 length2 = right_set.Methods.Length;
2830 ArrayList common = new ArrayList ();
2832 for (int i = 0; i < left_set.Methods.Length; i++) {
2833 for (int j = 0; j < right_set.Methods.Length; j++) {
2834 if (left_set.Methods [i] == right_set.Methods [j])
2835 common.Add (left_set.Methods [i]);
2839 miset = new MemberInfo [length1 + length2 - common.Count];
2841 left_set.Methods.CopyTo (miset, 0);
2845 for (int j = 0; j < right_set.Methods.Length; j++)
2846 if (!common.Contains (right_set.Methods [j]))
2847 miset [length1 + k++] = right_set.Methods [j];
2849 union = new MethodGroupExpr (miset);
2853 } else if (mg1 == null && mg2 != null) {
2855 MethodGroupExpr me = (MethodGroupExpr) mg2;
2857 miset = new MemberInfo [me.Methods.Length];
2858 me.Methods.CopyTo (miset, 0);
2860 union = new MethodGroupExpr (miset);
2864 } else if (mg2 == null && mg1 != null) {
2866 MethodGroupExpr me = (MethodGroupExpr) mg1;
2868 miset = new MemberInfo [me.Methods.Length];
2869 me.Methods.CopyTo (miset, 0);
2871 union = new MethodGroupExpr (miset);
2880 /// Determines is the candidate method, if a params method, is applicable
2881 /// in its expanded form to the given set of arguments
2883 static bool IsParamsMethodApplicable (ArrayList arguments, MethodBase candidate)
2887 if (arguments == null)
2890 arg_count = arguments.Count;
2892 ParameterData pd = GetParameterData (candidate);
2894 int pd_count = pd.Count;
2899 if (pd.ParameterModifier (pd_count - 1) != Parameter.Modifier.PARAMS)
2902 if (pd_count - 1 > arg_count)
2906 // If we have come this far, the case which remains is when the number of parameters
2907 // is less than or equal to the argument count. So, we now check if the element type
2908 // of the params array is compatible with each argument type
2911 Type element_type = pd.ParameterType (pd_count - 1);
2913 for (int i = pd_count - 1; i < arg_count - 1; i++) {
2914 Argument a = (Argument) arguments [i];
2916 if (!StandardConversionExists (a.Type, element_type))
2924 /// Determines if the candidate method is applicable (section 14.4.2.1)
2925 /// to the given set of arguments
2927 static bool IsApplicable (ArrayList arguments, MethodBase candidate)
2931 if (arguments == null)
2934 arg_count = arguments.Count;
2936 ParameterData pd = GetParameterData (candidate);
2938 int pd_count = pd.Count;
2940 if (arg_count != pd.Count)
2943 for (int i = arg_count; i > 0; ) {
2946 Argument a = (Argument) arguments [i];
2948 Parameter.Modifier a_mod = a.GetParameterModifier ();
2949 Parameter.Modifier p_mod = pd.ParameterModifier (i);
2951 if (a_mod == p_mod) {
2953 if (a_mod == Parameter.Modifier.NONE)
2954 if (!StandardConversionExists (a.Type, pd.ParameterType (i)))
2957 if (a_mod == Parameter.Modifier.REF ||
2958 a_mod == Parameter.Modifier.OUT)
2959 if (pd.ParameterType (i) != a.Type)
2971 /// Find the Applicable Function Members (7.4.2.1)
2973 /// me: Method Group expression with the members to select.
2974 /// it might contain constructors or methods (or anything
2975 /// that maps to a method).
2977 /// Arguments: ArrayList containing resolved Argument objects.
2979 /// loc: The location if we want an error to be reported, or a Null
2980 /// location for "probing" purposes.
2982 /// use_standard: controls whether OverloadResolve should use the
2983 /// ConvertImplicit or ConvertImplicitStandard during overload resolution.
2985 /// Returns: The MethodBase (either a ConstructorInfo or a MethodInfo)
2986 /// that is the best match of me on Arguments.
2989 public static MethodBase OverloadResolve (EmitContext ec, MethodGroupExpr me,
2990 ArrayList Arguments, Location loc,
2993 ArrayList afm = new ArrayList ();
2994 int best_match_idx = -1;
2995 MethodBase method = null;
2997 ArrayList candidates = new ArrayList ();
2999 for (int i = me.Methods.Length; i > 0; ){
3001 MethodBase candidate = me.Methods [i];
3004 // Check if candidate is applicable (section 14.4.2.1)
3005 if (!IsApplicable (Arguments, candidate))
3008 candidates.Add (candidate);
3010 x = BetterFunction (ec, Arguments, candidate, method, use_standard, loc);
3016 method = me.Methods [best_match_idx];
3020 if (Arguments == null)
3023 argument_count = Arguments.Count;
3026 // Now we see if we can find params functions, applicable in their expanded form
3027 // since if they were applicable in their normal form, they would have been selected
3030 if (best_match_idx == -1) {
3032 candidates = new ArrayList ();
3033 for (int i = me.Methods.Length; i > 0; ) {
3035 MethodBase candidate = me.Methods [i];
3037 if (!IsParamsMethodApplicable (Arguments, candidate))
3040 candidates.Add (candidate);
3042 int x = BetterFunction (ec, Arguments, candidate, method, use_standard, loc);
3048 method = me.Methods [best_match_idx];
3054 // Now we see if we can at least find a method with the same number of arguments
3057 int method_count = 0;
3059 if (best_match_idx == -1) {
3061 for (int i = me.Methods.Length; i > 0;) {
3063 MethodBase mb = me.Methods [i];
3064 pd = GetParameterData (mb);
3066 if (pd.Count == argument_count) {
3068 method = me.Methods [best_match_idx];
3080 // Now check that there are no ambiguities i.e the selected method
3081 // should be better than all the others
3085 for (int i = 0; i < candidates.Count; ++i) {
3086 MethodBase candidate = (MethodBase) candidates [i];
3087 x = BetterFunction (ec, Arguments, method, candidate, use_standard, loc);
3088 if (candidate == method)
3090 int x = BetterFunction (ec, Arguments, method, candidate, use_standard, loc);
3092 Console.WriteLine (candidate + " " + method);
3095 "Ambiguous call when selecting function due to implicit casts");
3101 // And now convert implicitly, each argument to the required type
3103 pd = GetParameterData (method);
3104 int pd_count = pd.Count;
3106 for (int j = 0; j < argument_count; j++) {
3107 Argument a = (Argument) Arguments [j];
3108 Expression a_expr = a.Expr;
3109 Type parameter_type = pd.ParameterType (j);
3111 if (a.Type != parameter_type){
3115 conv = ConvertImplicitStandard (
3116 ec, a_expr, parameter_type, Location.Null);
3118 conv = ConvertImplicit (
3119 ec, a_expr, parameter_type, Location.Null);
3122 if (!Location.IsNull (loc)) {
3124 "The best overloaded match for method '" +
3125 FullMethodDesc (method) +
3126 "' has some invalid arguments");
3128 "Argument " + (j+1) +
3129 ": Cannot convert from '" + Argument.FullDesc (a)
3130 + "' to '" + pd.ParameterDesc (j) + "'");
3138 // Update the argument with the implicit conversion
3143 // FIXME : For the case of params methods, we need to actually instantiate
3144 // an array and initialize it with the argument values etc etc.
3148 if (a.GetParameterModifier () != pd.ParameterModifier (j) &&
3149 pd.ParameterModifier (j) != Parameter.Modifier.PARAMS) {
3150 if (!Location.IsNull (loc)) {
3152 "The best overloaded match for method '" + FullMethodDesc (method)+
3153 "' has some invalid arguments");
3155 "Argument " + (j+1) +
3156 ": Cannot convert from '" + Argument.FullDesc (a)
3157 + "' to '" + pd.ParameterDesc (j) + "'");
3168 public static MethodBase OverloadResolve (EmitContext ec, MethodGroupExpr me,
3169 ArrayList Arguments, Location loc)
3171 return OverloadResolve (ec, me, Arguments, loc, false);
3174 public override Expression DoResolve (EmitContext ec)
3177 // First, resolve the expression that is used to
3178 // trigger the invocation
3180 expr = expr.Resolve (ec);
3184 if (!(expr is MethodGroupExpr)) {
3185 Type expr_type = expr.Type;
3187 if (expr_type != null){
3188 bool IsDelegate = TypeManager.IsDelegateType (expr_type);
3190 return (new DelegateInvocation (
3191 this.expr, Arguments, loc)).Resolve (ec);
3195 if (!(expr is MethodGroupExpr)){
3196 report118 (loc, this.expr, "method group");
3201 // Next, evaluate all the expressions in the argument list
3203 if (Arguments != null){
3204 for (int i = Arguments.Count; i > 0;){
3206 Argument a = (Argument) Arguments [i];
3208 if (!a.Resolve (ec, loc))
3213 method = OverloadResolve (ec, (MethodGroupExpr) this.expr, Arguments, loc);
3215 if (method == null){
3217 "Could not find any applicable function for this argument list");
3221 if (method is MethodInfo)
3222 type = ((MethodInfo)method).ReturnType;
3224 eclass = ExprClass.Value;
3229 // Emits the list of arguments as an array
3231 static void EmitParams (EmitContext ec, int idx, ArrayList arguments)
3233 ILGenerator ig = ec.ig;
3234 int count = arguments.Count - idx;
3235 Argument a = (Argument) arguments [idx];
3236 Type t = a.expr.Type;
3237 string array_type = t.FullName + "[]";
3240 array = ig.DeclareLocal (Type.GetType (array_type));
3241 IntConstant.EmitInt (ig, count);
3242 ig.Emit (OpCodes.Newarr, t);
3243 ig.Emit (OpCodes.Stloc, array);
3245 int top = arguments.Count;
3246 for (int j = idx; j < top; j++){
3247 a = (Argument) arguments [j];
3249 ig.Emit (OpCodes.Ldloc, array);
3250 IntConstant.EmitInt (ig, j - idx);
3253 ArrayAccess.EmitStoreOpcode (ig, t);
3255 ig.Emit (OpCodes.Ldloc, array);
3259 /// Emits a list of resolved Arguments that are in the arguments
3262 /// The MethodBase argument might be null if the
3263 /// emission of the arguments is known not to contain
3264 /// a `params' field (for example in constructors or other routines
3265 /// that keep their arguments in this structure
3267 public static void EmitArguments (EmitContext ec, MethodBase mb, ArrayList arguments)
3269 ParameterData pd = null;
3272 if (arguments != null)
3273 top = arguments.Count;
3278 pd = GetParameterData (mb);
3280 for (int i = 0; i < top; i++){
3281 Argument a = (Argument) arguments [i];
3284 if (pd.ParameterModifier (i) == Parameter.Modifier.PARAMS){
3285 EmitParams (ec, i, arguments);
3294 public static void EmitCall (EmitContext ec,
3295 bool is_static, Expression instance_expr,
3296 MethodBase method, ArrayList Arguments)
3298 ILGenerator ig = ec.ig;
3299 bool struct_call = false;
3303 // If this is ourselves, push "this"
3305 if (instance_expr == null){
3306 ig.Emit (OpCodes.Ldarg_0);
3309 // Push the instance expression
3311 if (instance_expr.Type.IsSubclassOf (TypeManager.value_type)){
3313 // Special case: calls to a function declared in a
3314 // reference-type with a value-type argument need
3315 // to have their value boxed.
3317 if (method.DeclaringType.IsValueType){
3321 // If the expression implements IMemoryLocation, then
3322 // we can optimize and use AddressOf on the
3325 // If not we have to use some temporary storage for
3327 if (instance_expr is IMemoryLocation){
3328 ((IMemoryLocation)instance_expr).
3332 Type t = instance_expr.Type;
3334 instance_expr.Emit (ec);
3335 LocalBuilder temp = ig.DeclareLocal (t);
3336 ig.Emit (OpCodes.Stloc, temp);
3337 ig.Emit (OpCodes.Ldloca, temp);
3340 instance_expr.Emit (ec);
3341 ig.Emit (OpCodes.Box, instance_expr.Type);
3344 instance_expr.Emit (ec);
3348 if (Arguments != null)
3349 EmitArguments (ec, method, Arguments);
3351 if (is_static || struct_call){
3352 if (method is MethodInfo)
3353 ig.Emit (OpCodes.Call, (MethodInfo) method);
3355 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
3357 if (method is MethodInfo)
3358 ig.Emit (OpCodes.Callvirt, (MethodInfo) method);
3360 ig.Emit (OpCodes.Callvirt, (ConstructorInfo) method);
3364 public override void Emit (EmitContext ec)
3366 MethodGroupExpr mg = (MethodGroupExpr) this.expr;
3368 EmitCall (ec, method.IsStatic, mg.InstanceExpression, method, Arguments);
3371 public override void EmitStatement (EmitContext ec)
3376 // Pop the return value if there is one
3378 if (method is MethodInfo){
3379 if (((MethodInfo)method).ReturnType != TypeManager.void_type)
3380 ec.ig.Emit (OpCodes.Pop);
3386 /// Implements the new expression
3388 public class New : ExpressionStatement {
3389 public readonly ArrayList Arguments;
3390 public readonly string RequestedType;
3393 MethodBase method = null;
3396 // If set, the new expression is for a value_target, and
3397 // we will not leave anything on the stack.
3399 Expression value_target;
3401 public New (string requested_type, ArrayList arguments, Location l)
3403 RequestedType = requested_type;
3404 Arguments = arguments;
3408 public Expression ValueTypeVariable {
3410 return value_target;
3414 value_target = value;
3418 public override Expression DoResolve (EmitContext ec)
3420 type = RootContext.LookupType (ec.TypeContainer, RequestedType, false, loc);
3425 bool IsDelegate = TypeManager.IsDelegateType (type);
3428 return (new NewDelegate (type, Arguments, loc)).Resolve (ec);
3430 bool is_struct = false;
3431 is_struct = type.IsSubclassOf (TypeManager.value_type);
3432 eclass = ExprClass.Value;
3435 // SRE returns a match for .ctor () on structs (the object constructor),
3436 // so we have to manually ignore it.
3438 if (is_struct && Arguments == null)
3442 ml = MemberLookup (ec, type, ".ctor", false,
3443 MemberTypes.Constructor, AllBindingFlags, loc);
3445 if (! (ml is MethodGroupExpr)){
3447 report118 (loc, ml, "method group");
3453 if (Arguments != null){
3454 for (int i = Arguments.Count; i > 0;){
3456 Argument a = (Argument) Arguments [i];
3458 if (!a.Resolve (ec, loc))
3463 method = Invocation.OverloadResolve (ec, (MethodGroupExpr) ml,
3467 if (method == null && !is_struct) {
3469 "New invocation: Can not find a constructor for " +
3470 "this argument list");
3477 // This DoEmit can be invoked in two contexts:
3478 // * As a mechanism that will leave a value on the stack (new object)
3479 // * As one that wont (init struct)
3481 // You can control whether a value is required on the stack by passing
3482 // need_value_on_stack. The code *might* leave a value on the stack
3483 // so it must be popped manually
3485 // If we are dealing with a ValueType, we have a few
3486 // situations to deal with:
3488 // * The target is a ValueType, and we have been provided
3489 // the instance (this is easy, we are being assigned).
3491 // * The target of New is being passed as an argument,
3492 // to a boxing operation or a function that takes a
3495 // In this case, we need to create a temporary variable
3496 // that is the argument of New.
3498 // Returns whether a value is left on the stack
3500 bool DoEmit (EmitContext ec, bool need_value_on_stack)
3502 if (method == null){
3505 if (value_target == null)
3506 value_target = new LocalTemporary (ec, type);
3508 ml = (IMemoryLocation) value_target;
3511 Invocation.EmitArguments (ec, method, Arguments);
3512 ec.ig.Emit (OpCodes.Newobj, (ConstructorInfo) method);
3517 // It must be a value type, sanity check
3519 if (value_target != null){
3520 ec.ig.Emit (OpCodes.Initobj, type);
3522 if (need_value_on_stack){
3523 value_target.Emit (ec);
3529 throw new Exception ("No method and no value type");
3532 public override void Emit (EmitContext ec)
3537 public override void EmitStatement (EmitContext ec)
3539 if (DoEmit (ec, false))
3540 ec.ig.Emit (OpCodes.Pop);
3545 /// Represents an array creation expression.
3549 /// There are two possible scenarios here: one is an array creation
3550 /// expression that specifies the dimensions and optionally the
3551 /// initialization data and the other which does not need dimensions
3552 /// specified but where initialization data is mandatory.
3554 public class ArrayCreation : ExpressionStatement {
3555 string RequestedType;
3557 ArrayList Initializers;
3559 ArrayList Arguments;
3561 MethodBase method = null;
3562 Type array_element_type;
3563 bool IsOneDimensional = false;
3564 bool IsBuiltinType = false;
3565 bool ExpectInitializers = false;
3568 Type underlying_type;
3570 ArrayList ArrayData;
3574 public ArrayCreation (string requested_type, ArrayList exprs,
3575 string rank, ArrayList initializers, Location l)
3577 RequestedType = requested_type;
3579 Initializers = initializers;
3582 Arguments = new ArrayList ();
3584 foreach (Expression e in exprs)
3585 Arguments.Add (new Argument (e, Argument.AType.Expression));
3589 public ArrayCreation (string requested_type, string rank, ArrayList initializers, Location l)
3591 RequestedType = requested_type;
3592 Initializers = initializers;
3595 Rank = rank.Substring (0, rank.LastIndexOf ("["));
3597 string tmp = rank.Substring (rank.LastIndexOf ("["));
3599 dimensions = tmp.Length - 1;
3600 ExpectInitializers = true;
3603 public static string FormArrayType (string base_type, int idx_count, string rank)
3605 StringBuilder sb = new StringBuilder (base_type);
3610 for (int i = 1; i < idx_count; i++)
3614 return sb.ToString ();
3617 public static string FormElementType (string base_type, int idx_count, string rank)
3619 StringBuilder sb = new StringBuilder (base_type);
3622 for (int i = 1; i < idx_count; i++)
3628 string val = sb.ToString ();
3630 return val.Substring (0, val.LastIndexOf ("["));
3635 Report.Error (178, loc, "Incorrectly structured array initializer");
3638 public bool CheckIndices (EmitContext ec, ArrayList probe, int idx, bool specified_dims)
3640 if (specified_dims) {
3641 Argument a = (Argument) Arguments [idx];
3643 if (!a.Resolve (ec, loc))
3646 if (!(a.Expr is Constant)) {
3647 Report.Error (150, loc, "A constant value is expected");
3651 int value = (int) ((Constant) a.Expr).GetValue ();
3653 if (value != probe.Count) {
3658 Bounds [idx] = value;
3661 foreach (object o in probe) {
3662 if (o is ArrayList) {
3663 bool ret = CheckIndices (ec, (ArrayList) o, idx + 1, specified_dims);
3667 Expression tmp = (Expression) o;
3668 tmp = tmp.Resolve (ec);
3672 // Handle initialization from vars, fields etc.
3674 Expression conv = ConvertImplicitRequired (
3675 ec, tmp, underlying_type, loc);
3680 if (conv is StringConstant)
3681 ArrayData.Add (conv);
3682 else if (conv is Constant)
3683 ArrayData.Add (((Constant) conv).GetValue ());
3685 ArrayData.Add (conv);
3692 public void UpdateIndices (EmitContext ec)
3695 for (ArrayList probe = Initializers; probe != null;) {
3696 if (probe.Count > 0 && probe [0] is ArrayList) {
3697 Expression e = new IntConstant (probe.Count);
3698 Arguments.Add (new Argument (e, Argument.AType.Expression));
3700 Bounds [i++] = probe.Count;
3702 probe = (ArrayList) probe [0];
3705 Expression e = new IntConstant (probe.Count);
3706 Arguments.Add (new Argument (e, Argument.AType.Expression));
3708 Bounds [i++] = probe.Count;
3715 public bool ValidateInitializers (EmitContext ec)
3717 if (Initializers == null) {
3718 if (ExpectInitializers)
3724 underlying_type = RootContext.LookupType (
3725 ec.TypeContainer, RequestedType, false, loc);
3728 // We use this to store all the date values in the order in which we
3729 // will need to store them in the byte blob later
3731 ArrayData = new ArrayList ();
3732 Bounds = new Hashtable ();
3736 if (Arguments != null) {
3737 ret = CheckIndices (ec, Initializers, 0, true);
3741 Arguments = new ArrayList ();
3743 ret = CheckIndices (ec, Initializers, 0, false);
3750 if (Arguments.Count != dimensions) {
3759 public override Expression DoResolve (EmitContext ec)
3763 if (!ValidateInitializers (ec))
3766 if (Arguments == null)
3769 arg_count = Arguments.Count;
3770 for (int i = arg_count; i > 0;){
3772 Argument a = (Argument) Arguments [i];
3774 if (!a.Resolve (ec, loc))
3779 string array_type = FormArrayType (RequestedType, arg_count, Rank);
3780 string element_type = FormElementType (RequestedType, arg_count, Rank);
3782 type = RootContext.LookupType (ec.TypeContainer, array_type, false, loc);
3784 array_element_type = RootContext.LookupType (
3785 ec.TypeContainer, element_type, false, loc);
3790 if (arg_count == 1) {
3791 IsOneDimensional = true;
3792 eclass = ExprClass.Value;
3796 IsBuiltinType = TypeManager.IsBuiltinType (type);
3798 if (IsBuiltinType) {
3802 ml = MemberLookup (ec, type, ".ctor", false, MemberTypes.Constructor,
3803 AllBindingFlags, loc);
3805 if (!(ml is MethodGroupExpr)){
3806 report118 (loc, ml, "method group");
3811 Report.Error (-6, loc, "New invocation: Can not find a constructor for " +
3812 "this argument list");
3816 method = Invocation.OverloadResolve (ec, (MethodGroupExpr) ml, Arguments, loc);
3818 if (method == null) {
3819 Report.Error (-6, loc, "New invocation: Can not find a constructor for " +
3820 "this argument list");
3824 eclass = ExprClass.Value;
3828 ModuleBuilder mb = RootContext.ModuleBuilder;
3830 ArrayList args = new ArrayList ();
3831 if (Arguments != null){
3832 for (int i = arg_count; i > 0;){
3834 Argument a = (Argument) Arguments [i];
3840 Type [] arg_types = null;
3843 arg_types = new Type [args.Count];
3845 args.CopyTo (arg_types, 0);
3847 method = mb.GetArrayMethod (type, ".ctor", CallingConventions.HasThis, null,
3850 if (method == null) {
3851 Report.Error (-6, loc, "New invocation: Can not find a constructor for " +
3852 "this argument list");
3856 eclass = ExprClass.Value;
3862 public static byte [] MakeByteBlob (ArrayList ArrayData, Type underlying_type, Location loc)
3867 int count = ArrayData.Count;
3869 if (underlying_type == TypeManager.int32_type ||
3870 underlying_type == TypeManager.uint32_type ||
3871 underlying_type == TypeManager.float_type)
3873 else if (underlying_type == TypeManager.int64_type ||
3874 underlying_type == TypeManager.uint64_type ||
3875 underlying_type == TypeManager.double_type)
3877 else if (underlying_type == TypeManager.byte_type ||
3878 underlying_type == TypeManager.sbyte_type ||
3879 underlying_type == TypeManager.bool_type)
3881 else if (underlying_type == TypeManager.short_type ||
3882 underlying_type == TypeManager.char_type ||
3883 underlying_type == TypeManager.ushort_type)
3888 data = new byte [count * factor];
3891 for (int i = 0; i < count; ++i) {
3892 object v = ArrayData [i];
3894 if (v is EnumConstant)
3895 v = ((EnumConstant) v).Child;
3897 if (underlying_type == TypeManager.int64_type ||
3898 underlying_type == TypeManager.uint64_type){
3900 if (!(v is Expression))
3903 for (int j = 0; j < factor; ++j) {
3904 data [idx + j] = (byte) (val & 0xFF);
3907 } else if (underlying_type == TypeManager.float_type) {
3913 if (!(v is Expression))
3916 byte *ptr = (byte *) &val;
3918 for (int j = 0; j < factor; ++j)
3919 data [idx + j] = (byte) ptr [j];
3922 } else if (underlying_type == TypeManager.double_type) {
3928 if (!(v is Expression))
3931 byte *ptr = (byte *) &val;
3933 for (int j = 0; j < factor; ++j)
3934 data [idx + j] = (byte) ptr [j];
3937 } else if (underlying_type == TypeManager.char_type){
3940 if (!(v is Expression))
3941 v = (int) ((char) v);
3943 data [idx] = (byte) (val & 0xff);
3944 data [idx+1] = (byte) (val >> 8);
3946 } else if (underlying_type == TypeManager.int32_type) {
3949 if (!(v is Expression))
3952 data [idx] = (byte) (val & 0xff);
3953 data [idx+1] = (byte) ((val >> 8) & 0xff);
3954 data [idx+2] = (byte) ((val >> 16) & 0xff);
3955 data [idx+3] = (byte) (val >> 24);
3957 throw new Exception ("Unrecognized type in MakeByteBlob");
3966 // Emits the initializers for the array
3968 void EmitStaticInitializers (EmitContext ec, bool is_expression)
3971 // First, the static data
3974 ILGenerator ig = ec.ig;
3976 byte [] data = MakeByteBlob (ArrayData, underlying_type, loc);
3979 fb = RootContext.MakeStaticData (data);
3982 ig.Emit (OpCodes.Dup);
3983 ig.Emit (OpCodes.Ldtoken, fb);
3984 ig.Emit (OpCodes.Call,
3985 TypeManager.void_initializearray_array_fieldhandle);
3990 // Emits pieces of the array that can not be computed at compile
3991 // time (variables and string locations).
3993 // This always expect the top value on the stack to be the array
3995 void EmitDynamicInitializers (EmitContext ec, bool is_expression)
3997 ILGenerator ig = ec.ig;
3998 int dims = Bounds.Count;
3999 int [] current_pos = new int [dims];
4000 int top = ArrayData.Count;
4001 LocalBuilder temp = ig.DeclareLocal (type);
4003 ig.Emit (OpCodes.Stloc, temp);
4005 MethodInfo set = null;
4009 ModuleBuilder mb = null;
4010 mb = RootContext.ModuleBuilder;
4011 args = new Type [dims + 1];
4014 for (j = 0; j < dims; j++)
4015 args [j] = TypeManager.int32_type;
4017 args [j] = array_element_type;
4019 set = mb.GetArrayMethod (
4021 CallingConventions.HasThis | CallingConventions.Standard,
4022 TypeManager.void_type, args);
4025 for (int i = 0; i < top; i++){
4027 Expression e = null;
4029 if (ArrayData [i] is Expression)
4030 e = (Expression) ArrayData [i];
4034 // Basically we do this for string literals and
4035 // other non-literal expressions
4037 if (e is StringConstant || !(e is Constant)) {
4039 ig.Emit (OpCodes.Ldloc, temp);
4041 for (int idx = dims; idx > 0; ) {
4043 IntConstant.EmitInt (ig, current_pos [idx]);
4049 ArrayAccess.EmitStoreOpcode (ig, array_element_type);
4051 ig.Emit (OpCodes.Call, set);
4059 for (int j = 0; j < dims; j++){
4061 if (current_pos [j] < (int) Bounds [j])
4063 current_pos [j] = 0;
4068 ig.Emit (OpCodes.Ldloc, temp);
4071 void DoEmit (EmitContext ec, bool is_statement)
4073 ILGenerator ig = ec.ig;
4075 if (IsOneDimensional) {
4076 Invocation.EmitArguments (ec, null, Arguments);
4077 ig.Emit (OpCodes.Newarr, array_element_type);
4080 Invocation.EmitArguments (ec, null, Arguments);
4083 ig.Emit (OpCodes.Newobj, (ConstructorInfo) method);
4085 ig.Emit (OpCodes.Newobj, (MethodInfo) method);
4088 if (Initializers != null){
4090 // FIXME: Set this variable correctly.
4092 bool dynamic_initializers = true;
4094 if (underlying_type != TypeManager.string_type &&
4095 underlying_type != TypeManager.object_type)
4096 EmitStaticInitializers (ec, dynamic_initializers || !is_statement);
4098 if (dynamic_initializers)
4099 EmitDynamicInitializers (ec, !is_statement);
4103 public override void Emit (EmitContext ec)
4108 public override void EmitStatement (EmitContext ec)
4116 /// Represents the `this' construct
4118 public class This : Expression, IAssignMethod, IMemoryLocation {
4121 public This (Location loc)
4126 public override Expression DoResolve (EmitContext ec)
4128 eclass = ExprClass.Variable;
4129 type = ec.TypeContainer.TypeBuilder;
4132 Report.Error (26, loc,
4133 "Keyword this not valid in static code");
4140 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
4144 if (ec.TypeContainer is Class){
4145 Report.Error (1604, loc, "Cannot assign to `this'");
4152 public override void Emit (EmitContext ec)
4154 ec.ig.Emit (OpCodes.Ldarg_0);
4157 public void EmitAssign (EmitContext ec, Expression source)
4160 ec.ig.Emit (OpCodes.Starg, 0);
4163 public void AddressOf (EmitContext ec)
4165 ec.ig.Emit (OpCodes.Ldarg_0);
4168 // FIGURE OUT WHY LDARG_S does not work
4170 // consider: struct X { int val; int P { set { val = value; }}}
4172 // Yes, this looks very bad. Look at `NOTAS' for
4174 // ec.ig.Emit (OpCodes.Ldarga_S, (byte) 0);
4179 /// Implements the typeof operator
4181 public class TypeOf : Expression {
4182 public readonly string QueriedType;
4186 public TypeOf (string queried_type, Location l)
4188 QueriedType = queried_type;
4192 public override Expression DoResolve (EmitContext ec)
4194 typearg = RootContext.LookupType (
4195 ec.TypeContainer, QueriedType, false, loc);
4197 if (typearg == null)
4200 type = TypeManager.type_type;
4201 eclass = ExprClass.Type;
4205 public override void Emit (EmitContext ec)
4207 ec.ig.Emit (OpCodes.Ldtoken, typearg);
4208 ec.ig.Emit (OpCodes.Call, TypeManager.system_type_get_type_from_handle);
4213 /// Implements the sizeof expression
4215 public class SizeOf : Expression {
4216 public readonly string QueriedType;
4218 public SizeOf (string queried_type)
4220 this.QueriedType = queried_type;
4223 public override Expression DoResolve (EmitContext ec)
4225 // FIXME: Implement;
4226 throw new Exception ("Unimplemented");
4230 public override void Emit (EmitContext ec)
4232 throw new Exception ("Implement me");
4237 /// Implements the member access expression
4239 public class MemberAccess : Expression {
4240 public readonly string Identifier;
4242 Expression member_lookup;
4245 public MemberAccess (Expression expr, string id, Location l)
4252 public Expression Expr {
4258 static void error176 (Location loc, string name)
4260 Report.Error (176, loc, "Static member `" +
4261 name + "' cannot be accessed " +
4262 "with an instance reference, qualify with a " +
4263 "type name instead");
4267 static bool IdenticalNameAndTypeName (EmitContext ec, Expression left_original, Location loc)
4269 if (left_original == null)
4272 if (!(left_original is SimpleName))
4275 SimpleName sn = (SimpleName) left_original;
4277 Type t = RootContext.LookupType (ec.TypeContainer, sn.Name, true, loc);
4284 public static Expression ResolveMemberAccess (EmitContext ec, Expression member_lookup,
4285 Expression left, Location loc,
4286 Expression left_original)
4291 if (member_lookup is MethodGroupExpr){
4292 MethodGroupExpr mg = (MethodGroupExpr) member_lookup;
4297 if (left is TypeExpr){
4298 if (!mg.RemoveInstanceMethods ()){
4299 SimpleName.Error120 (loc, mg.Methods [0].Name);
4303 return member_lookup;
4307 // Instance.MethodGroup
4309 if (!mg.RemoveStaticMethods ()){
4310 if (IdenticalNameAndTypeName (ec, left_original, loc)){
4311 if (!mg.RemoveInstanceMethods ()){
4312 SimpleName.Error120 (loc, mg.Methods [0].Name);
4315 return member_lookup;
4318 error176 (loc, mg.Methods [0].Name);
4322 mg.InstanceExpression = left;
4324 return member_lookup;
4327 if (member_lookup is FieldExpr){
4328 FieldExpr fe = (FieldExpr) member_lookup;
4329 FieldInfo fi = fe.FieldInfo;
4331 if (fi is FieldBuilder) {
4332 Const c = TypeManager.LookupConstant ((FieldBuilder) fi);
4335 object o = c.LookupConstantValue (ec);
4336 object real_value = ((Constant) c.Expr).GetValue ();
4337 return Constantify (real_value, fi.FieldType);
4342 Type t = fi.FieldType;
4343 Type decl_type = fi.DeclaringType;
4346 if (fi is FieldBuilder)
4347 o = TypeManager.GetValue ((FieldBuilder) fi);
4349 o = fi.GetValue (fi);
4351 if (decl_type.IsSubclassOf (TypeManager.enum_type)) {
4352 Expression enum_member = MemberLookup (
4353 ec, decl_type, "value__", false, loc);
4355 Enum en = TypeManager.LookupEnum (decl_type);
4359 c = Constantify (o, en.UnderlyingType);
4361 c = Constantify (o, enum_member.Type);
4363 return new EnumConstant (c, decl_type);
4366 Expression exp = Constantify (o, t);
4368 if (!(left is TypeExpr)) {
4369 error176 (loc, fe.FieldInfo.Name);
4376 if (left is TypeExpr){
4377 // and refers to a type name or an
4378 if (!fe.FieldInfo.IsStatic){
4379 error176 (loc, fe.FieldInfo.Name);
4382 return member_lookup;
4384 if (fe.FieldInfo.IsStatic){
4385 if (IdenticalNameAndTypeName (ec, left_original, loc))
4386 return member_lookup;
4388 error176 (loc, fe.FieldInfo.Name);
4391 fe.InstanceExpression = left;
4397 if (member_lookup is PropertyExpr){
4398 PropertyExpr pe = (PropertyExpr) member_lookup;
4400 if (left is TypeExpr){
4402 SimpleName.Error120 (loc, pe.PropertyInfo.Name);
4408 if (IdenticalNameAndTypeName (ec, left_original, loc))
4409 return member_lookup;
4410 error176 (loc, pe.PropertyInfo.Name);
4413 pe.InstanceExpression = left;
4419 if (member_lookup is EventExpr) {
4421 EventExpr ee = (EventExpr) member_lookup;
4424 // If the event is local to this class, we transform ourselves into
4428 Expression ml = MemberLookup (ec, ec.TypeContainer.TypeBuilder, ee.EventInfo.Name,
4429 true, MemberTypes.Event, AllBindingFlags, loc);
4432 MemberInfo mi = ec.TypeContainer.GetFieldFromEvent ((EventExpr) ml);
4436 // If this happens, then we have an event with its own
4437 // accessors and private field etc so there's no need
4438 // to transform ourselves : we should instead flag an error
4440 Assign.error70 (ee.EventInfo, loc);
4444 ml = ExprClassFromMemberInfo (ec, mi, loc);
4447 Report.Error (-200, loc, "Internal error!!");
4450 return ResolveMemberAccess (ec, ml, left, loc, left_original);
4453 if (left is TypeExpr) {
4455 SimpleName.Error120 (loc, ee.EventInfo.Name);
4463 if (IdenticalNameAndTypeName (ec, left_original, loc))
4466 error176 (loc, ee.EventInfo.Name);
4470 ee.InstanceExpression = left;
4476 if (member_lookup is TypeExpr){
4477 member_lookup.Resolve (ec);
4478 return member_lookup;
4481 Console.WriteLine ("Left is: " + left);
4482 Report.Error (-100, loc, "Support for [" + member_lookup + "] is not present yet");
4483 Environment.Exit (0);
4487 public override Expression DoResolve (EmitContext ec)
4490 // We are the sole users of ResolveWithSimpleName (ie, the only
4491 // ones that can cope with it
4493 Expression original = expr;
4494 expr = expr.ResolveWithSimpleName (ec);
4499 if (expr is SimpleName){
4500 SimpleName child_expr = (SimpleName) expr;
4502 expr = new SimpleName (child_expr.Name + "." + Identifier, loc);
4504 return expr.ResolveWithSimpleName (ec);
4508 // Handle enums here when they are in transit.
4509 // Note that we cannot afford to hit MemberLookup in this case because
4510 // it will fail to find any members at all
4513 Type expr_type = expr.Type;
4514 if ((expr is TypeExpr) && (expr_type.IsSubclassOf (TypeManager.enum_type))){
4516 Enum en = TypeManager.LookupEnum (expr_type);
4519 object value = en.LookupEnumValue (ec, Identifier, loc);
4522 Constant c = Constantify (value, en.UnderlyingType);
4523 return new EnumConstant (c, expr_type);
4528 member_lookup = MemberLookup (ec, expr_type, Identifier, false, loc);
4530 if (member_lookup == null)
4533 return ResolveMemberAccess (ec, member_lookup, expr, loc, original);
4540 // This code is more conformant to the spec (it follows it step by step),
4541 // but it has not been tested yet, and there is nothing here that is not
4542 // caught by the above code. But it might be a better foundation to improve
4545 public ResolveTypeMemberAccess (EmitContext ec, Expression member_lookup,
4546 Expression left, Location loc)
4548 if (member_lookup is TypeExpr){
4549 member_lookup.Resolve (ec);
4550 return member_lookup;
4553 if (member_lookup is MethodGroupExpr){
4554 if (!mg.RemoveStaticMethods ()){
4555 SimpleName.Error120 (loc, mg.Methods [0].Name);
4559 return member_lookup;
4562 if (member_lookup is PropertyExpr){
4563 PropertyExpr pe = (PropertyExpr) member_lookup;
4566 SimpleName.Error120 (loc, pe.PropertyInfo.Name);
4572 if (member_lookup is FieldExpr){
4573 FieldExpr fe = (FieldExpr) member_lookup;
4574 FieldInfo fi = fe.FieldInfo;
4576 if (fi is FieldBuilder) {
4577 Const c = TypeManager.LookupConstant ((FieldBuilder) fi);
4580 object o = c.LookupConstantValue (ec);
4581 return Constantify (o, fi.FieldType);
4586 Type t = fi.FieldType;
4587 Type decl_type = fi.DeclaringType;
4590 if (fi is FieldBuilder)
4591 o = TypeManager.GetValue ((FieldBuilder) fi);
4593 o = fi.GetValue (fi);
4595 if (decl_type.IsSubclassOf (TypeManager.enum_type)) {
4596 Expression enum_member = MemberLookup (
4597 ec, decl_type, "value__",
4600 Enum en = TypeManager.LookupEnum (decl_type);
4604 c = Constantify (o, en.UnderlyingType);
4606 c = Constantify (o, enum_member.Type);
4608 return new EnumConstant (c, decl_type);
4611 Expression exp = Constantify (o, t);
4616 if (!fe.FieldInfo.IsStatic){
4617 error176 (loc, fe.FieldInfo.Name);
4620 return member_lookup;
4623 if (member_lookup is EventExpr){
4625 EventExpr ee = (EventExpr) member_lookup;
4628 // If the event is local to this class, we transform ourselves into
4632 Expression ml = MemberLookup (
4633 ec, ec.TypeContainer.TypeBuilder, ee.EventInfo.Name,
4634 true, MemberTypes.Event, AllBindingFlags, loc);
4637 MemberInfo mi = ec.TypeContainer.GetFieldFromEvent ((EventExpr) ml);
4639 ml = ExprClassFromMemberInfo (ec, mi, loc);
4642 Report.Error (-200, loc, "Internal error!!");
4646 return ResolveMemberAccess (ec, ml, left, loc);
4650 SimpleName.Error120 (loc, ee.EventInfo.Name);
4657 Console.WriteLine ("Left is: " + left);
4658 Report.Error (-100, loc, "Support for [" + member_lookup + "] is not present yet");
4659 Environment.Exit (0);
4664 public ResolveInstanceMemberAccess (EmitContext ec, Expression member_lookup,
4665 Expression left, Location loc)
4667 if (member_lookup is MethodGroupExpr){
4669 // Instance.MethodGroup
4671 if (!mg.RemoveStaticMethods ()){
4672 error176 (loc, mg.Methods [0].Name);
4676 mg.InstanceExpression = left;
4678 return member_lookup;
4681 if (member_lookup is PropertyExpr){
4682 PropertyExpr pe = (PropertyExpr) member_lookup;
4685 error176 (loc, pe.PropertyInfo.Name);
4688 pe.InstanceExpression = left;
4693 Type left_type = left.type;
4695 if (left_type.IsValueType){
4701 public override Expression DoResolve (EmitContext ec)
4704 // We are the sole users of ResolveWithSimpleName (ie, the only
4705 // ones that can cope with it
4707 expr = expr.ResolveWithSimpleName (ec);
4712 if (expr is SimpleName){
4713 SimpleName child_expr = (SimpleName) expr;
4715 expr = new SimpleName (child_expr.Name + "." + Identifier, loc);
4717 return expr.ResolveWithSimpleName (ec);
4721 // Handle enums here when they are in transit.
4722 // Note that we cannot afford to hit MemberLookup in this case because
4723 // it will fail to find any members at all (Why?)
4726 Type expr_type = expr.Type;
4727 if (expr_type.IsSubclassOf (TypeManager.enum_type)) {
4729 Enum en = TypeManager.LookupEnum (expr_type);
4732 object value = en.LookupEnumValue (ec, Identifier, loc);
4737 Constant c = Constantify (value, en.UnderlyingType);
4738 return new EnumConstant (c, expr_type);
4742 member_lookup = MemberLookup (ec, expr.Type, Identifier, false, loc);
4744 if (member_lookup == null)
4747 if (expr is TypeExpr)
4748 return ResolveTypeMemberAccess (ec, member_lookup, expr, loc);
4750 return ResolveInstanceMemberAccess (ec, member_lookup, expr, loc);
4753 public override void Emit (EmitContext ec)
4755 throw new Exception ("Should not happen");
4760 /// Implements checked expressions
4762 public class CheckedExpr : Expression {
4764 public Expression Expr;
4766 public CheckedExpr (Expression e)
4771 public override Expression DoResolve (EmitContext ec)
4773 Expr = Expr.Resolve (ec);
4778 eclass = Expr.eclass;
4783 public override void Emit (EmitContext ec)
4785 bool last_check = ec.CheckState;
4787 ec.CheckState = true;
4789 ec.CheckState = last_check;
4795 /// Implements the unchecked expression
4797 public class UnCheckedExpr : Expression {
4799 public Expression Expr;
4801 public UnCheckedExpr (Expression e)
4806 public override Expression DoResolve (EmitContext ec)
4808 Expr = Expr.Resolve (ec);
4813 eclass = Expr.eclass;
4818 public override void Emit (EmitContext ec)
4820 bool last_check = ec.CheckState;
4822 ec.CheckState = false;
4824 ec.CheckState = last_check;
4830 /// An Element Access expression.
4832 /// During semantic analysis these are transformed into
4833 /// IndexerAccess or ArrayAccess
4835 public class ElementAccess : Expression {
4836 public ArrayList Arguments;
4837 public Expression Expr;
4838 public Location loc;
4840 public ElementAccess (Expression e, ArrayList e_list, Location l)
4849 Arguments = new ArrayList ();
4850 foreach (Expression tmp in e_list)
4851 Arguments.Add (new Argument (tmp, Argument.AType.Expression));
4855 bool CommonResolve (EmitContext ec)
4857 Expr = Expr.Resolve (ec);
4862 if (Arguments == null)
4865 for (int i = Arguments.Count; i > 0;){
4867 Argument a = (Argument) Arguments [i];
4869 if (!a.Resolve (ec, loc))
4876 public override Expression DoResolve (EmitContext ec)
4878 if (!CommonResolve (ec))
4882 // We perform some simple tests, and then to "split" the emit and store
4883 // code we create an instance of a different class, and return that.
4885 // I am experimenting with this pattern.
4887 if (Expr.Type.IsSubclassOf (TypeManager.array_type))
4888 return (new ArrayAccess (this)).Resolve (ec);
4890 return (new IndexerAccess (this)).Resolve (ec);
4893 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
4895 if (!CommonResolve (ec))
4898 if (Expr.Type.IsSubclassOf (TypeManager.array_type))
4899 return (new ArrayAccess (this)).ResolveLValue (ec, right_side);
4901 return (new IndexerAccess (this)).ResolveLValue (ec, right_side);
4904 public override void Emit (EmitContext ec)
4906 throw new Exception ("Should never be reached");
4911 /// Implements array access
4913 public class ArrayAccess : Expression, IAssignMethod, IMemoryLocation {
4915 // Points to our "data" repository
4919 public ArrayAccess (ElementAccess ea_data)
4922 eclass = ExprClass.Variable;
4925 public override Expression DoResolve (EmitContext ec)
4927 if (ea.Expr.eclass != ExprClass.Variable) {
4928 report118 (ea.loc, ea.Expr, "variable");
4932 Type t = ea.Expr.Type;
4934 if (t.GetArrayRank () != ea.Arguments.Count){
4935 Report.Error (22, ea.loc,
4936 "Incorrect number of indexes for array " +
4937 " expected: " + t.GetArrayRank () + " got: " +
4938 ea.Arguments.Count);
4941 type = t.GetElementType ();
4942 eclass = ExprClass.Variable;
4948 /// Emits the right opcode to load an object of Type `t'
4949 /// from an array of T
4951 static public void EmitLoadOpcode (ILGenerator ig, Type type)
4953 if (type == TypeManager.byte_type)
4954 ig.Emit (OpCodes.Ldelem_I1);
4955 else if (type == TypeManager.sbyte_type)
4956 ig.Emit (OpCodes.Ldelem_U1);
4957 else if (type == TypeManager.short_type)
4958 ig.Emit (OpCodes.Ldelem_I2);
4959 else if (type == TypeManager.ushort_type)
4960 ig.Emit (OpCodes.Ldelem_U2);
4961 else if (type == TypeManager.int32_type)
4962 ig.Emit (OpCodes.Ldelem_I4);
4963 else if (type == TypeManager.uint32_type)
4964 ig.Emit (OpCodes.Ldelem_U4);
4965 else if (type == TypeManager.uint64_type)
4966 ig.Emit (OpCodes.Ldelem_I8);
4967 else if (type == TypeManager.int64_type)
4968 ig.Emit (OpCodes.Ldelem_I8);
4969 else if (type == TypeManager.float_type)
4970 ig.Emit (OpCodes.Ldelem_R4);
4971 else if (type == TypeManager.double_type)
4972 ig.Emit (OpCodes.Ldelem_R8);
4973 else if (type == TypeManager.intptr_type)
4974 ig.Emit (OpCodes.Ldelem_I);
4975 else if (type.IsValueType)
4976 ig.Emit (OpCodes.Ldelema, type);
4978 ig.Emit (OpCodes.Ldelem_Ref);
4982 /// Emits the right opcode to store an object of Type `t'
4983 /// from an array of T.
4985 static public void EmitStoreOpcode (ILGenerator ig, Type t)
4987 if (t == TypeManager.byte_type || t == TypeManager.sbyte_type)
4988 ig.Emit (OpCodes.Stelem_I1);
4989 else if (t == TypeManager.short_type || t == TypeManager.ushort_type)
4990 ig.Emit (OpCodes.Stelem_I2);
4991 else if (t == TypeManager.int32_type || t == TypeManager.uint32_type)
4992 ig.Emit (OpCodes.Stelem_I4);
4993 else if (t == TypeManager.int64_type || t == TypeManager.uint64_type)
4994 ig.Emit (OpCodes.Stelem_I8);
4995 else if (t == TypeManager.float_type)
4996 ig.Emit (OpCodes.Stelem_R4);
4997 else if (t == TypeManager.double_type)
4998 ig.Emit (OpCodes.Stelem_R8);
4999 else if (t == TypeManager.intptr_type)
5000 ig.Emit (OpCodes.Stelem_I);
5002 ig.Emit (OpCodes.Stelem_Ref);
5005 MethodInfo FetchGetMethod ()
5007 ModuleBuilder mb = RootContext.ModuleBuilder;
5008 Type [] args = new Type [ea.Arguments.Count];
5013 foreach (Argument a in ea.Arguments)
5014 args [i++] = a.Type;
5016 get = mb.GetArrayMethod (
5017 ea.Expr.Type, "Get",
5018 CallingConventions.HasThis |
5019 CallingConventions.Standard,
5025 MethodInfo FetchAddressMethod ()
5027 ModuleBuilder mb = RootContext.ModuleBuilder;
5028 Type [] args = new Type [ea.Arguments.Count];
5030 string ptr_type_name;
5034 ptr_type_name = type.FullName + "&";
5035 ret_type = Type.GetType (ptr_type_name);
5038 // It is a type defined by the source code we are compiling
5040 if (ret_type == null){
5041 ret_type = mb.GetType (ptr_type_name);
5044 foreach (Argument a in ea.Arguments)
5045 args [i++] = a.Type;
5047 address = mb.GetArrayMethod (
5048 ea.Expr.Type, "Address",
5049 CallingConventions.HasThis |
5050 CallingConventions.Standard,
5056 public override void Emit (EmitContext ec)
5058 int rank = ea.Expr.Type.GetArrayRank ();
5059 ILGenerator ig = ec.ig;
5063 foreach (Argument a in ea.Arguments)
5067 EmitLoadOpcode (ig, type);
5071 method = FetchGetMethod ();
5072 ig.Emit (OpCodes.Call, method);
5076 public void EmitAssign (EmitContext ec, Expression source)
5078 int rank = ea.Expr.Type.GetArrayRank ();
5079 ILGenerator ig = ec.ig;
5083 foreach (Argument a in ea.Arguments)
5088 Type t = source.Type;
5091 EmitStoreOpcode (ig, t);
5093 ModuleBuilder mb = RootContext.ModuleBuilder;
5094 Type [] args = new Type [ea.Arguments.Count + 1];
5099 foreach (Argument a in ea.Arguments)
5100 args [i++] = a.Type;
5104 set = mb.GetArrayMethod (
5105 ea.Expr.Type, "Set",
5106 CallingConventions.HasThis |
5107 CallingConventions.Standard,
5108 TypeManager.void_type, args);
5110 ig.Emit (OpCodes.Call, set);
5114 public void AddressOf (EmitContext ec)
5116 int rank = ea.Expr.Type.GetArrayRank ();
5117 ILGenerator ig = ec.ig;
5121 foreach (Argument a in ea.Arguments)
5125 ig.Emit (OpCodes.Ldelema, type);
5127 MethodInfo address = FetchAddressMethod ();
5128 ig.Emit (OpCodes.Call, address);
5135 public ArrayList getters, setters;
5136 static Hashtable map;
5140 map = new Hashtable ();
5143 Indexers (MemberInfo [] mi)
5145 foreach (PropertyInfo property in mi){
5146 MethodInfo get, set;
5148 get = property.GetGetMethod (true);
5150 if (getters == null)
5151 getters = new ArrayList ();
5156 set = property.GetSetMethod (true);
5158 if (setters == null)
5159 setters = new ArrayList ();
5165 static public Indexers GetIndexersForType (Type t, TypeManager tm, Location loc)
5167 Indexers ix = (Indexers) map [t];
5168 string p_name = TypeManager.IndexerPropertyName (t);
5173 MemberInfo [] mi = tm.FindMembers (
5174 t, MemberTypes.Property,
5175 BindingFlags.Public | BindingFlags.Instance,
5176 Type.FilterName, p_name);
5178 if (mi == null || mi.Length == 0){
5179 Report.Error (21, loc,
5180 "Type `" + TypeManager.CSharpName (t) + "' does not have " +
5181 "any indexers defined");
5185 ix = new Indexers (mi);
5193 /// Expressions that represent an indexer call.
5195 public class IndexerAccess : Expression, IAssignMethod {
5197 // Points to our "data" repository
5200 MethodInfo get, set;
5202 ArrayList set_arguments;
5204 public IndexerAccess (ElementAccess ea_data)
5207 eclass = ExprClass.Value;
5210 public override Expression DoResolve (EmitContext ec)
5212 Type indexer_type = ea.Expr.Type;
5215 // Step 1: Query for all `Item' *properties*. Notice
5216 // that the actual methods are pointed from here.
5218 // This is a group of properties, piles of them.
5221 ilist = Indexers.GetIndexersForType (
5222 indexer_type, RootContext.TypeManager, ea.loc);
5226 // Step 2: find the proper match
5228 if (ilist != null && ilist.getters != null && ilist.getters.Count > 0)
5229 get = (MethodInfo) Invocation.OverloadResolve (
5230 ec, new MethodGroupExpr (ilist.getters), ea.Arguments, ea.loc);
5233 Report.Error (154, ea.loc,
5234 "indexer can not be used in this context, because " +
5235 "it lacks a `get' accessor");
5239 type = get.ReturnType;
5240 eclass = ExprClass.IndexerAccess;
5244 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
5246 Type indexer_type = ea.Expr.Type;
5247 Type right_type = right_side.Type;
5250 ilist = Indexers.GetIndexersForType (
5251 indexer_type, RootContext.TypeManager, ea.loc);
5253 if (ilist != null && ilist.setters != null && ilist.setters.Count > 0){
5254 set_arguments = (ArrayList) ea.Arguments.Clone ();
5255 set_arguments.Add (new Argument (right_side, Argument.AType.Expression));
5257 set = (MethodInfo) Invocation.OverloadResolve (
5258 ec, new MethodGroupExpr (ilist.setters), set_arguments, ea.loc);
5262 Report.Error (200, ea.loc,
5263 "indexer X.this [" + TypeManager.CSharpName (right_type) +
5264 "] lacks a `set' accessor");
5268 type = TypeManager.void_type;
5269 eclass = ExprClass.IndexerAccess;
5273 public override void Emit (EmitContext ec)
5275 Invocation.EmitCall (ec, false, ea.Expr, get, ea.Arguments);
5279 // source is ignored, because we already have a copy of it from the
5280 // LValue resolution and we have already constructed a pre-cached
5281 // version of the arguments (ea.set_arguments);
5283 public void EmitAssign (EmitContext ec, Expression source)
5285 Invocation.EmitCall (ec, false, ea.Expr, set, set_arguments);
5290 /// The base operator for method names
5292 public class BaseAccess : Expression {
5296 public BaseAccess (string member, Location l)
5298 this.member = member;
5302 public override Expression DoResolve (EmitContext ec)
5304 Expression member_lookup;
5305 Type current_type = ec.TypeContainer.TypeBuilder;
5306 Type base_type = current_type.BaseType;
5308 member_lookup = MemberLookup (ec, base_type, member, false, loc);
5309 if (member_lookup == null)
5315 left = new TypeExpr (base_type);
5317 left = new This (loc).Resolve (ec);
5319 return MemberAccess.ResolveMemberAccess (ec, member_lookup, left, loc, null);
5322 public override void Emit (EmitContext ec)
5324 throw new Exception ("Should never be called");
5329 /// The base indexer operator
5331 public class BaseIndexerAccess : Expression {
5332 ArrayList Arguments;
5334 public BaseIndexerAccess (ArrayList args)
5339 public override Expression DoResolve (EmitContext ec)
5341 // FIXME: Implement;
5342 throw new Exception ("Unimplemented");
5346 public override void Emit (EmitContext ec)
5348 throw new Exception ("Unimplemented");
5353 /// This class exists solely to pass the Type around and to be a dummy
5354 /// that can be passed to the conversion functions (this is used by
5355 /// foreach implementation to typecast the object return value from
5356 /// get_Current into the proper type. All code has been generated and
5357 /// we only care about the side effect conversions to be performed
5359 public class EmptyExpression : Expression {
5360 public EmptyExpression ()
5362 type = TypeManager.object_type;
5363 eclass = ExprClass.Value;
5366 public EmptyExpression (Type t)
5369 eclass = ExprClass.Value;
5372 public override Expression DoResolve (EmitContext ec)
5377 public override void Emit (EmitContext ec)
5379 // nothing, as we only exist to not do anything.
5383 // This is just because we might want to reuse this bad boy
5384 // instead of creating gazillions of EmptyExpressions.
5385 // (CanConvertImplicit uses it)
5387 public void SetType (Type t)
5393 public class UserCast : Expression {
5397 public UserCast (MethodInfo method, Expression source)
5399 this.method = method;
5400 this.source = source;
5401 type = method.ReturnType;
5402 eclass = ExprClass.Value;
5405 public override Expression DoResolve (EmitContext ec)
5408 // We are born fully resolved
5413 public override void Emit (EmitContext ec)
5415 ILGenerator ig = ec.ig;
5419 if (method is MethodInfo)
5420 ig.Emit (OpCodes.Call, (MethodInfo) method);
5422 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
5429 // This class is used to "construct" the type during a typecast
5430 // operation. Since the Type.GetType class in .NET can parse
5431 // the type specification, we just use this to construct the type
5432 // one bit at a time.
5434 public class ComposedCast : Expression {
5439 public ComposedCast (Expression left, string dim, Location l)
5446 public override Expression DoResolve (EmitContext ec)
5448 left = left.Resolve (ec);
5452 if (left.eclass != ExprClass.Type){
5453 report118 (loc, left, "type");
5457 type = RootContext.LookupType (
5458 ec.TypeContainer, left.Type.FullName + dim, false, loc);
5462 eclass = ExprClass.Type;
5466 public override void Emit (EmitContext ec)
5468 throw new Exception ("This should never be called");