2 // expression.cs: Expression representation for the IL tree.
5 // Miguel de Icaza (miguel@ximian.com)
7 // (C) 2001 Ximian, Inc.
11 namespace Mono.CSharp {
13 using System.Collections;
14 using System.Diagnostics;
15 using System.Reflection;
16 using System.Reflection.Emit;
20 /// This is just a helper class, it is generated by Unary, UnaryMutator
21 /// when an overloaded method has been found. It just emits the code for a
24 public class StaticCallExpr : ExpressionStatement {
28 StaticCallExpr (MethodInfo m, ArrayList a)
34 eclass = ExprClass.Value;
37 public override Expression DoResolve (EmitContext ec)
40 // We are born fully resolved
45 public override void Emit (EmitContext ec)
48 Invocation.EmitArguments (ec, mi, args);
50 ec.ig.Emit (OpCodes.Call, mi);
54 static public Expression MakeSimpleCall (EmitContext ec, MethodGroupExpr mg,
55 Expression e, Location loc)
60 args = new ArrayList (1);
61 args.Add (new Argument (e, Argument.AType.Expression));
62 method = Invocation.OverloadResolve (ec, (MethodGroupExpr) mg, args, loc);
67 return new StaticCallExpr ((MethodInfo) method, args);
70 public override void EmitStatement (EmitContext ec)
73 if (type != TypeManager.void_type)
74 ec.ig.Emit (OpCodes.Pop);
79 /// Unary expressions.
83 /// Unary implements unary expressions. It derives from
84 /// ExpressionStatement becuase the pre/post increment/decrement
85 /// operators can be used in a statement context.
87 public class Unary : Expression {
88 public enum Operator : byte {
89 UnaryPlus, UnaryNegation, LogicalNot, OnesComplement,
90 Indirection, AddressOf,
97 public Unary (Operator op, Expression expr, Location loc)
104 public Expression Expr {
114 public Operator Oper {
125 /// Returns a stringified representation of the Operator
130 case Operator.UnaryPlus:
132 case Operator.UnaryNegation:
134 case Operator.LogicalNot:
136 case Operator.OnesComplement:
138 case Operator.AddressOf:
140 case Operator.Indirection:
144 return oper.ToString ();
147 void error23 (Type t)
150 23, loc, "Operator " + OperName () +
151 " cannot be applied to operand of type `" +
152 TypeManager.CSharpName (t) + "'");
156 /// The result has been already resolved:
158 /// FIXME: a minus constant -128 sbyte cant be turned into a
161 static Expression TryReduceNegative (Expression expr)
165 if (expr is IntConstant)
166 e = new IntConstant (-((IntConstant) expr).Value);
167 else if (expr is UIntConstant)
168 e = new LongConstant (-((UIntConstant) expr).Value);
169 else if (expr is LongConstant)
170 e = new LongConstant (-((LongConstant) expr).Value);
171 else if (expr is FloatConstant)
172 e = new FloatConstant (-((FloatConstant) expr).Value);
173 else if (expr is DoubleConstant)
174 e = new DoubleConstant (-((DoubleConstant) expr).Value);
175 else if (expr is DecimalConstant)
176 e = new DecimalConstant (-((DecimalConstant) expr).Value);
177 else if (expr is ShortConstant)
178 e = new IntConstant (-((ShortConstant) expr).Value);
179 else if (expr is UShortConstant)
180 e = new IntConstant (-((UShortConstant) expr).Value);
185 Expression Reduce (EmitContext ec)
187 Type expr_type = expr.Type;
190 case Operator.UnaryPlus:
193 case Operator.UnaryNegation:
194 return TryReduceNegative (expr);
196 case Operator.LogicalNot:
197 if (expr_type != TypeManager.bool_type) {
202 BoolConstant b = (BoolConstant) expr;
203 return new BoolConstant (!(b.Value));
205 case Operator.OnesComplement:
206 if (!((expr_type == TypeManager.int32_type) ||
207 (expr_type == TypeManager.uint32_type) ||
208 (expr_type == TypeManager.int64_type) ||
209 (expr_type == TypeManager.uint64_type) ||
210 (expr_type.IsSubclassOf (TypeManager.enum_type)))){
216 if (et == TypeManager.int32_type)
217 return new IntConstant (~ ((IntConstant) expr).Value);
218 if (et == TypeManager.uint32_type)
219 return new UIntConstant (~ ((UIntConstant) expr).Value);
220 if (et == TypeManager.int64_type)
221 return new LongConstant (~ ((LongConstant) expr).Value);
222 if (et == TypeManager.uint64_type)
223 return new ULongConstant (~ ((ULongConstant) expr).Value);
225 throw new Exception ("FIXME: Implement constant OnesComplement of enumerations");
227 throw new Exception ("Can not constant fold");
230 Expression ResolveOperator (EmitContext ec)
232 Type expr_type = expr.Type;
235 // Step 1: Perform Operator Overload location
240 op_name = "op_" + oper;
242 mg = MemberLookup (ec, expr_type, op_name, false, loc);
244 if (mg == null && expr_type.BaseType != null)
245 mg = MemberLookup (ec, expr_type.BaseType, op_name, false, loc);
248 Expression e = StaticCallExpr.MakeSimpleCall (
249 ec, (MethodGroupExpr) mg, expr, loc);
259 // Only perform numeric promotions on:
262 if (expr_type == null)
266 // Step 2: Default operations on CLI native types.
268 if (expr is Constant)
271 if (oper == Operator.LogicalNot){
272 if (expr_type != TypeManager.bool_type) {
277 type = TypeManager.bool_type;
281 if (oper == Operator.OnesComplement) {
282 if (!((expr_type == TypeManager.int32_type) ||
283 (expr_type == TypeManager.uint32_type) ||
284 (expr_type == TypeManager.int64_type) ||
285 (expr_type == TypeManager.uint64_type) ||
286 (expr_type.IsSubclassOf (TypeManager.enum_type)))){
294 if (oper == Operator.UnaryPlus) {
296 // A plus in front of something is just a no-op, so return the child.
302 // Deals with -literals
303 // int operator- (int x)
304 // long operator- (long x)
305 // float operator- (float f)
306 // double operator- (double d)
307 // decimal operator- (decimal d)
309 if (oper == Operator.UnaryNegation){
311 // Fold a "- Constant" into a negative constant
317 // Not a constant we can optimize, perform numeric
318 // promotions to int, long, double.
321 // The following is inneficient, because we call
322 // ConvertImplicit too many times.
324 // It is also not clear if we should convert to Float
325 // or Double initially.
327 if (expr_type == TypeManager.uint32_type){
329 // FIXME: handle exception to this rule that
330 // permits the int value -2147483648 (-2^31) to
331 // bt wrote as a decimal interger literal
333 type = TypeManager.int64_type;
334 expr = ConvertImplicit (ec, expr, type, loc);
338 if (expr_type == TypeManager.uint64_type){
340 // FIXME: Handle exception of `long value'
341 // -92233720368547758087 (-2^63) to be wrote as
342 // decimal integer literal.
348 e = ConvertImplicit (ec, expr, TypeManager.int32_type, loc);
355 e = ConvertImplicit (ec, expr, TypeManager.int64_type, loc);
362 e = ConvertImplicit (ec, expr, TypeManager.double_type, loc);
373 if (oper == Operator.AddressOf){
374 if (expr.eclass != ExprClass.Variable){
375 Error (211, loc, "Cannot take the address of non-variables");
378 type = Type.GetType (expr.Type.ToString () + "*");
383 Error (187, loc, "No such operator '" + OperName () + "' defined for type '" +
384 TypeManager.CSharpName (expr_type) + "'");
388 public override Expression DoResolve (EmitContext ec)
390 expr = expr.Resolve (ec);
395 eclass = ExprClass.Value;
396 return ResolveOperator (ec);
399 public override void Emit (EmitContext ec)
401 ILGenerator ig = ec.ig;
402 Type expr_type = expr.Type;
405 case Operator.UnaryPlus:
406 throw new Exception ("This should be caught by Resolve");
408 case Operator.UnaryNegation:
410 ig.Emit (OpCodes.Neg);
413 case Operator.LogicalNot:
415 ig.Emit (OpCodes.Ldc_I4_0);
416 ig.Emit (OpCodes.Ceq);
419 case Operator.OnesComplement:
421 ig.Emit (OpCodes.Not);
424 case Operator.AddressOf:
425 ((IMemoryLocation)expr).AddressOf (ec);
428 case Operator.Indirection:
429 throw new Exception ("Not implemented yet");
432 throw new Exception ("This should not happen: Operator = "
438 /// This will emit the child expression for `ec' avoiding the logical
439 /// not. The parent will take care of changing brfalse/brtrue
441 public void EmitLogicalNot (EmitContext ec)
443 if (oper != Operator.LogicalNot)
444 throw new Exception ("EmitLogicalNot can only be called with !expr");
452 /// Unary Mutator expressions (pre and post ++ and --)
456 /// UnaryMutator implements ++ and -- expressions. It derives from
457 /// ExpressionStatement becuase the pre/post increment/decrement
458 /// operators can be used in a statement context.
460 /// FIXME: Idea, we could split this up in two classes, one simpler
461 /// for the common case, and one with the extra fields for more complex
462 /// classes (indexers require temporary access; overloaded require method)
464 /// Maybe we should have classes PreIncrement, PostIncrement, PreDecrement,
465 /// PostDecrement, that way we could save the `Mode' byte as well.
467 public class UnaryMutator : ExpressionStatement {
468 public enum Mode : byte {
469 PreIncrement, PreDecrement, PostIncrement, PostDecrement
475 LocalTemporary temp_storage;
478 // This is expensive for the simplest case.
482 public UnaryMutator (Mode m, Expression e, Location l)
491 return (mode == Mode.PreIncrement || mode == Mode.PostIncrement) ?
495 void error23 (Type t)
498 23, loc, "Operator " + OperName () +
499 " cannot be applied to operand of type `" +
500 TypeManager.CSharpName (t) + "'");
504 /// Returns whether an object of type `t' can be incremented
505 /// or decremented with add/sub (ie, basically whether we can
506 /// use pre-post incr-decr operations on it, but it is not a
507 /// System.Decimal, which we require operator overloading to catch)
509 static bool IsIncrementableNumber (Type t)
511 return (t == TypeManager.sbyte_type) ||
512 (t == TypeManager.byte_type) ||
513 (t == TypeManager.short_type) ||
514 (t == TypeManager.ushort_type) ||
515 (t == TypeManager.int32_type) ||
516 (t == TypeManager.uint32_type) ||
517 (t == TypeManager.int64_type) ||
518 (t == TypeManager.uint64_type) ||
519 (t == TypeManager.char_type) ||
520 (t.IsSubclassOf (TypeManager.enum_type)) ||
521 (t == TypeManager.float_type) ||
522 (t == TypeManager.double_type);
525 Expression ResolveOperator (EmitContext ec)
527 Type expr_type = expr.Type;
530 // Step 1: Perform Operator Overload location
535 if (mode == Mode.PreIncrement || mode == Mode.PostIncrement)
536 op_name = "op_Increment";
538 op_name = "op_Decrement";
540 mg = MemberLookup (ec, expr_type, op_name, false, loc);
542 if (mg == null && expr_type.BaseType != null)
543 mg = MemberLookup (ec, expr_type.BaseType, op_name, false, loc);
546 method = StaticCallExpr.MakeSimpleCall (
547 ec, (MethodGroupExpr) mg, expr, loc);
554 // The operand of the prefix/postfix increment decrement operators
555 // should be an expression that is classified as a variable,
556 // a property access or an indexer access
559 if (expr.eclass == ExprClass.Variable){
560 if (IsIncrementableNumber (expr_type) ||
561 expr_type == TypeManager.decimal_type){
564 } else if (expr.eclass == ExprClass.IndexerAccess){
565 IndexerAccess ia = (IndexerAccess) expr;
567 temp_storage = new LocalTemporary (ec, expr.Type);
569 expr = ia.ResolveLValue (ec, temp_storage);
574 } else if (expr.eclass == ExprClass.PropertyAccess){
575 PropertyExpr pe = (PropertyExpr) expr;
577 if (pe.VerifyAssignable ())
582 report118 (loc, expr, "variable, indexer or property access");
586 Error (187, loc, "No such operator '" + OperName () + "' defined for type '" +
587 TypeManager.CSharpName (expr_type) + "'");
591 public override Expression DoResolve (EmitContext ec)
593 expr = expr.Resolve (ec);
598 eclass = ExprClass.Value;
599 return ResolveOperator (ec);
604 // FIXME: We need some way of avoiding the use of temp_storage
605 // for some types of storage (parameters, local variables,
606 // static fields) and single-dimension array access.
608 void EmitCode (EmitContext ec, bool is_expr)
610 ILGenerator ig = ec.ig;
611 IAssignMethod ia = (IAssignMethod) expr;
613 if (temp_storage == null)
614 temp_storage = new LocalTemporary (ec, expr.Type);
617 case Mode.PreIncrement:
618 case Mode.PreDecrement:
622 ig.Emit (OpCodes.Ldc_I4_1);
624 if (mode == Mode.PreDecrement)
625 ig.Emit (OpCodes.Sub);
627 ig.Emit (OpCodes.Add);
631 temp_storage.Store (ec);
632 ia.EmitAssign (ec, temp_storage);
634 temp_storage.Emit (ec);
637 case Mode.PostIncrement:
638 case Mode.PostDecrement:
646 ig.Emit (OpCodes.Dup);
648 ig.Emit (OpCodes.Ldc_I4_1);
650 if (mode == Mode.PostDecrement)
651 ig.Emit (OpCodes.Sub);
653 ig.Emit (OpCodes.Add);
658 temp_storage.Store (ec);
659 ia.EmitAssign (ec, temp_storage);
664 public override void Emit (EmitContext ec)
670 public override void EmitStatement (EmitContext ec)
672 EmitCode (ec, false);
678 /// Base class for the `Is' and `As' classes.
682 /// FIXME: Split this in two, and we get to save the `Operator' Oper
685 public abstract class Probe : Expression {
686 public readonly string ProbeType;
687 protected Expression expr;
688 protected Type probe_type;
691 public Probe (Expression expr, string probe_type, Location l)
693 ProbeType = probe_type;
698 public Expression Expr {
704 public override Expression DoResolve (EmitContext ec)
706 probe_type = RootContext.LookupType (ec.TypeContainer, ProbeType, false, loc);
708 if (probe_type == null)
711 expr = expr.Resolve (ec);
718 /// Implementation of the `is' operator.
720 public class Is : Probe {
721 public Is (Expression expr, string probe_type, Location l)
722 : base (expr, probe_type, l)
726 public override void Emit (EmitContext ec)
728 ILGenerator ig = ec.ig;
732 ig.Emit (OpCodes.Isinst, probe_type);
733 ig.Emit (OpCodes.Ldnull);
734 ig.Emit (OpCodes.Cgt_Un);
737 public override Expression DoResolve (EmitContext ec)
739 Expression e = base.DoResolve (ec);
744 type = TypeManager.bool_type;
745 eclass = ExprClass.Value;
752 /// Implementation of the `as' operator.
754 public class As : Probe {
755 public As (Expression expr, string probe_type, Location l)
756 : base (expr, probe_type, l)
760 public override void Emit (EmitContext ec)
762 ILGenerator ig = ec.ig;
765 ig.Emit (OpCodes.Isinst, probe_type);
768 public override Expression DoResolve (EmitContext ec)
770 Expression e = base.DoResolve (ec);
776 eclass = ExprClass.Value;
783 /// This represents a typecast in the source language.
785 /// FIXME: Cast expressions have an unusual set of parsing
786 /// rules, we need to figure those out.
788 public class Cast : Expression {
789 Expression target_type;
793 public Cast (Expression cast_type, Expression expr, Location loc)
795 this.target_type = cast_type;
800 public Expression TargetType {
806 public Expression Expr {
816 /// Attempts to do a compile-time folding of a constant cast.
818 Expression TryReduce (EmitContext ec, Type target_type)
820 if (expr is ByteConstant){
821 byte v = ((ByteConstant) expr).Value;
823 if (target_type == TypeManager.sbyte_type)
824 return new SByteConstant ((sbyte) v);
825 if (target_type == TypeManager.short_type)
826 return new ShortConstant ((short) v);
827 if (target_type == TypeManager.ushort_type)
828 return new UShortConstant ((ushort) v);
829 if (target_type == TypeManager.int32_type)
830 return new IntConstant ((int) v);
831 if (target_type == TypeManager.uint32_type)
832 return new UIntConstant ((uint) v);
833 if (target_type == TypeManager.int64_type)
834 return new LongConstant ((long) v);
835 if (target_type == TypeManager.uint64_type)
836 return new ULongConstant ((ulong) v);
837 if (target_type == TypeManager.float_type)
838 return new FloatConstant ((float) v);
839 if (target_type == TypeManager.double_type)
840 return new DoubleConstant ((double) v);
842 if (expr is SByteConstant){
843 sbyte v = ((SByteConstant) expr).Value;
845 if (target_type == TypeManager.byte_type)
846 return new ByteConstant ((byte) v);
847 if (target_type == TypeManager.short_type)
848 return new ShortConstant ((short) v);
849 if (target_type == TypeManager.ushort_type)
850 return new UShortConstant ((ushort) v);
851 if (target_type == TypeManager.int32_type)
852 return new IntConstant ((int) v);
853 if (target_type == TypeManager.uint32_type)
854 return new UIntConstant ((uint) v);
855 if (target_type == TypeManager.int64_type)
856 return new LongConstant ((long) v);
857 if (target_type == TypeManager.uint64_type)
858 return new ULongConstant ((ulong) v);
859 if (target_type == TypeManager.float_type)
860 return new FloatConstant ((float) v);
861 if (target_type == TypeManager.double_type)
862 return new DoubleConstant ((double) v);
864 if (expr is ShortConstant){
865 short v = ((ShortConstant) expr).Value;
867 if (target_type == TypeManager.byte_type)
868 return new ByteConstant ((byte) v);
869 if (target_type == TypeManager.sbyte_type)
870 return new SByteConstant ((sbyte) v);
871 if (target_type == TypeManager.ushort_type)
872 return new UShortConstant ((ushort) v);
873 if (target_type == TypeManager.int32_type)
874 return new IntConstant ((int) v);
875 if (target_type == TypeManager.uint32_type)
876 return new UIntConstant ((uint) v);
877 if (target_type == TypeManager.int64_type)
878 return new LongConstant ((long) v);
879 if (target_type == TypeManager.uint64_type)
880 return new ULongConstant ((ulong) v);
881 if (target_type == TypeManager.float_type)
882 return new FloatConstant ((float) v);
883 if (target_type == TypeManager.double_type)
884 return new DoubleConstant ((double) v);
886 if (expr is UShortConstant){
887 ushort v = ((UShortConstant) expr).Value;
889 if (target_type == TypeManager.byte_type)
890 return new ByteConstant ((byte) v);
891 if (target_type == TypeManager.sbyte_type)
892 return new SByteConstant ((sbyte) v);
893 if (target_type == TypeManager.short_type)
894 return new ShortConstant ((short) v);
895 if (target_type == TypeManager.int32_type)
896 return new IntConstant ((int) v);
897 if (target_type == TypeManager.uint32_type)
898 return new UIntConstant ((uint) v);
899 if (target_type == TypeManager.int64_type)
900 return new LongConstant ((long) v);
901 if (target_type == TypeManager.uint64_type)
902 return new ULongConstant ((ulong) v);
903 if (target_type == TypeManager.float_type)
904 return new FloatConstant ((float) v);
905 if (target_type == TypeManager.double_type)
906 return new DoubleConstant ((double) v);
908 if (expr is IntConstant){
909 int v = ((IntConstant) expr).Value;
911 if (target_type == TypeManager.byte_type)
912 return new ByteConstant ((byte) v);
913 if (target_type == TypeManager.sbyte_type)
914 return new SByteConstant ((sbyte) v);
915 if (target_type == TypeManager.short_type)
916 return new ShortConstant ((short) v);
917 if (target_type == TypeManager.ushort_type)
918 return new UShortConstant ((ushort) v);
919 if (target_type == TypeManager.uint32_type)
920 return new UIntConstant ((uint) v);
921 if (target_type == TypeManager.int64_type)
922 return new LongConstant ((long) v);
923 if (target_type == TypeManager.uint64_type)
924 return new ULongConstant ((ulong) v);
925 if (target_type == TypeManager.float_type)
926 return new FloatConstant ((float) v);
927 if (target_type == TypeManager.double_type)
928 return new DoubleConstant ((double) v);
930 if (expr is UIntConstant){
931 uint v = ((UIntConstant) expr).Value;
933 if (target_type == TypeManager.byte_type)
934 return new ByteConstant ((byte) v);
935 if (target_type == TypeManager.sbyte_type)
936 return new SByteConstant ((sbyte) v);
937 if (target_type == TypeManager.short_type)
938 return new ShortConstant ((short) v);
939 if (target_type == TypeManager.ushort_type)
940 return new UShortConstant ((ushort) v);
941 if (target_type == TypeManager.int32_type)
942 return new IntConstant ((int) v);
943 if (target_type == TypeManager.int64_type)
944 return new LongConstant ((long) v);
945 if (target_type == TypeManager.uint64_type)
946 return new ULongConstant ((ulong) v);
947 if (target_type == TypeManager.float_type)
948 return new FloatConstant ((float) v);
949 if (target_type == TypeManager.double_type)
950 return new DoubleConstant ((double) v);
952 if (expr is LongConstant){
953 long v = ((LongConstant) expr).Value;
955 if (target_type == TypeManager.byte_type)
956 return new ByteConstant ((byte) v);
957 if (target_type == TypeManager.sbyte_type)
958 return new SByteConstant ((sbyte) v);
959 if (target_type == TypeManager.short_type)
960 return new ShortConstant ((short) v);
961 if (target_type == TypeManager.ushort_type)
962 return new UShortConstant ((ushort) v);
963 if (target_type == TypeManager.int32_type)
964 return new IntConstant ((int) v);
965 if (target_type == TypeManager.uint32_type)
966 return new UIntConstant ((uint) v);
967 if (target_type == TypeManager.uint64_type)
968 return new ULongConstant ((ulong) v);
969 if (target_type == TypeManager.float_type)
970 return new FloatConstant ((float) v);
971 if (target_type == TypeManager.double_type)
972 return new DoubleConstant ((double) v);
974 if (expr is ULongConstant){
975 ulong v = ((ULongConstant) expr).Value;
977 if (target_type == TypeManager.byte_type)
978 return new ByteConstant ((byte) v);
979 if (target_type == TypeManager.sbyte_type)
980 return new SByteConstant ((sbyte) v);
981 if (target_type == TypeManager.short_type)
982 return new ShortConstant ((short) v);
983 if (target_type == TypeManager.ushort_type)
984 return new UShortConstant ((ushort) v);
985 if (target_type == TypeManager.int32_type)
986 return new IntConstant ((int) v);
987 if (target_type == TypeManager.uint32_type)
988 return new UIntConstant ((uint) v);
989 if (target_type == TypeManager.int64_type)
990 return new LongConstant ((long) v);
991 if (target_type == TypeManager.float_type)
992 return new FloatConstant ((float) v);
993 if (target_type == TypeManager.double_type)
994 return new DoubleConstant ((double) v);
996 if (expr is FloatConstant){
997 float v = ((FloatConstant) expr).Value;
999 if (target_type == TypeManager.byte_type)
1000 return new ByteConstant ((byte) v);
1001 if (target_type == TypeManager.sbyte_type)
1002 return new SByteConstant ((sbyte) v);
1003 if (target_type == TypeManager.short_type)
1004 return new ShortConstant ((short) v);
1005 if (target_type == TypeManager.ushort_type)
1006 return new UShortConstant ((ushort) v);
1007 if (target_type == TypeManager.int32_type)
1008 return new IntConstant ((int) v);
1009 if (target_type == TypeManager.uint32_type)
1010 return new UIntConstant ((uint) v);
1011 if (target_type == TypeManager.int64_type)
1012 return new LongConstant ((long) v);
1013 if (target_type == TypeManager.uint64_type)
1014 return new ULongConstant ((ulong) v);
1015 if (target_type == TypeManager.double_type)
1016 return new DoubleConstant ((double) v);
1018 if (expr is DoubleConstant){
1019 double v = ((DoubleConstant) expr).Value;
1021 if (target_type == TypeManager.byte_type)
1022 return new ByteConstant ((byte) v);
1023 if (target_type == TypeManager.sbyte_type)
1024 return new SByteConstant ((sbyte) v);
1025 if (target_type == TypeManager.short_type)
1026 return new ShortConstant ((short) v);
1027 if (target_type == TypeManager.ushort_type)
1028 return new UShortConstant ((ushort) v);
1029 if (target_type == TypeManager.int32_type)
1030 return new IntConstant ((int) v);
1031 if (target_type == TypeManager.uint32_type)
1032 return new UIntConstant ((uint) v);
1033 if (target_type == TypeManager.int64_type)
1034 return new LongConstant ((long) v);
1035 if (target_type == TypeManager.uint64_type)
1036 return new ULongConstant ((ulong) v);
1037 if (target_type == TypeManager.float_type)
1038 return new FloatConstant ((float) v);
1044 public override Expression DoResolve (EmitContext ec)
1046 expr = expr.Resolve (ec);
1050 target_type = target_type.Resolve (ec);
1051 if (target_type == null)
1054 if (target_type.eclass != ExprClass.Type){
1055 report118 (loc, target_type, "class");
1059 type = target_type.Type;
1060 eclass = ExprClass.Value;
1065 if (expr is Constant){
1066 Expression e = TryReduce (ec, type);
1072 expr = ConvertExplicit (ec, expr, type, loc);
1076 public override void Emit (EmitContext ec)
1079 // This one will never happen
1081 throw new Exception ("Should not happen");
1086 /// Binary operators
1088 public class Binary : Expression {
1089 public enum Operator : byte {
1090 Multiply, Division, Modulus,
1091 Addition, Subtraction,
1092 LeftShift, RightShift,
1093 LessThan, GreaterThan, LessThanOrEqual, GreaterThanOrEqual,
1094 Equality, Inequality,
1103 Expression left, right;
1105 ArrayList Arguments;
1109 public Binary (Operator oper, Expression left, Expression right, Location loc)
1117 public Operator Oper {
1126 public Expression Left {
1135 public Expression Right {
1146 /// Returns a stringified representation of the Operator
1151 case Operator.Multiply:
1153 case Operator.Division:
1155 case Operator.Modulus:
1157 case Operator.Addition:
1159 case Operator.Subtraction:
1161 case Operator.LeftShift:
1163 case Operator.RightShift:
1165 case Operator.LessThan:
1167 case Operator.GreaterThan:
1169 case Operator.LessThanOrEqual:
1171 case Operator.GreaterThanOrEqual:
1173 case Operator.Equality:
1175 case Operator.Inequality:
1177 case Operator.BitwiseAnd:
1179 case Operator.BitwiseOr:
1181 case Operator.ExclusiveOr:
1183 case Operator.LogicalOr:
1185 case Operator.LogicalAnd:
1189 return oper.ToString ();
1192 Expression ForceConversion (EmitContext ec, Expression expr, Type target_type)
1194 if (expr.Type == target_type)
1197 return ConvertImplicit (ec, expr, target_type, new Location (-1));
1201 // Note that handling the case l == Decimal || r == Decimal
1202 // is taken care of by the Step 1 Operator Overload resolution.
1204 bool DoNumericPromotions (EmitContext ec, Type l, Type r)
1206 if (l == TypeManager.double_type || r == TypeManager.double_type){
1208 // If either operand is of type double, the other operand is
1209 // conveted to type double.
1211 if (r != TypeManager.double_type)
1212 right = ConvertImplicit (ec, right, TypeManager.double_type, loc);
1213 if (l != TypeManager.double_type)
1214 left = ConvertImplicit (ec, left, TypeManager.double_type, loc);
1216 type = TypeManager.double_type;
1217 } else if (l == TypeManager.float_type || r == TypeManager.float_type){
1219 // if either operand is of type float, th eother operand is
1220 // converd to type float.
1222 if (r != TypeManager.double_type)
1223 right = ConvertImplicit (ec, right, TypeManager.float_type, loc);
1224 if (l != TypeManager.double_type)
1225 left = ConvertImplicit (ec, left, TypeManager.float_type, loc);
1226 type = TypeManager.float_type;
1227 } else if (l == TypeManager.uint64_type || r == TypeManager.uint64_type){
1231 // If either operand is of type ulong, the other operand is
1232 // converted to type ulong. or an error ocurrs if the other
1233 // operand is of type sbyte, short, int or long
1236 if (l == TypeManager.uint64_type){
1237 if (r != TypeManager.uint64_type){
1238 if (right is IntConstant){
1239 e = TryImplicitIntConversion(l, (IntConstant) right);
1242 } else if (right is LongConstant){
1243 long ll = ((LongConstant) right).Value;
1246 right = new ULongConstant ((ulong) ll);
1251 if (left is IntConstant){
1252 e = TryImplicitIntConversion (r, (IntConstant) left);
1255 } else if (left is LongConstant){
1256 long ll = ((LongConstant) left).Value;
1259 left = new ULongConstant ((ulong) ll);
1264 if ((other == TypeManager.sbyte_type) ||
1265 (other == TypeManager.short_type) ||
1266 (other == TypeManager.int32_type) ||
1267 (other == TypeManager.int64_type)){
1268 string oper = OperName ();
1270 Error (34, loc, "Operator `" + OperName ()
1271 + "' is ambiguous on operands of type `"
1272 + TypeManager.CSharpName (l) + "' "
1273 + "and `" + TypeManager.CSharpName (r)
1276 type = TypeManager.uint64_type;
1277 } else if (l == TypeManager.int64_type || r == TypeManager.int64_type){
1279 // If either operand is of type long, the other operand is converted
1282 if (l != TypeManager.int64_type)
1283 left = ConvertImplicit (ec, left, TypeManager.int64_type, loc);
1284 if (r != TypeManager.int64_type)
1285 right = ConvertImplicit (ec, right, TypeManager.int64_type, loc);
1287 type = TypeManager.int64_type;
1288 } else if (l == TypeManager.uint32_type || r == TypeManager.uint32_type){
1290 // If either operand is of type uint, and the other
1291 // operand is of type sbyte, short or int, othe operands are
1292 // converted to type long.
1296 if (l == TypeManager.uint32_type)
1298 else if (r == TypeManager.uint32_type)
1301 if ((other == TypeManager.sbyte_type) ||
1302 (other == TypeManager.short_type) ||
1303 (other == TypeManager.int32_type)){
1304 left = ForceConversion (ec, left, TypeManager.int64_type);
1305 right = ForceConversion (ec, right, TypeManager.int64_type);
1306 type = TypeManager.int64_type;
1309 // if either operand is of type uint, the other
1310 // operand is converd to type uint
1312 left = ForceConversion (ec, left, TypeManager.uint32_type);
1313 right = ForceConversion (ec, right, TypeManager.uint32_type);
1314 type = TypeManager.uint32_type;
1316 } else if (l == TypeManager.decimal_type || r == TypeManager.decimal_type){
1317 if (l != TypeManager.decimal_type)
1318 left = ConvertImplicit (ec, left, TypeManager.decimal_type, loc);
1319 if (r != TypeManager.decimal_type)
1320 right = ConvertImplicit (ec, right, TypeManager.decimal_type, loc);
1322 type = TypeManager.decimal_type;
1324 Expression l_tmp, r_tmp;
1326 l_tmp = ForceConversion (ec, left, TypeManager.int32_type);
1330 r_tmp = ForceConversion (ec, right, TypeManager.int32_type);
1337 type = TypeManager.int32_type;
1346 "Operator " + OperName () + " cannot be applied to operands of type `" +
1347 TypeManager.CSharpName (left.Type) + "' and `" +
1348 TypeManager.CSharpName (right.Type) + "'");
1352 Expression CheckShiftArguments (EmitContext ec)
1356 Type r = right.Type;
1358 e = ForceConversion (ec, right, TypeManager.int32_type);
1365 if (((e = ConvertImplicit (ec, left, TypeManager.int32_type, loc)) != null) ||
1366 ((e = ConvertImplicit (ec, left, TypeManager.uint32_type, loc)) != null) ||
1367 ((e = ConvertImplicit (ec, left, TypeManager.int64_type, loc)) != null) ||
1368 ((e = ConvertImplicit (ec, left, TypeManager.uint64_type, loc)) != null)){
1378 Expression ResolveOperator (EmitContext ec)
1381 Type r = right.Type;
1384 // Step 1: Perform Operator Overload location
1386 Expression left_expr, right_expr;
1388 string op = "op_" + oper;
1390 left_expr = MemberLookup (ec, l, op, false, loc);
1391 if (left_expr == null && l.BaseType != null)
1392 left_expr = MemberLookup (ec, l.BaseType, op, false, loc);
1394 right_expr = MemberLookup (ec, r, op, false, loc);
1395 if (right_expr == null && r.BaseType != null)
1396 right_expr = MemberLookup (ec, r.BaseType, op, false, loc);
1398 MethodGroupExpr union = Invocation.MakeUnionSet (left_expr, right_expr);
1400 if (union != null) {
1401 Arguments = new ArrayList ();
1402 Arguments.Add (new Argument (left, Argument.AType.Expression));
1403 Arguments.Add (new Argument (right, Argument.AType.Expression));
1405 method = Invocation.OverloadResolve (ec, union, Arguments, loc);
1406 if (method != null) {
1407 MethodInfo mi = (MethodInfo) method;
1408 type = mi.ReturnType;
1417 // Step 2: Default operations on CLI native types.
1420 // Only perform numeric promotions on:
1421 // +, -, *, /, %, &, |, ^, ==, !=, <, >, <=, >=
1423 if (oper == Operator.Addition){
1425 // If any of the arguments is a string, cast to string
1427 if (l == TypeManager.string_type){
1428 if (r == TypeManager.string_type){
1429 if (left is Constant && right is Constant){
1430 StringConstant ls = (StringConstant) left;
1431 StringConstant rs = (StringConstant) right;
1433 return new StringConstant (
1434 ls.Value + rs.Value);
1438 method = TypeManager.string_concat_string_string;
1441 method = TypeManager.string_concat_object_object;
1442 right = ConvertImplicit (ec, right,
1443 TypeManager.object_type, loc);
1445 type = TypeManager.string_type;
1447 Arguments = new ArrayList ();
1448 Arguments.Add (new Argument (left, Argument.AType.Expression));
1449 Arguments.Add (new Argument (right, Argument.AType.Expression));
1453 } else if (r == TypeManager.string_type){
1455 method = TypeManager.string_concat_object_object;
1456 Arguments = new ArrayList ();
1457 Arguments.Add (new Argument (left, Argument.AType.Expression));
1458 Arguments.Add (new Argument (right, Argument.AType.Expression));
1460 left = ConvertImplicit (ec, left, TypeManager.object_type, loc);
1461 type = TypeManager.string_type;
1466 if (l.IsSubclassOf (TypeManager.delegate_type) &&
1467 r.IsSubclassOf (TypeManager.delegate_type)) {
1469 Arguments = new ArrayList ();
1470 Arguments.Add (new Argument (left, Argument.AType.Expression));
1471 Arguments.Add (new Argument (right, Argument.AType.Expression));
1473 method = TypeManager.delegate_combine_delegate_delegate;
1479 if (oper == Operator.LeftShift || oper == Operator.RightShift)
1480 return CheckShiftArguments (ec);
1482 if (oper == Operator.LogicalOr || oper == Operator.LogicalAnd){
1483 if (l != TypeManager.bool_type || r != TypeManager.bool_type){
1488 type = TypeManager.bool_type;
1492 if (oper == Operator.Equality || oper == Operator.Inequality){
1493 if (l == TypeManager.bool_type || r == TypeManager.bool_type){
1494 if (r != TypeManager.bool_type || l != TypeManager.bool_type){
1499 type = TypeManager.bool_type;
1506 // We are dealing with numbers
1509 if (!DoNumericPromotions (ec, l, r)){
1512 // operator != (object a, object b)
1513 // operator == (object a, object b)
1516 if (oper == Operator.Equality || oper == Operator.Inequality){
1518 li = ConvertImplicit (ec, left, TypeManager.object_type, loc);
1520 ri = ConvertImplicit (ec, right, TypeManager.object_type,
1526 type = TypeManager.bool_type;
1533 if (left == null || right == null)
1537 // reload our cached types if required
1542 if (oper == Operator.BitwiseAnd ||
1543 oper == Operator.BitwiseOr ||
1544 oper == Operator.ExclusiveOr){
1546 if (l.IsSubclassOf (TypeManager.enum_type) ||
1547 !((l == TypeManager.int32_type) ||
1548 (l == TypeManager.uint32_type) ||
1549 (l == TypeManager.int64_type) ||
1550 (l == TypeManager.uint64_type)))
1558 if (oper == Operator.Equality ||
1559 oper == Operator.Inequality ||
1560 oper == Operator.LessThanOrEqual ||
1561 oper == Operator.LessThan ||
1562 oper == Operator.GreaterThanOrEqual ||
1563 oper == Operator.GreaterThan){
1564 type = TypeManager.bool_type;
1571 /// Constant expression reducer for binary operations
1573 public Expression ConstantFold (EmitContext ec)
1575 object l = ((Constant) left).GetValue ();
1576 object r = ((Constant) right).GetValue ();
1578 if (l is string && r is string)
1579 return new StringConstant ((string) l + (string) r);
1581 Type result_type = null;
1584 // Enumerator folding
1586 if (left.Type == right.Type && left is EnumConstant)
1587 result_type = left.Type;
1590 case Operator.BitwiseOr:
1591 if ((l is int) && (r is int)){
1593 int res = (int)l | (int)r;
1595 v = new IntConstant (res);
1596 if (result_type == null)
1599 return new EnumConstant (v, result_type);
1603 case Operator.BitwiseAnd:
1604 if ((l is int) && (r is int)){
1606 int res = (int)l & (int)r;
1608 v = new IntConstant (res);
1609 if (result_type == null)
1612 return new EnumConstant (v, result_type);
1620 public override Expression DoResolve (EmitContext ec)
1622 left = left.Resolve (ec);
1623 right = right.Resolve (ec);
1625 if (left == null || right == null)
1628 if (left.Type == null)
1629 throw new Exception (
1630 "Resolve returned non null, but did not set the type! (" +
1631 left + ") at Line: " + loc.Row);
1632 if (right.Type == null)
1633 throw new Exception (
1634 "Resolve returned non null, but did not set the type! (" +
1635 right + ") at Line: "+ loc.Row);
1637 eclass = ExprClass.Value;
1639 if (left is Constant && right is Constant){
1641 // This is temporary until we do the full folding
1643 Expression e = ConstantFold (ec);
1648 return ResolveOperator (ec);
1651 public bool IsBranchable ()
1653 if (oper == Operator.Equality ||
1654 oper == Operator.Inequality ||
1655 oper == Operator.LessThan ||
1656 oper == Operator.GreaterThan ||
1657 oper == Operator.LessThanOrEqual ||
1658 oper == Operator.GreaterThanOrEqual){
1665 /// This entry point is used by routines that might want
1666 /// to emit a brfalse/brtrue after an expression, and instead
1667 /// they could use a more compact notation.
1669 /// Typically the code would generate l.emit/r.emit, followed
1670 /// by the comparission and then a brtrue/brfalse. The comparissions
1671 /// are sometimes inneficient (there are not as complete as the branches
1672 /// look for the hacks in Emit using double ceqs).
1674 /// So for those cases we provide EmitBranchable that can emit the
1675 /// branch with the test
1677 public void EmitBranchable (EmitContext ec, int target)
1680 bool close_target = false;
1681 ILGenerator ig = ec.ig;
1684 // short-circuit operators
1686 if (oper == Operator.LogicalAnd){
1688 ig.Emit (OpCodes.Brfalse, target);
1690 ig.Emit (OpCodes.Brfalse, target);
1691 } else if (oper == Operator.LogicalOr){
1693 ig.Emit (OpCodes.Brtrue, target);
1695 ig.Emit (OpCodes.Brfalse, target);
1702 case Operator.Equality:
1704 opcode = OpCodes.Beq_S;
1706 opcode = OpCodes.Beq;
1709 case Operator.Inequality:
1711 opcode = OpCodes.Bne_Un_S;
1713 opcode = OpCodes.Bne_Un;
1716 case Operator.LessThan:
1718 opcode = OpCodes.Blt_S;
1720 opcode = OpCodes.Blt;
1723 case Operator.GreaterThan:
1725 opcode = OpCodes.Bgt_S;
1727 opcode = OpCodes.Bgt;
1730 case Operator.LessThanOrEqual:
1732 opcode = OpCodes.Ble_S;
1734 opcode = OpCodes.Ble;
1737 case Operator.GreaterThanOrEqual:
1739 opcode = OpCodes.Bge_S;
1741 opcode = OpCodes.Ble;
1745 throw new Exception ("EmitBranchable called on non-EmitBranchable operator: "
1746 + oper.ToString ());
1749 ig.Emit (opcode, target);
1752 public override void Emit (EmitContext ec)
1754 ILGenerator ig = ec.ig;
1756 Type r = right.Type;
1759 if (method != null) {
1761 // Note that operators are static anyway
1763 if (Arguments != null)
1764 Invocation.EmitArguments (ec, method, Arguments);
1766 if (method is MethodInfo)
1767 ig.Emit (OpCodes.Call, (MethodInfo) method);
1769 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
1775 // Handle short-circuit operators differently
1778 if (oper == Operator.LogicalAnd){
1779 Label load_zero = ig.DefineLabel ();
1780 Label end = ig.DefineLabel ();
1783 ig.Emit (OpCodes.Brfalse, load_zero);
1785 ig.Emit (OpCodes.Br, end);
1786 ig.MarkLabel (load_zero);
1787 ig.Emit (OpCodes.Ldc_I4_0);
1790 } else if (oper == Operator.LogicalOr){
1791 Label load_one = ig.DefineLabel ();
1792 Label end = ig.DefineLabel ();
1795 ig.Emit (OpCodes.Brtrue, load_one);
1797 ig.Emit (OpCodes.Br, end);
1798 ig.MarkLabel (load_one);
1799 ig.Emit (OpCodes.Ldc_I4_1);
1808 case Operator.Multiply:
1810 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
1811 opcode = OpCodes.Mul_Ovf;
1812 else if (l==TypeManager.uint32_type || l==TypeManager.uint64_type)
1813 opcode = OpCodes.Mul_Ovf_Un;
1815 opcode = OpCodes.Mul;
1817 opcode = OpCodes.Mul;
1821 case Operator.Division:
1822 if (l == TypeManager.uint32_type || l == TypeManager.uint64_type)
1823 opcode = OpCodes.Div_Un;
1825 opcode = OpCodes.Div;
1828 case Operator.Modulus:
1829 if (l == TypeManager.uint32_type || l == TypeManager.uint64_type)
1830 opcode = OpCodes.Rem_Un;
1832 opcode = OpCodes.Rem;
1835 case Operator.Addition:
1837 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
1838 opcode = OpCodes.Add_Ovf;
1839 else if (l==TypeManager.uint32_type || l==TypeManager.uint64_type)
1840 opcode = OpCodes.Add_Ovf_Un;
1842 opcode = OpCodes.Mul;
1844 opcode = OpCodes.Add;
1847 case Operator.Subtraction:
1849 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
1850 opcode = OpCodes.Sub_Ovf;
1851 else if (l==TypeManager.uint32_type || l==TypeManager.uint64_type)
1852 opcode = OpCodes.Sub_Ovf_Un;
1854 opcode = OpCodes.Sub;
1856 opcode = OpCodes.Sub;
1859 case Operator.RightShift:
1860 opcode = OpCodes.Shr;
1863 case Operator.LeftShift:
1864 opcode = OpCodes.Shl;
1867 case Operator.Equality:
1868 opcode = OpCodes.Ceq;
1871 case Operator.Inequality:
1872 ec.ig.Emit (OpCodes.Ceq);
1873 ec.ig.Emit (OpCodes.Ldc_I4_0);
1875 opcode = OpCodes.Ceq;
1878 case Operator.LessThan:
1879 opcode = OpCodes.Clt;
1882 case Operator.GreaterThan:
1883 opcode = OpCodes.Cgt;
1886 case Operator.LessThanOrEqual:
1887 ec.ig.Emit (OpCodes.Cgt);
1888 ec.ig.Emit (OpCodes.Ldc_I4_0);
1890 opcode = OpCodes.Ceq;
1893 case Operator.GreaterThanOrEqual:
1894 ec.ig.Emit (OpCodes.Clt);
1895 ec.ig.Emit (OpCodes.Ldc_I4_1);
1897 opcode = OpCodes.Sub;
1900 case Operator.BitwiseOr:
1901 opcode = OpCodes.Or;
1904 case Operator.BitwiseAnd:
1905 opcode = OpCodes.And;
1908 case Operator.ExclusiveOr:
1909 opcode = OpCodes.Xor;
1913 throw new Exception ("This should not happen: Operator = "
1914 + oper.ToString ());
1922 /// Implements the ternary conditiona operator (?:)
1924 public class Conditional : Expression {
1925 Expression expr, trueExpr, falseExpr;
1928 public Conditional (Expression expr, Expression trueExpr, Expression falseExpr, Location l)
1931 this.trueExpr = trueExpr;
1932 this.falseExpr = falseExpr;
1936 public Expression Expr {
1942 public Expression TrueExpr {
1948 public Expression FalseExpr {
1954 public override Expression DoResolve (EmitContext ec)
1956 expr = expr.Resolve (ec);
1958 if (expr.Type != TypeManager.bool_type)
1959 expr = Expression.ConvertImplicitRequired (
1960 ec, expr, TypeManager.bool_type, loc);
1962 trueExpr = trueExpr.Resolve (ec);
1963 falseExpr = falseExpr.Resolve (ec);
1965 if (expr == null || trueExpr == null || falseExpr == null)
1968 if (trueExpr.Type == falseExpr.Type)
1969 type = trueExpr.Type;
1974 // First, if an implicit conversion exists from trueExpr
1975 // to falseExpr, then the result type is of type falseExpr.Type
1977 conv = ConvertImplicit (ec, trueExpr, falseExpr.Type, loc);
1979 type = falseExpr.Type;
1981 } else if ((conv = ConvertImplicit(ec, falseExpr,trueExpr.Type,loc))!= null){
1982 type = trueExpr.Type;
1985 Error (173, loc, "The type of the conditional expression can " +
1986 "not be computed because there is no implicit conversion" +
1987 " from `" + TypeManager.CSharpName (trueExpr.Type) + "'" +
1988 " and `" + TypeManager.CSharpName (falseExpr.Type) + "'");
1993 if (expr is BoolConstant){
1994 BoolConstant bc = (BoolConstant) expr;
2002 eclass = ExprClass.Value;
2006 public override void Emit (EmitContext ec)
2008 ILGenerator ig = ec.ig;
2009 Label false_target = ig.DefineLabel ();
2010 Label end_target = ig.DefineLabel ();
2013 ig.Emit (OpCodes.Brfalse, false_target);
2015 ig.Emit (OpCodes.Br, end_target);
2016 ig.MarkLabel (false_target);
2017 falseExpr.Emit (ec);
2018 ig.MarkLabel (end_target);
2026 public class LocalVariableReference : Expression, IAssignMethod, IMemoryLocation {
2027 public readonly string Name;
2028 public readonly Block Block;
2030 VariableInfo variable_info;
2032 public LocalVariableReference (Block block, string name, Location l)
2037 eclass = ExprClass.Variable;
2040 public VariableInfo VariableInfo {
2042 if (variable_info == null)
2043 variable_info = Block.GetVariableInfo (Name);
2044 return variable_info;
2048 public override Expression DoResolve (EmitContext ec)
2050 VariableInfo vi = VariableInfo;
2052 if (Block.IsConstant (Name)) {
2053 Expression e = Block.GetConstantExpression (Name);
2059 if (!(e is Constant)) {
2060 Report.Error (150, loc, "A constant value is expected");
2068 type = vi.VariableType;
2072 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
2074 Expression e = DoResolve (ec);
2079 VariableInfo vi = VariableInfo;
2085 "cannot assign to `" + Name + "' because it is readonly");
2093 public override void Emit (EmitContext ec)
2095 VariableInfo vi = VariableInfo;
2096 ILGenerator ig = ec.ig;
2103 ig.Emit (OpCodes.Ldloc_0);
2107 ig.Emit (OpCodes.Ldloc_1);
2111 ig.Emit (OpCodes.Ldloc_2);
2115 ig.Emit (OpCodes.Ldloc_3);
2120 ig.Emit (OpCodes.Ldloc_S, (byte) idx);
2122 ig.Emit (OpCodes.Ldloc, idx);
2127 public static void Store (ILGenerator ig, int idx)
2131 ig.Emit (OpCodes.Stloc_0);
2135 ig.Emit (OpCodes.Stloc_1);
2139 ig.Emit (OpCodes.Stloc_2);
2143 ig.Emit (OpCodes.Stloc_3);
2148 ig.Emit (OpCodes.Stloc_S, (byte) idx);
2150 ig.Emit (OpCodes.Stloc, idx);
2155 public void EmitAssign (EmitContext ec, Expression source)
2157 ILGenerator ig = ec.ig;
2158 VariableInfo vi = VariableInfo;
2164 // Funny seems the code below generates optimal code for us, but
2165 // seems to take too long to generate what we need.
2166 // ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
2171 public void AddressOf (EmitContext ec)
2173 VariableInfo vi = VariableInfo;
2180 ec.ig.Emit (OpCodes.Ldloca_S, (byte) idx);
2182 ec.ig.Emit (OpCodes.Ldloca, idx);
2187 /// This represents a reference to a parameter in the intermediate
2190 public class ParameterReference : Expression, IAssignMethod, IMemoryLocation {
2196 public ParameterReference (Parameters pars, int idx, string name)
2201 eclass = ExprClass.Variable;
2205 // Notice that for ref/out parameters, the type exposed is not the
2206 // same type exposed externally.
2209 // externally we expose "int&"
2210 // here we expose "int".
2212 // We record this in "is_ref". This means that the type system can treat
2213 // the type as it is expected, but when we generate the code, we generate
2214 // the alternate kind of code.
2216 public override Expression DoResolve (EmitContext ec)
2218 type = pars.GetParameterInfo (ec.TypeContainer, idx, out is_ref);
2219 eclass = ExprClass.Variable;
2224 public override void Emit (EmitContext ec)
2226 ILGenerator ig = ec.ig;
2233 ig.Emit (OpCodes.Ldarg_S, (byte) arg_idx);
2235 ig.Emit (OpCodes.Ldarg, arg_idx);
2241 // If we are a reference, we loaded on the stack a pointer
2242 // Now lets load the real value
2245 if (type == TypeManager.int32_type)
2246 ig.Emit (OpCodes.Ldind_I4);
2247 else if (type == TypeManager.uint32_type)
2248 ig.Emit (OpCodes.Ldind_U4);
2249 else if (type == TypeManager.int64_type || type == TypeManager.uint64_type)
2250 ig.Emit (OpCodes.Ldind_I8);
2251 else if (type == TypeManager.char_type)
2252 ig.Emit (OpCodes.Ldind_U2);
2253 else if (type == TypeManager.short_type)
2254 ig.Emit (OpCodes.Ldind_I2);
2255 else if (type == TypeManager.ushort_type)
2256 ig.Emit (OpCodes.Ldind_U2);
2257 else if (type == TypeManager.float_type)
2258 ig.Emit (OpCodes.Ldind_R4);
2259 else if (type == TypeManager.double_type)
2260 ig.Emit (OpCodes.Ldind_R8);
2261 else if (type == TypeManager.byte_type)
2262 ig.Emit (OpCodes.Ldind_U1);
2263 else if (type == TypeManager.sbyte_type)
2264 ig.Emit (OpCodes.Ldind_I1);
2265 else if (type == TypeManager.intptr_type)
2266 ig.Emit (OpCodes.Ldind_I);
2268 ig.Emit (OpCodes.Ldind_Ref);
2271 public void EmitAssign (EmitContext ec, Expression source)
2273 ILGenerator ig = ec.ig;
2282 ig.Emit (OpCodes.Ldarg_S, (byte) arg_idx);
2284 ig.Emit (OpCodes.Ldarg, arg_idx);
2290 if (type == TypeManager.int32_type || type == TypeManager.uint32_type)
2291 ig.Emit (OpCodes.Stind_I4);
2292 else if (type == TypeManager.int64_type || type == TypeManager.uint64_type)
2293 ig.Emit (OpCodes.Stind_I8);
2294 else if (type == TypeManager.char_type || type == TypeManager.short_type ||
2295 type == TypeManager.ushort_type)
2296 ig.Emit (OpCodes.Stind_I2);
2297 else if (type == TypeManager.float_type)
2298 ig.Emit (OpCodes.Stind_R4);
2299 else if (type == TypeManager.double_type)
2300 ig.Emit (OpCodes.Stind_R8);
2301 else if (type == TypeManager.byte_type || type == TypeManager.sbyte_type)
2302 ig.Emit (OpCodes.Stind_I1);
2303 else if (type == TypeManager.intptr_type)
2304 ig.Emit (OpCodes.Stind_I);
2306 ig.Emit (OpCodes.Stind_Ref);
2309 ig.Emit (OpCodes.Starg_S, (byte) arg_idx);
2311 ig.Emit (OpCodes.Starg, arg_idx);
2316 public void AddressOf (EmitContext ec)
2324 ec.ig.Emit (OpCodes.Ldarga_S, (byte) arg_idx);
2326 ec.ig.Emit (OpCodes.Ldarga, arg_idx);
2331 /// Used for arguments to New(), Invocation()
2333 public class Argument {
2334 public enum AType : byte {
2340 public readonly AType ArgType;
2341 public Expression expr;
2343 public Argument (Expression expr, AType type)
2346 this.ArgType = type;
2349 public Expression Expr {
2365 public Parameter.Modifier GetParameterModifier ()
2367 if (ArgType == AType.Ref)
2368 return Parameter.Modifier.REF;
2370 if (ArgType == AType.Out)
2371 return Parameter.Modifier.OUT;
2373 return Parameter.Modifier.NONE;
2376 public static string FullDesc (Argument a)
2378 return (a.ArgType == AType.Ref ? "ref " :
2379 (a.ArgType == AType.Out ? "out " : "")) +
2380 TypeManager.CSharpName (a.Expr.Type);
2383 public bool Resolve (EmitContext ec, Location loc)
2385 expr = expr.Resolve (ec);
2387 if (ArgType == AType.Expression)
2388 return expr != null;
2390 if (expr.eclass != ExprClass.Variable){
2391 Report.Error (206, loc,
2392 "A property or indexer can not be passed as an out or ref " +
2397 return expr != null;
2400 public void Emit (EmitContext ec)
2402 if (ArgType == AType.Ref || ArgType == AType.Out)
2403 ((IMemoryLocation)expr).AddressOf (ec);
2410 /// Invocation of methods or delegates.
2412 public class Invocation : ExpressionStatement {
2413 public readonly ArrayList Arguments;
2417 MethodBase method = null;
2419 static Hashtable method_parameter_cache;
2421 static Invocation ()
2423 method_parameter_cache = new Hashtable ();
2427 // arguments is an ArrayList, but we do not want to typecast,
2428 // as it might be null.
2430 // FIXME: only allow expr to be a method invocation or a
2431 // delegate invocation (7.5.5)
2433 public Invocation (Expression expr, ArrayList arguments, Location l)
2436 Arguments = arguments;
2440 public Expression Expr {
2447 /// Returns the Parameters (a ParameterData interface) for the
2450 public static ParameterData GetParameterData (MethodBase mb)
2452 object pd = method_parameter_cache [mb];
2456 return (ParameterData) pd;
2459 ip = TypeManager.LookupParametersByBuilder (mb);
2461 method_parameter_cache [mb] = ip;
2463 return (ParameterData) ip;
2465 ParameterInfo [] pi = mb.GetParameters ();
2466 ReflectionParameters rp = new ReflectionParameters (pi);
2467 method_parameter_cache [mb] = rp;
2469 return (ParameterData) rp;
2474 /// Tells whether a user defined conversion from Type `from' to
2475 /// Type `to' exists.
2477 /// FIXME: we could implement a cache here.
2479 static bool ConversionExists (EmitContext ec, Type from, Type to, Location loc)
2481 // Locate user-defined implicit operators
2485 mg = MemberLookup (ec, to, "op_Implicit", false, loc);
2488 MethodGroupExpr me = (MethodGroupExpr) mg;
2490 for (int i = me.Methods.Length; i > 0;) {
2492 MethodBase mb = me.Methods [i];
2493 ParameterData pd = GetParameterData (mb);
2495 if (from == pd.ParameterType (0))
2500 mg = MemberLookup (ec, from, "op_Implicit", false, loc);
2503 MethodGroupExpr me = (MethodGroupExpr) mg;
2505 for (int i = me.Methods.Length; i > 0;) {
2507 MethodBase mb = me.Methods [i];
2508 MethodInfo mi = (MethodInfo) mb;
2510 if (mi.ReturnType == to)
2519 /// Determines "better conversion" as specified in 7.4.2.3
2520 /// Returns : 1 if a->p is better
2521 /// 0 if a->q or neither is better
2523 static int BetterConversion (EmitContext ec, Argument a, Type p, Type q, bool use_standard,
2526 Type argument_type = a.Type;
2527 Expression argument_expr = a.Expr;
2529 if (argument_type == null)
2530 throw new Exception ("Expression of type " + a.Expr + " does not resolve its type");
2535 if (argument_type == p)
2538 if (argument_type == q)
2542 // Now probe whether an implicit constant expression conversion
2545 // An implicit constant expression conversion permits the following
2548 // * A constant-expression of type `int' can be converted to type
2549 // sbyte, byute, short, ushort, uint, ulong provided the value of
2550 // of the expression is withing the range of the destination type.
2552 // * A constant-expression of type long can be converted to type
2553 // ulong, provided the value of the constant expression is not negative
2555 // FIXME: Note that this assumes that constant folding has
2556 // taken place. We dont do constant folding yet.
2559 if (argument_expr is IntConstant){
2560 IntConstant ei = (IntConstant) argument_expr;
2561 int value = ei.Value;
2563 if (p == TypeManager.sbyte_type){
2564 if (value >= SByte.MinValue && value <= SByte.MaxValue)
2566 } else if (p == TypeManager.byte_type){
2567 if (Byte.MinValue >= 0 && value <= Byte.MaxValue)
2569 } else if (p == TypeManager.short_type){
2570 if (value >= Int16.MinValue && value <= Int16.MaxValue)
2572 } else if (p == TypeManager.ushort_type){
2573 if (value >= UInt16.MinValue && value <= UInt16.MaxValue)
2575 } else if (p == TypeManager.uint32_type){
2577 // we can optimize this case: a positive int32
2578 // always fits on a uint32
2582 } else if (p == TypeManager.uint64_type){
2584 // we can optimize this case: a positive int32
2585 // always fits on a uint64
2590 } else if (argument_type == TypeManager.int64_type && argument_expr is LongConstant){
2591 LongConstant lc = (LongConstant) argument_expr;
2593 if (p == TypeManager.uint64_type){
2604 tmp = ConvertImplicitStandard (ec, argument_expr, p, loc);
2606 tmp = ConvertImplicit (ec, argument_expr, p, loc);
2615 if (ConversionExists (ec, p, q, loc) == true &&
2616 ConversionExists (ec, q, p, loc) == false)
2619 if (p == TypeManager.sbyte_type)
2620 if (q == TypeManager.byte_type || q == TypeManager.ushort_type ||
2621 q == TypeManager.uint32_type || q == TypeManager.uint64_type)
2624 if (p == TypeManager.short_type)
2625 if (q == TypeManager.ushort_type || q == TypeManager.uint32_type ||
2626 q == TypeManager.uint64_type)
2629 if (p == TypeManager.int32_type)
2630 if (q == TypeManager.uint32_type || q == TypeManager.uint64_type)
2633 if (p == TypeManager.int64_type)
2634 if (q == TypeManager.uint64_type)
2641 /// Determines "Better function"
2644 /// and returns an integer indicating :
2645 /// 0 if candidate ain't better
2646 /// 1 if candidate is better than the current best match
2648 static int BetterFunction (EmitContext ec, ArrayList args,
2649 MethodBase candidate, MethodBase best,
2650 bool use_standard, Location loc)
2652 ParameterData candidate_pd = GetParameterData (candidate);
2653 ParameterData best_pd;
2659 argument_count = args.Count;
2661 if (candidate_pd.Count == 0 && argument_count == 0)
2665 if (candidate_pd.Count == argument_count) {
2667 for (int j = argument_count; j > 0;) {
2670 Argument a = (Argument) args [j];
2672 x = BetterConversion (
2673 ec, a, candidate_pd.ParameterType (j), null,
2689 best_pd = GetParameterData (best);
2691 if (candidate_pd.Count == argument_count && best_pd.Count == argument_count) {
2692 int rating1 = 0, rating2 = 0;
2694 for (int j = argument_count; j > 0;) {
2698 Argument a = (Argument) args [j];
2700 x = BetterConversion (ec, a, candidate_pd.ParameterType (j),
2701 best_pd.ParameterType (j), use_standard, loc);
2702 y = BetterConversion (ec, a, best_pd.ParameterType (j),
2703 candidate_pd.ParameterType (j), use_standard,
2710 if (rating1 > rating2)
2719 public static string FullMethodDesc (MethodBase mb)
2721 StringBuilder sb = new StringBuilder (mb.Name);
2722 ParameterData pd = GetParameterData (mb);
2724 int count = pd.Count;
2727 for (int i = count; i > 0; ) {
2730 sb.Append (pd.ParameterDesc (count - i - 1));
2736 return sb.ToString ();
2739 public static MethodGroupExpr MakeUnionSet (Expression mg1, Expression mg2)
2741 MemberInfo [] miset;
2742 MethodGroupExpr union;
2744 if (mg1 != null && mg2 != null) {
2746 MethodGroupExpr left_set = null, right_set = null;
2747 int length1 = 0, length2 = 0;
2749 left_set = (MethodGroupExpr) mg1;
2750 length1 = left_set.Methods.Length;
2752 right_set = (MethodGroupExpr) mg2;
2753 length2 = right_set.Methods.Length;
2755 ArrayList common = new ArrayList ();
2757 for (int i = 0; i < left_set.Methods.Length; i++) {
2758 for (int j = 0; j < right_set.Methods.Length; j++) {
2759 if (left_set.Methods [i] == right_set.Methods [j])
2760 common.Add (left_set.Methods [i]);
2764 miset = new MemberInfo [length1 + length2 - common.Count];
2766 left_set.Methods.CopyTo (miset, 0);
2770 for (int j = 0; j < right_set.Methods.Length; j++)
2771 if (!common.Contains (right_set.Methods [j]))
2772 miset [length1 + k++] = right_set.Methods [j];
2774 union = new MethodGroupExpr (miset);
2778 } else if (mg1 == null && mg2 != null) {
2780 MethodGroupExpr me = (MethodGroupExpr) mg2;
2782 miset = new MemberInfo [me.Methods.Length];
2783 me.Methods.CopyTo (miset, 0);
2785 union = new MethodGroupExpr (miset);
2789 } else if (mg2 == null && mg1 != null) {
2791 MethodGroupExpr me = (MethodGroupExpr) mg1;
2793 miset = new MemberInfo [me.Methods.Length];
2794 me.Methods.CopyTo (miset, 0);
2796 union = new MethodGroupExpr (miset);
2805 /// Determines is the candidate method, if a params method, is applicable
2806 /// in its expanded form to the given set of arguments
2808 static bool IsParamsMethodApplicable (ArrayList arguments, MethodBase candidate)
2812 if (arguments == null)
2815 arg_count = arguments.Count;
2817 ParameterData pd = GetParameterData (candidate);
2819 int pd_count = pd.Count;
2821 if (pd.ParameterModifier (pd_count - 1) != Parameter.Modifier.PARAMS)
2824 if (pd_count - 1 > arg_count)
2827 // If we have come this far, the case which remains is when the number of parameters
2828 // is less than or equal to the argument count. So, we now check if the element type
2829 // of the params array is compatible with each argument type
2832 Type element_type = pd.ParameterType (pd_count - 1).GetElementType ();
2834 for (int i = pd_count - 1; i < arg_count - 1; i++) {
2835 Argument a = (Argument) arguments [i];
2836 if (!StandardConversionExists (a.Type, element_type))
2844 /// Determines if the candidate method is applicable (section 14.4.2.1)
2845 /// to the given set of arguments
2847 static bool IsApplicable (ArrayList arguments, MethodBase candidate)
2851 if (arguments == null)
2854 arg_count = arguments.Count;
2856 ParameterData pd = GetParameterData (candidate);
2858 int pd_count = pd.Count;
2860 if (arg_count != pd.Count)
2863 for (int i = arg_count; i > 0; ) {
2866 Argument a = (Argument) arguments [i];
2868 Parameter.Modifier a_mod = a.GetParameterModifier ();
2869 Parameter.Modifier p_mod = pd.ParameterModifier (i);
2871 if (a_mod == p_mod) {
2873 if (a_mod == Parameter.Modifier.NONE)
2874 if (!StandardConversionExists (a.Type, pd.ParameterType (i)))
2877 if (a_mod == Parameter.Modifier.REF ||
2878 a_mod == Parameter.Modifier.OUT)
2879 if (pd.ParameterType (i) != a.Type)
2891 /// Find the Applicable Function Members (7.4.2.1)
2893 /// me: Method Group expression with the members to select.
2894 /// it might contain constructors or methods (or anything
2895 /// that maps to a method).
2897 /// Arguments: ArrayList containing resolved Argument objects.
2899 /// loc: The location if we want an error to be reported, or a Null
2900 /// location for "probing" purposes.
2902 /// use_standard: controls whether OverloadResolve should use the
2903 /// ConvertImplicit or ConvertImplicitStandard during overload resolution.
2905 /// Returns: The MethodBase (either a ConstructorInfo or a MethodInfo)
2906 /// that is the best match of me on Arguments.
2909 public static MethodBase OverloadResolve (EmitContext ec, MethodGroupExpr me,
2910 ArrayList Arguments, Location loc,
2913 ArrayList afm = new ArrayList ();
2914 int best_match_idx = -1;
2915 MethodBase method = null;
2917 ArrayList candidates = new ArrayList ();
2919 for (int i = me.Methods.Length; i > 0; ){
2921 MethodBase candidate = me.Methods [i];
2924 // Check if candidate is applicable (section 14.4.2.1)
2925 if (!IsApplicable (Arguments, candidate))
2928 candidates.Add (candidate);
2929 x = BetterFunction (ec, Arguments, candidate, method, use_standard, loc);
2935 method = me.Methods [best_match_idx];
2939 if (Arguments == null)
2942 argument_count = Arguments.Count;
2945 // Now we see if we can find params functions, applicable in their expanded form
2946 // since if they were applicable in their normal form, they would have been selected
2949 if (best_match_idx == -1) {
2951 for (int i = me.Methods.Length; i > 0; ) {
2953 MethodBase candidate = me.Methods [i];
2955 if (IsParamsMethodApplicable (Arguments, candidate)) {
2957 method = me.Methods [best_match_idx];
2964 // Now we see if we can at least find a method with the same number of arguments
2967 int method_count = 0;
2969 if (best_match_idx == -1) {
2971 for (int i = me.Methods.Length; i > 0;) {
2973 MethodBase mb = me.Methods [i];
2974 pd = GetParameterData (mb);
2976 if (pd.Count == argument_count) {
2978 method = me.Methods [best_match_idx];
2989 // Now check that there are no ambiguities i.e the selected method
2990 // should be better than all the others
2993 for (int i = candidates.Count; i > 0; ) {
2995 MethodBase candidate = (MethodBase) candidates [i];
2998 if (candidate == method)
3001 x = BetterFunction (ec, Arguments, method, candidate, use_standard, loc);
3006 "Ambiguous call when selecting function due to implicit casts");
3012 // And now convert implicitly, each argument to the required type
3014 pd = GetParameterData (method);
3015 int pd_count = pd.Count;
3017 for (int j = 0; j < argument_count; j++) {
3018 Argument a = (Argument) Arguments [j];
3019 Expression a_expr = a.Expr;
3020 Type parameter_type = pd.ParameterType (j);
3023 // Note that we need to compare against the element type
3024 // when we have a params method
3026 if (pd.ParameterModifier (pd_count - 1) == Parameter.Modifier.PARAMS) {
3027 if (j >= pd_count - 1)
3028 parameter_type = pd.ParameterType (pd_count - 1).GetElementType ();
3031 if (a.Type != parameter_type){
3035 conv = ConvertImplicitStandard (
3036 ec, a_expr, parameter_type, Location.Null);
3038 conv = ConvertImplicit (
3039 ec, a_expr, parameter_type, Location.Null);
3042 if (!Location.IsNull (loc)) {
3044 "The best overloaded match for method '" +
3045 FullMethodDesc (method) +
3046 "' has some invalid arguments");
3048 "Argument " + (j+1) +
3049 ": Cannot convert from '" + Argument.FullDesc (a)
3050 + "' to '" + pd.ParameterDesc (j) + "'");
3058 // Update the argument with the implicit conversion
3063 // FIXME : For the case of params methods, we need to actually instantiate
3064 // an array and initialize it with the argument values etc etc.
3068 if (a.GetParameterModifier () != pd.ParameterModifier (j) &&
3069 pd.ParameterModifier (j) != Parameter.Modifier.PARAMS) {
3070 if (!Location.IsNull (loc)) {
3072 "The best overloaded match for method '" + FullMethodDesc (method)+
3073 "' has some invalid arguments");
3075 "Argument " + (j+1) +
3076 ": Cannot convert from '" + Argument.FullDesc (a)
3077 + "' to '" + pd.ParameterDesc (j) + "'");
3088 public static MethodBase OverloadResolve (EmitContext ec, MethodGroupExpr me,
3089 ArrayList Arguments, Location loc)
3091 return OverloadResolve (ec, me, Arguments, loc, false);
3094 public override Expression DoResolve (EmitContext ec)
3097 // First, resolve the expression that is used to
3098 // trigger the invocation
3100 expr = expr.Resolve (ec);
3104 if (!(expr is MethodGroupExpr)) {
3105 Type expr_type = expr.Type;
3107 if (expr_type != null){
3108 bool IsDelegate = TypeManager.IsDelegateType (expr_type);
3110 return (new DelegateInvocation (
3111 this.expr, Arguments, loc)).Resolve (ec);
3115 if (!(expr is MethodGroupExpr)){
3116 report118 (loc, this.expr, "method group");
3121 // Next, evaluate all the expressions in the argument list
3123 if (Arguments != null){
3124 for (int i = Arguments.Count; i > 0;){
3126 Argument a = (Argument) Arguments [i];
3128 if (!a.Resolve (ec, loc))
3133 method = OverloadResolve (ec, (MethodGroupExpr) this.expr, Arguments, loc);
3135 if (method == null){
3137 "Could not find any applicable function for this argument list");
3141 if (method is MethodInfo)
3142 type = ((MethodInfo)method).ReturnType;
3144 eclass = ExprClass.Value;
3149 // Emits the list of arguments as an array
3151 static void EmitParams (EmitContext ec, int idx, ArrayList arguments)
3153 ILGenerator ig = ec.ig;
3154 int count = arguments.Count - idx;
3155 Argument a = (Argument) arguments [idx];
3156 Type t = a.expr.Type;
3157 string array_type = t.FullName + "[]";
3160 array = ig.DeclareLocal (Type.GetType (array_type));
3161 IntConstant.EmitInt (ig, count);
3162 ig.Emit (OpCodes.Newarr, t);
3163 ig.Emit (OpCodes.Stloc, array);
3165 int top = arguments.Count;
3166 for (int j = idx; j < top; j++){
3167 a = (Argument) arguments [j];
3169 ig.Emit (OpCodes.Ldloc, array);
3170 IntConstant.EmitInt (ig, j - idx);
3173 ArrayAccess.EmitStoreOpcode (ig, t);
3175 ig.Emit (OpCodes.Ldloc, array);
3179 /// Emits a list of resolved Arguments that are in the arguments
3182 /// The MethodBase argument might be null if the
3183 /// emission of the arguments is known not to contain
3184 /// a `params' field (for example in constructors or other routines
3185 /// that keep their arguments in this structure
3187 public static void EmitArguments (EmitContext ec, MethodBase mb, ArrayList arguments)
3189 ParameterData pd = null;
3192 if (arguments != null)
3193 top = arguments.Count;
3198 pd = GetParameterData (mb);
3200 for (int i = 0; i < top; i++){
3201 Argument a = (Argument) arguments [i];
3204 if (pd.ParameterModifier (i) == Parameter.Modifier.PARAMS){
3205 EmitParams (ec, i, arguments);
3214 public static void EmitCall (EmitContext ec,
3215 bool is_static, Expression instance_expr,
3216 MethodBase method, ArrayList Arguments)
3218 ILGenerator ig = ec.ig;
3219 bool struct_call = false;
3223 // If this is ourselves, push "this"
3225 if (instance_expr == null){
3226 ig.Emit (OpCodes.Ldarg_0);
3229 // Push the instance expression
3231 if (instance_expr.Type.IsSubclassOf (TypeManager.value_type)){
3236 // If the expression implements IMemoryLocation, then
3237 // we can optimize and use AddressOf on the
3240 // If not we have to use some temporary storage for
3242 if (instance_expr is IMemoryLocation)
3243 ((IMemoryLocation) instance_expr).AddressOf (ec);
3245 Type t = instance_expr.Type;
3247 instance_expr.Emit (ec);
3248 LocalBuilder temp = ig.DeclareLocal (t);
3249 ig.Emit (OpCodes.Stloc, temp);
3250 ig.Emit (OpCodes.Ldloca, temp);
3253 instance_expr.Emit (ec);
3257 if (Arguments != null)
3258 EmitArguments (ec, method, Arguments);
3260 if (is_static || struct_call){
3261 if (method is MethodInfo)
3262 ig.Emit (OpCodes.Call, (MethodInfo) method);
3264 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
3266 if (method is MethodInfo)
3267 ig.Emit (OpCodes.Callvirt, (MethodInfo) method);
3269 ig.Emit (OpCodes.Callvirt, (ConstructorInfo) method);
3273 public override void Emit (EmitContext ec)
3275 MethodGroupExpr mg = (MethodGroupExpr) this.expr;
3276 EmitCall (ec, method.IsStatic, mg.InstanceExpression, method, Arguments);
3279 public override void EmitStatement (EmitContext ec)
3284 // Pop the return value if there is one
3286 if (method is MethodInfo){
3287 if (((MethodInfo)method).ReturnType != TypeManager.void_type)
3288 ec.ig.Emit (OpCodes.Pop);
3294 /// Implements the new expression
3296 public class New : ExpressionStatement {
3297 public readonly ArrayList Arguments;
3298 public readonly string RequestedType;
3301 MethodBase method = null;
3304 // If set, the new expression is for a value_target, and
3305 // we will not leave anything on the stack.
3307 Expression value_target;
3309 public New (string requested_type, ArrayList arguments, Location l)
3311 RequestedType = requested_type;
3312 Arguments = arguments;
3316 public Expression ValueTypeVariable {
3318 return value_target;
3322 value_target = value;
3326 public override Expression DoResolve (EmitContext ec)
3328 type = RootContext.LookupType (ec.TypeContainer, RequestedType, false, loc);
3333 bool IsDelegate = TypeManager.IsDelegateType (type);
3336 return (new NewDelegate (type, Arguments, loc)).Resolve (ec);
3340 ml = MemberLookup (ec, type, ".ctor", false,
3341 MemberTypes.Constructor, AllBindingsFlags, loc);
3343 bool is_struct = false;
3344 is_struct = type.IsSubclassOf (TypeManager.value_type);
3346 if (! (ml is MethodGroupExpr)){
3348 report118 (loc, ml, "method group");
3354 if (Arguments != null){
3355 for (int i = Arguments.Count; i > 0;){
3357 Argument a = (Argument) Arguments [i];
3359 if (!a.Resolve (ec, loc))
3364 method = Invocation.OverloadResolve (ec, (MethodGroupExpr) ml,
3368 if (method == null && !is_struct) {
3370 "New invocation: Can not find a constructor for " +
3371 "this argument list");
3375 eclass = ExprClass.Value;
3380 // This DoEmit can be invoked in two contexts:
3381 // * As a mechanism that will leave a value on the stack (new object)
3382 // * As one that wont (init struct)
3384 // You can control whether a value is required on the stack by passing
3385 // need_value_on_stack. The code *might* leave a value on the stack
3386 // so it must be popped manually
3388 // Returns whether a value is left on the stack
3390 bool DoEmit (EmitContext ec, bool need_value_on_stack)
3392 if (method == null){
3393 IMemoryLocation ml = (IMemoryLocation) value_target;
3397 Invocation.EmitArguments (ec, method, Arguments);
3398 ec.ig.Emit (OpCodes.Newobj, (ConstructorInfo) method);
3403 // It must be a value type, sanity check
3405 if (value_target != null){
3406 ec.ig.Emit (OpCodes.Initobj, type);
3408 if (need_value_on_stack){
3409 value_target.Emit (ec);
3415 throw new Exception ("No method and no value type");
3418 public override void Emit (EmitContext ec)
3423 public override void EmitStatement (EmitContext ec)
3425 if (DoEmit (ec, false))
3426 ec.ig.Emit (OpCodes.Pop);
3431 /// Represents an array creation expression.
3435 /// There are two possible scenarios here: one is an array creation
3436 /// expression that specifies the dimensions and optionally the
3437 /// initialization data and the other which does not need dimensions
3438 /// specified but where initialization data is mandatory.
3440 public class ArrayCreation : ExpressionStatement {
3441 string RequestedType;
3443 ArrayList Initializers;
3445 ArrayList Arguments;
3447 MethodBase method = null;
3448 Type array_element_type;
3449 bool IsOneDimensional = false;
3450 bool IsBuiltinType = false;
3451 bool ExpectInitializers = false;
3454 Type underlying_type;
3456 ArrayList ArrayData;
3460 public ArrayCreation (string requested_type, ArrayList exprs,
3461 string rank, ArrayList initializers, Location l)
3463 RequestedType = requested_type;
3465 Initializers = initializers;
3468 Arguments = new ArrayList ();
3470 foreach (Expression e in exprs)
3471 Arguments.Add (new Argument (e, Argument.AType.Expression));
3475 public ArrayCreation (string requested_type, string rank, ArrayList initializers, Location l)
3477 RequestedType = requested_type;
3478 Initializers = initializers;
3481 Rank = rank.Substring (0, rank.LastIndexOf ("["));
3483 string tmp = rank.Substring (rank.LastIndexOf ("["));
3485 dimensions = tmp.Length - 1;
3486 ExpectInitializers = true;
3489 public static string FormArrayType (string base_type, int idx_count, string rank)
3491 StringBuilder sb = new StringBuilder (base_type);
3496 for (int i = 1; i < idx_count; i++)
3500 return sb.ToString ();
3503 public static string FormElementType (string base_type, int idx_count, string rank)
3505 StringBuilder sb = new StringBuilder (base_type);
3508 for (int i = 1; i < idx_count; i++)
3514 string val = sb.ToString ();
3516 return val.Substring (0, val.LastIndexOf ("["));
3521 Report.Error (178, loc, "Incorrectly structured array initializer");
3524 public bool CheckIndices (EmitContext ec, ArrayList probe, int idx, bool specified_dims)
3526 if (specified_dims) {
3527 Argument a = (Argument) Arguments [idx];
3529 if (!a.Resolve (ec, loc))
3532 if (!(a.Expr is Constant)) {
3533 Report.Error (150, loc, "A constant value is expected");
3537 int value = (int) ((Constant) a.Expr).GetValue ();
3539 if (value != probe.Count) {
3544 Bounds [idx] = value;
3547 foreach (object o in probe) {
3548 if (o is ArrayList) {
3549 bool ret = CheckIndices (ec, (ArrayList) o, idx + 1, specified_dims);
3553 Expression tmp = (Expression) o;
3554 tmp = tmp.Resolve (ec);
3558 // Handle initialization from vars, fields etc.
3560 Expression conv = ConvertImplicitRequired (
3561 ec, tmp, underlying_type, loc);
3566 if (conv is StringConstant)
3567 ArrayData.Add (conv);
3568 else if (conv is Constant)
3569 ArrayData.Add (((Constant) conv).GetValue ());
3571 ArrayData.Add (conv);
3578 public void UpdateIndices (EmitContext ec)
3581 for (ArrayList probe = Initializers; probe != null;) {
3583 if (probe [0] is ArrayList) {
3584 Expression e = new IntConstant (probe.Count);
3585 Arguments.Add (new Argument (e, Argument.AType.Expression));
3587 Bounds [i++] = probe.Count;
3589 probe = (ArrayList) probe [0];
3592 Expression e = new IntConstant (probe.Count);
3593 Arguments.Add (new Argument (e, Argument.AType.Expression));
3595 Bounds [i++] = probe.Count;
3602 public bool ValidateInitializers (EmitContext ec)
3604 if (Initializers == null) {
3605 if (ExpectInitializers)
3611 underlying_type = RootContext.LookupType (
3612 ec.TypeContainer, RequestedType, false, loc);
3615 // We use this to store all the date values in the order in which we
3616 // will need to store them in the byte blob later
3618 ArrayData = new ArrayList ();
3619 Bounds = new Hashtable ();
3623 if (Arguments != null) {
3624 ret = CheckIndices (ec, Initializers, 0, true);
3628 Arguments = new ArrayList ();
3630 ret = CheckIndices (ec, Initializers, 0, false);
3637 if (Arguments.Count != dimensions) {
3646 public override Expression DoResolve (EmitContext ec)
3650 if (!ValidateInitializers (ec))
3653 if (Arguments == null)
3656 arg_count = Arguments.Count;
3657 for (int i = arg_count; i > 0;){
3659 Argument a = (Argument) Arguments [i];
3661 if (!a.Resolve (ec, loc))
3666 string array_type = FormArrayType (RequestedType, arg_count, Rank);
3667 string element_type = FormElementType (RequestedType, arg_count, Rank);
3669 type = RootContext.LookupType (ec.TypeContainer, array_type, false, loc);
3671 array_element_type = RootContext.LookupType (
3672 ec.TypeContainer, element_type, false, loc);
3677 if (arg_count == 1) {
3678 IsOneDimensional = true;
3679 eclass = ExprClass.Value;
3683 IsBuiltinType = TypeManager.IsBuiltinType (type);
3685 if (IsBuiltinType) {
3689 ml = MemberLookup (ec, type, ".ctor", false, MemberTypes.Constructor,
3690 AllBindingsFlags, loc);
3692 if (!(ml is MethodGroupExpr)){
3693 report118 (loc, ml, "method group");
3698 Report.Error (-6, loc, "New invocation: Can not find a constructor for " +
3699 "this argument list");
3703 method = Invocation.OverloadResolve (ec, (MethodGroupExpr) ml, Arguments, loc);
3705 if (method == null) {
3706 Report.Error (-6, loc, "New invocation: Can not find a constructor for " +
3707 "this argument list");
3711 eclass = ExprClass.Value;
3715 ModuleBuilder mb = RootContext.ModuleBuilder;
3717 ArrayList args = new ArrayList ();
3718 if (Arguments != null){
3719 for (int i = arg_count; i > 0;){
3721 Argument a = (Argument) Arguments [i];
3727 Type [] arg_types = null;
3730 arg_types = new Type [args.Count];
3732 args.CopyTo (arg_types, 0);
3734 method = mb.GetArrayMethod (type, ".ctor", CallingConventions.HasThis, null,
3737 if (method == null) {
3738 Report.Error (-6, loc, "New invocation: Can not find a constructor for " +
3739 "this argument list");
3743 eclass = ExprClass.Value;
3749 public static byte [] MakeByteBlob (ArrayList ArrayData, Type underlying_type, Location loc)
3754 int count = ArrayData.Count;
3756 if (underlying_type == TypeManager.int32_type ||
3757 underlying_type == TypeManager.uint32_type ||
3758 underlying_type == TypeManager.float_type)
3760 else if (underlying_type == TypeManager.int64_type ||
3761 underlying_type == TypeManager.uint64_type ||
3762 underlying_type == TypeManager.double_type)
3764 else if (underlying_type == TypeManager.byte_type ||
3765 underlying_type == TypeManager.sbyte_type ||
3766 underlying_type == TypeManager.bool_type)
3768 else if (underlying_type == TypeManager.short_type ||
3769 underlying_type == TypeManager.char_type ||
3770 underlying_type == TypeManager.ushort_type)
3773 Report.Error (-100, loc, "Unhandled type in MakeByteBlob!!");
3777 data = new byte [count * factor];
3780 for (int i = 0; i < count; ++i) {
3781 object v = ArrayData [i];
3783 if (v is EnumConstant)
3784 v = ((EnumConstant) v).Child;
3786 if (underlying_type == TypeManager.int64_type ||
3787 underlying_type == TypeManager.uint64_type){
3789 if (!(v is Expression))
3792 for (int j = 0; j < factor; ++j) {
3793 data [idx + j] = (byte) (val & 0xFF);
3796 } else if (underlying_type == TypeManager.float_type) {
3802 if (!(v is Expression))
3805 byte *ptr = (byte *) &val;
3807 for (int j = 0; j < factor; ++j)
3808 data [idx + j] = (byte) ptr [j];
3811 } else if (underlying_type == TypeManager.double_type) {
3817 if (!(v is Expression))
3820 byte *ptr = (byte *) &val;
3822 for (int j = 0; j < factor; ++j)
3823 data [idx + j] = (byte) ptr [j];
3826 } else if (underlying_type == TypeManager.char_type){
3829 if (!(v is Expression))
3830 v = (int) ((char) v);
3832 data [idx] = (byte) (val & 0xff);
3833 data [idx+1] = (byte) (val >> 8);
3835 } else if (underlying_type == TypeManager.int32_type) {
3838 if (!(v is Expression))
3841 data [idx] = (byte) (val & 0xff);
3842 data [idx+1] = (byte) ((val >> 8) & 0xff);
3843 data [idx+2] = (byte) ((val >> 16) & 0xff);
3844 data [idx+3] = (byte) (val >> 24);
3846 throw new Exception ("Unrecognized type in MakeByteBlob");
3855 // Emits the initializers for the array
3857 void EmitStaticInitializers (EmitContext ec, bool is_expression)
3860 // First, the static data
3863 ILGenerator ig = ec.ig;
3865 byte [] data = MakeByteBlob (ArrayData, underlying_type, loc);
3868 fb = RootContext.MakeStaticData (data);
3871 ig.Emit (OpCodes.Dup);
3872 ig.Emit (OpCodes.Ldtoken, fb);
3873 ig.Emit (OpCodes.Call,
3874 TypeManager.void_initializearray_array_fieldhandle);
3879 // Emits pieces of the array that can not be computed at compile
3880 // time (variables and string locations).
3882 // This always expect the top value on the stack to be the array
3884 void EmitDynamicInitializers (EmitContext ec, bool is_expression)
3886 ILGenerator ig = ec.ig;
3887 int dims = Bounds.Count;
3888 int [] current_pos = new int [dims];
3889 int top = ArrayData.Count;
3890 LocalBuilder temp = ig.DeclareLocal (type);
3892 ig.Emit (OpCodes.Stloc, temp);
3894 MethodInfo set = null;
3898 ModuleBuilder mb = null;
3899 mb = RootContext.ModuleBuilder;
3900 args = new Type [dims + 1];
3903 for (j = 0; j < dims; j++)
3904 args [j] = TypeManager.int32_type;
3906 args [j] = array_element_type;
3908 set = mb.GetArrayMethod (
3910 CallingConventions.HasThis | CallingConventions.Standard,
3911 TypeManager.void_type, args);
3914 for (int i = 0; i < top; i++){
3916 Expression e = null;
3918 if (ArrayData [i] is Expression)
3919 e = (Expression) ArrayData [i];
3923 // Basically we do this for string literals and
3924 // other non-literal expressions
3926 if (e is StringConstant || !(e is Constant)) {
3928 ig.Emit (OpCodes.Ldloc, temp);
3930 for (int idx = dims; idx > 0; ) {
3932 IntConstant.EmitInt (ig, current_pos [idx]);
3938 ArrayAccess.EmitStoreOpcode (ig, array_element_type);
3940 ig.Emit (OpCodes.Call, set);
3948 for (int j = 0; j < dims; j++){
3950 if (current_pos [j] < (int) Bounds [j])
3952 current_pos [j] = 0;
3957 ig.Emit (OpCodes.Ldloc, temp);
3960 void DoEmit (EmitContext ec, bool is_statement)
3962 ILGenerator ig = ec.ig;
3964 if (IsOneDimensional) {
3965 Invocation.EmitArguments (ec, null, Arguments);
3966 ig.Emit (OpCodes.Newarr, array_element_type);
3969 Invocation.EmitArguments (ec, null, Arguments);
3972 ig.Emit (OpCodes.Newobj, (ConstructorInfo) method);
3974 ig.Emit (OpCodes.Newobj, (MethodInfo) method);
3977 if (Initializers != null){
3979 // FIXME: Set this variable correctly.
3981 bool dynamic_initializers = true;
3983 if (underlying_type != TypeManager.string_type &&
3984 underlying_type != TypeManager.object_type)
3985 EmitStaticInitializers (ec, dynamic_initializers || !is_statement);
3987 if (dynamic_initializers)
3988 EmitDynamicInitializers (ec, !is_statement);
3992 public override void Emit (EmitContext ec)
3997 public override void EmitStatement (EmitContext ec)
4005 /// Represents the `this' construct
4007 public class This : Expression, IAssignMethod, IMemoryLocation {
4010 public This (Location loc)
4015 public override Expression DoResolve (EmitContext ec)
4017 eclass = ExprClass.Variable;
4018 type = ec.TypeContainer.TypeBuilder;
4021 Report.Error (26, loc,
4022 "Keyword this not valid in static code");
4029 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
4033 if (ec.TypeContainer is Class){
4034 Report.Error (1604, loc, "Cannot assign to `this'");
4041 public override void Emit (EmitContext ec)
4043 ec.ig.Emit (OpCodes.Ldarg_0);
4046 public void EmitAssign (EmitContext ec, Expression source)
4049 ec.ig.Emit (OpCodes.Starg, 0);
4052 public void AddressOf (EmitContext ec)
4054 ec.ig.Emit (OpCodes.Ldarg_0);
4057 // FIGURE OUT WHY LDARG_S does not work
4059 // consider: struct X { int val; int P { set { val = value; }}}
4061 // Yes, this looks very bad. Look at `NOTAS' for
4063 // ec.ig.Emit (OpCodes.Ldarga_S, (byte) 0);
4068 /// Implements the typeof operator
4070 public class TypeOf : Expression {
4071 public readonly string QueriedType;
4075 public TypeOf (string queried_type, Location l)
4077 QueriedType = queried_type;
4081 public override Expression DoResolve (EmitContext ec)
4083 typearg = RootContext.LookupType (
4084 ec.TypeContainer, QueriedType, false, loc);
4086 if (typearg == null)
4089 type = TypeManager.type_type;
4090 eclass = ExprClass.Type;
4094 public override void Emit (EmitContext ec)
4096 ec.ig.Emit (OpCodes.Ldtoken, typearg);
4097 ec.ig.Emit (OpCodes.Call, TypeManager.system_type_get_type_from_handle);
4102 /// Implements the sizeof expression
4104 public class SizeOf : Expression {
4105 public readonly string QueriedType;
4107 public SizeOf (string queried_type)
4109 this.QueriedType = queried_type;
4112 public override Expression DoResolve (EmitContext ec)
4114 // FIXME: Implement;
4115 throw new Exception ("Unimplemented");
4119 public override void Emit (EmitContext ec)
4121 throw new Exception ("Implement me");
4126 /// Implements the member access expression
4128 public class MemberAccess : Expression {
4129 public readonly string Identifier;
4131 Expression member_lookup;
4134 public MemberAccess (Expression expr, string id, Location l)
4141 public Expression Expr {
4147 static void error176 (Location loc, string name)
4149 Report.Error (176, loc, "Static member `" +
4150 name + "' cannot be accessed " +
4151 "with an instance reference, qualify with a " +
4152 "type name instead");
4155 public static Expression ResolveMemberAccess (EmitContext ec, Expression member_lookup,
4156 Expression left, Location loc)
4161 if (member_lookup is MethodGroupExpr){
4162 MethodGroupExpr mg = (MethodGroupExpr) member_lookup;
4167 if (left is TypeExpr){
4168 if (!mg.RemoveInstanceMethods ()){
4169 SimpleName.Error120 (loc, mg.Methods [0].Name);
4173 return member_lookup;
4177 // Instance.MethodGroup
4179 if (!mg.RemoveStaticMethods ()){
4180 error176 (loc, mg.Methods [0].Name);
4184 mg.InstanceExpression = left;
4186 return member_lookup;
4189 if (member_lookup is FieldExpr){
4190 FieldExpr fe = (FieldExpr) member_lookup;
4191 FieldInfo fi = fe.FieldInfo;
4193 if (fi is FieldBuilder) {
4194 Const c = TypeManager.LookupConstant ((FieldBuilder) fi);
4197 object o = c.LookupConstantValue (ec);
4198 return Constantify (o, fi.FieldType);
4203 Type t = fi.FieldType;
4204 Type decl_type = fi.DeclaringType;
4207 if (fi is FieldBuilder)
4208 o = TypeManager.GetValue ((FieldBuilder) fi);
4210 o = fi.GetValue (fi);
4212 if (decl_type.IsSubclassOf (TypeManager.enum_type)) {
4213 Expression enum_member = MemberLookup (ec, decl_type, "value__",
4216 Enum en = TypeManager.LookupEnum (decl_type);
4220 c = Constantify (o, en.UnderlyingType);
4222 c = Constantify (o, enum_member.Type);
4224 return new EnumConstant (c, decl_type);
4227 Expression exp = Constantify (o, t);
4229 if (!(left is TypeExpr)) {
4230 error176 (loc, fe.FieldInfo.Name);
4237 if (left is TypeExpr){
4238 if (!fe.FieldInfo.IsStatic){
4239 error176 (loc, fe.FieldInfo.Name);
4242 return member_lookup;
4244 if (fe.FieldInfo.IsStatic){
4245 error176 (loc, fe.FieldInfo.Name);
4248 fe.InstanceExpression = left;
4254 if (member_lookup is PropertyExpr){
4255 PropertyExpr pe = (PropertyExpr) member_lookup;
4257 if (left is TypeExpr){
4259 SimpleName.Error120 (loc, pe.PropertyInfo.Name);
4265 error176 (loc, pe.PropertyInfo.Name);
4268 pe.InstanceExpression = left;
4274 if (member_lookup is EventExpr) {
4275 EventExpr ee = (EventExpr) member_lookup;
4277 if (left is TypeExpr) {
4279 SimpleName.Error120 (loc, ee.EventInfo.Name);
4287 error176 (loc, ee.EventInfo.Name);
4291 ee.InstanceExpression = left;
4297 if (member_lookup is TypeExpr){
4298 member_lookup.Resolve (ec);
4299 return member_lookup;
4302 Console.WriteLine ("Left is: " + left);
4303 Report.Error (-100, loc, "Support for [" + member_lookup + "] is not present yet");
4304 Environment.Exit (0);
4308 public override Expression DoResolve (EmitContext ec)
4311 // We are the sole users of ResolveWithSimpleName (ie, the only
4312 // ones that can cope with it
4314 expr = expr.ResolveWithSimpleName (ec);
4319 if (expr is SimpleName){
4320 SimpleName child_expr = (SimpleName) expr;
4322 expr = new SimpleName (child_expr.Name + "." + Identifier, loc);
4324 return expr.ResolveWithSimpleName (ec);
4328 // Handle enums here when they are in transit.
4329 // Note that we cannot afford to hit MemberLookup in this case because
4330 // it will fail to find any members at all
4333 Type expr_type = expr.Type;
4334 if (expr_type.IsSubclassOf (TypeManager.enum_type)) {
4336 Enum en = TypeManager.LookupEnum (expr_type);
4339 object value = en.LookupEnumValue (ec, Identifier, loc);
4344 Constant c = Constantify (value, en.UnderlyingType);
4345 return new EnumConstant (c, expr_type);
4349 member_lookup = MemberLookup (ec, expr.Type, Identifier, false, loc);
4351 if (member_lookup == null)
4354 return ResolveMemberAccess (ec, member_lookup, expr, loc);
4357 public override void Emit (EmitContext ec)
4359 throw new Exception ("Should not happen I think");
4364 /// Implements checked expressions
4366 public class CheckedExpr : Expression {
4368 public Expression Expr;
4370 public CheckedExpr (Expression e)
4375 public override Expression DoResolve (EmitContext ec)
4377 Expr = Expr.Resolve (ec);
4382 eclass = Expr.eclass;
4387 public override void Emit (EmitContext ec)
4389 bool last_check = ec.CheckState;
4391 ec.CheckState = true;
4393 ec.CheckState = last_check;
4399 /// Implements the unchecked expression
4401 public class UnCheckedExpr : Expression {
4403 public Expression Expr;
4405 public UnCheckedExpr (Expression e)
4410 public override Expression DoResolve (EmitContext ec)
4412 Expr = Expr.Resolve (ec);
4417 eclass = Expr.eclass;
4422 public override void Emit (EmitContext ec)
4424 bool last_check = ec.CheckState;
4426 ec.CheckState = false;
4428 ec.CheckState = last_check;
4434 /// An Element Access expression.
4436 /// During semantic analysis these are transformed into
4437 /// IndexerAccess or ArrayAccess
4439 public class ElementAccess : Expression {
4440 public ArrayList Arguments;
4441 public Expression Expr;
4442 public Location loc;
4444 public ElementAccess (Expression e, ArrayList e_list, Location l)
4453 Arguments = new ArrayList ();
4454 foreach (Expression tmp in e_list)
4455 Arguments.Add (new Argument (tmp, Argument.AType.Expression));
4459 bool CommonResolve (EmitContext ec)
4461 Expr = Expr.Resolve (ec);
4466 if (Arguments == null)
4469 for (int i = Arguments.Count; i > 0;){
4471 Argument a = (Argument) Arguments [i];
4473 if (!a.Resolve (ec, loc))
4480 public override Expression DoResolve (EmitContext ec)
4482 if (!CommonResolve (ec))
4486 // We perform some simple tests, and then to "split" the emit and store
4487 // code we create an instance of a different class, and return that.
4489 // I am experimenting with this pattern.
4491 if (Expr.Type.IsSubclassOf (TypeManager.array_type))
4492 return (new ArrayAccess (this)).Resolve (ec);
4494 return (new IndexerAccess (this)).Resolve (ec);
4497 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
4499 if (!CommonResolve (ec))
4502 if (Expr.Type.IsSubclassOf (TypeManager.array_type))
4503 return (new ArrayAccess (this)).ResolveLValue (ec, right_side);
4505 return (new IndexerAccess (this)).ResolveLValue (ec, right_side);
4508 public override void Emit (EmitContext ec)
4510 throw new Exception ("Should never be reached");
4515 /// Implements array access
4517 public class ArrayAccess : Expression, IAssignMethod {
4519 // Points to our "data" repository
4523 public ArrayAccess (ElementAccess ea_data)
4526 eclass = ExprClass.Variable;
4529 public override Expression DoResolve (EmitContext ec)
4531 if (ea.Expr.eclass != ExprClass.Variable) {
4532 report118 (ea.loc, ea.Expr, "variable");
4536 Type t = ea.Expr.Type;
4538 if (t.GetArrayRank () != ea.Arguments.Count){
4539 Report.Error (22, ea.loc,
4540 "Incorrect number of indexes for array " +
4541 " expected: " + t.GetArrayRank () + " got: " +
4542 ea.Arguments.Count);
4545 type = t.GetElementType ();
4546 eclass = ExprClass.Variable;
4552 /// Emits the right opcode to load an object of Type `t'
4553 /// from an array of T
4555 static public void EmitLoadOpcode (ILGenerator ig, Type type)
4557 if (type == TypeManager.byte_type)
4558 ig.Emit (OpCodes.Ldelem_I1);
4559 else if (type == TypeManager.sbyte_type)
4560 ig.Emit (OpCodes.Ldelem_U1);
4561 else if (type == TypeManager.short_type)
4562 ig.Emit (OpCodes.Ldelem_I2);
4563 else if (type == TypeManager.ushort_type)
4564 ig.Emit (OpCodes.Ldelem_U2);
4565 else if (type == TypeManager.int32_type)
4566 ig.Emit (OpCodes.Ldelem_I4);
4567 else if (type == TypeManager.uint32_type)
4568 ig.Emit (OpCodes.Ldelem_U4);
4569 else if (type == TypeManager.uint64_type)
4570 ig.Emit (OpCodes.Ldelem_I8);
4571 else if (type == TypeManager.int64_type)
4572 ig.Emit (OpCodes.Ldelem_I8);
4573 else if (type == TypeManager.float_type)
4574 ig.Emit (OpCodes.Ldelem_R4);
4575 else if (type == TypeManager.double_type)
4576 ig.Emit (OpCodes.Ldelem_R8);
4577 else if (type == TypeManager.intptr_type)
4578 ig.Emit (OpCodes.Ldelem_I);
4580 ig.Emit (OpCodes.Ldelem_Ref);
4584 /// Emits the right opcode to store an object of Type `t'
4585 /// from an array of T.
4587 static public void EmitStoreOpcode (ILGenerator ig, Type t)
4589 if (t == TypeManager.byte_type || t == TypeManager.sbyte_type)
4590 ig.Emit (OpCodes.Stelem_I1);
4591 else if (t == TypeManager.short_type || t == TypeManager.ushort_type)
4592 ig.Emit (OpCodes.Stelem_I2);
4593 else if (t == TypeManager.int32_type || t == TypeManager.uint32_type)
4594 ig.Emit (OpCodes.Stelem_I4);
4595 else if (t == TypeManager.int64_type || t == TypeManager.uint64_type)
4596 ig.Emit (OpCodes.Stelem_I8);
4597 else if (t == TypeManager.float_type)
4598 ig.Emit (OpCodes.Stelem_R4);
4599 else if (t == TypeManager.double_type)
4600 ig.Emit (OpCodes.Stelem_R8);
4601 else if (t == TypeManager.intptr_type)
4602 ig.Emit (OpCodes.Stelem_I);
4604 ig.Emit (OpCodes.Stelem_Ref);
4607 public override void Emit (EmitContext ec)
4609 int rank = ea.Expr.Type.GetArrayRank ();
4610 ILGenerator ig = ec.ig;
4614 foreach (Argument a in ea.Arguments)
4618 EmitLoadOpcode (ig, type);
4620 ModuleBuilder mb = RootContext.ModuleBuilder;
4621 Type [] args = new Type [ea.Arguments.Count];
4626 foreach (Argument a in ea.Arguments)
4627 args [i++] = a.Type;
4629 get = mb.GetArrayMethod (
4630 ea.Expr.Type, "Get",
4631 CallingConventions.HasThis |
4632 CallingConventions.Standard,
4635 ig.Emit (OpCodes.Call, get);
4639 public void EmitAssign (EmitContext ec, Expression source)
4641 int rank = ea.Expr.Type.GetArrayRank ();
4642 ILGenerator ig = ec.ig;
4646 foreach (Argument a in ea.Arguments)
4651 Type t = source.Type;
4654 EmitStoreOpcode (ig, t);
4656 ModuleBuilder mb = RootContext.ModuleBuilder;
4657 Type [] args = new Type [ea.Arguments.Count + 1];
4662 foreach (Argument a in ea.Arguments)
4663 args [i++] = a.Type;
4667 set = mb.GetArrayMethod (
4668 ea.Expr.Type, "Set",
4669 CallingConventions.HasThis |
4670 CallingConventions.Standard,
4671 TypeManager.void_type, args);
4673 ig.Emit (OpCodes.Call, set);
4680 public ArrayList getters, setters;
4681 static Hashtable map;
4685 map = new Hashtable ();
4688 Indexers (MemberInfo [] mi)
4690 foreach (PropertyInfo property in mi){
4691 MethodInfo get, set;
4693 get = property.GetGetMethod (true);
4695 if (getters == null)
4696 getters = new ArrayList ();
4701 set = property.GetSetMethod (true);
4703 if (setters == null)
4704 setters = new ArrayList ();
4710 static public Indexers GetIndexersForType (Type t, TypeManager tm, Location loc)
4712 Indexers ix = (Indexers) map [t];
4713 string p_name = TypeManager.IndexerPropertyName (t);
4718 MemberInfo [] mi = tm.FindMembers (
4719 t, MemberTypes.Property,
4720 BindingFlags.Public | BindingFlags.Instance,
4721 Type.FilterName, p_name);
4723 if (mi == null || mi.Length == 0){
4724 Report.Error (21, loc,
4725 "Type `" + TypeManager.CSharpName (t) + "' does not have " +
4726 "any indexers defined");
4730 ix = new Indexers (mi);
4738 /// Expressions that represent an indexer call.
4740 public class IndexerAccess : Expression, IAssignMethod {
4742 // Points to our "data" repository
4745 MethodInfo get, set;
4747 ArrayList set_arguments;
4749 public IndexerAccess (ElementAccess ea_data)
4752 eclass = ExprClass.Value;
4755 public override Expression DoResolve (EmitContext ec)
4757 Type indexer_type = ea.Expr.Type;
4760 // Step 1: Query for all `Item' *properties*. Notice
4761 // that the actual methods are pointed from here.
4763 // This is a group of properties, piles of them.
4766 ilist = Indexers.GetIndexersForType (
4767 indexer_type, RootContext.TypeManager, ea.loc);
4771 // Step 2: find the proper match
4773 if (ilist != null && ilist.getters != null && ilist.getters.Count > 0)
4774 get = (MethodInfo) Invocation.OverloadResolve (
4775 ec, new MethodGroupExpr (ilist.getters), ea.Arguments, ea.loc);
4778 Report.Error (154, ea.loc,
4779 "indexer can not be used in this context, because " +
4780 "it lacks a `get' accessor");
4784 type = get.ReturnType;
4785 eclass = ExprClass.IndexerAccess;
4789 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
4791 Type indexer_type = ea.Expr.Type;
4792 Type right_type = right_side.Type;
4795 ilist = Indexers.GetIndexersForType (
4796 indexer_type, RootContext.TypeManager, ea.loc);
4798 if (ilist != null && ilist.setters != null && ilist.setters.Count > 0){
4799 set_arguments = (ArrayList) ea.Arguments.Clone ();
4800 set_arguments.Add (new Argument (right_side, Argument.AType.Expression));
4802 set = (MethodInfo) Invocation.OverloadResolve (
4803 ec, new MethodGroupExpr (ilist.setters), set_arguments, ea.loc);
4807 Report.Error (200, ea.loc,
4808 "indexer X.this [" + TypeManager.CSharpName (right_type) +
4809 "] lacks a `set' accessor");
4813 type = TypeManager.void_type;
4814 eclass = ExprClass.IndexerAccess;
4818 public override void Emit (EmitContext ec)
4820 Invocation.EmitCall (ec, false, ea.Expr, get, ea.Arguments);
4824 // source is ignored, because we already have a copy of it from the
4825 // LValue resolution and we have already constructed a pre-cached
4826 // version of the arguments (ea.set_arguments);
4828 public void EmitAssign (EmitContext ec, Expression source)
4830 Invocation.EmitCall (ec, false, ea.Expr, set, set_arguments);
4835 /// The base operator for method names
4837 public class BaseAccess : Expression {
4841 public BaseAccess (string member, Location l)
4843 this.member = member;
4847 public override Expression DoResolve (EmitContext ec)
4849 Expression member_lookup;
4850 Type current_type = ec.TypeContainer.TypeBuilder;
4851 Type base_type = current_type.BaseType;
4853 member_lookup = MemberLookup (ec, base_type, member, false, loc);
4854 if (member_lookup == null)
4860 left = new TypeExpr (base_type);
4862 left = new This (loc).Resolve (ec);
4864 return MemberAccess.ResolveMemberAccess (ec, member_lookup, left, loc);
4867 public override void Emit (EmitContext ec)
4869 throw new Exception ("Should never be called");
4874 /// The base indexer operator
4876 public class BaseIndexerAccess : Expression {
4877 ArrayList Arguments;
4879 public BaseIndexerAccess (ArrayList args)
4884 public override Expression DoResolve (EmitContext ec)
4886 // FIXME: Implement;
4887 throw new Exception ("Unimplemented");
4891 public override void Emit (EmitContext ec)
4893 throw new Exception ("Unimplemented");
4898 /// This class exists solely to pass the Type around and to be a dummy
4899 /// that can be passed to the conversion functions (this is used by
4900 /// foreach implementation to typecast the object return value from
4901 /// get_Current into the proper type. All code has been generated and
4902 /// we only care about the side effect conversions to be performed
4904 public class EmptyExpression : Expression {
4905 public EmptyExpression ()
4907 type = TypeManager.object_type;
4908 eclass = ExprClass.Value;
4911 public EmptyExpression (Type t)
4914 eclass = ExprClass.Value;
4917 public override Expression DoResolve (EmitContext ec)
4922 public override void Emit (EmitContext ec)
4924 // nothing, as we only exist to not do anything.
4928 // This is just because we might want to reuse this bad boy
4929 // instead of creating gazillions of EmptyExpressions.
4930 // (CanConvertImplicit uses it)
4932 public void SetType (Type t)
4938 public class UserCast : Expression {
4942 public UserCast (MethodInfo method, Expression source)
4944 this.method = method;
4945 this.source = source;
4946 type = method.ReturnType;
4947 eclass = ExprClass.Value;
4950 public override Expression DoResolve (EmitContext ec)
4953 // We are born fully resolved
4958 public override void Emit (EmitContext ec)
4960 ILGenerator ig = ec.ig;
4964 if (method is MethodInfo)
4965 ig.Emit (OpCodes.Call, (MethodInfo) method);
4967 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
4974 // This class is used to "construct" the type during a typecast
4975 // operation. Since the Type.GetType class in .NET can parse
4976 // the type specification, we just use this to construct the type
4977 // one bit at a time.
4979 public class ComposedCast : Expression {
4984 public ComposedCast (Expression left, string dim, Location l)
4991 public override Expression DoResolve (EmitContext ec)
4993 left = left.Resolve (ec);
4997 if (left.eclass != ExprClass.Type){
4998 report118 (loc, left, "type");
5002 type = RootContext.LookupType (
5003 ec.TypeContainer, left.Type.FullName + dim, false, loc);
5007 eclass = ExprClass.Type;
5011 public override void Emit (EmitContext ec)
5013 throw new Exception ("This should never be called");