2 // expression.cs: Expression representation for the IL tree.
5 // Miguel de Icaza (miguel@ximian.com)
7 // (C) 2001 Ximian, Inc.
12 namespace Mono.CSharp {
14 using System.Collections;
15 using System.Diagnostics;
16 using System.Reflection;
17 using System.Reflection.Emit;
21 /// This is just a helper class, it is generated by Unary, UnaryMutator
22 /// when an overloaded method has been found. It just emits the code for a
25 public class StaticCallExpr : ExpressionStatement {
29 StaticCallExpr (MethodInfo m, ArrayList a)
35 eclass = ExprClass.Value;
38 public override Expression DoResolve (EmitContext ec)
41 // We are born fully resolved
46 public override void Emit (EmitContext ec)
49 Invocation.EmitArguments (ec, mi, args);
51 ec.ig.Emit (OpCodes.Call, mi);
55 static public Expression MakeSimpleCall (EmitContext ec, MethodGroupExpr mg,
56 Expression e, Location loc)
61 args = new ArrayList (1);
62 args.Add (new Argument (e, Argument.AType.Expression));
63 method = Invocation.OverloadResolve (ec, (MethodGroupExpr) mg, args, loc);
68 return new StaticCallExpr ((MethodInfo) method, args);
71 public override void EmitStatement (EmitContext ec)
74 if (type != TypeManager.void_type)
75 ec.ig.Emit (OpCodes.Pop);
80 /// Unary expressions.
84 /// Unary implements unary expressions. It derives from
85 /// ExpressionStatement becuase the pre/post increment/decrement
86 /// operators can be used in a statement context.
88 public class Unary : Expression {
89 public enum Operator : byte {
90 UnaryPlus, UnaryNegation, LogicalNot, OnesComplement,
91 Indirection, AddressOf, TOP
98 public Unary (Operator op, Expression expr, Location loc)
105 public Expression Expr {
115 public Operator Oper {
126 /// Returns a stringified representation of the Operator
131 case Operator.UnaryPlus:
133 case Operator.UnaryNegation:
135 case Operator.LogicalNot:
137 case Operator.OnesComplement:
139 case Operator.AddressOf:
141 case Operator.Indirection:
145 return oper.ToString ();
148 static string [] oper_names;
152 oper_names = new string [(int)Operator.TOP];
154 oper_names [(int) Operator.UnaryPlus] = "op_UnaryPlus";
155 oper_names [(int) Operator.UnaryNegation] = "op_UnaryNegation";
156 oper_names [(int) Operator.LogicalNot] = "op_LogicalNot";
157 oper_names [(int) Operator.OnesComplement] = "op_OnesComplement";
158 oper_names [(int) Operator.Indirection] = "op_Indirection";
159 oper_names [(int) Operator.AddressOf] = "op_AddressOf";
162 void error23 (Type t)
165 23, loc, "Operator " + OperName () +
166 " cannot be applied to operand of type `" +
167 TypeManager.CSharpName (t) + "'");
171 /// The result has been already resolved:
173 /// FIXME: a minus constant -128 sbyte cant be turned into a
176 static Expression TryReduceNegative (Expression expr)
180 if (expr is IntConstant)
181 e = new IntConstant (-((IntConstant) expr).Value);
182 else if (expr is UIntConstant)
183 e = new LongConstant (-((UIntConstant) expr).Value);
184 else if (expr is LongConstant)
185 e = new LongConstant (-((LongConstant) expr).Value);
186 else if (expr is FloatConstant)
187 e = new FloatConstant (-((FloatConstant) expr).Value);
188 else if (expr is DoubleConstant)
189 e = new DoubleConstant (-((DoubleConstant) expr).Value);
190 else if (expr is DecimalConstant)
191 e = new DecimalConstant (-((DecimalConstant) expr).Value);
192 else if (expr is ShortConstant)
193 e = new IntConstant (-((ShortConstant) expr).Value);
194 else if (expr is UShortConstant)
195 e = new IntConstant (-((UShortConstant) expr).Value);
200 Expression Reduce (EmitContext ec, Expression e)
202 Type expr_type = e.Type;
205 case Operator.UnaryPlus:
208 case Operator.UnaryNegation:
209 return TryReduceNegative (e);
211 case Operator.LogicalNot:
212 if (expr_type != TypeManager.bool_type) {
217 BoolConstant b = (BoolConstant) e;
218 return new BoolConstant (!(b.Value));
220 case Operator.OnesComplement:
221 if (!((expr_type == TypeManager.int32_type) ||
222 (expr_type == TypeManager.uint32_type) ||
223 (expr_type == TypeManager.int64_type) ||
224 (expr_type == TypeManager.uint64_type) ||
225 (expr_type.IsSubclassOf (TypeManager.enum_type)))){
230 if (e is EnumConstant){
231 EnumConstant enum_constant = (EnumConstant) e;
233 Expression reduced = Reduce (ec, enum_constant.Child);
235 return new EnumConstant ((Constant) reduced, enum_constant.Type);
238 if (expr_type == TypeManager.int32_type)
239 return new IntConstant (~ ((IntConstant) e).Value);
240 if (expr_type == TypeManager.uint32_type)
241 return new UIntConstant (~ ((UIntConstant) e).Value);
242 if (expr_type == TypeManager.int64_type)
243 return new LongConstant (~ ((LongConstant) e).Value);
244 if (expr_type == TypeManager.uint64_type)
245 return new ULongConstant (~ ((ULongConstant) e).Value);
247 throw new Exception (
248 "FIXME: Implement constant OnesComplement of:" +
251 throw new Exception ("Can not constant fold");
254 Expression ResolveOperator (EmitContext ec)
256 Type expr_type = expr.Type;
259 // Step 1: Perform Operator Overload location
264 op_name = oper_names [(int) oper];
266 mg = MemberLookup (ec, expr_type, op_name, false, loc);
268 if (mg == null && expr_type.BaseType != null)
269 mg = MemberLookup (ec, expr_type.BaseType, op_name, false, loc);
272 Expression e = StaticCallExpr.MakeSimpleCall (
273 ec, (MethodGroupExpr) mg, expr, loc);
283 // Only perform numeric promotions on:
286 if (expr_type == null)
290 // Step 2: Default operations on CLI native types.
292 if (expr is Constant)
293 return Reduce (ec, expr);
295 if (oper == Operator.LogicalNot){
296 if (expr_type != TypeManager.bool_type) {
301 type = TypeManager.bool_type;
305 if (oper == Operator.OnesComplement) {
306 if (!((expr_type == TypeManager.int32_type) ||
307 (expr_type == TypeManager.uint32_type) ||
308 (expr_type == TypeManager.int64_type) ||
309 (expr_type == TypeManager.uint64_type) ||
310 (expr_type.IsSubclassOf (TypeManager.enum_type)))){
318 if (oper == Operator.UnaryPlus) {
320 // A plus in front of something is just a no-op, so return the child.
326 // Deals with -literals
327 // int operator- (int x)
328 // long operator- (long x)
329 // float operator- (float f)
330 // double operator- (double d)
331 // decimal operator- (decimal d)
333 if (oper == Operator.UnaryNegation){
335 // Fold a "- Constant" into a negative constant
341 // Not a constant we can optimize, perform numeric
342 // promotions to int, long, double.
345 // The following is inneficient, because we call
346 // ConvertImplicit too many times.
348 // It is also not clear if we should convert to Float
349 // or Double initially.
351 if (expr_type == TypeManager.uint32_type){
353 // FIXME: handle exception to this rule that
354 // permits the int value -2147483648 (-2^31) to
355 // bt wrote as a decimal interger literal
357 type = TypeManager.int64_type;
358 expr = ConvertImplicit (ec, expr, type, loc);
362 if (expr_type == TypeManager.uint64_type){
364 // FIXME: Handle exception of `long value'
365 // -92233720368547758087 (-2^63) to be wrote as
366 // decimal integer literal.
372 e = ConvertImplicit (ec, expr, TypeManager.int32_type, loc);
379 e = ConvertImplicit (ec, expr, TypeManager.int64_type, loc);
386 e = ConvertImplicit (ec, expr, TypeManager.double_type, loc);
397 if (oper == Operator.AddressOf){
398 if (expr.eclass != ExprClass.Variable){
399 Error (211, loc, "Cannot take the address of non-variables");
402 type = Type.GetType (expr.Type.ToString () + "*");
407 Error (187, loc, "No such operator '" + OperName () + "' defined for type '" +
408 TypeManager.CSharpName (expr_type) + "'");
412 public override Expression DoResolve (EmitContext ec)
414 expr = expr.Resolve (ec);
419 eclass = ExprClass.Value;
420 return ResolveOperator (ec);
423 public override void Emit (EmitContext ec)
425 ILGenerator ig = ec.ig;
426 Type expr_type = expr.Type;
429 case Operator.UnaryPlus:
430 throw new Exception ("This should be caught by Resolve");
432 case Operator.UnaryNegation:
434 ig.Emit (OpCodes.Neg);
437 case Operator.LogicalNot:
439 ig.Emit (OpCodes.Ldc_I4_0);
440 ig.Emit (OpCodes.Ceq);
443 case Operator.OnesComplement:
445 ig.Emit (OpCodes.Not);
448 case Operator.AddressOf:
449 ((IMemoryLocation)expr).AddressOf (ec);
452 case Operator.Indirection:
453 throw new Exception ("Not implemented yet");
456 throw new Exception ("This should not happen: Operator = "
462 /// This will emit the child expression for `ec' avoiding the logical
463 /// not. The parent will take care of changing brfalse/brtrue
465 public void EmitLogicalNot (EmitContext ec)
467 if (oper != Operator.LogicalNot)
468 throw new Exception ("EmitLogicalNot can only be called with !expr");
476 /// Unary Mutator expressions (pre and post ++ and --)
480 /// UnaryMutator implements ++ and -- expressions. It derives from
481 /// ExpressionStatement becuase the pre/post increment/decrement
482 /// operators can be used in a statement context.
484 /// FIXME: Idea, we could split this up in two classes, one simpler
485 /// for the common case, and one with the extra fields for more complex
486 /// classes (indexers require temporary access; overloaded require method)
488 /// Maybe we should have classes PreIncrement, PostIncrement, PreDecrement,
489 /// PostDecrement, that way we could save the `Mode' byte as well.
491 public class UnaryMutator : ExpressionStatement {
492 public enum Mode : byte {
493 PreIncrement, PreDecrement, PostIncrement, PostDecrement
499 LocalTemporary temp_storage;
502 // This is expensive for the simplest case.
506 public UnaryMutator (Mode m, Expression e, Location l)
515 return (mode == Mode.PreIncrement || mode == Mode.PostIncrement) ?
519 void error23 (Type t)
522 23, loc, "Operator " + OperName () +
523 " cannot be applied to operand of type `" +
524 TypeManager.CSharpName (t) + "'");
528 /// Returns whether an object of type `t' can be incremented
529 /// or decremented with add/sub (ie, basically whether we can
530 /// use pre-post incr-decr operations on it, but it is not a
531 /// System.Decimal, which we require operator overloading to catch)
533 static bool IsIncrementableNumber (Type t)
535 return (t == TypeManager.sbyte_type) ||
536 (t == TypeManager.byte_type) ||
537 (t == TypeManager.short_type) ||
538 (t == TypeManager.ushort_type) ||
539 (t == TypeManager.int32_type) ||
540 (t == TypeManager.uint32_type) ||
541 (t == TypeManager.int64_type) ||
542 (t == TypeManager.uint64_type) ||
543 (t == TypeManager.char_type) ||
544 (t.IsSubclassOf (TypeManager.enum_type)) ||
545 (t == TypeManager.float_type) ||
546 (t == TypeManager.double_type);
549 Expression ResolveOperator (EmitContext ec)
551 Type expr_type = expr.Type;
554 // Step 1: Perform Operator Overload location
559 if (mode == Mode.PreIncrement || mode == Mode.PostIncrement)
560 op_name = "op_Increment";
562 op_name = "op_Decrement";
564 mg = MemberLookup (ec, expr_type, op_name, false, loc);
566 if (mg == null && expr_type.BaseType != null)
567 mg = MemberLookup (ec, expr_type.BaseType, op_name, false, loc);
570 method = StaticCallExpr.MakeSimpleCall (
571 ec, (MethodGroupExpr) mg, expr, loc);
578 // The operand of the prefix/postfix increment decrement operators
579 // should be an expression that is classified as a variable,
580 // a property access or an indexer access
583 if (expr.eclass == ExprClass.Variable){
584 if (IsIncrementableNumber (expr_type) ||
585 expr_type == TypeManager.decimal_type){
588 } else if (expr.eclass == ExprClass.IndexerAccess){
589 IndexerAccess ia = (IndexerAccess) expr;
591 temp_storage = new LocalTemporary (ec, expr.Type);
593 expr = ia.ResolveLValue (ec, temp_storage);
598 } else if (expr.eclass == ExprClass.PropertyAccess){
599 PropertyExpr pe = (PropertyExpr) expr;
601 if (pe.VerifyAssignable ())
606 report118 (loc, expr, "variable, indexer or property access");
610 Error (187, loc, "No such operator '" + OperName () + "' defined for type '" +
611 TypeManager.CSharpName (expr_type) + "'");
615 public override Expression DoResolve (EmitContext ec)
617 expr = expr.Resolve (ec);
622 eclass = ExprClass.Value;
623 return ResolveOperator (ec);
628 // FIXME: We need some way of avoiding the use of temp_storage
629 // for some types of storage (parameters, local variables,
630 // static fields) and single-dimension array access.
632 void EmitCode (EmitContext ec, bool is_expr)
634 ILGenerator ig = ec.ig;
635 IAssignMethod ia = (IAssignMethod) expr;
637 if (temp_storage == null)
638 temp_storage = new LocalTemporary (ec, expr.Type);
641 case Mode.PreIncrement:
642 case Mode.PreDecrement:
646 ig.Emit (OpCodes.Ldc_I4_1);
648 if (mode == Mode.PreDecrement)
649 ig.Emit (OpCodes.Sub);
651 ig.Emit (OpCodes.Add);
655 temp_storage.Store (ec);
656 ia.EmitAssign (ec, temp_storage);
658 temp_storage.Emit (ec);
661 case Mode.PostIncrement:
662 case Mode.PostDecrement:
670 ig.Emit (OpCodes.Dup);
672 ig.Emit (OpCodes.Ldc_I4_1);
674 if (mode == Mode.PostDecrement)
675 ig.Emit (OpCodes.Sub);
677 ig.Emit (OpCodes.Add);
682 temp_storage.Store (ec);
683 ia.EmitAssign (ec, temp_storage);
688 public override void Emit (EmitContext ec)
694 public override void EmitStatement (EmitContext ec)
696 EmitCode (ec, false);
702 /// Base class for the `Is' and `As' classes.
706 /// FIXME: Split this in two, and we get to save the `Operator' Oper
709 public abstract class Probe : Expression {
710 public readonly string ProbeType;
711 protected Expression expr;
712 protected Type probe_type;
715 public Probe (Expression expr, string probe_type, Location l)
717 ProbeType = probe_type;
722 public Expression Expr {
728 public override Expression DoResolve (EmitContext ec)
730 probe_type = RootContext.LookupType (ec.TypeContainer, ProbeType, false, loc);
732 if (probe_type == null)
735 expr = expr.Resolve (ec);
742 /// Implementation of the `is' operator.
744 public class Is : Probe {
745 public Is (Expression expr, string probe_type, Location l)
746 : base (expr, probe_type, l)
750 public override void Emit (EmitContext ec)
752 ILGenerator ig = ec.ig;
756 ig.Emit (OpCodes.Isinst, probe_type);
757 ig.Emit (OpCodes.Ldnull);
758 ig.Emit (OpCodes.Cgt_Un);
761 public override Expression DoResolve (EmitContext ec)
763 Expression e = base.DoResolve (ec);
768 type = TypeManager.bool_type;
769 eclass = ExprClass.Value;
776 /// Implementation of the `as' operator.
778 public class As : Probe {
779 public As (Expression expr, string probe_type, Location l)
780 : base (expr, probe_type, l)
784 public override void Emit (EmitContext ec)
786 ILGenerator ig = ec.ig;
789 ig.Emit (OpCodes.Isinst, probe_type);
792 public override Expression DoResolve (EmitContext ec)
794 Expression e = base.DoResolve (ec);
800 eclass = ExprClass.Value;
807 /// This represents a typecast in the source language.
809 /// FIXME: Cast expressions have an unusual set of parsing
810 /// rules, we need to figure those out.
812 public class Cast : Expression {
813 Expression target_type;
817 public Cast (Expression cast_type, Expression expr, Location loc)
819 this.target_type = cast_type;
824 public Expression TargetType {
830 public Expression Expr {
840 /// Attempts to do a compile-time folding of a constant cast.
842 Expression TryReduce (EmitContext ec, Type target_type)
844 if (expr is ByteConstant){
845 byte v = ((ByteConstant) expr).Value;
847 if (target_type == TypeManager.sbyte_type)
848 return new SByteConstant ((sbyte) v);
849 if (target_type == TypeManager.short_type)
850 return new ShortConstant ((short) v);
851 if (target_type == TypeManager.ushort_type)
852 return new UShortConstant ((ushort) v);
853 if (target_type == TypeManager.int32_type)
854 return new IntConstant ((int) v);
855 if (target_type == TypeManager.uint32_type)
856 return new UIntConstant ((uint) v);
857 if (target_type == TypeManager.int64_type)
858 return new LongConstant ((long) v);
859 if (target_type == TypeManager.uint64_type)
860 return new ULongConstant ((ulong) v);
861 if (target_type == TypeManager.float_type)
862 return new FloatConstant ((float) v);
863 if (target_type == TypeManager.double_type)
864 return new DoubleConstant ((double) v);
866 if (expr is SByteConstant){
867 sbyte v = ((SByteConstant) expr).Value;
869 if (target_type == TypeManager.byte_type)
870 return new ByteConstant ((byte) v);
871 if (target_type == TypeManager.short_type)
872 return new ShortConstant ((short) v);
873 if (target_type == TypeManager.ushort_type)
874 return new UShortConstant ((ushort) v);
875 if (target_type == TypeManager.int32_type)
876 return new IntConstant ((int) v);
877 if (target_type == TypeManager.uint32_type)
878 return new UIntConstant ((uint) v);
879 if (target_type == TypeManager.int64_type)
880 return new LongConstant ((long) v);
881 if (target_type == TypeManager.uint64_type)
882 return new ULongConstant ((ulong) v);
883 if (target_type == TypeManager.float_type)
884 return new FloatConstant ((float) v);
885 if (target_type == TypeManager.double_type)
886 return new DoubleConstant ((double) v);
888 if (expr is ShortConstant){
889 short v = ((ShortConstant) expr).Value;
891 if (target_type == TypeManager.byte_type)
892 return new ByteConstant ((byte) v);
893 if (target_type == TypeManager.sbyte_type)
894 return new SByteConstant ((sbyte) v);
895 if (target_type == TypeManager.ushort_type)
896 return new UShortConstant ((ushort) v);
897 if (target_type == TypeManager.int32_type)
898 return new IntConstant ((int) v);
899 if (target_type == TypeManager.uint32_type)
900 return new UIntConstant ((uint) v);
901 if (target_type == TypeManager.int64_type)
902 return new LongConstant ((long) v);
903 if (target_type == TypeManager.uint64_type)
904 return new ULongConstant ((ulong) v);
905 if (target_type == TypeManager.float_type)
906 return new FloatConstant ((float) v);
907 if (target_type == TypeManager.double_type)
908 return new DoubleConstant ((double) v);
910 if (expr is UShortConstant){
911 ushort v = ((UShortConstant) expr).Value;
913 if (target_type == TypeManager.byte_type)
914 return new ByteConstant ((byte) v);
915 if (target_type == TypeManager.sbyte_type)
916 return new SByteConstant ((sbyte) v);
917 if (target_type == TypeManager.short_type)
918 return new ShortConstant ((short) v);
919 if (target_type == TypeManager.int32_type)
920 return new IntConstant ((int) v);
921 if (target_type == TypeManager.uint32_type)
922 return new UIntConstant ((uint) v);
923 if (target_type == TypeManager.int64_type)
924 return new LongConstant ((long) v);
925 if (target_type == TypeManager.uint64_type)
926 return new ULongConstant ((ulong) v);
927 if (target_type == TypeManager.float_type)
928 return new FloatConstant ((float) v);
929 if (target_type == TypeManager.double_type)
930 return new DoubleConstant ((double) v);
932 if (expr is IntConstant){
933 int v = ((IntConstant) expr).Value;
935 if (target_type == TypeManager.byte_type)
936 return new ByteConstant ((byte) v);
937 if (target_type == TypeManager.sbyte_type)
938 return new SByteConstant ((sbyte) v);
939 if (target_type == TypeManager.short_type)
940 return new ShortConstant ((short) v);
941 if (target_type == TypeManager.ushort_type)
942 return new UShortConstant ((ushort) v);
943 if (target_type == TypeManager.uint32_type)
944 return new UIntConstant ((uint) v);
945 if (target_type == TypeManager.int64_type)
946 return new LongConstant ((long) v);
947 if (target_type == TypeManager.uint64_type)
948 return new ULongConstant ((ulong) v);
949 if (target_type == TypeManager.float_type)
950 return new FloatConstant ((float) v);
951 if (target_type == TypeManager.double_type)
952 return new DoubleConstant ((double) v);
954 if (expr is UIntConstant){
955 uint v = ((UIntConstant) expr).Value;
957 if (target_type == TypeManager.byte_type)
958 return new ByteConstant ((byte) v);
959 if (target_type == TypeManager.sbyte_type)
960 return new SByteConstant ((sbyte) v);
961 if (target_type == TypeManager.short_type)
962 return new ShortConstant ((short) v);
963 if (target_type == TypeManager.ushort_type)
964 return new UShortConstant ((ushort) v);
965 if (target_type == TypeManager.int32_type)
966 return new IntConstant ((int) v);
967 if (target_type == TypeManager.int64_type)
968 return new LongConstant ((long) v);
969 if (target_type == TypeManager.uint64_type)
970 return new ULongConstant ((ulong) v);
971 if (target_type == TypeManager.float_type)
972 return new FloatConstant ((float) v);
973 if (target_type == TypeManager.double_type)
974 return new DoubleConstant ((double) v);
976 if (expr is LongConstant){
977 long v = ((LongConstant) expr).Value;
979 if (target_type == TypeManager.byte_type)
980 return new ByteConstant ((byte) v);
981 if (target_type == TypeManager.sbyte_type)
982 return new SByteConstant ((sbyte) v);
983 if (target_type == TypeManager.short_type)
984 return new ShortConstant ((short) v);
985 if (target_type == TypeManager.ushort_type)
986 return new UShortConstant ((ushort) v);
987 if (target_type == TypeManager.int32_type)
988 return new IntConstant ((int) v);
989 if (target_type == TypeManager.uint32_type)
990 return new UIntConstant ((uint) v);
991 if (target_type == TypeManager.uint64_type)
992 return new ULongConstant ((ulong) v);
993 if (target_type == TypeManager.float_type)
994 return new FloatConstant ((float) v);
995 if (target_type == TypeManager.double_type)
996 return new DoubleConstant ((double) v);
998 if (expr is ULongConstant){
999 ulong v = ((ULongConstant) expr).Value;
1001 if (target_type == TypeManager.byte_type)
1002 return new ByteConstant ((byte) v);
1003 if (target_type == TypeManager.sbyte_type)
1004 return new SByteConstant ((sbyte) v);
1005 if (target_type == TypeManager.short_type)
1006 return new ShortConstant ((short) v);
1007 if (target_type == TypeManager.ushort_type)
1008 return new UShortConstant ((ushort) v);
1009 if (target_type == TypeManager.int32_type)
1010 return new IntConstant ((int) v);
1011 if (target_type == TypeManager.uint32_type)
1012 return new UIntConstant ((uint) v);
1013 if (target_type == TypeManager.int64_type)
1014 return new LongConstant ((long) v);
1015 if (target_type == TypeManager.float_type)
1016 return new FloatConstant ((float) v);
1017 if (target_type == TypeManager.double_type)
1018 return new DoubleConstant ((double) v);
1020 if (expr is FloatConstant){
1021 float v = ((FloatConstant) expr).Value;
1023 if (target_type == TypeManager.byte_type)
1024 return new ByteConstant ((byte) v);
1025 if (target_type == TypeManager.sbyte_type)
1026 return new SByteConstant ((sbyte) v);
1027 if (target_type == TypeManager.short_type)
1028 return new ShortConstant ((short) v);
1029 if (target_type == TypeManager.ushort_type)
1030 return new UShortConstant ((ushort) v);
1031 if (target_type == TypeManager.int32_type)
1032 return new IntConstant ((int) v);
1033 if (target_type == TypeManager.uint32_type)
1034 return new UIntConstant ((uint) v);
1035 if (target_type == TypeManager.int64_type)
1036 return new LongConstant ((long) v);
1037 if (target_type == TypeManager.uint64_type)
1038 return new ULongConstant ((ulong) v);
1039 if (target_type == TypeManager.double_type)
1040 return new DoubleConstant ((double) v);
1042 if (expr is DoubleConstant){
1043 double v = ((DoubleConstant) expr).Value;
1045 if (target_type == TypeManager.byte_type)
1046 return new ByteConstant ((byte) v);
1047 if (target_type == TypeManager.sbyte_type)
1048 return new SByteConstant ((sbyte) v);
1049 if (target_type == TypeManager.short_type)
1050 return new ShortConstant ((short) v);
1051 if (target_type == TypeManager.ushort_type)
1052 return new UShortConstant ((ushort) v);
1053 if (target_type == TypeManager.int32_type)
1054 return new IntConstant ((int) v);
1055 if (target_type == TypeManager.uint32_type)
1056 return new UIntConstant ((uint) v);
1057 if (target_type == TypeManager.int64_type)
1058 return new LongConstant ((long) v);
1059 if (target_type == TypeManager.uint64_type)
1060 return new ULongConstant ((ulong) v);
1061 if (target_type == TypeManager.float_type)
1062 return new FloatConstant ((float) v);
1068 public override Expression DoResolve (EmitContext ec)
1070 expr = expr.Resolve (ec);
1074 target_type = target_type.Resolve (ec);
1075 if (target_type == null)
1078 if (target_type.eclass != ExprClass.Type){
1079 report118 (loc, target_type, "class");
1083 type = target_type.Type;
1084 eclass = ExprClass.Value;
1089 if (expr is Constant){
1090 Expression e = TryReduce (ec, type);
1096 expr = ConvertExplicit (ec, expr, type, loc);
1100 public override void Emit (EmitContext ec)
1103 // This one will never happen
1105 throw new Exception ("Should not happen");
1110 /// Binary operators
1112 public class Binary : Expression {
1113 public enum Operator : byte {
1114 Multiply, Division, Modulus,
1115 Addition, Subtraction,
1116 LeftShift, RightShift,
1117 LessThan, GreaterThan, LessThanOrEqual, GreaterThanOrEqual,
1118 Equality, Inequality,
1127 Expression left, right;
1129 ArrayList Arguments;
1132 bool DelegateOperation;
1134 public Binary (Operator oper, Expression left, Expression right, Location loc)
1142 public Operator Oper {
1151 public Expression Left {
1160 public Expression Right {
1171 /// Returns a stringified representation of the Operator
1176 case Operator.Multiply:
1178 case Operator.Division:
1180 case Operator.Modulus:
1182 case Operator.Addition:
1184 case Operator.Subtraction:
1186 case Operator.LeftShift:
1188 case Operator.RightShift:
1190 case Operator.LessThan:
1192 case Operator.GreaterThan:
1194 case Operator.LessThanOrEqual:
1196 case Operator.GreaterThanOrEqual:
1198 case Operator.Equality:
1200 case Operator.Inequality:
1202 case Operator.BitwiseAnd:
1204 case Operator.BitwiseOr:
1206 case Operator.ExclusiveOr:
1208 case Operator.LogicalOr:
1210 case Operator.LogicalAnd:
1214 return oper.ToString ();
1217 Expression ForceConversion (EmitContext ec, Expression expr, Type target_type)
1219 if (expr.Type == target_type)
1222 return ConvertImplicit (ec, expr, target_type, new Location (-1));
1226 // Note that handling the case l == Decimal || r == Decimal
1227 // is taken care of by the Step 1 Operator Overload resolution.
1229 bool DoNumericPromotions (EmitContext ec, Type l, Type r)
1231 if (l == TypeManager.double_type || r == TypeManager.double_type){
1233 // If either operand is of type double, the other operand is
1234 // conveted to type double.
1236 if (r != TypeManager.double_type)
1237 right = ConvertImplicit (ec, right, TypeManager.double_type, loc);
1238 if (l != TypeManager.double_type)
1239 left = ConvertImplicit (ec, left, TypeManager.double_type, loc);
1241 type = TypeManager.double_type;
1242 } else if (l == TypeManager.float_type || r == TypeManager.float_type){
1244 // if either operand is of type float, th eother operand is
1245 // converd to type float.
1247 if (r != TypeManager.double_type)
1248 right = ConvertImplicit (ec, right, TypeManager.float_type, loc);
1249 if (l != TypeManager.double_type)
1250 left = ConvertImplicit (ec, left, TypeManager.float_type, loc);
1251 type = TypeManager.float_type;
1252 } else if (l == TypeManager.uint64_type || r == TypeManager.uint64_type){
1256 // If either operand is of type ulong, the other operand is
1257 // converted to type ulong. or an error ocurrs if the other
1258 // operand is of type sbyte, short, int or long
1261 if (l == TypeManager.uint64_type){
1262 if (r != TypeManager.uint64_type){
1263 if (right is IntConstant){
1264 e = TryImplicitIntConversion(l, (IntConstant) right);
1267 } else if (right is LongConstant){
1268 long ll = ((LongConstant) right).Value;
1271 right = new ULongConstant ((ulong) ll);
1276 if (left is IntConstant){
1277 e = TryImplicitIntConversion (r, (IntConstant) left);
1280 } else if (left is LongConstant){
1281 long ll = ((LongConstant) left).Value;
1284 left = new ULongConstant ((ulong) ll);
1289 if ((other == TypeManager.sbyte_type) ||
1290 (other == TypeManager.short_type) ||
1291 (other == TypeManager.int32_type) ||
1292 (other == TypeManager.int64_type)){
1293 string oper = OperName ();
1295 Error (34, loc, "Operator `" + OperName ()
1296 + "' is ambiguous on operands of type `"
1297 + TypeManager.CSharpName (l) + "' "
1298 + "and `" + TypeManager.CSharpName (r)
1301 type = TypeManager.uint64_type;
1302 } else if (l == TypeManager.int64_type || r == TypeManager.int64_type){
1304 // If either operand is of type long, the other operand is converted
1307 if (l != TypeManager.int64_type)
1308 left = ConvertImplicit (ec, left, TypeManager.int64_type, loc);
1309 if (r != TypeManager.int64_type)
1310 right = ConvertImplicit (ec, right, TypeManager.int64_type, loc);
1312 type = TypeManager.int64_type;
1313 } else if (l == TypeManager.uint32_type || r == TypeManager.uint32_type){
1315 // If either operand is of type uint, and the other
1316 // operand is of type sbyte, short or int, othe operands are
1317 // converted to type long.
1321 if (l == TypeManager.uint32_type)
1323 else if (r == TypeManager.uint32_type)
1326 if ((other == TypeManager.sbyte_type) ||
1327 (other == TypeManager.short_type) ||
1328 (other == TypeManager.int32_type)){
1329 left = ForceConversion (ec, left, TypeManager.int64_type);
1330 right = ForceConversion (ec, right, TypeManager.int64_type);
1331 type = TypeManager.int64_type;
1334 // if either operand is of type uint, the other
1335 // operand is converd to type uint
1337 left = ForceConversion (ec, left, TypeManager.uint32_type);
1338 right = ForceConversion (ec, right, TypeManager.uint32_type);
1339 type = TypeManager.uint32_type;
1341 } else if (l == TypeManager.decimal_type || r == TypeManager.decimal_type){
1342 if (l != TypeManager.decimal_type)
1343 left = ConvertImplicit (ec, left, TypeManager.decimal_type, loc);
1344 if (r != TypeManager.decimal_type)
1345 right = ConvertImplicit (ec, right, TypeManager.decimal_type, loc);
1347 type = TypeManager.decimal_type;
1349 Expression l_tmp, r_tmp;
1351 l_tmp = ForceConversion (ec, left, TypeManager.int32_type);
1355 r_tmp = ForceConversion (ec, right, TypeManager.int32_type);
1362 type = TypeManager.int32_type;
1371 "Operator " + OperName () + " cannot be applied to operands of type `" +
1372 TypeManager.CSharpName (left.Type) + "' and `" +
1373 TypeManager.CSharpName (right.Type) + "'");
1377 Expression CheckShiftArguments (EmitContext ec)
1381 Type r = right.Type;
1383 e = ForceConversion (ec, right, TypeManager.int32_type);
1390 if (((e = ConvertImplicit (ec, left, TypeManager.int32_type, loc)) != null) ||
1391 ((e = ConvertImplicit (ec, left, TypeManager.uint32_type, loc)) != null) ||
1392 ((e = ConvertImplicit (ec, left, TypeManager.int64_type, loc)) != null) ||
1393 ((e = ConvertImplicit (ec, left, TypeManager.uint64_type, loc)) != null)){
1403 Expression ResolveOperator (EmitContext ec)
1406 Type r = right.Type;
1409 // Step 1: Perform Operator Overload location
1411 Expression left_expr, right_expr;
1413 string op = "op_" + oper;
1415 left_expr = MemberLookup (ec, l, op, false, loc);
1416 if (left_expr == null && l.BaseType != null)
1417 left_expr = MemberLookup (ec, l.BaseType, op, false, loc);
1419 right_expr = MemberLookup (ec, r, op, false, loc);
1420 if (right_expr == null && r.BaseType != null)
1421 right_expr = MemberLookup (ec, r.BaseType, op, false, loc);
1423 MethodGroupExpr union = Invocation.MakeUnionSet (left_expr, right_expr);
1425 if (union != null) {
1426 Arguments = new ArrayList ();
1427 Arguments.Add (new Argument (left, Argument.AType.Expression));
1428 Arguments.Add (new Argument (right, Argument.AType.Expression));
1430 method = Invocation.OverloadResolve (ec, union, Arguments, loc);
1431 if (method != null) {
1432 MethodInfo mi = (MethodInfo) method;
1433 type = mi.ReturnType;
1442 // Step 2: Default operations on CLI native types.
1445 // Only perform numeric promotions on:
1446 // +, -, *, /, %, &, |, ^, ==, !=, <, >, <=, >=
1448 if (oper == Operator.Addition){
1450 // If any of the arguments is a string, cast to string
1452 if (l == TypeManager.string_type){
1453 if (r == TypeManager.string_type){
1454 if (left is Constant && right is Constant){
1455 StringConstant ls = (StringConstant) left;
1456 StringConstant rs = (StringConstant) right;
1458 return new StringConstant (
1459 ls.Value + rs.Value);
1463 method = TypeManager.string_concat_string_string;
1466 method = TypeManager.string_concat_object_object;
1467 right = ConvertImplicit (ec, right,
1468 TypeManager.object_type, loc);
1470 type = TypeManager.string_type;
1472 Arguments = new ArrayList ();
1473 Arguments.Add (new Argument (left, Argument.AType.Expression));
1474 Arguments.Add (new Argument (right, Argument.AType.Expression));
1478 } else if (r == TypeManager.string_type){
1480 method = TypeManager.string_concat_object_object;
1481 Arguments = new ArrayList ();
1482 Arguments.Add (new Argument (left, Argument.AType.Expression));
1483 Arguments.Add (new Argument (right, Argument.AType.Expression));
1485 left = ConvertImplicit (ec, left, TypeManager.object_type, loc);
1486 type = TypeManager.string_type;
1492 if (oper == Operator.Addition || oper == Operator.Subtraction) {
1493 if (l.IsSubclassOf (TypeManager.delegate_type) &&
1494 r.IsSubclassOf (TypeManager.delegate_type)) {
1496 Arguments = new ArrayList ();
1497 Arguments.Add (new Argument (left, Argument.AType.Expression));
1498 Arguments.Add (new Argument (right, Argument.AType.Expression));
1500 if (oper == Operator.Addition)
1501 method = TypeManager.delegate_combine_delegate_delegate;
1503 method = TypeManager.delegate_remove_delegate_delegate;
1505 DelegateOperation = true;
1512 // Enumeration operators
1514 bool lie = TypeManager.IsEnumType (l);
1515 bool rie = TypeManager.IsEnumType (r);
1520 temp = ConvertImplicit (ec, right, l, loc);
1524 temp = ConvertImplicit (ec, left, r, loc);
1531 if (oper == Operator.Equality || oper == Operator.Inequality ||
1532 oper == Operator.LessThanOrEqual || oper == Operator.LessThan ||
1533 oper == Operator.GreaterThanOrEqual || oper == Operator.GreaterThan){
1534 type = TypeManager.bool_type;
1538 if (oper == Operator.BitwiseAnd ||
1539 oper == Operator.BitwiseOr ||
1540 oper == Operator.ExclusiveOr){
1546 if (oper == Operator.LeftShift || oper == Operator.RightShift)
1547 return CheckShiftArguments (ec);
1549 if (oper == Operator.LogicalOr || oper == Operator.LogicalAnd){
1550 if (l != TypeManager.bool_type || r != TypeManager.bool_type){
1555 type = TypeManager.bool_type;
1559 if (oper == Operator.Equality || oper == Operator.Inequality){
1560 if (l == TypeManager.bool_type || r == TypeManager.bool_type){
1561 if (r != TypeManager.bool_type || l != TypeManager.bool_type){
1566 type = TypeManager.bool_type;
1571 // operator != (object a, object b)
1572 // operator == (object a, object b)
1574 // For this to be used, both arguments have to be reference-types.
1575 // Read the rationale on the spec (14.9.6)
1577 // Also, if at compile time we know that the classes do not inherit
1578 // one from the other, then we catch the error there.
1580 if (!(l.IsValueType || r.IsValueType)){
1581 type = TypeManager.bool_type;
1586 if (l.IsSubclassOf (r) || r.IsSubclassOf (l))
1592 // We are dealing with numbers
1595 if (!DoNumericPromotions (ec, l, r)){
1600 if (left == null || right == null)
1604 // reload our cached types if required
1609 if (oper == Operator.BitwiseAnd ||
1610 oper == Operator.BitwiseOr ||
1611 oper == Operator.ExclusiveOr){
1613 if (!((l == TypeManager.int32_type) ||
1614 (l == TypeManager.uint32_type) ||
1615 (l == TypeManager.int64_type) ||
1616 (l == TypeManager.uint64_type)))
1624 if (oper == Operator.Equality ||
1625 oper == Operator.Inequality ||
1626 oper == Operator.LessThanOrEqual ||
1627 oper == Operator.LessThan ||
1628 oper == Operator.GreaterThanOrEqual ||
1629 oper == Operator.GreaterThan){
1630 type = TypeManager.bool_type;
1637 /// Constant expression reducer for binary operations
1639 public Expression ConstantFold (EmitContext ec)
1641 object l = ((Constant) left).GetValue ();
1642 object r = ((Constant) right).GetValue ();
1644 if (l is string && r is string)
1645 return new StringConstant ((string) l + (string) r);
1647 Type result_type = null;
1650 // Enumerator folding
1652 if (left.Type == right.Type && left is EnumConstant)
1653 result_type = left.Type;
1656 case Operator.BitwiseOr:
1657 if ((l is int) && (r is int)){
1659 int res = (int)l | (int)r;
1661 v = new IntConstant (res);
1662 if (result_type == null)
1665 return new EnumConstant (v, result_type);
1669 case Operator.BitwiseAnd:
1670 if ((l is int) && (r is int)){
1672 int res = (int)l & (int)r;
1674 v = new IntConstant (res);
1675 if (result_type == null)
1678 return new EnumConstant (v, result_type);
1686 public override Expression DoResolve (EmitContext ec)
1688 left = left.Resolve (ec);
1689 right = right.Resolve (ec);
1691 if (left == null || right == null)
1694 if (left.Type == null)
1695 throw new Exception (
1696 "Resolve returned non null, but did not set the type! (" +
1697 left + ") at Line: " + loc.Row);
1698 if (right.Type == null)
1699 throw new Exception (
1700 "Resolve returned non null, but did not set the type! (" +
1701 right + ") at Line: "+ loc.Row);
1703 eclass = ExprClass.Value;
1705 if (left is Constant && right is Constant){
1707 // This is temporary until we do the full folding
1709 Expression e = ConstantFold (ec);
1714 return ResolveOperator (ec);
1717 public bool IsBranchable ()
1719 if (oper == Operator.Equality ||
1720 oper == Operator.Inequality ||
1721 oper == Operator.LessThan ||
1722 oper == Operator.GreaterThan ||
1723 oper == Operator.LessThanOrEqual ||
1724 oper == Operator.GreaterThanOrEqual){
1731 /// This entry point is used by routines that might want
1732 /// to emit a brfalse/brtrue after an expression, and instead
1733 /// they could use a more compact notation.
1735 /// Typically the code would generate l.emit/r.emit, followed
1736 /// by the comparission and then a brtrue/brfalse. The comparissions
1737 /// are sometimes inneficient (there are not as complete as the branches
1738 /// look for the hacks in Emit using double ceqs).
1740 /// So for those cases we provide EmitBranchable that can emit the
1741 /// branch with the test
1743 public void EmitBranchable (EmitContext ec, int target)
1746 bool close_target = false;
1747 ILGenerator ig = ec.ig;
1750 // short-circuit operators
1752 if (oper == Operator.LogicalAnd){
1754 ig.Emit (OpCodes.Brfalse, target);
1756 ig.Emit (OpCodes.Brfalse, target);
1757 } else if (oper == Operator.LogicalOr){
1759 ig.Emit (OpCodes.Brtrue, target);
1761 ig.Emit (OpCodes.Brfalse, target);
1768 case Operator.Equality:
1770 opcode = OpCodes.Beq_S;
1772 opcode = OpCodes.Beq;
1775 case Operator.Inequality:
1777 opcode = OpCodes.Bne_Un_S;
1779 opcode = OpCodes.Bne_Un;
1782 case Operator.LessThan:
1784 opcode = OpCodes.Blt_S;
1786 opcode = OpCodes.Blt;
1789 case Operator.GreaterThan:
1791 opcode = OpCodes.Bgt_S;
1793 opcode = OpCodes.Bgt;
1796 case Operator.LessThanOrEqual:
1798 opcode = OpCodes.Ble_S;
1800 opcode = OpCodes.Ble;
1803 case Operator.GreaterThanOrEqual:
1805 opcode = OpCodes.Bge_S;
1807 opcode = OpCodes.Ble;
1811 throw new Exception ("EmitBranchable called on non-EmitBranchable operator: "
1812 + oper.ToString ());
1815 ig.Emit (opcode, target);
1818 public override void Emit (EmitContext ec)
1820 ILGenerator ig = ec.ig;
1822 Type r = right.Type;
1825 if (method != null) {
1827 // Note that operators are static anyway
1829 if (Arguments != null)
1830 Invocation.EmitArguments (ec, method, Arguments);
1832 if (method is MethodInfo)
1833 ig.Emit (OpCodes.Call, (MethodInfo) method);
1835 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
1837 if (DelegateOperation)
1838 ig.Emit (OpCodes.Castclass, type);
1844 // Handle short-circuit operators differently
1847 if (oper == Operator.LogicalAnd){
1848 Label load_zero = ig.DefineLabel ();
1849 Label end = ig.DefineLabel ();
1852 ig.Emit (OpCodes.Brfalse, load_zero);
1854 ig.Emit (OpCodes.Br, end);
1855 ig.MarkLabel (load_zero);
1856 ig.Emit (OpCodes.Ldc_I4_0);
1859 } else if (oper == Operator.LogicalOr){
1860 Label load_one = ig.DefineLabel ();
1861 Label end = ig.DefineLabel ();
1864 ig.Emit (OpCodes.Brtrue, load_one);
1866 ig.Emit (OpCodes.Br, end);
1867 ig.MarkLabel (load_one);
1868 ig.Emit (OpCodes.Ldc_I4_1);
1877 case Operator.Multiply:
1879 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
1880 opcode = OpCodes.Mul_Ovf;
1881 else if (l==TypeManager.uint32_type || l==TypeManager.uint64_type)
1882 opcode = OpCodes.Mul_Ovf_Un;
1884 opcode = OpCodes.Mul;
1886 opcode = OpCodes.Mul;
1890 case Operator.Division:
1891 if (l == TypeManager.uint32_type || l == TypeManager.uint64_type)
1892 opcode = OpCodes.Div_Un;
1894 opcode = OpCodes.Div;
1897 case Operator.Modulus:
1898 if (l == TypeManager.uint32_type || l == TypeManager.uint64_type)
1899 opcode = OpCodes.Rem_Un;
1901 opcode = OpCodes.Rem;
1904 case Operator.Addition:
1906 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
1907 opcode = OpCodes.Add_Ovf;
1908 else if (l==TypeManager.uint32_type || l==TypeManager.uint64_type)
1909 opcode = OpCodes.Add_Ovf_Un;
1911 opcode = OpCodes.Mul;
1913 opcode = OpCodes.Add;
1916 case Operator.Subtraction:
1918 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
1919 opcode = OpCodes.Sub_Ovf;
1920 else if (l==TypeManager.uint32_type || l==TypeManager.uint64_type)
1921 opcode = OpCodes.Sub_Ovf_Un;
1923 opcode = OpCodes.Sub;
1925 opcode = OpCodes.Sub;
1928 case Operator.RightShift:
1929 opcode = OpCodes.Shr;
1932 case Operator.LeftShift:
1933 opcode = OpCodes.Shl;
1936 case Operator.Equality:
1937 opcode = OpCodes.Ceq;
1940 case Operator.Inequality:
1941 ec.ig.Emit (OpCodes.Ceq);
1942 ec.ig.Emit (OpCodes.Ldc_I4_0);
1944 opcode = OpCodes.Ceq;
1947 case Operator.LessThan:
1948 opcode = OpCodes.Clt;
1951 case Operator.GreaterThan:
1952 opcode = OpCodes.Cgt;
1955 case Operator.LessThanOrEqual:
1956 ec.ig.Emit (OpCodes.Cgt);
1957 ec.ig.Emit (OpCodes.Ldc_I4_0);
1959 opcode = OpCodes.Ceq;
1962 case Operator.GreaterThanOrEqual:
1963 ec.ig.Emit (OpCodes.Clt);
1964 ec.ig.Emit (OpCodes.Ldc_I4_1);
1966 opcode = OpCodes.Sub;
1969 case Operator.BitwiseOr:
1970 opcode = OpCodes.Or;
1973 case Operator.BitwiseAnd:
1974 opcode = OpCodes.And;
1977 case Operator.ExclusiveOr:
1978 opcode = OpCodes.Xor;
1982 throw new Exception ("This should not happen: Operator = "
1983 + oper.ToString ());
1991 /// Implements the ternary conditiona operator (?:)
1993 public class Conditional : Expression {
1994 Expression expr, trueExpr, falseExpr;
1997 public Conditional (Expression expr, Expression trueExpr, Expression falseExpr, Location l)
2000 this.trueExpr = trueExpr;
2001 this.falseExpr = falseExpr;
2005 public Expression Expr {
2011 public Expression TrueExpr {
2017 public Expression FalseExpr {
2023 public override Expression DoResolve (EmitContext ec)
2025 expr = expr.Resolve (ec);
2027 if (expr.Type != TypeManager.bool_type)
2028 expr = Expression.ConvertImplicitRequired (
2029 ec, expr, TypeManager.bool_type, loc);
2031 trueExpr = trueExpr.Resolve (ec);
2032 falseExpr = falseExpr.Resolve (ec);
2034 if (expr == null || trueExpr == null || falseExpr == null)
2037 if (trueExpr.Type == falseExpr.Type)
2038 type = trueExpr.Type;
2043 // First, if an implicit conversion exists from trueExpr
2044 // to falseExpr, then the result type is of type falseExpr.Type
2046 conv = ConvertImplicit (ec, trueExpr, falseExpr.Type, loc);
2048 type = falseExpr.Type;
2050 } else if ((conv = ConvertImplicit(ec, falseExpr,trueExpr.Type,loc))!= null){
2051 type = trueExpr.Type;
2054 Error (173, loc, "The type of the conditional expression can " +
2055 "not be computed because there is no implicit conversion" +
2056 " from `" + TypeManager.CSharpName (trueExpr.Type) + "'" +
2057 " and `" + TypeManager.CSharpName (falseExpr.Type) + "'");
2062 if (expr is BoolConstant){
2063 BoolConstant bc = (BoolConstant) expr;
2071 eclass = ExprClass.Value;
2075 public override void Emit (EmitContext ec)
2077 ILGenerator ig = ec.ig;
2078 Label false_target = ig.DefineLabel ();
2079 Label end_target = ig.DefineLabel ();
2082 ig.Emit (OpCodes.Brfalse, false_target);
2084 ig.Emit (OpCodes.Br, end_target);
2085 ig.MarkLabel (false_target);
2086 falseExpr.Emit (ec);
2087 ig.MarkLabel (end_target);
2095 public class LocalVariableReference : Expression, IAssignMethod, IMemoryLocation {
2096 public readonly string Name;
2097 public readonly Block Block;
2099 VariableInfo variable_info;
2101 public LocalVariableReference (Block block, string name, Location l)
2106 eclass = ExprClass.Variable;
2109 public VariableInfo VariableInfo {
2111 if (variable_info == null)
2112 variable_info = Block.GetVariableInfo (Name);
2113 return variable_info;
2117 public override Expression DoResolve (EmitContext ec)
2119 VariableInfo vi = VariableInfo;
2121 if (Block.IsConstant (Name)) {
2122 Expression e = Block.GetConstantExpression (Name);
2128 if (!(e is Constant)) {
2129 Report.Error (150, loc, "A constant value is expected");
2137 type = vi.VariableType;
2141 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
2143 Expression e = DoResolve (ec);
2148 VariableInfo vi = VariableInfo;
2154 "cannot assign to `" + Name + "' because it is readonly");
2162 public override void Emit (EmitContext ec)
2164 VariableInfo vi = VariableInfo;
2165 ILGenerator ig = ec.ig;
2172 ig.Emit (OpCodes.Ldloc_0);
2176 ig.Emit (OpCodes.Ldloc_1);
2180 ig.Emit (OpCodes.Ldloc_2);
2184 ig.Emit (OpCodes.Ldloc_3);
2189 ig.Emit (OpCodes.Ldloc_S, (byte) idx);
2191 ig.Emit (OpCodes.Ldloc, idx);
2196 public static void Store (ILGenerator ig, int idx)
2200 ig.Emit (OpCodes.Stloc_0);
2204 ig.Emit (OpCodes.Stloc_1);
2208 ig.Emit (OpCodes.Stloc_2);
2212 ig.Emit (OpCodes.Stloc_3);
2217 ig.Emit (OpCodes.Stloc_S, (byte) idx);
2219 ig.Emit (OpCodes.Stloc, idx);
2224 public void EmitAssign (EmitContext ec, Expression source)
2226 ILGenerator ig = ec.ig;
2227 VariableInfo vi = VariableInfo;
2233 // Funny seems the code below generates optimal code for us, but
2234 // seems to take too long to generate what we need.
2235 // ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
2240 public void AddressOf (EmitContext ec)
2242 VariableInfo vi = VariableInfo;
2249 ec.ig.Emit (OpCodes.Ldloca_S, (byte) idx);
2251 ec.ig.Emit (OpCodes.Ldloca, idx);
2256 /// This represents a reference to a parameter in the intermediate
2259 public class ParameterReference : Expression, IAssignMethod, IMemoryLocation {
2265 public ParameterReference (Parameters pars, int idx, string name)
2270 eclass = ExprClass.Variable;
2274 // Notice that for ref/out parameters, the type exposed is not the
2275 // same type exposed externally.
2278 // externally we expose "int&"
2279 // here we expose "int".
2281 // We record this in "is_ref". This means that the type system can treat
2282 // the type as it is expected, but when we generate the code, we generate
2283 // the alternate kind of code.
2285 public override Expression DoResolve (EmitContext ec)
2287 type = pars.GetParameterInfo (ec.TypeContainer, idx, out is_ref);
2288 eclass = ExprClass.Variable;
2293 public override void Emit (EmitContext ec)
2295 ILGenerator ig = ec.ig;
2302 ig.Emit (OpCodes.Ldarg_S, (byte) arg_idx);
2304 ig.Emit (OpCodes.Ldarg, arg_idx);
2310 // If we are a reference, we loaded on the stack a pointer
2311 // Now lets load the real value
2314 if (type == TypeManager.int32_type)
2315 ig.Emit (OpCodes.Ldind_I4);
2316 else if (type == TypeManager.uint32_type)
2317 ig.Emit (OpCodes.Ldind_U4);
2318 else if (type == TypeManager.int64_type || type == TypeManager.uint64_type)
2319 ig.Emit (OpCodes.Ldind_I8);
2320 else if (type == TypeManager.char_type)
2321 ig.Emit (OpCodes.Ldind_U2);
2322 else if (type == TypeManager.short_type)
2323 ig.Emit (OpCodes.Ldind_I2);
2324 else if (type == TypeManager.ushort_type)
2325 ig.Emit (OpCodes.Ldind_U2);
2326 else if (type == TypeManager.float_type)
2327 ig.Emit (OpCodes.Ldind_R4);
2328 else if (type == TypeManager.double_type)
2329 ig.Emit (OpCodes.Ldind_R8);
2330 else if (type == TypeManager.byte_type)
2331 ig.Emit (OpCodes.Ldind_U1);
2332 else if (type == TypeManager.sbyte_type)
2333 ig.Emit (OpCodes.Ldind_I1);
2334 else if (type == TypeManager.intptr_type)
2335 ig.Emit (OpCodes.Ldind_I);
2337 ig.Emit (OpCodes.Ldind_Ref);
2340 public void EmitAssign (EmitContext ec, Expression source)
2342 ILGenerator ig = ec.ig;
2351 ig.Emit (OpCodes.Ldarg_S, (byte) arg_idx);
2353 ig.Emit (OpCodes.Ldarg, arg_idx);
2359 if (type == TypeManager.int32_type || type == TypeManager.uint32_type)
2360 ig.Emit (OpCodes.Stind_I4);
2361 else if (type == TypeManager.int64_type || type == TypeManager.uint64_type)
2362 ig.Emit (OpCodes.Stind_I8);
2363 else if (type == TypeManager.char_type || type == TypeManager.short_type ||
2364 type == TypeManager.ushort_type)
2365 ig.Emit (OpCodes.Stind_I2);
2366 else if (type == TypeManager.float_type)
2367 ig.Emit (OpCodes.Stind_R4);
2368 else if (type == TypeManager.double_type)
2369 ig.Emit (OpCodes.Stind_R8);
2370 else if (type == TypeManager.byte_type || type == TypeManager.sbyte_type)
2371 ig.Emit (OpCodes.Stind_I1);
2372 else if (type == TypeManager.intptr_type)
2373 ig.Emit (OpCodes.Stind_I);
2375 ig.Emit (OpCodes.Stind_Ref);
2378 ig.Emit (OpCodes.Starg_S, (byte) arg_idx);
2380 ig.Emit (OpCodes.Starg, arg_idx);
2385 public void AddressOf (EmitContext ec)
2393 ec.ig.Emit (OpCodes.Ldarga_S, (byte) arg_idx);
2395 ec.ig.Emit (OpCodes.Ldarga, arg_idx);
2400 /// Used for arguments to New(), Invocation()
2402 public class Argument {
2403 public enum AType : byte {
2409 public readonly AType ArgType;
2410 public Expression expr;
2412 public Argument (Expression expr, AType type)
2415 this.ArgType = type;
2418 public Expression Expr {
2434 public Parameter.Modifier GetParameterModifier ()
2436 if (ArgType == AType.Ref)
2437 return Parameter.Modifier.REF;
2439 if (ArgType == AType.Out)
2440 return Parameter.Modifier.OUT;
2442 return Parameter.Modifier.NONE;
2445 public static string FullDesc (Argument a)
2447 return (a.ArgType == AType.Ref ? "ref " :
2448 (a.ArgType == AType.Out ? "out " : "")) +
2449 TypeManager.CSharpName (a.Expr.Type);
2452 public bool Resolve (EmitContext ec, Location loc)
2454 expr = expr.Resolve (ec);
2456 if (ArgType == AType.Expression)
2457 return expr != null;
2459 if (expr.eclass != ExprClass.Variable){
2460 Report.Error (206, loc,
2461 "A property or indexer can not be passed as an out or ref " +
2466 return expr != null;
2469 public void Emit (EmitContext ec)
2471 if (ArgType == AType.Ref || ArgType == AType.Out)
2472 ((IMemoryLocation)expr).AddressOf (ec);
2479 /// Invocation of methods or delegates.
2481 public class Invocation : ExpressionStatement {
2482 public readonly ArrayList Arguments;
2486 MethodBase method = null;
2488 static Hashtable method_parameter_cache;
2490 static Invocation ()
2492 method_parameter_cache = new PtrHashtable ();
2496 // arguments is an ArrayList, but we do not want to typecast,
2497 // as it might be null.
2499 // FIXME: only allow expr to be a method invocation or a
2500 // delegate invocation (7.5.5)
2502 public Invocation (Expression expr, ArrayList arguments, Location l)
2505 Arguments = arguments;
2509 public Expression Expr {
2516 /// Returns the Parameters (a ParameterData interface) for the
2519 public static ParameterData GetParameterData (MethodBase mb)
2521 object pd = method_parameter_cache [mb];
2525 return (ParameterData) pd;
2528 ip = TypeManager.LookupParametersByBuilder (mb);
2530 method_parameter_cache [mb] = ip;
2532 return (ParameterData) ip;
2534 ParameterInfo [] pi = mb.GetParameters ();
2535 ReflectionParameters rp = new ReflectionParameters (pi);
2536 method_parameter_cache [mb] = rp;
2538 return (ParameterData) rp;
2543 /// Tells whether a user defined conversion from Type `from' to
2544 /// Type `to' exists.
2546 /// FIXME: we could implement a cache here.
2548 static bool ConversionExists (EmitContext ec, Type from, Type to, Location loc)
2550 // Locate user-defined implicit operators
2554 mg = MemberLookup (ec, to, "op_Implicit", false, loc);
2557 MethodGroupExpr me = (MethodGroupExpr) mg;
2559 for (int i = me.Methods.Length; i > 0;) {
2561 MethodBase mb = me.Methods [i];
2562 ParameterData pd = GetParameterData (mb);
2564 if (from == pd.ParameterType (0))
2569 mg = MemberLookup (ec, from, "op_Implicit", false, loc);
2572 MethodGroupExpr me = (MethodGroupExpr) mg;
2574 for (int i = me.Methods.Length; i > 0;) {
2576 MethodBase mb = me.Methods [i];
2577 MethodInfo mi = (MethodInfo) mb;
2579 if (mi.ReturnType == to)
2588 /// Determines "better conversion" as specified in 7.4.2.3
2589 /// Returns : 1 if a->p is better
2590 /// 0 if a->q or neither is better
2592 static int BetterConversion (EmitContext ec, Argument a, Type p, Type q, bool use_standard,
2595 Type argument_type = a.Type;
2596 Expression argument_expr = a.Expr;
2598 if (argument_type == null)
2599 throw new Exception ("Expression of type " + a.Expr + " does not resolve its type");
2604 if (argument_type == p)
2607 if (argument_type == q)
2611 // Now probe whether an implicit constant expression conversion
2614 // An implicit constant expression conversion permits the following
2617 // * A constant-expression of type `int' can be converted to type
2618 // sbyte, byute, short, ushort, uint, ulong provided the value of
2619 // of the expression is withing the range of the destination type.
2621 // * A constant-expression of type long can be converted to type
2622 // ulong, provided the value of the constant expression is not negative
2624 // FIXME: Note that this assumes that constant folding has
2625 // taken place. We dont do constant folding yet.
2628 if (argument_expr is IntConstant){
2629 IntConstant ei = (IntConstant) argument_expr;
2630 int value = ei.Value;
2632 if (p == TypeManager.sbyte_type){
2633 if (value >= SByte.MinValue && value <= SByte.MaxValue)
2635 } else if (p == TypeManager.byte_type){
2636 if (Byte.MinValue >= 0 && value <= Byte.MaxValue)
2638 } else if (p == TypeManager.short_type){
2639 if (value >= Int16.MinValue && value <= Int16.MaxValue)
2641 } else if (p == TypeManager.ushort_type){
2642 if (value >= UInt16.MinValue && value <= UInt16.MaxValue)
2644 } else if (p == TypeManager.uint32_type){
2646 // we can optimize this case: a positive int32
2647 // always fits on a uint32
2651 } else if (p == TypeManager.uint64_type){
2653 // we can optimize this case: a positive int32
2654 // always fits on a uint64
2659 } else if (argument_type == TypeManager.int64_type && argument_expr is LongConstant){
2660 LongConstant lc = (LongConstant) argument_expr;
2662 if (p == TypeManager.uint64_type){
2673 tmp = ConvertImplicitStandard (ec, argument_expr, p, loc);
2675 tmp = ConvertImplicit (ec, argument_expr, p, loc);
2684 if (ConversionExists (ec, p, q, loc) == true &&
2685 ConversionExists (ec, q, p, loc) == false)
2688 if (p == TypeManager.sbyte_type)
2689 if (q == TypeManager.byte_type || q == TypeManager.ushort_type ||
2690 q == TypeManager.uint32_type || q == TypeManager.uint64_type)
2693 if (p == TypeManager.short_type)
2694 if (q == TypeManager.ushort_type || q == TypeManager.uint32_type ||
2695 q == TypeManager.uint64_type)
2698 if (p == TypeManager.int32_type)
2699 if (q == TypeManager.uint32_type || q == TypeManager.uint64_type)
2702 if (p == TypeManager.int64_type)
2703 if (q == TypeManager.uint64_type)
2710 /// Determines "Better function"
2713 /// and returns an integer indicating :
2714 /// 0 if candidate ain't better
2715 /// 1 if candidate is better than the current best match
2717 static int BetterFunction (EmitContext ec, ArrayList args,
2718 MethodBase candidate, MethodBase best,
2719 bool use_standard, Location loc)
2721 ParameterData candidate_pd = GetParameterData (candidate);
2722 ParameterData best_pd;
2728 argument_count = args.Count;
2730 if (candidate_pd.Count == 0 && argument_count == 0)
2734 if (candidate_pd.Count == argument_count) {
2736 for (int j = argument_count; j > 0;) {
2739 Argument a = (Argument) args [j];
2741 x = BetterConversion (
2742 ec, a, candidate_pd.ParameterType (j), null,
2758 best_pd = GetParameterData (best);
2760 if (candidate_pd.Count == argument_count && best_pd.Count == argument_count) {
2761 int rating1 = 0, rating2 = 0;
2763 for (int j = argument_count; j > 0;) {
2767 Argument a = (Argument) args [j];
2769 x = BetterConversion (ec, a, candidate_pd.ParameterType (j),
2770 best_pd.ParameterType (j), use_standard, loc);
2771 y = BetterConversion (ec, a, best_pd.ParameterType (j),
2772 candidate_pd.ParameterType (j), use_standard,
2779 if (rating1 > rating2)
2788 public static string FullMethodDesc (MethodBase mb)
2790 StringBuilder sb = new StringBuilder (mb.Name);
2791 ParameterData pd = GetParameterData (mb);
2793 int count = pd.Count;
2796 for (int i = count; i > 0; ) {
2799 sb.Append (pd.ParameterDesc (count - i - 1));
2805 return sb.ToString ();
2808 public static MethodGroupExpr MakeUnionSet (Expression mg1, Expression mg2)
2810 MemberInfo [] miset;
2811 MethodGroupExpr union;
2813 if (mg1 != null && mg2 != null) {
2815 MethodGroupExpr left_set = null, right_set = null;
2816 int length1 = 0, length2 = 0;
2818 left_set = (MethodGroupExpr) mg1;
2819 length1 = left_set.Methods.Length;
2821 right_set = (MethodGroupExpr) mg2;
2822 length2 = right_set.Methods.Length;
2824 ArrayList common = new ArrayList ();
2826 for (int i = 0; i < left_set.Methods.Length; i++) {
2827 for (int j = 0; j < right_set.Methods.Length; j++) {
2828 if (left_set.Methods [i] == right_set.Methods [j])
2829 common.Add (left_set.Methods [i]);
2833 miset = new MemberInfo [length1 + length2 - common.Count];
2835 left_set.Methods.CopyTo (miset, 0);
2839 for (int j = 0; j < right_set.Methods.Length; j++)
2840 if (!common.Contains (right_set.Methods [j]))
2841 miset [length1 + k++] = right_set.Methods [j];
2843 union = new MethodGroupExpr (miset);
2847 } else if (mg1 == null && mg2 != null) {
2849 MethodGroupExpr me = (MethodGroupExpr) mg2;
2851 miset = new MemberInfo [me.Methods.Length];
2852 me.Methods.CopyTo (miset, 0);
2854 union = new MethodGroupExpr (miset);
2858 } else if (mg2 == null && mg1 != null) {
2860 MethodGroupExpr me = (MethodGroupExpr) mg1;
2862 miset = new MemberInfo [me.Methods.Length];
2863 me.Methods.CopyTo (miset, 0);
2865 union = new MethodGroupExpr (miset);
2874 /// Determines is the candidate method, if a params method, is applicable
2875 /// in its expanded form to the given set of arguments
2877 static bool IsParamsMethodApplicable (ArrayList arguments, MethodBase candidate)
2881 if (arguments == null)
2884 arg_count = arguments.Count;
2886 ParameterData pd = GetParameterData (candidate);
2888 int pd_count = pd.Count;
2893 if (pd.ParameterModifier (pd_count - 1) != Parameter.Modifier.PARAMS)
2896 if (pd_count - 1 > arg_count)
2899 // If we have come this far, the case which remains is when the number of parameters
2900 // is less than or equal to the argument count. So, we now check if the element type
2901 // of the params array is compatible with each argument type
2904 Type element_type = pd.ParameterType (pd_count - 1).GetElementType ();
2906 for (int i = pd_count - 1; i < arg_count - 1; i++) {
2907 Argument a = (Argument) arguments [i];
2908 if (!StandardConversionExists (a.Type, element_type))
2916 /// Determines if the candidate method is applicable (section 14.4.2.1)
2917 /// to the given set of arguments
2919 static bool IsApplicable (ArrayList arguments, MethodBase candidate)
2923 if (arguments == null)
2926 arg_count = arguments.Count;
2928 ParameterData pd = GetParameterData (candidate);
2930 int pd_count = pd.Count;
2932 if (arg_count != pd.Count)
2935 for (int i = arg_count; i > 0; ) {
2938 Argument a = (Argument) arguments [i];
2940 Parameter.Modifier a_mod = a.GetParameterModifier ();
2941 Parameter.Modifier p_mod = pd.ParameterModifier (i);
2943 if (a_mod == p_mod) {
2945 if (a_mod == Parameter.Modifier.NONE)
2946 if (!StandardConversionExists (a.Type, pd.ParameterType (i)))
2949 if (a_mod == Parameter.Modifier.REF ||
2950 a_mod == Parameter.Modifier.OUT)
2951 if (pd.ParameterType (i) != a.Type)
2963 /// Find the Applicable Function Members (7.4.2.1)
2965 /// me: Method Group expression with the members to select.
2966 /// it might contain constructors or methods (or anything
2967 /// that maps to a method).
2969 /// Arguments: ArrayList containing resolved Argument objects.
2971 /// loc: The location if we want an error to be reported, or a Null
2972 /// location for "probing" purposes.
2974 /// use_standard: controls whether OverloadResolve should use the
2975 /// ConvertImplicit or ConvertImplicitStandard during overload resolution.
2977 /// Returns: The MethodBase (either a ConstructorInfo or a MethodInfo)
2978 /// that is the best match of me on Arguments.
2981 public static MethodBase OverloadResolve (EmitContext ec, MethodGroupExpr me,
2982 ArrayList Arguments, Location loc,
2985 ArrayList afm = new ArrayList ();
2986 int best_match_idx = -1;
2987 MethodBase method = null;
2989 ArrayList candidates = new ArrayList ();
2991 for (int i = me.Methods.Length; i > 0; ){
2993 MethodBase candidate = me.Methods [i];
2996 // Check if candidate is applicable (section 14.4.2.1)
2997 if (!IsApplicable (Arguments, candidate))
3000 candidates.Add (candidate);
3001 x = BetterFunction (ec, Arguments, candidate, method, use_standard, loc);
3007 method = me.Methods [best_match_idx];
3011 if (Arguments == null)
3014 argument_count = Arguments.Count;
3017 // Now we see if we can find params functions, applicable in their expanded form
3018 // since if they were applicable in their normal form, they would have been selected
3021 if (best_match_idx == -1) {
3023 for (int i = me.Methods.Length; i > 0; ) {
3025 MethodBase candidate = me.Methods [i];
3027 if (IsParamsMethodApplicable (Arguments, candidate)) {
3029 method = me.Methods [best_match_idx];
3036 // Now we see if we can at least find a method with the same number of arguments
3039 int method_count = 0;
3041 if (best_match_idx == -1) {
3043 for (int i = me.Methods.Length; i > 0;) {
3045 MethodBase mb = me.Methods [i];
3046 pd = GetParameterData (mb);
3048 if (pd.Count == argument_count) {
3050 method = me.Methods [best_match_idx];
3061 // Now check that there are no ambiguities i.e the selected method
3062 // should be better than all the others
3065 for (int i = candidates.Count; i > 0; ) {
3067 MethodBase candidate = (MethodBase) candidates [i];
3070 if (candidate == method)
3073 x = BetterFunction (ec, Arguments, method, candidate, use_standard, loc);
3078 "Ambiguous call when selecting function due to implicit casts");
3084 // And now convert implicitly, each argument to the required type
3086 pd = GetParameterData (method);
3087 int pd_count = pd.Count;
3089 for (int j = 0; j < argument_count; j++) {
3090 Argument a = (Argument) Arguments [j];
3091 Expression a_expr = a.Expr;
3092 Type parameter_type = pd.ParameterType (j);
3095 // Note that we need to compare against the element type
3096 // when we have a params method
3098 if (pd.ParameterModifier (pd_count - 1) == Parameter.Modifier.PARAMS) {
3099 if (j >= pd_count - 1)
3100 parameter_type = pd.ParameterType (pd_count - 1).GetElementType ();
3103 if (a.Type != parameter_type){
3107 conv = ConvertImplicitStandard (
3108 ec, a_expr, parameter_type, Location.Null);
3110 conv = ConvertImplicit (
3111 ec, a_expr, parameter_type, Location.Null);
3114 if (!Location.IsNull (loc)) {
3116 "The best overloaded match for method '" +
3117 FullMethodDesc (method) +
3118 "' has some invalid arguments");
3120 "Argument " + (j+1) +
3121 ": Cannot convert from '" + Argument.FullDesc (a)
3122 + "' to '" + pd.ParameterDesc (j) + "'");
3130 // Update the argument with the implicit conversion
3135 // FIXME : For the case of params methods, we need to actually instantiate
3136 // an array and initialize it with the argument values etc etc.
3140 if (a.GetParameterModifier () != pd.ParameterModifier (j) &&
3141 pd.ParameterModifier (j) != Parameter.Modifier.PARAMS) {
3142 if (!Location.IsNull (loc)) {
3144 "The best overloaded match for method '" + FullMethodDesc (method)+
3145 "' has some invalid arguments");
3147 "Argument " + (j+1) +
3148 ": Cannot convert from '" + Argument.FullDesc (a)
3149 + "' to '" + pd.ParameterDesc (j) + "'");
3160 public static MethodBase OverloadResolve (EmitContext ec, MethodGroupExpr me,
3161 ArrayList Arguments, Location loc)
3163 return OverloadResolve (ec, me, Arguments, loc, false);
3166 public override Expression DoResolve (EmitContext ec)
3169 // First, resolve the expression that is used to
3170 // trigger the invocation
3172 expr = expr.Resolve (ec);
3176 if (!(expr is MethodGroupExpr)) {
3177 Type expr_type = expr.Type;
3179 if (expr_type != null){
3180 bool IsDelegate = TypeManager.IsDelegateType (expr_type);
3182 return (new DelegateInvocation (
3183 this.expr, Arguments, loc)).Resolve (ec);
3187 if (!(expr is MethodGroupExpr)){
3188 report118 (loc, this.expr, "method group");
3193 // Next, evaluate all the expressions in the argument list
3195 if (Arguments != null){
3196 for (int i = Arguments.Count; i > 0;){
3198 Argument a = (Argument) Arguments [i];
3200 if (!a.Resolve (ec, loc))
3205 method = OverloadResolve (ec, (MethodGroupExpr) this.expr, Arguments, loc);
3207 if (method == null){
3209 "Could not find any applicable function for this argument list");
3213 if (method is MethodInfo)
3214 type = ((MethodInfo)method).ReturnType;
3216 eclass = ExprClass.Value;
3221 // Emits the list of arguments as an array
3223 static void EmitParams (EmitContext ec, int idx, ArrayList arguments)
3225 ILGenerator ig = ec.ig;
3226 int count = arguments.Count - idx;
3227 Argument a = (Argument) arguments [idx];
3228 Type t = a.expr.Type;
3229 string array_type = t.FullName + "[]";
3232 array = ig.DeclareLocal (Type.GetType (array_type));
3233 IntConstant.EmitInt (ig, count);
3234 ig.Emit (OpCodes.Newarr, t);
3235 ig.Emit (OpCodes.Stloc, array);
3237 int top = arguments.Count;
3238 for (int j = idx; j < top; j++){
3239 a = (Argument) arguments [j];
3241 ig.Emit (OpCodes.Ldloc, array);
3242 IntConstant.EmitInt (ig, j - idx);
3245 ArrayAccess.EmitStoreOpcode (ig, t);
3247 ig.Emit (OpCodes.Ldloc, array);
3251 /// Emits a list of resolved Arguments that are in the arguments
3254 /// The MethodBase argument might be null if the
3255 /// emission of the arguments is known not to contain
3256 /// a `params' field (for example in constructors or other routines
3257 /// that keep their arguments in this structure
3259 public static void EmitArguments (EmitContext ec, MethodBase mb, ArrayList arguments)
3261 ParameterData pd = null;
3264 if (arguments != null)
3265 top = arguments.Count;
3270 pd = GetParameterData (mb);
3272 for (int i = 0; i < top; i++){
3273 Argument a = (Argument) arguments [i];
3276 if (pd.ParameterModifier (i) == Parameter.Modifier.PARAMS){
3277 EmitParams (ec, i, arguments);
3286 public static void EmitCall (EmitContext ec,
3287 bool is_static, Expression instance_expr,
3288 MethodBase method, ArrayList Arguments)
3290 ILGenerator ig = ec.ig;
3291 bool struct_call = false;
3295 // If this is ourselves, push "this"
3297 if (instance_expr == null){
3298 ig.Emit (OpCodes.Ldarg_0);
3301 // Push the instance expression
3303 if (instance_expr.Type.IsSubclassOf (TypeManager.value_type)){
3308 // If the expression implements IMemoryLocation, then
3309 // we can optimize and use AddressOf on the
3312 // If not we have to use some temporary storage for
3314 if (instance_expr is IMemoryLocation)
3315 ((IMemoryLocation) instance_expr).AddressOf (ec);
3317 Type t = instance_expr.Type;
3319 instance_expr.Emit (ec);
3320 LocalBuilder temp = ig.DeclareLocal (t);
3321 ig.Emit (OpCodes.Stloc, temp);
3322 ig.Emit (OpCodes.Ldloca, temp);
3325 instance_expr.Emit (ec);
3329 if (Arguments != null)
3330 EmitArguments (ec, method, Arguments);
3332 if (is_static || struct_call){
3333 if (method is MethodInfo)
3334 ig.Emit (OpCodes.Call, (MethodInfo) method);
3336 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
3338 if (method is MethodInfo)
3339 ig.Emit (OpCodes.Callvirt, (MethodInfo) method);
3341 ig.Emit (OpCodes.Callvirt, (ConstructorInfo) method);
3345 public override void Emit (EmitContext ec)
3347 MethodGroupExpr mg = (MethodGroupExpr) this.expr;
3348 EmitCall (ec, method.IsStatic, mg.InstanceExpression, method, Arguments);
3351 public override void EmitStatement (EmitContext ec)
3356 // Pop the return value if there is one
3358 if (method is MethodInfo){
3359 if (((MethodInfo)method).ReturnType != TypeManager.void_type)
3360 ec.ig.Emit (OpCodes.Pop);
3366 /// Implements the new expression
3368 public class New : ExpressionStatement {
3369 public readonly ArrayList Arguments;
3370 public readonly string RequestedType;
3373 MethodBase method = null;
3376 // If set, the new expression is for a value_target, and
3377 // we will not leave anything on the stack.
3379 Expression value_target;
3381 public New (string requested_type, ArrayList arguments, Location l)
3383 RequestedType = requested_type;
3384 Arguments = arguments;
3388 public Expression ValueTypeVariable {
3390 return value_target;
3394 value_target = value;
3398 public override Expression DoResolve (EmitContext ec)
3400 type = RootContext.LookupType (ec.TypeContainer, RequestedType, false, loc);
3405 bool IsDelegate = TypeManager.IsDelegateType (type);
3408 return (new NewDelegate (type, Arguments, loc)).Resolve (ec);
3410 bool is_struct = false;
3411 is_struct = type.IsSubclassOf (TypeManager.value_type);
3412 eclass = ExprClass.Value;
3415 // SRE returns a match for .ctor () on structs (the object constructor),
3416 // so we have to manually ignore it.
3418 if (is_struct && Arguments == null)
3422 ml = MemberLookup (ec, type, ".ctor", false,
3423 MemberTypes.Constructor, AllBindingFlags, loc);
3425 if (! (ml is MethodGroupExpr)){
3427 report118 (loc, ml, "method group");
3433 if (Arguments != null){
3434 for (int i = Arguments.Count; i > 0;){
3436 Argument a = (Argument) Arguments [i];
3438 if (!a.Resolve (ec, loc))
3443 method = Invocation.OverloadResolve (ec, (MethodGroupExpr) ml,
3447 if (method == null && !is_struct) {
3449 "New invocation: Can not find a constructor for " +
3450 "this argument list");
3457 // This DoEmit can be invoked in two contexts:
3458 // * As a mechanism that will leave a value on the stack (new object)
3459 // * As one that wont (init struct)
3461 // You can control whether a value is required on the stack by passing
3462 // need_value_on_stack. The code *might* leave a value on the stack
3463 // so it must be popped manually
3465 // If we are dealing with a ValueType, we have a few
3466 // situations to deal with:
3468 // * The target is a ValueType, and we have been provided
3469 // the instance (this is easy, we are being assigned).
3471 // * The target of New is being passed as an argument,
3472 // to a boxing operation or a function that takes a
3475 // In this case, we need to create a temporary variable
3476 // that is the argument of New.
3478 // Returns whether a value is left on the stack
3480 bool DoEmit (EmitContext ec, bool need_value_on_stack)
3482 if (method == null){
3485 if (value_target == null)
3486 value_target = new LocalTemporary (ec, type);
3488 ml = (IMemoryLocation) value_target;
3491 Invocation.EmitArguments (ec, method, Arguments);
3492 ec.ig.Emit (OpCodes.Newobj, (ConstructorInfo) method);
3497 // It must be a value type, sanity check
3499 if (value_target != null){
3500 ec.ig.Emit (OpCodes.Initobj, type);
3502 if (need_value_on_stack){
3503 value_target.Emit (ec);
3509 throw new Exception ("No method and no value type");
3512 public override void Emit (EmitContext ec)
3517 public override void EmitStatement (EmitContext ec)
3519 if (DoEmit (ec, false))
3520 ec.ig.Emit (OpCodes.Pop);
3525 /// Represents an array creation expression.
3529 /// There are two possible scenarios here: one is an array creation
3530 /// expression that specifies the dimensions and optionally the
3531 /// initialization data and the other which does not need dimensions
3532 /// specified but where initialization data is mandatory.
3534 public class ArrayCreation : ExpressionStatement {
3535 string RequestedType;
3537 ArrayList Initializers;
3539 ArrayList Arguments;
3541 MethodBase method = null;
3542 Type array_element_type;
3543 bool IsOneDimensional = false;
3544 bool IsBuiltinType = false;
3545 bool ExpectInitializers = false;
3548 Type underlying_type;
3550 ArrayList ArrayData;
3554 public ArrayCreation (string requested_type, ArrayList exprs,
3555 string rank, ArrayList initializers, Location l)
3557 RequestedType = requested_type;
3559 Initializers = initializers;
3562 Arguments = new ArrayList ();
3564 foreach (Expression e in exprs)
3565 Arguments.Add (new Argument (e, Argument.AType.Expression));
3569 public ArrayCreation (string requested_type, string rank, ArrayList initializers, Location l)
3571 RequestedType = requested_type;
3572 Initializers = initializers;
3575 Rank = rank.Substring (0, rank.LastIndexOf ("["));
3577 string tmp = rank.Substring (rank.LastIndexOf ("["));
3579 dimensions = tmp.Length - 1;
3580 ExpectInitializers = true;
3583 public static string FormArrayType (string base_type, int idx_count, string rank)
3585 StringBuilder sb = new StringBuilder (base_type);
3590 for (int i = 1; i < idx_count; i++)
3594 return sb.ToString ();
3597 public static string FormElementType (string base_type, int idx_count, string rank)
3599 StringBuilder sb = new StringBuilder (base_type);
3602 for (int i = 1; i < idx_count; i++)
3608 string val = sb.ToString ();
3610 return val.Substring (0, val.LastIndexOf ("["));
3615 Report.Error (178, loc, "Incorrectly structured array initializer");
3618 public bool CheckIndices (EmitContext ec, ArrayList probe, int idx, bool specified_dims)
3620 if (specified_dims) {
3621 Argument a = (Argument) Arguments [idx];
3623 if (!a.Resolve (ec, loc))
3626 if (!(a.Expr is Constant)) {
3627 Report.Error (150, loc, "A constant value is expected");
3631 int value = (int) ((Constant) a.Expr).GetValue ();
3633 if (value != probe.Count) {
3638 Bounds [idx] = value;
3641 foreach (object o in probe) {
3642 if (o is ArrayList) {
3643 bool ret = CheckIndices (ec, (ArrayList) o, idx + 1, specified_dims);
3647 Expression tmp = (Expression) o;
3648 tmp = tmp.Resolve (ec);
3652 // Handle initialization from vars, fields etc.
3654 Expression conv = ConvertImplicitRequired (
3655 ec, tmp, underlying_type, loc);
3660 if (conv is StringConstant)
3661 ArrayData.Add (conv);
3662 else if (conv is Constant)
3663 ArrayData.Add (((Constant) conv).GetValue ());
3665 ArrayData.Add (conv);
3672 public void UpdateIndices (EmitContext ec)
3675 for (ArrayList probe = Initializers; probe != null;) {
3677 if (probe [0] is ArrayList) {
3678 Expression e = new IntConstant (probe.Count);
3679 Arguments.Add (new Argument (e, Argument.AType.Expression));
3681 Bounds [i++] = probe.Count;
3683 probe = (ArrayList) probe [0];
3686 Expression e = new IntConstant (probe.Count);
3687 Arguments.Add (new Argument (e, Argument.AType.Expression));
3689 Bounds [i++] = probe.Count;
3696 public bool ValidateInitializers (EmitContext ec)
3698 if (Initializers == null) {
3699 if (ExpectInitializers)
3705 underlying_type = RootContext.LookupType (
3706 ec.TypeContainer, RequestedType, false, loc);
3709 // We use this to store all the date values in the order in which we
3710 // will need to store them in the byte blob later
3712 ArrayData = new ArrayList ();
3713 Bounds = new Hashtable ();
3717 if (Arguments != null) {
3718 ret = CheckIndices (ec, Initializers, 0, true);
3722 Arguments = new ArrayList ();
3724 ret = CheckIndices (ec, Initializers, 0, false);
3731 if (Arguments.Count != dimensions) {
3740 public override Expression DoResolve (EmitContext ec)
3744 if (!ValidateInitializers (ec))
3747 if (Arguments == null)
3750 arg_count = Arguments.Count;
3751 for (int i = arg_count; i > 0;){
3753 Argument a = (Argument) Arguments [i];
3755 if (!a.Resolve (ec, loc))
3760 string array_type = FormArrayType (RequestedType, arg_count, Rank);
3761 string element_type = FormElementType (RequestedType, arg_count, Rank);
3763 type = RootContext.LookupType (ec.TypeContainer, array_type, false, loc);
3765 array_element_type = RootContext.LookupType (
3766 ec.TypeContainer, element_type, false, loc);
3771 if (arg_count == 1) {
3772 IsOneDimensional = true;
3773 eclass = ExprClass.Value;
3777 IsBuiltinType = TypeManager.IsBuiltinType (type);
3779 if (IsBuiltinType) {
3783 ml = MemberLookup (ec, type, ".ctor", false, MemberTypes.Constructor,
3784 AllBindingFlags, loc);
3786 if (!(ml is MethodGroupExpr)){
3787 report118 (loc, ml, "method group");
3792 Report.Error (-6, loc, "New invocation: Can not find a constructor for " +
3793 "this argument list");
3797 method = Invocation.OverloadResolve (ec, (MethodGroupExpr) ml, Arguments, loc);
3799 if (method == null) {
3800 Report.Error (-6, loc, "New invocation: Can not find a constructor for " +
3801 "this argument list");
3805 eclass = ExprClass.Value;
3809 ModuleBuilder mb = RootContext.ModuleBuilder;
3811 ArrayList args = new ArrayList ();
3812 if (Arguments != null){
3813 for (int i = arg_count; i > 0;){
3815 Argument a = (Argument) Arguments [i];
3821 Type [] arg_types = null;
3824 arg_types = new Type [args.Count];
3826 args.CopyTo (arg_types, 0);
3828 method = mb.GetArrayMethod (type, ".ctor", CallingConventions.HasThis, null,
3831 if (method == null) {
3832 Report.Error (-6, loc, "New invocation: Can not find a constructor for " +
3833 "this argument list");
3837 eclass = ExprClass.Value;
3843 public static byte [] MakeByteBlob (ArrayList ArrayData, Type underlying_type, Location loc)
3848 int count = ArrayData.Count;
3850 if (underlying_type == TypeManager.int32_type ||
3851 underlying_type == TypeManager.uint32_type ||
3852 underlying_type == TypeManager.float_type)
3854 else if (underlying_type == TypeManager.int64_type ||
3855 underlying_type == TypeManager.uint64_type ||
3856 underlying_type == TypeManager.double_type)
3858 else if (underlying_type == TypeManager.byte_type ||
3859 underlying_type == TypeManager.sbyte_type ||
3860 underlying_type == TypeManager.bool_type)
3862 else if (underlying_type == TypeManager.short_type ||
3863 underlying_type == TypeManager.char_type ||
3864 underlying_type == TypeManager.ushort_type)
3867 Report.Error (-100, loc, "Unhandled type in MakeByteBlob!!");
3871 data = new byte [count * factor];
3874 for (int i = 0; i < count; ++i) {
3875 object v = ArrayData [i];
3877 if (v is EnumConstant)
3878 v = ((EnumConstant) v).Child;
3880 if (underlying_type == TypeManager.int64_type ||
3881 underlying_type == TypeManager.uint64_type){
3883 if (!(v is Expression))
3886 for (int j = 0; j < factor; ++j) {
3887 data [idx + j] = (byte) (val & 0xFF);
3890 } else if (underlying_type == TypeManager.float_type) {
3896 if (!(v is Expression))
3899 byte *ptr = (byte *) &val;
3901 for (int j = 0; j < factor; ++j)
3902 data [idx + j] = (byte) ptr [j];
3905 } else if (underlying_type == TypeManager.double_type) {
3911 if (!(v is Expression))
3914 byte *ptr = (byte *) &val;
3916 for (int j = 0; j < factor; ++j)
3917 data [idx + j] = (byte) ptr [j];
3920 } else if (underlying_type == TypeManager.char_type){
3923 if (!(v is Expression))
3924 v = (int) ((char) v);
3926 data [idx] = (byte) (val & 0xff);
3927 data [idx+1] = (byte) (val >> 8);
3929 } else if (underlying_type == TypeManager.int32_type) {
3932 if (!(v is Expression))
3935 data [idx] = (byte) (val & 0xff);
3936 data [idx+1] = (byte) ((val >> 8) & 0xff);
3937 data [idx+2] = (byte) ((val >> 16) & 0xff);
3938 data [idx+3] = (byte) (val >> 24);
3940 throw new Exception ("Unrecognized type in MakeByteBlob");
3949 // Emits the initializers for the array
3951 void EmitStaticInitializers (EmitContext ec, bool is_expression)
3954 // First, the static data
3957 ILGenerator ig = ec.ig;
3959 byte [] data = MakeByteBlob (ArrayData, underlying_type, loc);
3962 fb = RootContext.MakeStaticData (data);
3965 ig.Emit (OpCodes.Dup);
3966 ig.Emit (OpCodes.Ldtoken, fb);
3967 ig.Emit (OpCodes.Call,
3968 TypeManager.void_initializearray_array_fieldhandle);
3973 // Emits pieces of the array that can not be computed at compile
3974 // time (variables and string locations).
3976 // This always expect the top value on the stack to be the array
3978 void EmitDynamicInitializers (EmitContext ec, bool is_expression)
3980 ILGenerator ig = ec.ig;
3981 int dims = Bounds.Count;
3982 int [] current_pos = new int [dims];
3983 int top = ArrayData.Count;
3984 LocalBuilder temp = ig.DeclareLocal (type);
3986 ig.Emit (OpCodes.Stloc, temp);
3988 MethodInfo set = null;
3992 ModuleBuilder mb = null;
3993 mb = RootContext.ModuleBuilder;
3994 args = new Type [dims + 1];
3997 for (j = 0; j < dims; j++)
3998 args [j] = TypeManager.int32_type;
4000 args [j] = array_element_type;
4002 set = mb.GetArrayMethod (
4004 CallingConventions.HasThis | CallingConventions.Standard,
4005 TypeManager.void_type, args);
4008 for (int i = 0; i < top; i++){
4010 Expression e = null;
4012 if (ArrayData [i] is Expression)
4013 e = (Expression) ArrayData [i];
4017 // Basically we do this for string literals and
4018 // other non-literal expressions
4020 if (e is StringConstant || !(e is Constant)) {
4022 ig.Emit (OpCodes.Ldloc, temp);
4024 for (int idx = dims; idx > 0; ) {
4026 IntConstant.EmitInt (ig, current_pos [idx]);
4032 ArrayAccess.EmitStoreOpcode (ig, array_element_type);
4034 ig.Emit (OpCodes.Call, set);
4042 for (int j = 0; j < dims; j++){
4044 if (current_pos [j] < (int) Bounds [j])
4046 current_pos [j] = 0;
4051 ig.Emit (OpCodes.Ldloc, temp);
4054 void DoEmit (EmitContext ec, bool is_statement)
4056 ILGenerator ig = ec.ig;
4058 if (IsOneDimensional) {
4059 Invocation.EmitArguments (ec, null, Arguments);
4060 ig.Emit (OpCodes.Newarr, array_element_type);
4063 Invocation.EmitArguments (ec, null, Arguments);
4066 ig.Emit (OpCodes.Newobj, (ConstructorInfo) method);
4068 ig.Emit (OpCodes.Newobj, (MethodInfo) method);
4071 if (Initializers != null){
4073 // FIXME: Set this variable correctly.
4075 bool dynamic_initializers = true;
4077 if (underlying_type != TypeManager.string_type &&
4078 underlying_type != TypeManager.object_type)
4079 EmitStaticInitializers (ec, dynamic_initializers || !is_statement);
4081 if (dynamic_initializers)
4082 EmitDynamicInitializers (ec, !is_statement);
4086 public override void Emit (EmitContext ec)
4091 public override void EmitStatement (EmitContext ec)
4099 /// Represents the `this' construct
4101 public class This : Expression, IAssignMethod, IMemoryLocation {
4104 public This (Location loc)
4109 public override Expression DoResolve (EmitContext ec)
4111 eclass = ExprClass.Variable;
4112 type = ec.TypeContainer.TypeBuilder;
4115 Report.Error (26, loc,
4116 "Keyword this not valid in static code");
4123 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
4127 if (ec.TypeContainer is Class){
4128 Report.Error (1604, loc, "Cannot assign to `this'");
4135 public override void Emit (EmitContext ec)
4137 ec.ig.Emit (OpCodes.Ldarg_0);
4140 public void EmitAssign (EmitContext ec, Expression source)
4143 ec.ig.Emit (OpCodes.Starg, 0);
4146 public void AddressOf (EmitContext ec)
4148 ec.ig.Emit (OpCodes.Ldarg_0);
4151 // FIGURE OUT WHY LDARG_S does not work
4153 // consider: struct X { int val; int P { set { val = value; }}}
4155 // Yes, this looks very bad. Look at `NOTAS' for
4157 // ec.ig.Emit (OpCodes.Ldarga_S, (byte) 0);
4162 /// Implements the typeof operator
4164 public class TypeOf : Expression {
4165 public readonly string QueriedType;
4169 public TypeOf (string queried_type, Location l)
4171 QueriedType = queried_type;
4175 public override Expression DoResolve (EmitContext ec)
4177 typearg = RootContext.LookupType (
4178 ec.TypeContainer, QueriedType, false, loc);
4180 if (typearg == null)
4183 type = TypeManager.type_type;
4184 eclass = ExprClass.Type;
4188 public override void Emit (EmitContext ec)
4190 ec.ig.Emit (OpCodes.Ldtoken, typearg);
4191 ec.ig.Emit (OpCodes.Call, TypeManager.system_type_get_type_from_handle);
4196 /// Implements the sizeof expression
4198 public class SizeOf : Expression {
4199 public readonly string QueriedType;
4201 public SizeOf (string queried_type)
4203 this.QueriedType = queried_type;
4206 public override Expression DoResolve (EmitContext ec)
4208 // FIXME: Implement;
4209 throw new Exception ("Unimplemented");
4213 public override void Emit (EmitContext ec)
4215 throw new Exception ("Implement me");
4220 /// Implements the member access expression
4222 public class MemberAccess : Expression {
4223 public readonly string Identifier;
4225 Expression member_lookup;
4228 public MemberAccess (Expression expr, string id, Location l)
4235 public Expression Expr {
4241 static void error176 (Location loc, string name)
4243 Report.Error (176, loc, "Static member `" +
4244 name + "' cannot be accessed " +
4245 "with an instance reference, qualify with a " +
4246 "type name instead");
4250 public static Expression ResolveMemberAccess (EmitContext ec, Expression member_lookup,
4251 Expression left, Location loc)
4256 if (member_lookup is MethodGroupExpr){
4257 MethodGroupExpr mg = (MethodGroupExpr) member_lookup;
4262 if (left is TypeExpr){
4263 if (!mg.RemoveInstanceMethods ()){
4264 SimpleName.Error120 (loc, mg.Methods [0].Name);
4268 return member_lookup;
4272 // Instance.MethodGroup
4274 if (!mg.RemoveStaticMethods ()){
4275 error176 (loc, mg.Methods [0].Name);
4279 mg.InstanceExpression = left;
4281 return member_lookup;
4284 if (member_lookup is FieldExpr){
4285 FieldExpr fe = (FieldExpr) member_lookup;
4286 FieldInfo fi = fe.FieldInfo;
4288 if (fi is FieldBuilder) {
4289 Const c = TypeManager.LookupConstant ((FieldBuilder) fi);
4292 object o = c.LookupConstantValue (ec);
4293 return Constantify (o, fi.FieldType);
4298 Type t = fi.FieldType;
4299 Type decl_type = fi.DeclaringType;
4302 if (fi is FieldBuilder)
4303 o = TypeManager.GetValue ((FieldBuilder) fi);
4305 o = fi.GetValue (fi);
4307 if (decl_type.IsSubclassOf (TypeManager.enum_type)) {
4308 Expression enum_member = MemberLookup (ec, decl_type, "value__",
4311 Enum en = TypeManager.LookupEnum (decl_type);
4315 c = Constantify (o, en.UnderlyingType);
4317 c = Constantify (o, enum_member.Type);
4319 return new EnumConstant (c, decl_type);
4322 Expression exp = Constantify (o, t);
4324 if (!(left is TypeExpr)) {
4325 error176 (loc, fe.FieldInfo.Name);
4332 if (left is TypeExpr){
4333 if (!fe.FieldInfo.IsStatic){
4334 error176 (loc, fe.FieldInfo.Name);
4337 return member_lookup;
4339 if (fe.FieldInfo.IsStatic){
4340 error176 (loc, fe.FieldInfo.Name);
4343 fe.InstanceExpression = left;
4349 if (member_lookup is PropertyExpr){
4350 PropertyExpr pe = (PropertyExpr) member_lookup;
4352 if (left is TypeExpr){
4354 SimpleName.Error120 (loc, pe.PropertyInfo.Name);
4360 error176 (loc, pe.PropertyInfo.Name);
4363 pe.InstanceExpression = left;
4369 if (member_lookup is EventExpr) {
4371 EventExpr ee = (EventExpr) member_lookup;
4374 // If the event is local to this class, we transform ourselves into
4378 Expression ml = MemberLookup (ec, ec.TypeContainer.TypeBuilder, ee.EventInfo.Name,
4379 true, MemberTypes.Event, AllBindingFlags, loc);
4382 MemberInfo mi = ec.TypeContainer.GetFieldFromEvent ((EventExpr) ml);
4384 ml = ExprClassFromMemberInfo (ec, mi, loc);
4387 Report.Error (-200, loc, "Internal error!!");
4391 return ResolveMemberAccess (ec, ml, left, loc);
4394 if (left is TypeExpr) {
4396 SimpleName.Error120 (loc, ee.EventInfo.Name);
4404 error176 (loc, ee.EventInfo.Name);
4408 ee.InstanceExpression = left;
4414 if (member_lookup is TypeExpr){
4415 member_lookup.Resolve (ec);
4416 return member_lookup;
4419 Console.WriteLine ("Left is: " + left);
4420 Report.Error (-100, loc, "Support for [" + member_lookup + "] is not present yet");
4421 Environment.Exit (0);
4425 public override Expression DoResolve (EmitContext ec)
4428 // We are the sole users of ResolveWithSimpleName (ie, the only
4429 // ones that can cope with it
4431 expr = expr.ResolveWithSimpleName (ec);
4436 if (expr is SimpleName){
4437 SimpleName child_expr = (SimpleName) expr;
4439 expr = new SimpleName (child_expr.Name + "." + Identifier, loc);
4441 return expr.ResolveWithSimpleName (ec);
4445 // Handle enums here when they are in transit.
4446 // Note that we cannot afford to hit MemberLookup in this case because
4447 // it will fail to find any members at all
4450 Type expr_type = expr.Type;
4451 if (expr_type.IsSubclassOf (TypeManager.enum_type)) {
4453 Enum en = TypeManager.LookupEnum (expr_type);
4456 object value = en.LookupEnumValue (ec, Identifier, loc);
4461 Constant c = Constantify (value, en.UnderlyingType);
4462 return new EnumConstant (c, expr_type);
4466 member_lookup = MemberLookup (ec, expr.Type, Identifier, false, loc);
4468 if (member_lookup == null)
4471 return ResolveMemberAccess (ec, member_lookup, expr, loc);
4478 // This code is more conformant to the spec (it follows it step by step),
4479 // but it has not been tested yet, and there is nothing here that is not
4480 // caught by the above code. But it might be a better foundation to improve
4483 public ResolveTypeMemberAccess (EmitContext ec, Expression member_lookup,
4484 Expression left, Location loc)
4486 if (member_lookup is TypeExpr){
4487 member_lookup.Resolve (ec);
4488 return member_lookup;
4491 if (member_lookup is MethodGroupExpr){
4492 if (!mg.RemoveStaticMethods ()){
4493 SimpleName.Error120 (loc, mg.Methods [0].Name);
4497 return member_lookup;
4500 if (member_lookup is PropertyExpr){
4501 PropertyExpr pe = (PropertyExpr) member_lookup;
4504 SimpleName.Error120 (loc, pe.PropertyInfo.Name);
4510 if (member_lookup is FieldExpr){
4511 FieldExpr fe = (FieldExpr) member_lookup;
4512 FieldInfo fi = fe.FieldInfo;
4514 if (fi is FieldBuilder) {
4515 Const c = TypeManager.LookupConstant ((FieldBuilder) fi);
4518 object o = c.LookupConstantValue (ec);
4519 return Constantify (o, fi.FieldType);
4524 Type t = fi.FieldType;
4525 Type decl_type = fi.DeclaringType;
4528 if (fi is FieldBuilder)
4529 o = TypeManager.GetValue ((FieldBuilder) fi);
4531 o = fi.GetValue (fi);
4533 if (decl_type.IsSubclassOf (TypeManager.enum_type)) {
4534 Expression enum_member = MemberLookup (
4535 ec, decl_type, "value__",
4538 Enum en = TypeManager.LookupEnum (decl_type);
4542 c = Constantify (o, en.UnderlyingType);
4544 c = Constantify (o, enum_member.Type);
4546 return new EnumConstant (c, decl_type);
4549 Expression exp = Constantify (o, t);
4554 if (!fe.FieldInfo.IsStatic){
4555 error176 (loc, fe.FieldInfo.Name);
4558 return member_lookup;
4561 if (member_lookup is EventExpr){
4563 EventExpr ee = (EventExpr) member_lookup;
4566 // If the event is local to this class, we transform ourselves into
4570 Expression ml = MemberLookup (
4571 ec, ec.TypeContainer.TypeBuilder, ee.EventInfo.Name,
4572 true, MemberTypes.Event, AllBindingFlags, loc);
4575 MemberInfo mi = ec.TypeContainer.GetFieldFromEvent ((EventExpr) ml);
4577 ml = ExprClassFromMemberInfo (ec, mi, loc);
4580 Report.Error (-200, loc, "Internal error!!");
4584 return ResolveMemberAccess (ec, ml, left, loc);
4588 SimpleName.Error120 (loc, ee.EventInfo.Name);
4595 Console.WriteLine ("Left is: " + left);
4596 Report.Error (-100, loc, "Support for [" + member_lookup + "] is not present yet");
4597 Environment.Exit (0);
4602 public ResolveInstanceMemberAccess (EmitContext ec, Expression member_lookup,
4603 Expression left, Location loc)
4605 if (member_lookup is MethodGroupExpr){
4607 // Instance.MethodGroup
4609 if (!mg.RemoveStaticMethods ()){
4610 error176 (loc, mg.Methods [0].Name);
4614 mg.InstanceExpression = left;
4616 return member_lookup;
4619 if (member_lookup is PropertyExpr){
4620 PropertyExpr pe = (PropertyExpr) member_lookup;
4623 error176 (loc, pe.PropertyInfo.Name);
4626 pe.InstanceExpression = left;
4631 Type left_type = left.type;
4633 if (left_type.IsValueType){
4639 public override Expression DoResolve (EmitContext ec)
4642 // We are the sole users of ResolveWithSimpleName (ie, the only
4643 // ones that can cope with it
4645 expr = expr.ResolveWithSimpleName (ec);
4650 if (expr is SimpleName){
4651 SimpleName child_expr = (SimpleName) expr;
4653 expr = new SimpleName (child_expr.Name + "." + Identifier, loc);
4655 return expr.ResolveWithSimpleName (ec);
4659 // Handle enums here when they are in transit.
4660 // Note that we cannot afford to hit MemberLookup in this case because
4661 // it will fail to find any members at all (Why?)
4664 Type expr_type = expr.Type;
4665 if (expr_type.IsSubclassOf (TypeManager.enum_type)) {
4667 Enum en = TypeManager.LookupEnum (expr_type);
4670 object value = en.LookupEnumValue (ec, Identifier, loc);
4675 Constant c = Constantify (value, en.UnderlyingType);
4676 return new EnumConstant (c, expr_type);
4680 member_lookup = MemberLookup (ec, expr.Type, Identifier, false, loc);
4682 if (member_lookup == null)
4685 if (expr is TypeExpr)
4686 return ResolveTypeMemberAccess (ec, member_lookup, expr, loc);
4688 return ResolveInstanceMemberAccess (ec, member_lookup, expr, loc);
4691 public override void Emit (EmitContext ec)
4693 throw new Exception ("Should not happen I think");
4698 /// Implements checked expressions
4700 public class CheckedExpr : Expression {
4702 public Expression Expr;
4704 public CheckedExpr (Expression e)
4709 public override Expression DoResolve (EmitContext ec)
4711 Expr = Expr.Resolve (ec);
4716 eclass = Expr.eclass;
4721 public override void Emit (EmitContext ec)
4723 bool last_check = ec.CheckState;
4725 ec.CheckState = true;
4727 ec.CheckState = last_check;
4733 /// Implements the unchecked expression
4735 public class UnCheckedExpr : Expression {
4737 public Expression Expr;
4739 public UnCheckedExpr (Expression e)
4744 public override Expression DoResolve (EmitContext ec)
4746 Expr = Expr.Resolve (ec);
4751 eclass = Expr.eclass;
4756 public override void Emit (EmitContext ec)
4758 bool last_check = ec.CheckState;
4760 ec.CheckState = false;
4762 ec.CheckState = last_check;
4768 /// An Element Access expression.
4770 /// During semantic analysis these are transformed into
4771 /// IndexerAccess or ArrayAccess
4773 public class ElementAccess : Expression {
4774 public ArrayList Arguments;
4775 public Expression Expr;
4776 public Location loc;
4778 public ElementAccess (Expression e, ArrayList e_list, Location l)
4787 Arguments = new ArrayList ();
4788 foreach (Expression tmp in e_list)
4789 Arguments.Add (new Argument (tmp, Argument.AType.Expression));
4793 bool CommonResolve (EmitContext ec)
4795 Expr = Expr.Resolve (ec);
4800 if (Arguments == null)
4803 for (int i = Arguments.Count; i > 0;){
4805 Argument a = (Argument) Arguments [i];
4807 if (!a.Resolve (ec, loc))
4814 public override Expression DoResolve (EmitContext ec)
4816 if (!CommonResolve (ec))
4820 // We perform some simple tests, and then to "split" the emit and store
4821 // code we create an instance of a different class, and return that.
4823 // I am experimenting with this pattern.
4825 if (Expr.Type.IsSubclassOf (TypeManager.array_type))
4826 return (new ArrayAccess (this)).Resolve (ec);
4828 return (new IndexerAccess (this)).Resolve (ec);
4831 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
4833 if (!CommonResolve (ec))
4836 if (Expr.Type.IsSubclassOf (TypeManager.array_type))
4837 return (new ArrayAccess (this)).ResolveLValue (ec, right_side);
4839 return (new IndexerAccess (this)).ResolveLValue (ec, right_side);
4842 public override void Emit (EmitContext ec)
4844 throw new Exception ("Should never be reached");
4849 /// Implements array access
4851 public class ArrayAccess : Expression, IAssignMethod, IMemoryLocation {
4853 // Points to our "data" repository
4857 public ArrayAccess (ElementAccess ea_data)
4860 eclass = ExprClass.Variable;
4863 public override Expression DoResolve (EmitContext ec)
4865 if (ea.Expr.eclass != ExprClass.Variable) {
4866 report118 (ea.loc, ea.Expr, "variable");
4870 Type t = ea.Expr.Type;
4872 if (t.GetArrayRank () != ea.Arguments.Count){
4873 Report.Error (22, ea.loc,
4874 "Incorrect number of indexes for array " +
4875 " expected: " + t.GetArrayRank () + " got: " +
4876 ea.Arguments.Count);
4879 type = t.GetElementType ();
4880 eclass = ExprClass.Variable;
4886 /// Emits the right opcode to load an object of Type `t'
4887 /// from an array of T
4889 static public void EmitLoadOpcode (ILGenerator ig, Type type)
4891 if (type == TypeManager.byte_type)
4892 ig.Emit (OpCodes.Ldelem_I1);
4893 else if (type == TypeManager.sbyte_type)
4894 ig.Emit (OpCodes.Ldelem_U1);
4895 else if (type == TypeManager.short_type)
4896 ig.Emit (OpCodes.Ldelem_I2);
4897 else if (type == TypeManager.ushort_type)
4898 ig.Emit (OpCodes.Ldelem_U2);
4899 else if (type == TypeManager.int32_type)
4900 ig.Emit (OpCodes.Ldelem_I4);
4901 else if (type == TypeManager.uint32_type)
4902 ig.Emit (OpCodes.Ldelem_U4);
4903 else if (type == TypeManager.uint64_type)
4904 ig.Emit (OpCodes.Ldelem_I8);
4905 else if (type == TypeManager.int64_type)
4906 ig.Emit (OpCodes.Ldelem_I8);
4907 else if (type == TypeManager.float_type)
4908 ig.Emit (OpCodes.Ldelem_R4);
4909 else if (type == TypeManager.double_type)
4910 ig.Emit (OpCodes.Ldelem_R8);
4911 else if (type == TypeManager.intptr_type)
4912 ig.Emit (OpCodes.Ldelem_I);
4913 else if (type.IsValueType)
4914 ig.Emit (OpCodes.Ldelema, type);
4916 ig.Emit (OpCodes.Ldelem_Ref);
4920 /// Emits the right opcode to store an object of Type `t'
4921 /// from an array of T.
4923 static public void EmitStoreOpcode (ILGenerator ig, Type t)
4925 if (t == TypeManager.byte_type || t == TypeManager.sbyte_type)
4926 ig.Emit (OpCodes.Stelem_I1);
4927 else if (t == TypeManager.short_type || t == TypeManager.ushort_type)
4928 ig.Emit (OpCodes.Stelem_I2);
4929 else if (t == TypeManager.int32_type || t == TypeManager.uint32_type)
4930 ig.Emit (OpCodes.Stelem_I4);
4931 else if (t == TypeManager.int64_type || t == TypeManager.uint64_type)
4932 ig.Emit (OpCodes.Stelem_I8);
4933 else if (t == TypeManager.float_type)
4934 ig.Emit (OpCodes.Stelem_R4);
4935 else if (t == TypeManager.double_type)
4936 ig.Emit (OpCodes.Stelem_R8);
4937 else if (t == TypeManager.intptr_type)
4938 ig.Emit (OpCodes.Stelem_I);
4940 ig.Emit (OpCodes.Stelem_Ref);
4943 MethodInfo FetchGetMethod ()
4945 ModuleBuilder mb = RootContext.ModuleBuilder;
4946 Type [] args = new Type [ea.Arguments.Count];
4951 foreach (Argument a in ea.Arguments)
4952 args [i++] = a.Type;
4954 get = mb.GetArrayMethod (
4955 ea.Expr.Type, "Get",
4956 CallingConventions.HasThis |
4957 CallingConventions.Standard,
4963 MethodInfo FetchAddressMethod ()
4965 ModuleBuilder mb = RootContext.ModuleBuilder;
4966 Type [] args = new Type [ea.Arguments.Count];
4968 string ptr_type_name;
4972 ptr_type_name = type.FullName + "&";
4973 ret_type = Type.GetType (ptr_type_name);
4976 // It is a type defined by the source code we are compiling
4978 if (ret_type == null){
4979 ret_type = mb.GetType (ptr_type_name);
4982 foreach (Argument a in ea.Arguments)
4983 args [i++] = a.Type;
4985 address = mb.GetArrayMethod (
4986 ea.Expr.Type, "Address",
4987 CallingConventions.HasThis |
4988 CallingConventions.Standard,
4994 public override void Emit (EmitContext ec)
4996 int rank = ea.Expr.Type.GetArrayRank ();
4997 ILGenerator ig = ec.ig;
5001 foreach (Argument a in ea.Arguments)
5005 EmitLoadOpcode (ig, type);
5009 method = FetchGetMethod ();
5010 ig.Emit (OpCodes.Call, method);
5014 public void EmitAssign (EmitContext ec, Expression source)
5016 int rank = ea.Expr.Type.GetArrayRank ();
5017 ILGenerator ig = ec.ig;
5021 foreach (Argument a in ea.Arguments)
5026 Type t = source.Type;
5029 EmitStoreOpcode (ig, t);
5031 ModuleBuilder mb = RootContext.ModuleBuilder;
5032 Type [] args = new Type [ea.Arguments.Count + 1];
5037 foreach (Argument a in ea.Arguments)
5038 args [i++] = a.Type;
5042 set = mb.GetArrayMethod (
5043 ea.Expr.Type, "Set",
5044 CallingConventions.HasThis |
5045 CallingConventions.Standard,
5046 TypeManager.void_type, args);
5048 ig.Emit (OpCodes.Call, set);
5052 public void AddressOf (EmitContext ec)
5054 int rank = ea.Expr.Type.GetArrayRank ();
5055 ILGenerator ig = ec.ig;
5059 foreach (Argument a in ea.Arguments)
5063 ig.Emit (OpCodes.Ldelema, type);
5065 MethodInfo address = FetchAddressMethod ();
5066 ig.Emit (OpCodes.Call, address);
5073 public ArrayList getters, setters;
5074 static Hashtable map;
5078 map = new Hashtable ();
5081 Indexers (MemberInfo [] mi)
5083 foreach (PropertyInfo property in mi){
5084 MethodInfo get, set;
5086 get = property.GetGetMethod (true);
5088 if (getters == null)
5089 getters = new ArrayList ();
5094 set = property.GetSetMethod (true);
5096 if (setters == null)
5097 setters = new ArrayList ();
5103 static public Indexers GetIndexersForType (Type t, TypeManager tm, Location loc)
5105 Indexers ix = (Indexers) map [t];
5106 string p_name = TypeManager.IndexerPropertyName (t);
5111 MemberInfo [] mi = tm.FindMembers (
5112 t, MemberTypes.Property,
5113 BindingFlags.Public | BindingFlags.Instance,
5114 Type.FilterName, p_name);
5116 if (mi == null || mi.Length == 0){
5117 Report.Error (21, loc,
5118 "Type `" + TypeManager.CSharpName (t) + "' does not have " +
5119 "any indexers defined");
5123 ix = new Indexers (mi);
5131 /// Expressions that represent an indexer call.
5133 public class IndexerAccess : Expression, IAssignMethod {
5135 // Points to our "data" repository
5138 MethodInfo get, set;
5140 ArrayList set_arguments;
5142 public IndexerAccess (ElementAccess ea_data)
5145 eclass = ExprClass.Value;
5148 public override Expression DoResolve (EmitContext ec)
5150 Type indexer_type = ea.Expr.Type;
5153 // Step 1: Query for all `Item' *properties*. Notice
5154 // that the actual methods are pointed from here.
5156 // This is a group of properties, piles of them.
5159 ilist = Indexers.GetIndexersForType (
5160 indexer_type, RootContext.TypeManager, ea.loc);
5164 // Step 2: find the proper match
5166 if (ilist != null && ilist.getters != null && ilist.getters.Count > 0)
5167 get = (MethodInfo) Invocation.OverloadResolve (
5168 ec, new MethodGroupExpr (ilist.getters), ea.Arguments, ea.loc);
5171 Report.Error (154, ea.loc,
5172 "indexer can not be used in this context, because " +
5173 "it lacks a `get' accessor");
5177 type = get.ReturnType;
5178 eclass = ExprClass.IndexerAccess;
5182 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
5184 Type indexer_type = ea.Expr.Type;
5185 Type right_type = right_side.Type;
5188 ilist = Indexers.GetIndexersForType (
5189 indexer_type, RootContext.TypeManager, ea.loc);
5191 if (ilist != null && ilist.setters != null && ilist.setters.Count > 0){
5192 set_arguments = (ArrayList) ea.Arguments.Clone ();
5193 set_arguments.Add (new Argument (right_side, Argument.AType.Expression));
5195 set = (MethodInfo) Invocation.OverloadResolve (
5196 ec, new MethodGroupExpr (ilist.setters), set_arguments, ea.loc);
5200 Report.Error (200, ea.loc,
5201 "indexer X.this [" + TypeManager.CSharpName (right_type) +
5202 "] lacks a `set' accessor");
5206 type = TypeManager.void_type;
5207 eclass = ExprClass.IndexerAccess;
5211 public override void Emit (EmitContext ec)
5213 Invocation.EmitCall (ec, false, ea.Expr, get, ea.Arguments);
5217 // source is ignored, because we already have a copy of it from the
5218 // LValue resolution and we have already constructed a pre-cached
5219 // version of the arguments (ea.set_arguments);
5221 public void EmitAssign (EmitContext ec, Expression source)
5223 Invocation.EmitCall (ec, false, ea.Expr, set, set_arguments);
5228 /// The base operator for method names
5230 public class BaseAccess : Expression {
5234 public BaseAccess (string member, Location l)
5236 this.member = member;
5240 public override Expression DoResolve (EmitContext ec)
5242 Expression member_lookup;
5243 Type current_type = ec.TypeContainer.TypeBuilder;
5244 Type base_type = current_type.BaseType;
5246 member_lookup = MemberLookup (ec, base_type, member, false, loc);
5247 if (member_lookup == null)
5253 left = new TypeExpr (base_type);
5255 left = new This (loc).Resolve (ec);
5257 return MemberAccess.ResolveMemberAccess (ec, member_lookup, left, loc);
5260 public override void Emit (EmitContext ec)
5262 throw new Exception ("Should never be called");
5267 /// The base indexer operator
5269 public class BaseIndexerAccess : Expression {
5270 ArrayList Arguments;
5272 public BaseIndexerAccess (ArrayList args)
5277 public override Expression DoResolve (EmitContext ec)
5279 // FIXME: Implement;
5280 throw new Exception ("Unimplemented");
5284 public override void Emit (EmitContext ec)
5286 throw new Exception ("Unimplemented");
5291 /// This class exists solely to pass the Type around and to be a dummy
5292 /// that can be passed to the conversion functions (this is used by
5293 /// foreach implementation to typecast the object return value from
5294 /// get_Current into the proper type. All code has been generated and
5295 /// we only care about the side effect conversions to be performed
5297 public class EmptyExpression : Expression {
5298 public EmptyExpression ()
5300 type = TypeManager.object_type;
5301 eclass = ExprClass.Value;
5304 public EmptyExpression (Type t)
5307 eclass = ExprClass.Value;
5310 public override Expression DoResolve (EmitContext ec)
5315 public override void Emit (EmitContext ec)
5317 // nothing, as we only exist to not do anything.
5321 // This is just because we might want to reuse this bad boy
5322 // instead of creating gazillions of EmptyExpressions.
5323 // (CanConvertImplicit uses it)
5325 public void SetType (Type t)
5331 public class UserCast : Expression {
5335 public UserCast (MethodInfo method, Expression source)
5337 this.method = method;
5338 this.source = source;
5339 type = method.ReturnType;
5340 eclass = ExprClass.Value;
5343 public override Expression DoResolve (EmitContext ec)
5346 // We are born fully resolved
5351 public override void Emit (EmitContext ec)
5353 ILGenerator ig = ec.ig;
5357 if (method is MethodInfo)
5358 ig.Emit (OpCodes.Call, (MethodInfo) method);
5360 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
5367 // This class is used to "construct" the type during a typecast
5368 // operation. Since the Type.GetType class in .NET can parse
5369 // the type specification, we just use this to construct the type
5370 // one bit at a time.
5372 public class ComposedCast : Expression {
5377 public ComposedCast (Expression left, string dim, Location l)
5384 public override Expression DoResolve (EmitContext ec)
5386 left = left.Resolve (ec);
5390 if (left.eclass != ExprClass.Type){
5391 report118 (loc, left, "type");
5395 type = RootContext.LookupType (
5396 ec.TypeContainer, left.Type.FullName + dim, false, loc);
5400 eclass = ExprClass.Type;
5404 public override void Emit (EmitContext ec)
5406 throw new Exception ("This should never be called");