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
95 public Expression Expr;
98 public Unary (Operator op, Expression expr, Location loc)
106 /// Returns a stringified representation of the Operator
108 static public string OperName (Operator oper)
111 case Operator.UnaryPlus:
113 case Operator.UnaryNegation:
115 case Operator.LogicalNot:
117 case Operator.OnesComplement:
119 case Operator.AddressOf:
121 case Operator.Indirection:
125 return oper.ToString ();
128 static string [] oper_names;
132 oper_names = new string [(int)Operator.TOP];
134 oper_names [(int) Operator.UnaryPlus] = "op_UnaryPlus";
135 oper_names [(int) Operator.UnaryNegation] = "op_UnaryNegation";
136 oper_names [(int) Operator.LogicalNot] = "op_LogicalNot";
137 oper_names [(int) Operator.OnesComplement] = "op_OnesComplement";
138 oper_names [(int) Operator.Indirection] = "op_Indirection";
139 oper_names [(int) Operator.AddressOf] = "op_AddressOf";
142 void Error23 (Type t)
145 23, loc, "Operator " + OperName (Oper) +
146 " cannot be applied to operand of type `" +
147 TypeManager.CSharpName (t) + "'");
151 /// The result has been already resolved:
153 /// FIXME: a minus constant -128 sbyte cant be turned into a
156 static Expression TryReduceNegative (Expression expr)
160 if (expr is IntConstant)
161 e = new IntConstant (-((IntConstant) expr).Value);
162 else if (expr is UIntConstant)
163 e = new LongConstant (-((UIntConstant) expr).Value);
164 else if (expr is LongConstant)
165 e = new LongConstant (-((LongConstant) expr).Value);
166 else if (expr is FloatConstant)
167 e = new FloatConstant (-((FloatConstant) expr).Value);
168 else if (expr is DoubleConstant)
169 e = new DoubleConstant (-((DoubleConstant) expr).Value);
170 else if (expr is DecimalConstant)
171 e = new DecimalConstant (-((DecimalConstant) expr).Value);
172 else if (expr is ShortConstant)
173 e = new IntConstant (-((ShortConstant) expr).Value);
174 else if (expr is UShortConstant)
175 e = new IntConstant (-((UShortConstant) expr).Value);
179 Expression Reduce (EmitContext ec, Expression e)
181 Type expr_type = e.Type;
184 case Operator.UnaryPlus:
187 case Operator.UnaryNegation:
188 return TryReduceNegative (e);
190 case Operator.LogicalNot:
191 if (expr_type != TypeManager.bool_type) {
196 BoolConstant b = (BoolConstant) e;
197 return new BoolConstant (!(b.Value));
199 case Operator.OnesComplement:
200 if (!((expr_type == TypeManager.int32_type) ||
201 (expr_type == TypeManager.uint32_type) ||
202 (expr_type == TypeManager.int64_type) ||
203 (expr_type == TypeManager.uint64_type) ||
204 (expr_type.IsSubclassOf (TypeManager.enum_type)))){
209 if (e is EnumConstant){
210 EnumConstant enum_constant = (EnumConstant) e;
212 Expression reduced = Reduce (ec, enum_constant.Child);
214 return new EnumConstant ((Constant) reduced, enum_constant.Type);
217 if (expr_type == TypeManager.int32_type)
218 return new IntConstant (~ ((IntConstant) e).Value);
219 if (expr_type == TypeManager.uint32_type)
220 return new UIntConstant (~ ((UIntConstant) e).Value);
221 if (expr_type == TypeManager.int64_type)
222 return new LongConstant (~ ((LongConstant) e).Value);
223 if (expr_type == TypeManager.uint64_type)
224 return new ULongConstant (~ ((ULongConstant) e).Value);
229 throw new Exception ("Can not constant fold");
232 Expression ResolveOperator (EmitContext ec)
234 Type expr_type = Expr.Type;
237 // Step 1: Perform Operator Overload location
242 op_name = oper_names [(int) Oper];
244 mg = MemberLookup (ec, expr_type, op_name, MemberTypes.Method, AllBindingFlags, loc);
247 Expression e = StaticCallExpr.MakeSimpleCall (
248 ec, (MethodGroupExpr) mg, Expr, loc);
258 // Only perform numeric promotions on:
261 if (expr_type == null)
265 // Step 2: Default operations on CLI native types.
267 if (Expr is Constant)
268 return Reduce (ec, Expr);
270 if (Oper == Operator.LogicalNot){
271 if (expr_type != TypeManager.bool_type) {
276 type = TypeManager.bool_type;
280 if (Oper == Operator.OnesComplement) {
281 if (!((expr_type == TypeManager.int32_type) ||
282 (expr_type == TypeManager.uint32_type) ||
283 (expr_type == TypeManager.int64_type) ||
284 (expr_type == TypeManager.uint64_type) ||
285 (expr_type.IsSubclassOf (TypeManager.enum_type)))){
288 e = ConvertImplicit (ec, Expr, TypeManager.int32_type, loc);
290 type = TypeManager.int32_type;
293 e = ConvertImplicit (ec, Expr, TypeManager.uint32_type, loc);
295 type = TypeManager.uint32_type;
298 e = ConvertImplicit (ec, Expr, TypeManager.int64_type, loc);
300 type = TypeManager.int64_type;
303 e = ConvertImplicit (ec, Expr, TypeManager.uint64_type, loc);
305 type = TypeManager.uint64_type;
315 if (Oper == Operator.UnaryPlus) {
317 // A plus in front of something is just a no-op, so return the child.
323 // Deals with -literals
324 // int operator- (int x)
325 // long operator- (long x)
326 // float operator- (float f)
327 // double operator- (double d)
328 // decimal operator- (decimal d)
330 if (Oper == Operator.UnaryNegation){
334 // transform - - expr into expr
337 Unary unary = (Unary) Expr;
339 if (unary.Oper == Operator.UnaryNegation)
344 // perform numeric promotions to int,
348 // The following is inneficient, because we call
349 // ConvertImplicit too many times.
351 // It is also not clear if we should convert to Float
352 // or Double initially.
354 if (expr_type == TypeManager.uint32_type){
356 // FIXME: handle exception to this rule that
357 // permits the int value -2147483648 (-2^31) to
358 // bt wrote as a decimal interger literal
360 type = TypeManager.int64_type;
361 Expr = ConvertImplicit (ec, Expr, type, loc);
365 if (expr_type == TypeManager.uint64_type){
367 // FIXME: Handle exception of `long value'
368 // -92233720368547758087 (-2^63) to be wrote as
369 // decimal integer literal.
375 if (expr_type == TypeManager.float_type){
380 e = ConvertImplicit (ec, Expr, TypeManager.int32_type, loc);
387 e = ConvertImplicit (ec, Expr, TypeManager.int64_type, loc);
394 e = ConvertImplicit (ec, Expr, TypeManager.double_type, loc);
405 if (Oper == Operator.AddressOf){
406 if (Expr.eclass != ExprClass.Variable){
407 Error (211, loc, "Cannot take the address of non-variables");
416 if (!TypeManager.VerifyUnManaged (Expr.Type, loc)){
421 // This construct is needed because dynamic types
422 // are not known by Type.GetType, so we have to try then to use
423 // ModuleBuilder.GetType.
425 string ptr_type_name = Expr.Type.FullName + "*";
426 type = Type.GetType (ptr_type_name);
428 type = CodeGen.ModuleBuilder.GetType (ptr_type_name);
433 if (Oper == Operator.Indirection){
439 if (!expr_type.IsPointer){
442 "The * or -> operator can only be applied to pointers");
447 // We create an Indirection expression, because
448 // it can implement the IMemoryLocation.
450 return new Indirection (Expr);
453 Error (187, loc, "No such operator '" + OperName (Oper) + "' defined for type '" +
454 TypeManager.CSharpName (expr_type) + "'");
458 public override Expression DoResolve (EmitContext ec)
460 Expr = Expr.Resolve (ec);
465 eclass = ExprClass.Value;
466 return ResolveOperator (ec);
469 public override void Emit (EmitContext ec)
471 ILGenerator ig = ec.ig;
472 Type expr_type = Expr.Type;
475 case Operator.UnaryPlus:
476 throw new Exception ("This should be caught by Resolve");
478 case Operator.UnaryNegation:
480 ig.Emit (OpCodes.Neg);
483 case Operator.LogicalNot:
485 ig.Emit (OpCodes.Ldc_I4_0);
486 ig.Emit (OpCodes.Ceq);
489 case Operator.OnesComplement:
491 ig.Emit (OpCodes.Not);
494 case Operator.AddressOf:
495 ((IMemoryLocation)Expr).AddressOf (ec, AddressOp.LoadStore);
499 throw new Exception ("This should not happen: Operator = "
505 /// This will emit the child expression for `ec' avoiding the logical
506 /// not. The parent will take care of changing brfalse/brtrue
508 public void EmitLogicalNot (EmitContext ec)
510 if (Oper != Operator.LogicalNot)
511 throw new Exception ("EmitLogicalNot can only be called with !expr");
516 public override string ToString ()
518 return "Unary (" + Oper + ", " + Expr + ")";
524 // Unary operators are turned into Indirection expressions
525 // after semantic analysis (this is so we can take the address
526 // of an indirection).
528 public class Indirection : Expression, IMemoryLocation, IAssignMethod {
531 public Indirection (Expression expr)
534 this.type = expr.Type.GetElementType ();
535 eclass = ExprClass.Variable;
538 public override void Emit (EmitContext ec)
541 LoadFromPtr (ec.ig, Type, false);
544 public void EmitAssign (EmitContext ec, Expression source)
548 StoreFromPtr (ec.ig, type);
551 public void AddressOf (EmitContext ec, AddressOp Mode)
556 public override Expression DoResolve (EmitContext ec)
559 // Born fully resolved
566 /// Unary Mutator expressions (pre and post ++ and --)
570 /// UnaryMutator implements ++ and -- expressions. It derives from
571 /// ExpressionStatement becuase the pre/post increment/decrement
572 /// operators can be used in a statement context.
574 /// FIXME: Idea, we could split this up in two classes, one simpler
575 /// for the common case, and one with the extra fields for more complex
576 /// classes (indexers require temporary access; overloaded require method)
578 /// Maybe we should have classes PreIncrement, PostIncrement, PreDecrement,
579 /// PostDecrement, that way we could save the `Mode' byte as well.
581 public class UnaryMutator : ExpressionStatement {
582 public enum Mode : byte {
583 PreIncrement, PreDecrement, PostIncrement, PostDecrement
589 LocalTemporary temp_storage;
592 // This is expensive for the simplest case.
596 public UnaryMutator (Mode m, Expression e, Location l)
603 static string OperName (Mode mode)
605 return (mode == Mode.PreIncrement || mode == Mode.PostIncrement) ?
609 void Error23 (Type t)
612 23, loc, "Operator " + OperName (mode) +
613 " cannot be applied to operand of type `" +
614 TypeManager.CSharpName (t) + "'");
618 /// Returns whether an object of type `t' can be incremented
619 /// or decremented with add/sub (ie, basically whether we can
620 /// use pre-post incr-decr operations on it, but it is not a
621 /// System.Decimal, which we require operator overloading to catch)
623 static bool IsIncrementableNumber (Type t)
625 return (t == TypeManager.sbyte_type) ||
626 (t == TypeManager.byte_type) ||
627 (t == TypeManager.short_type) ||
628 (t == TypeManager.ushort_type) ||
629 (t == TypeManager.int32_type) ||
630 (t == TypeManager.uint32_type) ||
631 (t == TypeManager.int64_type) ||
632 (t == TypeManager.uint64_type) ||
633 (t == TypeManager.char_type) ||
634 (t.IsSubclassOf (TypeManager.enum_type)) ||
635 (t == TypeManager.float_type) ||
636 (t == TypeManager.double_type) ||
637 (t.IsPointer && t != TypeManager.void_ptr_type);
640 Expression ResolveOperator (EmitContext ec)
642 Type expr_type = expr.Type;
645 // Step 1: Perform Operator Overload location
650 if (mode == Mode.PreIncrement || mode == Mode.PostIncrement)
651 op_name = "op_Increment";
653 op_name = "op_Decrement";
655 mg = MemberLookup (ec, expr_type, op_name, MemberTypes.Method, AllBindingFlags, loc);
657 if (mg == null && expr_type.BaseType != null)
658 mg = MemberLookup (ec, expr_type.BaseType, op_name,
659 MemberTypes.Method, AllBindingFlags, loc);
662 method = StaticCallExpr.MakeSimpleCall (
663 ec, (MethodGroupExpr) mg, expr, loc);
670 // The operand of the prefix/postfix increment decrement operators
671 // should be an expression that is classified as a variable,
672 // a property access or an indexer access
675 if (expr.eclass == ExprClass.Variable){
676 if (IsIncrementableNumber (expr_type) ||
677 expr_type == TypeManager.decimal_type){
680 } else if (expr.eclass == ExprClass.IndexerAccess){
681 IndexerAccess ia = (IndexerAccess) expr;
683 temp_storage = new LocalTemporary (ec, expr.Type);
685 expr = ia.ResolveLValue (ec, temp_storage);
690 } else if (expr.eclass == ExprClass.PropertyAccess){
691 PropertyExpr pe = (PropertyExpr) expr;
693 if (pe.VerifyAssignable ())
698 report118 (loc, expr, "variable, indexer or property access");
702 Error (187, loc, "No such operator '" + OperName (mode) + "' defined for type '" +
703 TypeManager.CSharpName (expr_type) + "'");
707 public override Expression DoResolve (EmitContext ec)
709 expr = expr.Resolve (ec);
714 eclass = ExprClass.Value;
715 return ResolveOperator (ec);
718 static int PtrTypeSize (Type t)
720 return GetTypeSize (t.GetElementType ());
724 // FIXME: We need some way of avoiding the use of temp_storage
725 // for some types of storage (parameters, local variables,
726 // static fields) and single-dimension array access.
728 void EmitCode (EmitContext ec, bool is_expr)
730 ILGenerator ig = ec.ig;
731 IAssignMethod ia = (IAssignMethod) expr;
732 Type expr_type = expr.Type;
734 if (temp_storage == null)
735 temp_storage = new LocalTemporary (ec, expr_type);
738 case Mode.PreIncrement:
739 case Mode.PreDecrement:
743 if (expr_type == TypeManager.uint64_type ||
744 expr_type == TypeManager.int64_type)
745 ig.Emit (OpCodes.Ldc_I8, 1L);
746 else if (expr_type == TypeManager.double_type)
747 ig.Emit (OpCodes.Ldc_R8, 1.0);
748 else if (expr_type == TypeManager.float_type)
749 ig.Emit (OpCodes.Ldc_R4, 1.0F);
750 else if (expr_type.IsPointer){
751 int n = PtrTypeSize (expr_type);
754 ig.Emit (OpCodes.Sizeof, expr_type);
756 IntConstant.EmitInt (ig, n);
758 ig.Emit (OpCodes.Ldc_I4_1);
761 // Select the opcode based on the check state (then the type)
762 // and the actual operation
765 if (expr_type == TypeManager.int32_type ||
766 expr_type == TypeManager.int64_type){
767 if (mode == Mode.PreDecrement)
768 ig.Emit (OpCodes.Sub_Ovf);
770 ig.Emit (OpCodes.Add_Ovf);
771 } else if (expr_type == TypeManager.uint32_type ||
772 expr_type == TypeManager.uint64_type){
773 if (mode == Mode.PreDecrement)
774 ig.Emit (OpCodes.Sub_Ovf_Un);
776 ig.Emit (OpCodes.Add_Ovf_Un);
778 if (mode == Mode.PreDecrement)
779 ig.Emit (OpCodes.Sub_Ovf);
781 ig.Emit (OpCodes.Add_Ovf);
784 if (mode == Mode.PreDecrement)
785 ig.Emit (OpCodes.Sub);
787 ig.Emit (OpCodes.Add);
792 temp_storage.Store (ec);
793 ia.EmitAssign (ec, temp_storage);
795 temp_storage.Emit (ec);
798 case Mode.PostIncrement:
799 case Mode.PostDecrement:
807 ig.Emit (OpCodes.Dup);
809 if (expr_type == TypeManager.uint64_type ||
810 expr_type == TypeManager.int64_type)
811 ig.Emit (OpCodes.Ldc_I8, 1L);
812 else if (expr_type == TypeManager.double_type)
813 ig.Emit (OpCodes.Ldc_R8, 1.0);
814 else if (expr_type == TypeManager.float_type)
815 ig.Emit (OpCodes.Ldc_R4, 1.0F);
816 else if (expr_type.IsPointer){
817 int n = PtrTypeSize (expr_type);
820 ig.Emit (OpCodes.Sizeof, expr_type);
822 IntConstant.EmitInt (ig, n);
824 ig.Emit (OpCodes.Ldc_I4_1);
827 if (expr_type == TypeManager.int32_type ||
828 expr_type == TypeManager.int64_type){
829 if (mode == Mode.PostDecrement)
830 ig.Emit (OpCodes.Sub_Ovf);
832 ig.Emit (OpCodes.Add_Ovf);
833 } else if (expr_type == TypeManager.uint32_type ||
834 expr_type == TypeManager.uint64_type){
835 if (mode == Mode.PostDecrement)
836 ig.Emit (OpCodes.Sub_Ovf_Un);
838 ig.Emit (OpCodes.Add_Ovf_Un);
840 if (mode == Mode.PostDecrement)
841 ig.Emit (OpCodes.Sub_Ovf);
843 ig.Emit (OpCodes.Add_Ovf);
846 if (mode == Mode.PostDecrement)
847 ig.Emit (OpCodes.Sub);
849 ig.Emit (OpCodes.Add);
855 temp_storage.Store (ec);
856 ia.EmitAssign (ec, temp_storage);
861 public override void Emit (EmitContext ec)
867 public override void EmitStatement (EmitContext ec)
869 EmitCode (ec, false);
875 /// Base class for the `Is' and `As' classes.
879 /// FIXME: Split this in two, and we get to save the `Operator' Oper
882 public abstract class Probe : Expression {
883 public readonly string ProbeType;
884 protected Expression expr;
885 protected Type probe_type;
886 protected Location loc;
888 public Probe (Expression expr, string probe_type, Location l)
890 ProbeType = probe_type;
895 public Expression Expr {
901 public override Expression DoResolve (EmitContext ec)
903 probe_type = RootContext.LookupType (ec.DeclSpace, ProbeType, false, loc);
905 if (probe_type == null)
908 expr = expr.Resolve (ec);
915 /// Implementation of the `is' operator.
917 public class Is : Probe {
918 public Is (Expression expr, string probe_type, Location l)
919 : base (expr, probe_type, l)
923 public override void Emit (EmitContext ec)
925 ILGenerator ig = ec.ig;
929 ig.Emit (OpCodes.Isinst, probe_type);
930 ig.Emit (OpCodes.Ldnull);
931 ig.Emit (OpCodes.Cgt_Un);
934 public override Expression DoResolve (EmitContext ec)
936 Expression e = base.DoResolve (ec);
941 if (RootContext.WarningLevel >= 1){
942 Type etype = expr.Type;
944 if (etype == probe_type || etype.IsSubclassOf (probe_type)){
947 "The expression is always of type `" +
948 TypeManager.CSharpName (probe_type) + "'");
949 } else if (etype != probe_type && !probe_type.IsSubclassOf (etype)){
950 if (!(probe_type.IsInterface || expr.Type.IsInterface))
953 "The expression is never of type `" +
954 TypeManager.CSharpName (probe_type) + "'");
958 type = TypeManager.bool_type;
959 eclass = ExprClass.Value;
966 /// Implementation of the `as' operator.
968 public class As : Probe {
969 public As (Expression expr, string probe_type, Location l)
970 : base (expr, probe_type, l)
974 public override void Emit (EmitContext ec)
976 ILGenerator ig = ec.ig;
978 Type etype = expr.Type;
981 if (etype == probe_type || etype.IsSubclassOf (probe_type))
984 ig.Emit (OpCodes.Isinst, probe_type);
987 public override Expression DoResolve (EmitContext ec)
989 Expression e = base.DoResolve (ec);
995 eclass = ExprClass.Value;
1002 /// This represents a typecast in the source language.
1004 /// FIXME: Cast expressions have an unusual set of parsing
1005 /// rules, we need to figure those out.
1007 public class Cast : Expression {
1008 Expression target_type;
1012 public Cast (Expression cast_type, Expression expr, Location loc)
1014 this.target_type = cast_type;
1019 public Expression TargetType {
1025 public Expression Expr {
1035 /// Attempts to do a compile-time folding of a constant cast.
1037 Expression TryReduce (EmitContext ec, Type target_type)
1039 if (expr is ByteConstant){
1040 byte v = ((ByteConstant) expr).Value;
1042 if (target_type == TypeManager.sbyte_type)
1043 return new SByteConstant ((sbyte) v);
1044 if (target_type == TypeManager.short_type)
1045 return new ShortConstant ((short) v);
1046 if (target_type == TypeManager.ushort_type)
1047 return new UShortConstant ((ushort) v);
1048 if (target_type == TypeManager.int32_type)
1049 return new IntConstant ((int) v);
1050 if (target_type == TypeManager.uint32_type)
1051 return new UIntConstant ((uint) v);
1052 if (target_type == TypeManager.int64_type)
1053 return new LongConstant ((long) v);
1054 if (target_type == TypeManager.uint64_type)
1055 return new ULongConstant ((ulong) v);
1056 if (target_type == TypeManager.float_type)
1057 return new FloatConstant ((float) v);
1058 if (target_type == TypeManager.double_type)
1059 return new DoubleConstant ((double) v);
1061 if (expr is SByteConstant){
1062 sbyte v = ((SByteConstant) expr).Value;
1064 if (target_type == TypeManager.byte_type)
1065 return new ByteConstant ((byte) v);
1066 if (target_type == TypeManager.short_type)
1067 return new ShortConstant ((short) v);
1068 if (target_type == TypeManager.ushort_type)
1069 return new UShortConstant ((ushort) v);
1070 if (target_type == TypeManager.int32_type)
1071 return new IntConstant ((int) v);
1072 if (target_type == TypeManager.uint32_type)
1073 return new UIntConstant ((uint) v);
1074 if (target_type == TypeManager.int64_type)
1075 return new LongConstant ((long) v);
1076 if (target_type == TypeManager.uint64_type)
1077 return new ULongConstant ((ulong) v);
1078 if (target_type == TypeManager.float_type)
1079 return new FloatConstant ((float) v);
1080 if (target_type == TypeManager.double_type)
1081 return new DoubleConstant ((double) v);
1083 if (expr is ShortConstant){
1084 short v = ((ShortConstant) expr).Value;
1086 if (target_type == TypeManager.byte_type)
1087 return new ByteConstant ((byte) v);
1088 if (target_type == TypeManager.sbyte_type)
1089 return new SByteConstant ((sbyte) v);
1090 if (target_type == TypeManager.ushort_type)
1091 return new UShortConstant ((ushort) v);
1092 if (target_type == TypeManager.int32_type)
1093 return new IntConstant ((int) v);
1094 if (target_type == TypeManager.uint32_type)
1095 return new UIntConstant ((uint) v);
1096 if (target_type == TypeManager.int64_type)
1097 return new LongConstant ((long) v);
1098 if (target_type == TypeManager.uint64_type)
1099 return new ULongConstant ((ulong) v);
1100 if (target_type == TypeManager.float_type)
1101 return new FloatConstant ((float) v);
1102 if (target_type == TypeManager.double_type)
1103 return new DoubleConstant ((double) v);
1105 if (expr is UShortConstant){
1106 ushort v = ((UShortConstant) expr).Value;
1108 if (target_type == TypeManager.byte_type)
1109 return new ByteConstant ((byte) v);
1110 if (target_type == TypeManager.sbyte_type)
1111 return new SByteConstant ((sbyte) v);
1112 if (target_type == TypeManager.short_type)
1113 return new ShortConstant ((short) v);
1114 if (target_type == TypeManager.int32_type)
1115 return new IntConstant ((int) v);
1116 if (target_type == TypeManager.uint32_type)
1117 return new UIntConstant ((uint) v);
1118 if (target_type == TypeManager.int64_type)
1119 return new LongConstant ((long) v);
1120 if (target_type == TypeManager.uint64_type)
1121 return new ULongConstant ((ulong) v);
1122 if (target_type == TypeManager.float_type)
1123 return new FloatConstant ((float) v);
1124 if (target_type == TypeManager.double_type)
1125 return new DoubleConstant ((double) v);
1127 if (expr is IntConstant){
1128 int v = ((IntConstant) expr).Value;
1130 if (target_type == TypeManager.byte_type)
1131 return new ByteConstant ((byte) v);
1132 if (target_type == TypeManager.sbyte_type)
1133 return new SByteConstant ((sbyte) v);
1134 if (target_type == TypeManager.short_type)
1135 return new ShortConstant ((short) v);
1136 if (target_type == TypeManager.ushort_type)
1137 return new UShortConstant ((ushort) v);
1138 if (target_type == TypeManager.uint32_type)
1139 return new UIntConstant ((uint) v);
1140 if (target_type == TypeManager.int64_type)
1141 return new LongConstant ((long) v);
1142 if (target_type == TypeManager.uint64_type)
1143 return new ULongConstant ((ulong) v);
1144 if (target_type == TypeManager.float_type)
1145 return new FloatConstant ((float) v);
1146 if (target_type == TypeManager.double_type)
1147 return new DoubleConstant ((double) v);
1149 if (expr is UIntConstant){
1150 uint v = ((UIntConstant) expr).Value;
1152 if (target_type == TypeManager.byte_type)
1153 return new ByteConstant ((byte) v);
1154 if (target_type == TypeManager.sbyte_type)
1155 return new SByteConstant ((sbyte) v);
1156 if (target_type == TypeManager.short_type)
1157 return new ShortConstant ((short) v);
1158 if (target_type == TypeManager.ushort_type)
1159 return new UShortConstant ((ushort) v);
1160 if (target_type == TypeManager.int32_type)
1161 return new IntConstant ((int) v);
1162 if (target_type == TypeManager.int64_type)
1163 return new LongConstant ((long) v);
1164 if (target_type == TypeManager.uint64_type)
1165 return new ULongConstant ((ulong) v);
1166 if (target_type == TypeManager.float_type)
1167 return new FloatConstant ((float) v);
1168 if (target_type == TypeManager.double_type)
1169 return new DoubleConstant ((double) v);
1171 if (expr is LongConstant){
1172 long v = ((LongConstant) expr).Value;
1174 if (target_type == TypeManager.byte_type)
1175 return new ByteConstant ((byte) v);
1176 if (target_type == TypeManager.sbyte_type)
1177 return new SByteConstant ((sbyte) v);
1178 if (target_type == TypeManager.short_type)
1179 return new ShortConstant ((short) v);
1180 if (target_type == TypeManager.ushort_type)
1181 return new UShortConstant ((ushort) v);
1182 if (target_type == TypeManager.int32_type)
1183 return new IntConstant ((int) v);
1184 if (target_type == TypeManager.uint32_type)
1185 return new UIntConstant ((uint) v);
1186 if (target_type == TypeManager.uint64_type)
1187 return new ULongConstant ((ulong) v);
1188 if (target_type == TypeManager.float_type)
1189 return new FloatConstant ((float) v);
1190 if (target_type == TypeManager.double_type)
1191 return new DoubleConstant ((double) v);
1193 if (expr is ULongConstant){
1194 ulong v = ((ULongConstant) expr).Value;
1196 if (target_type == TypeManager.byte_type)
1197 return new ByteConstant ((byte) v);
1198 if (target_type == TypeManager.sbyte_type)
1199 return new SByteConstant ((sbyte) v);
1200 if (target_type == TypeManager.short_type)
1201 return new ShortConstant ((short) v);
1202 if (target_type == TypeManager.ushort_type)
1203 return new UShortConstant ((ushort) v);
1204 if (target_type == TypeManager.int32_type)
1205 return new IntConstant ((int) v);
1206 if (target_type == TypeManager.uint32_type)
1207 return new UIntConstant ((uint) v);
1208 if (target_type == TypeManager.int64_type)
1209 return new LongConstant ((long) v);
1210 if (target_type == TypeManager.float_type)
1211 return new FloatConstant ((float) v);
1212 if (target_type == TypeManager.double_type)
1213 return new DoubleConstant ((double) v);
1215 if (expr is FloatConstant){
1216 float v = ((FloatConstant) expr).Value;
1218 if (target_type == TypeManager.byte_type)
1219 return new ByteConstant ((byte) v);
1220 if (target_type == TypeManager.sbyte_type)
1221 return new SByteConstant ((sbyte) v);
1222 if (target_type == TypeManager.short_type)
1223 return new ShortConstant ((short) v);
1224 if (target_type == TypeManager.ushort_type)
1225 return new UShortConstant ((ushort) v);
1226 if (target_type == TypeManager.int32_type)
1227 return new IntConstant ((int) v);
1228 if (target_type == TypeManager.uint32_type)
1229 return new UIntConstant ((uint) v);
1230 if (target_type == TypeManager.int64_type)
1231 return new LongConstant ((long) v);
1232 if (target_type == TypeManager.uint64_type)
1233 return new ULongConstant ((ulong) v);
1234 if (target_type == TypeManager.double_type)
1235 return new DoubleConstant ((double) v);
1237 if (expr is DoubleConstant){
1238 double v = ((DoubleConstant) expr).Value;
1240 if (target_type == TypeManager.byte_type)
1241 return new ByteConstant ((byte) v);
1242 if (target_type == TypeManager.sbyte_type)
1243 return new SByteConstant ((sbyte) v);
1244 if (target_type == TypeManager.short_type)
1245 return new ShortConstant ((short) v);
1246 if (target_type == TypeManager.ushort_type)
1247 return new UShortConstant ((ushort) v);
1248 if (target_type == TypeManager.int32_type)
1249 return new IntConstant ((int) v);
1250 if (target_type == TypeManager.uint32_type)
1251 return new UIntConstant ((uint) v);
1252 if (target_type == TypeManager.int64_type)
1253 return new LongConstant ((long) v);
1254 if (target_type == TypeManager.uint64_type)
1255 return new ULongConstant ((ulong) v);
1256 if (target_type == TypeManager.float_type)
1257 return new FloatConstant ((float) v);
1263 public override Expression DoResolve (EmitContext ec)
1265 expr = expr.Resolve (ec);
1269 bool old_state = ec.OnlyLookupTypes;
1270 ec.OnlyLookupTypes = true;
1271 target_type = target_type.Resolve (ec);
1272 ec.OnlyLookupTypes = old_state;
1274 if (target_type == null){
1275 Report.Error (-10, loc, "Can not resolve type");
1279 if (target_type.eclass != ExprClass.Type){
1280 report118 (loc, target_type, "class");
1284 type = target_type.Type;
1285 eclass = ExprClass.Value;
1290 if (expr is Constant){
1291 Expression e = TryReduce (ec, type);
1297 expr = ConvertExplicit (ec, expr, type, loc);
1301 public override void Emit (EmitContext ec)
1304 // This one will never happen
1306 throw new Exception ("Should not happen");
1311 /// Binary operators
1313 public class Binary : Expression {
1314 public enum Operator : byte {
1315 Multiply, Division, Modulus,
1316 Addition, Subtraction,
1317 LeftShift, RightShift,
1318 LessThan, GreaterThan, LessThanOrEqual, GreaterThanOrEqual,
1319 Equality, Inequality,
1329 Expression left, right;
1332 // After resolution, method might contain the operator overload
1335 protected MethodBase method;
1336 ArrayList Arguments;
1340 bool DelegateOperation;
1342 // This must be kept in sync with Operator!!!
1343 static string [] oper_names;
1347 oper_names = new string [(int) Operator.TOP];
1349 oper_names [(int) Operator.Multiply] = "op_Multiply";
1350 oper_names [(int) Operator.Division] = "op_Division";
1351 oper_names [(int) Operator.Modulus] = "op_Modulus";
1352 oper_names [(int) Operator.Addition] = "op_Addition";
1353 oper_names [(int) Operator.Subtraction] = "op_Subtraction";
1354 oper_names [(int) Operator.LeftShift] = "op_LeftShift";
1355 oper_names [(int) Operator.RightShift] = "op_RightShift";
1356 oper_names [(int) Operator.LessThan] = "op_LessThan";
1357 oper_names [(int) Operator.GreaterThan] = "op_GreaterThan";
1358 oper_names [(int) Operator.LessThanOrEqual] = "op_LessThanOrEqual";
1359 oper_names [(int) Operator.GreaterThanOrEqual] = "op_GreaterThanOrEqual";
1360 oper_names [(int) Operator.Equality] = "op_Equality";
1361 oper_names [(int) Operator.Inequality] = "op_Inequality";
1362 oper_names [(int) Operator.BitwiseAnd] = "op_BitwiseAnd";
1363 oper_names [(int) Operator.BitwiseOr] = "op_BitwiseOr";
1364 oper_names [(int) Operator.ExclusiveOr] = "op_ExclusiveOr";
1365 oper_names [(int) Operator.LogicalOr] = "op_LogicalOr";
1366 oper_names [(int) Operator.LogicalAnd] = "op_LogicalAnd";
1369 public Binary (Operator oper, Expression left, Expression right, Location loc)
1377 public Operator Oper {
1386 public Expression Left {
1395 public Expression Right {
1406 /// Returns a stringified representation of the Operator
1408 static string OperName (Operator oper)
1411 case Operator.Multiply:
1413 case Operator.Division:
1415 case Operator.Modulus:
1417 case Operator.Addition:
1419 case Operator.Subtraction:
1421 case Operator.LeftShift:
1423 case Operator.RightShift:
1425 case Operator.LessThan:
1427 case Operator.GreaterThan:
1429 case Operator.LessThanOrEqual:
1431 case Operator.GreaterThanOrEqual:
1433 case Operator.Equality:
1435 case Operator.Inequality:
1437 case Operator.BitwiseAnd:
1439 case Operator.BitwiseOr:
1441 case Operator.ExclusiveOr:
1443 case Operator.LogicalOr:
1445 case Operator.LogicalAnd:
1449 return oper.ToString ();
1452 public override string ToString ()
1454 return "operator " + OperName (oper) + "(" + left.ToString () + ", " +
1455 right.ToString () + ")";
1458 Expression ForceConversion (EmitContext ec, Expression expr, Type target_type)
1460 if (expr.Type == target_type)
1463 return ConvertImplicit (ec, expr, target_type, new Location (-1));
1466 public static void Error_OperatorAmbiguous (Location loc, Operator oper, Type l, Type r)
1469 34, loc, "Operator `" + OperName (oper)
1470 + "' is ambiguous on operands of type `"
1471 + TypeManager.CSharpName (l) + "' "
1472 + "and `" + TypeManager.CSharpName (r)
1477 // Note that handling the case l == Decimal || r == Decimal
1478 // is taken care of by the Step 1 Operator Overload resolution.
1480 bool DoNumericPromotions (EmitContext ec, Type l, Type r)
1482 if (l == TypeManager.double_type || r == TypeManager.double_type){
1484 // If either operand is of type double, the other operand is
1485 // conveted to type double.
1487 if (r != TypeManager.double_type)
1488 right = ConvertImplicit (ec, right, TypeManager.double_type, loc);
1489 if (l != TypeManager.double_type)
1490 left = ConvertImplicit (ec, left, TypeManager.double_type, loc);
1492 type = TypeManager.double_type;
1493 } else if (l == TypeManager.float_type || r == TypeManager.float_type){
1495 // if either operand is of type float, the other operand is
1496 // converted to type float.
1498 if (r != TypeManager.double_type)
1499 right = ConvertImplicit (ec, right, TypeManager.float_type, loc);
1500 if (l != TypeManager.double_type)
1501 left = ConvertImplicit (ec, left, TypeManager.float_type, loc);
1502 type = TypeManager.float_type;
1503 } else if (l == TypeManager.uint64_type || r == TypeManager.uint64_type){
1507 // If either operand is of type ulong, the other operand is
1508 // converted to type ulong. or an error ocurrs if the other
1509 // operand is of type sbyte, short, int or long
1511 if (l == TypeManager.uint64_type){
1512 if (r != TypeManager.uint64_type){
1513 if (right is IntConstant){
1514 IntConstant ic = (IntConstant) right;
1516 e = TryImplicitIntConversion (l, ic);
1519 } else if (right is LongConstant){
1520 long ll = ((LongConstant) right).Value;
1523 right = new ULongConstant ((ulong) ll);
1525 e = ImplicitNumericConversion (ec, right, l, loc);
1532 if (left is IntConstant){
1533 e = TryImplicitIntConversion (r, (IntConstant) left);
1536 } else if (left is LongConstant){
1537 long ll = ((LongConstant) left).Value;
1540 left = new ULongConstant ((ulong) ll);
1542 e = ImplicitNumericConversion (ec, left, r, loc);
1549 if ((other == TypeManager.sbyte_type) ||
1550 (other == TypeManager.short_type) ||
1551 (other == TypeManager.int32_type) ||
1552 (other == TypeManager.int64_type))
1553 Error_OperatorAmbiguous (loc, oper, l, r);
1554 type = TypeManager.uint64_type;
1555 } else if (l == TypeManager.int64_type || r == TypeManager.int64_type){
1557 // If either operand is of type long, the other operand is converted
1560 if (l != TypeManager.int64_type)
1561 left = ConvertImplicit (ec, left, TypeManager.int64_type, loc);
1562 if (r != TypeManager.int64_type)
1563 right = ConvertImplicit (ec, right, TypeManager.int64_type, loc);
1565 type = TypeManager.int64_type;
1566 } else if (l == TypeManager.uint32_type || r == TypeManager.uint32_type){
1568 // If either operand is of type uint, and the other
1569 // operand is of type sbyte, short or int, othe operands are
1570 // converted to type long.
1574 if (l == TypeManager.uint32_type){
1575 if (right is IntConstant){
1576 IntConstant ic = (IntConstant) right;
1580 right = new UIntConstant ((uint) val);
1587 else if (r == TypeManager.uint32_type){
1588 if (left is IntConstant){
1589 IntConstant ic = (IntConstant) left;
1593 left = new UIntConstant ((uint) val);
1602 if ((other == TypeManager.sbyte_type) ||
1603 (other == TypeManager.short_type) ||
1604 (other == TypeManager.int32_type)){
1605 left = ForceConversion (ec, left, TypeManager.int64_type);
1606 right = ForceConversion (ec, right, TypeManager.int64_type);
1607 type = TypeManager.int64_type;
1610 // if either operand is of type uint, the other
1611 // operand is converd to type uint
1613 left = ForceConversion (ec, left, TypeManager.uint32_type);
1614 right = ForceConversion (ec, right, TypeManager.uint32_type);
1615 type = TypeManager.uint32_type;
1617 } else if (l == TypeManager.decimal_type || r == TypeManager.decimal_type){
1618 if (l != TypeManager.decimal_type)
1619 left = ConvertImplicit (ec, left, TypeManager.decimal_type, loc);
1620 if (r != TypeManager.decimal_type)
1621 right = ConvertImplicit (ec, right, TypeManager.decimal_type, loc);
1623 type = TypeManager.decimal_type;
1625 Expression l_tmp, r_tmp;
1627 l_tmp = ForceConversion (ec, left, TypeManager.int32_type);
1631 r_tmp = ForceConversion (ec, right, TypeManager.int32_type);
1638 type = TypeManager.int32_type;
1644 static public void Error_OperatorCannotBeApplied (Location loc, string name, Type l, Type r)
1647 "Operator " + name + " cannot be applied to operands of type `" +
1648 TypeManager.CSharpName (l) + "' and `" +
1649 TypeManager.CSharpName (r) + "'");
1652 void Error_OperatorCannotBeApplied ()
1654 Error_OperatorCannotBeApplied (loc, OperName (oper), left.Type, right.Type);
1657 static bool is_32_or_64 (Type t)
1659 return (t == TypeManager.int32_type || t == TypeManager.uint32_type ||
1660 t == TypeManager.int64_type || t == TypeManager.uint64_type);
1663 Expression CheckShiftArguments (EmitContext ec)
1667 Type r = right.Type;
1669 e = ForceConversion (ec, right, TypeManager.int32_type);
1671 Error_OperatorCannotBeApplied ();
1676 if (((e = ConvertImplicit (ec, left, TypeManager.int32_type, loc)) != null) ||
1677 ((e = ConvertImplicit (ec, left, TypeManager.uint32_type, loc)) != null) ||
1678 ((e = ConvertImplicit (ec, left, TypeManager.int64_type, loc)) != null) ||
1679 ((e = ConvertImplicit (ec, left, TypeManager.uint64_type, loc)) != null)){
1685 Error_OperatorCannotBeApplied ();
1689 Expression ResolveOperator (EmitContext ec)
1692 Type r = right.Type;
1695 // Step 1: Perform Operator Overload location
1697 Expression left_expr, right_expr;
1699 string op = oper_names [(int) oper];
1701 bool overload_failed = false;
1702 MethodGroupExpr union;
1703 left_expr = MemberLookup (ec, l, op, MemberTypes.Method, AllBindingFlags, loc);
1705 right_expr = MemberLookup (
1706 ec, r, op, MemberTypes.Method, AllBindingFlags, loc);
1707 union = Invocation.MakeUnionSet (left_expr, right_expr, loc);
1709 union = (MethodGroupExpr) left_expr;
1711 if (union != null) {
1712 Arguments = new ArrayList ();
1713 Arguments.Add (new Argument (left, Argument.AType.Expression));
1714 Arguments.Add (new Argument (right, Argument.AType.Expression));
1716 method = Invocation.OverloadResolve (ec, union, Arguments, Location.Null);
1717 if (method != null) {
1718 MethodInfo mi = (MethodInfo) method;
1720 type = mi.ReturnType;
1723 overload_failed = true;
1728 // Step 2: Default operations on CLI native types.
1732 // Step 0: String concatenation (because overloading will get this wrong)
1734 if (oper == Operator.Addition){
1736 // If any of the arguments is a string, cast to string
1739 if (l == TypeManager.string_type){
1741 if (r == TypeManager.void_type) {
1742 Error_OperatorCannotBeApplied ();
1746 if (r == TypeManager.string_type){
1747 if (left is Constant && right is Constant){
1748 StringConstant ls = (StringConstant) left;
1749 StringConstant rs = (StringConstant) right;
1751 return new StringConstant (
1752 ls.Value + rs.Value);
1756 method = TypeManager.string_concat_string_string;
1759 method = TypeManager.string_concat_object_object;
1760 right = ConvertImplicit (ec, right,
1761 TypeManager.object_type, loc);
1763 type = TypeManager.string_type;
1765 Arguments = new ArrayList ();
1766 Arguments.Add (new Argument (left, Argument.AType.Expression));
1767 Arguments.Add (new Argument (right, Argument.AType.Expression));
1771 } else if (r == TypeManager.string_type){
1774 if (l == TypeManager.void_type) {
1775 Error_OperatorCannotBeApplied ();
1779 method = TypeManager.string_concat_object_object;
1780 left = ConvertImplicit (ec, left, TypeManager.object_type, loc);
1781 Arguments = new ArrayList ();
1782 Arguments.Add (new Argument (left, Argument.AType.Expression));
1783 Arguments.Add (new Argument (right, Argument.AType.Expression));
1785 type = TypeManager.string_type;
1791 // Transform a + ( - b) into a - b
1793 if (right is Unary){
1794 Unary right_unary = (Unary) right;
1796 if (right_unary.Oper == Unary.Operator.UnaryNegation){
1797 oper = Operator.Subtraction;
1798 right = right_unary.Expr;
1804 if (oper == Operator.Equality || oper == Operator.Inequality){
1805 if (l == TypeManager.bool_type || r == TypeManager.bool_type){
1806 if (r != TypeManager.bool_type || l != TypeManager.bool_type){
1807 Error_OperatorCannotBeApplied ();
1811 type = TypeManager.bool_type;
1816 // operator != (object a, object b)
1817 // operator == (object a, object b)
1819 // For this to be used, both arguments have to be reference-types.
1820 // Read the rationale on the spec (14.9.6)
1822 // Also, if at compile time we know that the classes do not inherit
1823 // one from the other, then we catch the error there.
1825 if (!(l.IsValueType || r.IsValueType)){
1826 type = TypeManager.bool_type;
1831 if (l.IsSubclassOf (r) || r.IsSubclassOf (l))
1835 // Also, a standard conversion must exist from either one
1837 if (!(StandardConversionExists (left, r) ||
1838 StandardConversionExists (right, l))){
1839 Error_OperatorCannotBeApplied ();
1843 // We are going to have to convert to an object to compare
1845 if (l != TypeManager.object_type)
1846 left = new EmptyCast (left, TypeManager.object_type);
1847 if (r != TypeManager.object_type)
1848 right = new EmptyCast (right, TypeManager.object_type);
1851 // FIXME: CSC here catches errors cs254 and cs252
1857 // Only perform numeric promotions on:
1858 // +, -, *, /, %, &, |, ^, ==, !=, <, >, <=, >=
1860 if (oper == Operator.Addition || oper == Operator.Subtraction) {
1861 if (l.IsSubclassOf (TypeManager.delegate_type) &&
1862 r.IsSubclassOf (TypeManager.delegate_type)) {
1864 Arguments = new ArrayList ();
1865 Arguments.Add (new Argument (left, Argument.AType.Expression));
1866 Arguments.Add (new Argument (right, Argument.AType.Expression));
1868 if (oper == Operator.Addition)
1869 method = TypeManager.delegate_combine_delegate_delegate;
1871 method = TypeManager.delegate_remove_delegate_delegate;
1873 DelegateOperation = true;
1879 // Pointer arithmetic:
1881 // T* operator + (T* x, int y);
1882 // T* operator + (T* x, uint y);
1883 // T* operator + (T* x, long y);
1884 // T* operator + (T* x, ulong y);
1886 // T* operator + (int y, T* x);
1887 // T* operator + (uint y, T *x);
1888 // T* operator + (long y, T *x);
1889 // T* operator + (ulong y, T *x);
1891 // T* operator - (T* x, int y);
1892 // T* operator - (T* x, uint y);
1893 // T* operator - (T* x, long y);
1894 // T* operator - (T* x, ulong y);
1896 // long operator - (T* x, T *y)
1899 if (r.IsPointer && oper == Operator.Subtraction){
1901 return new PointerArithmetic (
1902 false, left, right, TypeManager.int64_type);
1903 } else if (is_32_or_64 (r))
1904 return new PointerArithmetic (
1905 oper == Operator.Addition, left, right, l);
1906 } else if (r.IsPointer && is_32_or_64 (l) && oper == Operator.Addition)
1907 return new PointerArithmetic (
1908 true, right, left, r);
1912 // Enumeration operators
1914 bool lie = TypeManager.IsEnumType (l);
1915 bool rie = TypeManager.IsEnumType (r);
1920 // operator + (E e, U x)
1922 if (oper == Operator.Addition){
1924 Error_OperatorCannotBeApplied ();
1928 Type enum_type = lie ? l : r;
1929 Type other_type = lie ? r : l;
1930 Type underlying_type = TypeManager.EnumToUnderlying (enum_type);
1933 if (underlying_type != other_type){
1934 Error_OperatorCannotBeApplied ();
1943 temp = ConvertImplicit (ec, right, l, loc);
1947 temp = ConvertImplicit (ec, left, r, loc);
1954 if (oper == Operator.Equality || oper == Operator.Inequality ||
1955 oper == Operator.LessThanOrEqual || oper == Operator.LessThan ||
1956 oper == Operator.GreaterThanOrEqual || oper == Operator.GreaterThan){
1957 type = TypeManager.bool_type;
1961 if (oper == Operator.BitwiseAnd ||
1962 oper == Operator.BitwiseOr ||
1963 oper == Operator.ExclusiveOr){
1970 if (oper == Operator.LeftShift || oper == Operator.RightShift)
1971 return CheckShiftArguments (ec);
1973 if (oper == Operator.LogicalOr || oper == Operator.LogicalAnd){
1974 if (l != TypeManager.bool_type || r != TypeManager.bool_type){
1975 Error_OperatorCannotBeApplied ();
1979 type = TypeManager.bool_type;
1984 // operator & (bool x, bool y)
1985 // operator | (bool x, bool y)
1986 // operator ^ (bool x, bool y)
1988 if (l == TypeManager.bool_type && r == TypeManager.bool_type){
1989 if (oper == Operator.BitwiseAnd ||
1990 oper == Operator.BitwiseOr ||
1991 oper == Operator.ExclusiveOr){
1998 // Pointer comparison
2000 if (l.IsPointer && r.IsPointer){
2001 if (oper == Operator.Equality || oper == Operator.Inequality ||
2002 oper == Operator.LessThan || oper == Operator.LessThanOrEqual ||
2003 oper == Operator.GreaterThan || oper == Operator.GreaterThanOrEqual){
2004 type = TypeManager.bool_type;
2010 // We are dealing with numbers
2012 if (overload_failed){
2013 Error_OperatorCannotBeApplied ();
2017 if (!DoNumericPromotions (ec, l, r)){
2018 Error_OperatorCannotBeApplied ();
2022 if (left == null || right == null)
2026 // reload our cached types if required
2031 if (oper == Operator.BitwiseAnd ||
2032 oper == Operator.BitwiseOr ||
2033 oper == Operator.ExclusiveOr){
2035 if (!((l == TypeManager.int32_type) ||
2036 (l == TypeManager.uint32_type) ||
2037 (l == TypeManager.int64_type) ||
2038 (l == TypeManager.uint64_type)))
2041 Error_OperatorCannotBeApplied ();
2046 if (oper == Operator.Equality ||
2047 oper == Operator.Inequality ||
2048 oper == Operator.LessThanOrEqual ||
2049 oper == Operator.LessThan ||
2050 oper == Operator.GreaterThanOrEqual ||
2051 oper == Operator.GreaterThan){
2052 type = TypeManager.bool_type;
2058 public override Expression DoResolve (EmitContext ec)
2060 left = left.Resolve (ec);
2061 right = right.Resolve (ec);
2063 if (left == null || right == null)
2066 if (left.Type == null)
2067 throw new Exception (
2068 "Resolve returned non null, but did not set the type! (" +
2069 left + ") at Line: " + loc.Row);
2070 if (right.Type == null)
2071 throw new Exception (
2072 "Resolve returned non null, but did not set the type! (" +
2073 right + ") at Line: "+ loc.Row);
2075 eclass = ExprClass.Value;
2077 if (left is Constant && right is Constant){
2078 Expression e = ConstantFold.BinaryFold (
2079 ec, oper, (Constant) left, (Constant) right, loc);
2084 return ResolveOperator (ec);
2087 public bool IsBranchable ()
2089 if (oper == Operator.Equality ||
2090 oper == Operator.Inequality ||
2091 oper == Operator.LessThan ||
2092 oper == Operator.GreaterThan ||
2093 oper == Operator.LessThanOrEqual ||
2094 oper == Operator.GreaterThanOrEqual){
2101 /// This entry point is used by routines that might want
2102 /// to emit a brfalse/brtrue after an expression, and instead
2103 /// they could use a more compact notation.
2105 /// Typically the code would generate l.emit/r.emit, followed
2106 /// by the comparission and then a brtrue/brfalse. The comparissions
2107 /// are sometimes inneficient (there are not as complete as the branches
2108 /// look for the hacks in Emit using double ceqs).
2110 /// So for those cases we provide EmitBranchable that can emit the
2111 /// branch with the test
2113 public void EmitBranchable (EmitContext ec, int target)
2116 bool close_target = false;
2117 ILGenerator ig = ec.ig;
2120 // short-circuit operators
2122 if (oper == Operator.LogicalAnd){
2124 ig.Emit (OpCodes.Brfalse, target);
2126 ig.Emit (OpCodes.Brfalse, target);
2127 } else if (oper == Operator.LogicalOr){
2129 ig.Emit (OpCodes.Brtrue, target);
2131 ig.Emit (OpCodes.Brfalse, target);
2138 case Operator.Equality:
2140 opcode = OpCodes.Beq_S;
2142 opcode = OpCodes.Beq;
2145 case Operator.Inequality:
2147 opcode = OpCodes.Bne_Un_S;
2149 opcode = OpCodes.Bne_Un;
2152 case Operator.LessThan:
2154 opcode = OpCodes.Blt_S;
2156 opcode = OpCodes.Blt;
2159 case Operator.GreaterThan:
2161 opcode = OpCodes.Bgt_S;
2163 opcode = OpCodes.Bgt;
2166 case Operator.LessThanOrEqual:
2168 opcode = OpCodes.Ble_S;
2170 opcode = OpCodes.Ble;
2173 case Operator.GreaterThanOrEqual:
2175 opcode = OpCodes.Bge_S;
2177 opcode = OpCodes.Ble;
2181 throw new Exception ("EmitBranchable called on non-EmitBranchable operator: "
2182 + oper.ToString ());
2185 ig.Emit (opcode, target);
2188 public override void Emit (EmitContext ec)
2190 ILGenerator ig = ec.ig;
2192 Type r = right.Type;
2195 if (method != null) {
2197 // Note that operators are static anyway
2199 if (Arguments != null)
2200 Invocation.EmitArguments (ec, method, Arguments);
2202 if (method is MethodInfo)
2203 ig.Emit (OpCodes.Call, (MethodInfo) method);
2205 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
2207 if (DelegateOperation)
2208 ig.Emit (OpCodes.Castclass, type);
2214 // Handle short-circuit operators differently
2217 if (oper == Operator.LogicalAnd){
2218 Label load_zero = ig.DefineLabel ();
2219 Label end = ig.DefineLabel ();
2222 ig.Emit (OpCodes.Brfalse, load_zero);
2224 ig.Emit (OpCodes.Br, end);
2225 ig.MarkLabel (load_zero);
2226 ig.Emit (OpCodes.Ldc_I4_0);
2229 } else if (oper == Operator.LogicalOr){
2230 Label load_one = ig.DefineLabel ();
2231 Label end = ig.DefineLabel ();
2234 ig.Emit (OpCodes.Brtrue, load_one);
2236 ig.Emit (OpCodes.Br, end);
2237 ig.MarkLabel (load_one);
2238 ig.Emit (OpCodes.Ldc_I4_1);
2247 case Operator.Multiply:
2249 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
2250 opcode = OpCodes.Mul_Ovf;
2251 else if (l==TypeManager.uint32_type || l==TypeManager.uint64_type)
2252 opcode = OpCodes.Mul_Ovf_Un;
2254 opcode = OpCodes.Mul;
2256 opcode = OpCodes.Mul;
2260 case Operator.Division:
2261 if (l == TypeManager.uint32_type || l == TypeManager.uint64_type)
2262 opcode = OpCodes.Div_Un;
2264 opcode = OpCodes.Div;
2267 case Operator.Modulus:
2268 if (l == TypeManager.uint32_type || l == TypeManager.uint64_type)
2269 opcode = OpCodes.Rem_Un;
2271 opcode = OpCodes.Rem;
2274 case Operator.Addition:
2276 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
2277 opcode = OpCodes.Add_Ovf;
2278 else if (l==TypeManager.uint32_type || l==TypeManager.uint64_type)
2279 opcode = OpCodes.Add_Ovf_Un;
2281 opcode = OpCodes.Add;
2283 opcode = OpCodes.Add;
2286 case Operator.Subtraction:
2288 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
2289 opcode = OpCodes.Sub_Ovf;
2290 else if (l==TypeManager.uint32_type || l==TypeManager.uint64_type)
2291 opcode = OpCodes.Sub_Ovf_Un;
2293 opcode = OpCodes.Sub;
2295 opcode = OpCodes.Sub;
2298 case Operator.RightShift:
2299 opcode = OpCodes.Shr;
2302 case Operator.LeftShift:
2303 opcode = OpCodes.Shl;
2306 case Operator.Equality:
2307 opcode = OpCodes.Ceq;
2310 case Operator.Inequality:
2311 ec.ig.Emit (OpCodes.Ceq);
2312 ec.ig.Emit (OpCodes.Ldc_I4_0);
2314 opcode = OpCodes.Ceq;
2317 case Operator.LessThan:
2318 opcode = OpCodes.Clt;
2321 case Operator.GreaterThan:
2322 opcode = OpCodes.Cgt;
2325 case Operator.LessThanOrEqual:
2326 ec.ig.Emit (OpCodes.Cgt);
2327 ec.ig.Emit (OpCodes.Ldc_I4_0);
2329 opcode = OpCodes.Ceq;
2332 case Operator.GreaterThanOrEqual:
2333 ec.ig.Emit (OpCodes.Clt);
2334 ec.ig.Emit (OpCodes.Ldc_I4_1);
2336 opcode = OpCodes.Sub;
2339 case Operator.BitwiseOr:
2340 opcode = OpCodes.Or;
2343 case Operator.BitwiseAnd:
2344 opcode = OpCodes.And;
2347 case Operator.ExclusiveOr:
2348 opcode = OpCodes.Xor;
2352 throw new Exception ("This should not happen: Operator = "
2353 + oper.ToString ());
2359 public bool IsBuiltinOperator {
2361 return method == null;
2366 public class PointerArithmetic : Expression {
2367 Expression left, right;
2371 // We assume that `l' is always a pointer
2373 public PointerArithmetic (bool is_addition, Expression l, Expression r, Type t)
2376 eclass = ExprClass.Variable;
2379 is_add = is_addition;
2382 public override Expression DoResolve (EmitContext ec)
2385 // We are born fully resolved
2390 public override void Emit (EmitContext ec)
2392 Type op_type = left.Type;
2393 ILGenerator ig = ec.ig;
2394 int size = GetTypeSize (op_type.GetElementType ());
2396 if (right.Type.IsPointer){
2398 // handle (pointer - pointer)
2402 ig.Emit (OpCodes.Sub);
2406 ig.Emit (OpCodes.Sizeof, op_type);
2408 IntLiteral.EmitInt (ig, size);
2409 ig.Emit (OpCodes.Div);
2411 ig.Emit (OpCodes.Conv_I8);
2414 // handle + and - on (pointer op int)
2417 ig.Emit (OpCodes.Conv_I);
2421 ig.Emit (OpCodes.Sizeof, op_type);
2423 IntLiteral.EmitInt (ig, size);
2424 ig.Emit (OpCodes.Mul);
2427 ig.Emit (OpCodes.Add);
2429 ig.Emit (OpCodes.Sub);
2435 /// Implements the ternary conditiona operator (?:)
2437 public class Conditional : Expression {
2438 Expression expr, trueExpr, falseExpr;
2441 public Conditional (Expression expr, Expression trueExpr, Expression falseExpr, Location l)
2444 this.trueExpr = trueExpr;
2445 this.falseExpr = falseExpr;
2449 public Expression Expr {
2455 public Expression TrueExpr {
2461 public Expression FalseExpr {
2467 public override Expression DoResolve (EmitContext ec)
2469 expr = expr.Resolve (ec);
2471 if (expr.Type != TypeManager.bool_type)
2472 expr = Expression.ConvertImplicitRequired (
2473 ec, expr, TypeManager.bool_type, loc);
2475 trueExpr = trueExpr.Resolve (ec);
2476 falseExpr = falseExpr.Resolve (ec);
2478 if (expr == null || trueExpr == null || falseExpr == null)
2481 eclass = ExprClass.Value;
2482 if (trueExpr.Type == falseExpr.Type)
2483 type = trueExpr.Type;
2486 Type true_type = trueExpr.Type;
2487 Type false_type = falseExpr.Type;
2489 if (trueExpr is NullLiteral){
2492 } else if (falseExpr is NullLiteral){
2498 // First, if an implicit conversion exists from trueExpr
2499 // to falseExpr, then the result type is of type falseExpr.Type
2501 conv = ConvertImplicit (ec, trueExpr, false_type, loc);
2504 // Check if both can convert implicitl to each other's type
2506 if (ConvertImplicit (ec, falseExpr, true_type, loc) != null){
2509 "Can not compute type of conditional expression " +
2510 "as `" + TypeManager.CSharpName (trueExpr.Type) +
2511 "' and `" + TypeManager.CSharpName (falseExpr.Type) +
2512 "' convert implicitly to each other");
2517 } else if ((conv = ConvertImplicit(ec, falseExpr, true_type,loc))!= null){
2521 Error (173, loc, "The type of the conditional expression can " +
2522 "not be computed because there is no implicit conversion" +
2523 " from `" + TypeManager.CSharpName (trueExpr.Type) + "'" +
2524 " and `" + TypeManager.CSharpName (falseExpr.Type) + "'");
2529 if (expr is BoolConstant){
2530 BoolConstant bc = (BoolConstant) expr;
2541 public override void Emit (EmitContext ec)
2543 ILGenerator ig = ec.ig;
2544 Label false_target = ig.DefineLabel ();
2545 Label end_target = ig.DefineLabel ();
2548 ig.Emit (OpCodes.Brfalse, false_target);
2550 ig.Emit (OpCodes.Br, end_target);
2551 ig.MarkLabel (false_target);
2552 falseExpr.Emit (ec);
2553 ig.MarkLabel (end_target);
2561 public class LocalVariableReference : Expression, IAssignMethod, IMemoryLocation {
2562 public readonly string Name;
2563 public readonly Block Block;
2565 VariableInfo variable_info;
2567 public LocalVariableReference (Block block, string name, Location l)
2572 eclass = ExprClass.Variable;
2575 public VariableInfo VariableInfo {
2577 if (variable_info == null)
2578 variable_info = Block.GetVariableInfo (Name);
2579 return variable_info;
2583 public override Expression DoResolve (EmitContext ec)
2585 VariableInfo vi = VariableInfo;
2587 if (Block.IsConstant (Name)) {
2588 Expression e = Block.GetConstantExpression (Name);
2594 type = vi.VariableType;
2598 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
2600 Expression e = DoResolve (ec);
2605 VariableInfo vi = VariableInfo;
2611 "cannot assign to `" + Name + "' because it is readonly");
2619 public override void Emit (EmitContext ec)
2621 VariableInfo vi = VariableInfo;
2622 ILGenerator ig = ec.ig;
2624 ig.Emit (OpCodes.Ldloc, vi.LocalBuilder);
2628 public void EmitAssign (EmitContext ec, Expression source)
2630 ILGenerator ig = ec.ig;
2631 VariableInfo vi = VariableInfo;
2637 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
2640 public void AddressOf (EmitContext ec, AddressOp mode)
2642 VariableInfo vi = VariableInfo;
2644 if ((mode & AddressOp.Load) != 0)
2646 if ((mode & AddressOp.Store) != 0)
2649 ec.ig.Emit (OpCodes.Ldloca, vi.LocalBuilder);
2654 /// This represents a reference to a parameter in the intermediate
2657 public class ParameterReference : Expression, IAssignMethod, IMemoryLocation {
2663 public ParameterReference (Parameters pars, int idx, string name)
2668 eclass = ExprClass.Variable;
2672 // Notice that for ref/out parameters, the type exposed is not the
2673 // same type exposed externally.
2676 // externally we expose "int&"
2677 // here we expose "int".
2679 // We record this in "is_ref". This means that the type system can treat
2680 // the type as it is expected, but when we generate the code, we generate
2681 // the alternate kind of code.
2683 public override Expression DoResolve (EmitContext ec)
2685 type = pars.GetParameterInfo (ec.DeclSpace, idx, out is_ref);
2686 eclass = ExprClass.Variable;
2692 // This method is used by parameters that are references, that are
2693 // being passed as references: we only want to pass the pointer (that
2694 // is already stored in the parameter, not the address of the pointer,
2695 // and not the value of the variable).
2697 public void EmitLoad (EmitContext ec)
2699 ILGenerator ig = ec.ig;
2706 ig.Emit (OpCodes.Ldarg_S, (byte) arg_idx);
2708 ig.Emit (OpCodes.Ldarg, arg_idx);
2711 public override void Emit (EmitContext ec)
2713 ILGenerator ig = ec.ig;
2720 ig.Emit (OpCodes.Ldarg_S, (byte) arg_idx);
2722 ig.Emit (OpCodes.Ldarg, arg_idx);
2728 // If we are a reference, we loaded on the stack a pointer
2729 // Now lets load the real value
2731 LoadFromPtr (ig, type, true);
2734 public void EmitAssign (EmitContext ec, Expression source)
2736 ILGenerator ig = ec.ig;
2745 ig.Emit (OpCodes.Ldarg_S, (byte) arg_idx);
2747 ig.Emit (OpCodes.Ldarg, arg_idx);
2753 StoreFromPtr (ig, type);
2756 ig.Emit (OpCodes.Starg_S, (byte) arg_idx);
2758 ig.Emit (OpCodes.Starg, arg_idx);
2763 public void AddressOf (EmitContext ec, AddressOp mode)
2771 ec.ig.Emit (OpCodes.Ldarga_S, (byte) arg_idx);
2773 ec.ig.Emit (OpCodes.Ldarga, arg_idx);
2778 /// Used for arguments to New(), Invocation()
2780 public class Argument {
2781 public enum AType : byte {
2787 public readonly AType ArgType;
2788 public Expression expr;
2790 public Argument (Expression expr, AType type)
2793 this.ArgType = type;
2796 public Expression Expr {
2808 if (ArgType == AType.Ref || ArgType == AType.Out)
2809 return Type.GetType (expr.Type.ToString () + "&");
2815 public Parameter.Modifier GetParameterModifier ()
2817 if (ArgType == AType.Ref || ArgType == AType.Out)
2818 return Parameter.Modifier.OUT;
2820 return Parameter.Modifier.NONE;
2823 public static string FullDesc (Argument a)
2825 return (a.ArgType == AType.Ref ? "ref " :
2826 (a.ArgType == AType.Out ? "out " : "")) +
2827 TypeManager.CSharpName (a.Expr.Type);
2830 public bool Resolve (EmitContext ec, Location loc)
2832 expr = expr.Resolve (ec);
2834 if (ArgType == AType.Expression)
2835 return expr != null;
2837 if (expr.eclass != ExprClass.Variable){
2839 // We just probe to match the CSC output
2841 if (expr.eclass == ExprClass.PropertyAccess ||
2842 expr.eclass == ExprClass.IndexerAccess){
2845 "A property or indexer can not be passed as an out or ref " +
2850 "An lvalue is required as an argument to out or ref");
2855 return expr != null;
2858 public void Emit (EmitContext ec)
2861 // Ref and Out parameters need to have their addresses taken.
2863 // ParameterReferences might already be references, so we want
2864 // to pass just the value
2866 if (ArgType == AType.Ref || ArgType == AType.Out){
2867 AddressOp mode = AddressOp.Store;
2869 if (ArgType == AType.Ref)
2870 mode |= AddressOp.Load;
2872 if (expr is ParameterReference){
2873 ParameterReference pr = (ParameterReference) expr;
2879 pr.AddressOf (ec, mode);
2882 ((IMemoryLocation)expr).AddressOf (ec, mode);
2889 /// Invocation of methods or delegates.
2891 public class Invocation : ExpressionStatement {
2892 public readonly ArrayList Arguments;
2896 MethodBase method = null;
2899 static Hashtable method_parameter_cache;
2901 static Invocation ()
2903 method_parameter_cache = new PtrHashtable ();
2907 // arguments is an ArrayList, but we do not want to typecast,
2908 // as it might be null.
2910 // FIXME: only allow expr to be a method invocation or a
2911 // delegate invocation (7.5.5)
2913 public Invocation (Expression expr, ArrayList arguments, Location l)
2916 Arguments = arguments;
2920 public Expression Expr {
2927 /// Returns the Parameters (a ParameterData interface) for the
2930 public static ParameterData GetParameterData (MethodBase mb)
2932 object pd = method_parameter_cache [mb];
2936 return (ParameterData) pd;
2939 ip = TypeManager.LookupParametersByBuilder (mb);
2941 method_parameter_cache [mb] = ip;
2943 return (ParameterData) ip;
2945 ParameterInfo [] pi = mb.GetParameters ();
2946 ReflectionParameters rp = new ReflectionParameters (pi);
2947 method_parameter_cache [mb] = rp;
2949 return (ParameterData) rp;
2954 /// Determines "better conversion" as specified in 7.4.2.3
2955 /// Returns : 1 if a->p is better
2956 /// 0 if a->q or neither is better
2958 static int BetterConversion (EmitContext ec, Argument a, Type p, Type q, Location loc)
2960 Type argument_type = a.Type;
2961 Expression argument_expr = a.Expr;
2963 if (argument_type == null)
2964 throw new Exception ("Expression of type " + a.Expr + " does not resolve its type");
2969 if (argument_type == p)
2972 if (argument_type == q)
2976 // Now probe whether an implicit constant expression conversion
2979 // An implicit constant expression conversion permits the following
2982 // * A constant-expression of type `int' can be converted to type
2983 // sbyte, byute, short, ushort, uint, ulong provided the value of
2984 // of the expression is withing the range of the destination type.
2986 // * A constant-expression of type long can be converted to type
2987 // ulong, provided the value of the constant expression is not negative
2989 // FIXME: Note that this assumes that constant folding has
2990 // taken place. We dont do constant folding yet.
2993 if (argument_expr is IntConstant){
2994 IntConstant ei = (IntConstant) argument_expr;
2995 int value = ei.Value;
2997 if (p == TypeManager.sbyte_type){
2998 if (value >= SByte.MinValue && value <= SByte.MaxValue)
3000 } else if (p == TypeManager.byte_type){
3001 if (Byte.MinValue >= 0 && value <= Byte.MaxValue)
3003 } else if (p == TypeManager.short_type){
3004 if (value >= Int16.MinValue && value <= Int16.MaxValue)
3006 } else if (p == TypeManager.ushort_type){
3007 if (value >= UInt16.MinValue && value <= UInt16.MaxValue)
3009 } else if (p == TypeManager.uint32_type){
3011 // we can optimize this case: a positive int32
3012 // always fits on a uint32
3016 } else if (p == TypeManager.uint64_type){
3018 // we can optimize this case: a positive int32
3019 // always fits on a uint64
3024 } else if (argument_type == TypeManager.int64_type && argument_expr is LongConstant){
3025 LongConstant lc = (LongConstant) argument_expr;
3027 if (p == TypeManager.uint64_type){
3034 Expression tmp = ConvertImplicitStandard (ec, argument_expr, p, loc);
3042 Expression p_tmp = new EmptyExpression (p);
3043 Expression q_tmp = new EmptyExpression (q);
3045 if (StandardConversionExists (p_tmp, q) == true &&
3046 StandardConversionExists (q_tmp, p) == false)
3049 if (p == TypeManager.sbyte_type)
3050 if (q == TypeManager.byte_type || q == TypeManager.ushort_type ||
3051 q == TypeManager.uint32_type || q == TypeManager.uint64_type)
3054 if (p == TypeManager.short_type)
3055 if (q == TypeManager.ushort_type || q == TypeManager.uint32_type ||
3056 q == TypeManager.uint64_type)
3059 if (p == TypeManager.int32_type)
3060 if (q == TypeManager.uint32_type || q == TypeManager.uint64_type)
3063 if (p == TypeManager.int64_type)
3064 if (q == TypeManager.uint64_type)
3071 /// Determines "Better function"
3074 /// and returns an integer indicating :
3075 /// 0 if candidate ain't better
3076 /// 1 if candidate is better than the current best match
3078 static int BetterFunction (EmitContext ec, ArrayList args,
3079 MethodBase candidate, MethodBase best,
3080 bool expanded_form, Location loc)
3082 ParameterData candidate_pd = GetParameterData (candidate);
3083 ParameterData best_pd;
3089 argument_count = args.Count;
3091 int cand_count = candidate_pd.Count;
3093 if (cand_count == 0 && argument_count == 0)
3096 if (candidate_pd.ParameterModifier (cand_count - 1) != Parameter.Modifier.PARAMS)
3097 if (cand_count != argument_count)
3103 if (argument_count == 0 && cand_count == 1 &&
3104 candidate_pd.ParameterModifier (cand_count - 1) == Parameter.Modifier.PARAMS)
3107 for (int j = argument_count; j > 0;) {
3110 Argument a = (Argument) args [j];
3111 Type t = candidate_pd.ParameterType (j);
3113 if (candidate_pd.ParameterModifier (j) == Parameter.Modifier.PARAMS)
3115 t = t.GetElementType ();
3117 x = BetterConversion (ec, a, t, null, loc);
3129 best_pd = GetParameterData (best);
3131 int rating1 = 0, rating2 = 0;
3133 for (int j = 0; j < argument_count; ++j) {
3136 Argument a = (Argument) args [j];
3138 Type ct = candidate_pd.ParameterType (j);
3139 Type bt = best_pd.ParameterType (j);
3141 if (candidate_pd.ParameterModifier (j) == Parameter.Modifier.PARAMS)
3143 ct = ct.GetElementType ();
3145 if (best_pd.ParameterModifier (j) == Parameter.Modifier.PARAMS)
3147 bt = bt.GetElementType ();
3149 x = BetterConversion (ec, a, ct, bt, loc);
3150 y = BetterConversion (ec, a, bt, ct, loc);
3159 if (rating1 > rating2)
3165 public static string FullMethodDesc (MethodBase mb)
3167 string ret_type = "";
3169 if (mb is MethodInfo)
3170 ret_type = TypeManager.CSharpName (((MethodInfo) mb).ReturnType);
3172 StringBuilder sb = new StringBuilder (ret_type + " " + mb.Name);
3173 ParameterData pd = GetParameterData (mb);
3175 int count = pd.Count;
3178 for (int i = count; i > 0; ) {
3181 sb.Append (pd.ParameterDesc (count - i - 1));
3187 return sb.ToString ();
3190 public static MethodGroupExpr MakeUnionSet (Expression mg1, Expression mg2, Location loc)
3192 MemberInfo [] miset;
3193 MethodGroupExpr union;
3198 return (MethodGroupExpr) mg2;
3201 return (MethodGroupExpr) mg1;
3204 MethodGroupExpr left_set = null, right_set = null;
3205 int length1 = 0, length2 = 0;
3207 left_set = (MethodGroupExpr) mg1;
3208 length1 = left_set.Methods.Length;
3210 right_set = (MethodGroupExpr) mg2;
3211 length2 = right_set.Methods.Length;
3213 ArrayList common = new ArrayList ();
3215 for (int i = 0; i < left_set.Methods.Length; i++) {
3216 for (int j = 0; j < right_set.Methods.Length; j++) {
3217 if (left_set.Methods [i] == right_set.Methods [j])
3218 common.Add (left_set.Methods [i]);
3222 miset = new MemberInfo [length1 + length2 - common.Count];
3224 left_set.Methods.CopyTo (miset, 0);
3228 for (int j = 0; j < right_set.Methods.Length; j++)
3229 if (!common.Contains (right_set.Methods [j]))
3230 miset [length1 + k++] = right_set.Methods [j];
3232 union = new MethodGroupExpr (miset, loc);
3238 /// Determines is the candidate method, if a params method, is applicable
3239 /// in its expanded form to the given set of arguments
3241 static bool IsParamsMethodApplicable (ArrayList arguments, MethodBase candidate)
3245 if (arguments == null)
3248 arg_count = arguments.Count;
3250 ParameterData pd = GetParameterData (candidate);
3252 int pd_count = pd.Count;
3257 if (pd.ParameterModifier (pd_count - 1) != Parameter.Modifier.PARAMS)
3260 if (pd_count - 1 > arg_count)
3263 if (pd_count == 1 && arg_count == 0)
3267 // If we have come this far, the case which remains is when the number of parameters
3268 // is less than or equal to the argument count.
3270 for (int i = 0; i < pd_count - 1; ++i) {
3272 Argument a = (Argument) arguments [i];
3274 Parameter.Modifier a_mod = a.GetParameterModifier ();
3275 Parameter.Modifier p_mod = pd.ParameterModifier (i);
3277 if (a_mod == p_mod) {
3279 if (a_mod == Parameter.Modifier.NONE)
3280 if (!StandardConversionExists (a.Expr, pd.ParameterType (i)))
3283 if (a_mod == Parameter.Modifier.REF ||
3284 a_mod == Parameter.Modifier.OUT)
3285 if (pd.ParameterType (i) != a.Type)
3292 Type element_type = pd.ParameterType (pd_count - 1).GetElementType ();
3294 for (int i = pd_count - 1; i < arg_count; i++) {
3295 Argument a = (Argument) arguments [i];
3297 if (!StandardConversionExists (a.Expr, element_type))
3305 /// Determines if the candidate method is applicable (section 14.4.2.1)
3306 /// to the given set of arguments
3308 static bool IsApplicable (ArrayList arguments, MethodBase candidate)
3312 if (arguments == null)
3315 arg_count = arguments.Count;
3317 ParameterData pd = GetParameterData (candidate);
3319 int pd_count = pd.Count;
3321 if (arg_count != pd.Count)
3324 for (int i = arg_count; i > 0; ) {
3327 Argument a = (Argument) arguments [i];
3329 Parameter.Modifier a_mod = a.GetParameterModifier ();
3330 Parameter.Modifier p_mod = pd.ParameterModifier (i);
3332 if (a_mod == p_mod) {
3333 if (a_mod == Parameter.Modifier.NONE)
3334 if (!StandardConversionExists (a.Expr, pd.ParameterType (i)))
3337 if (a_mod == Parameter.Modifier.REF ||
3338 a_mod == Parameter.Modifier.OUT)
3339 if (pd.ParameterType (i) != a.Type)
3351 /// Find the Applicable Function Members (7.4.2.1)
3353 /// me: Method Group expression with the members to select.
3354 /// it might contain constructors or methods (or anything
3355 /// that maps to a method).
3357 /// Arguments: ArrayList containing resolved Argument objects.
3359 /// loc: The location if we want an error to be reported, or a Null
3360 /// location for "probing" purposes.
3362 /// Returns: The MethodBase (either a ConstructorInfo or a MethodInfo)
3363 /// that is the best match of me on Arguments.
3366 public static MethodBase OverloadResolve (EmitContext ec, MethodGroupExpr me,
3367 ArrayList Arguments, Location loc)
3369 ArrayList afm = new ArrayList ();
3370 int best_match_idx = -1;
3371 MethodBase method = null;
3373 ArrayList candidates = new ArrayList ();
3375 for (int i = me.Methods.Length; i > 0; ){
3377 MethodBase candidate = me.Methods [i];
3380 // Check if candidate is applicable (section 14.4.2.1)
3381 if (!IsApplicable (Arguments, candidate))
3384 candidates.Add (candidate);
3386 x = BetterFunction (ec, Arguments, candidate, method, false, loc);
3392 method = me.Methods [best_match_idx];
3396 if (Arguments == null)
3399 argument_count = Arguments.Count;
3402 // Now we see if we can find params functions, applicable in their expanded form
3403 // since if they were applicable in their normal form, they would have been selected
3406 bool chose_params_expanded = false;
3408 if (best_match_idx == -1) {
3410 candidates = new ArrayList ();
3411 for (int i = me.Methods.Length; i > 0; ) {
3413 MethodBase candidate = me.Methods [i];
3415 if (!IsParamsMethodApplicable (Arguments, candidate))
3418 candidates.Add (candidate);
3420 int x = BetterFunction (ec, Arguments, candidate, method, true, loc);
3426 method = me.Methods [best_match_idx];
3427 chose_params_expanded = true;
3433 // Now we see if we can at least find a method with the same number of arguments
3437 if (best_match_idx == -1) {
3439 for (int i = me.Methods.Length; i > 0;) {
3441 MethodBase mb = me.Methods [i];
3442 pd = GetParameterData (mb);
3444 if (pd.Count == argument_count) {
3446 method = me.Methods [best_match_idx];
3456 // Now check that there are no ambiguities i.e the selected method
3457 // should be better than all the others
3460 for (int i = 0; i < candidates.Count; ++i) {
3461 MethodBase candidate = (MethodBase) candidates [i];
3463 if (candidate == method)
3467 // If a normal method is applicable in the sense that it has the same
3468 // number of arguments, then the expanded params method is never applicable
3469 // so we debar the params method.
3471 if (IsParamsMethodApplicable (Arguments, candidate) &&
3472 IsApplicable (Arguments, method))
3475 int x = BetterFunction (ec, Arguments, method, candidate,
3476 chose_params_expanded, loc);
3481 "Ambiguous call when selecting function due to implicit casts");
3487 // And now check if the arguments are all compatible, perform conversions
3488 // if necessary etc. and return if everything is all right
3491 if (VerifyArgumentsCompat (ec, Arguments, argument_count, method,
3492 chose_params_expanded, null, loc))
3498 public static bool VerifyArgumentsCompat (EmitContext ec, ArrayList Arguments,
3501 bool chose_params_expanded,
3505 ParameterData pd = GetParameterData (method);
3506 int pd_count = pd.Count;
3508 for (int j = 0; j < argument_count; j++) {
3509 Argument a = (Argument) Arguments [j];
3510 Expression a_expr = a.Expr;
3511 Type parameter_type = pd.ParameterType (j);
3513 if (pd.ParameterModifier (j) == Parameter.Modifier.PARAMS && chose_params_expanded)
3514 parameter_type = parameter_type.GetElementType ();
3516 if (a.Type != parameter_type){
3519 conv = ConvertImplicitStandard (ec, a_expr, parameter_type, loc);
3522 if (!Location.IsNull (loc)) {
3523 if (delegate_type == null)
3525 "The best overloaded match for method '" +
3526 FullMethodDesc (method) +
3527 "' has some invalid arguments");
3529 Report.Error (1594, loc,
3530 "Delegate '" + delegate_type.ToString () +
3531 "' has some invalid arguments.");
3533 "Argument " + (j+1) +
3534 ": Cannot convert from '" + Argument.FullDesc (a)
3535 + "' to '" + pd.ParameterDesc (j) + "'");
3542 // Update the argument with the implicit conversion
3548 if (a.GetParameterModifier () != pd.ParameterModifier (j) &&
3549 pd.ParameterModifier (pd_count - 1) != Parameter.Modifier.PARAMS) {
3550 if (!Location.IsNull (loc)) {
3551 Console.WriteLine ("A:P: " + a.GetParameterModifier ());
3552 Console.WriteLine ("PP:: " + pd.ParameterModifier (j));
3553 Console.WriteLine ("PT: " + parameter_type.IsByRef);
3555 "The best overloaded match for method '" + FullMethodDesc (method)+
3556 "' has some invalid arguments");
3558 "Argument " + (j+1) +
3559 ": Cannot convert from '" + Argument.FullDesc (a)
3560 + "' to '" + pd.ParameterDesc (j) + "'");
3570 public override Expression DoResolve (EmitContext ec)
3573 // First, resolve the expression that is used to
3574 // trigger the invocation
3576 if (expr is BaseAccess)
3579 expr = expr.Resolve (ec);
3583 if (!(expr is MethodGroupExpr)) {
3584 Type expr_type = expr.Type;
3586 if (expr_type != null){
3587 bool IsDelegate = TypeManager.IsDelegateType (expr_type);
3589 return (new DelegateInvocation (
3590 this.expr, Arguments, loc)).Resolve (ec);
3594 if (!(expr is MethodGroupExpr)){
3595 report118 (loc, this.expr, "method group");
3600 // Next, evaluate all the expressions in the argument list
3602 if (Arguments != null){
3603 for (int i = Arguments.Count; i > 0;){
3605 Argument a = (Argument) Arguments [i];
3607 if (!a.Resolve (ec, loc))
3612 method = OverloadResolve (ec, (MethodGroupExpr) this.expr, Arguments, loc);
3614 if (method == null){
3616 "Could not find any applicable function for this argument list");
3620 if (method is MethodInfo)
3621 type = ((MethodInfo)method).ReturnType;
3623 if (type.IsPointer){
3630 eclass = ExprClass.Value;
3635 // Emits the list of arguments as an array
3637 static void EmitParams (EmitContext ec, int idx, ArrayList arguments)
3639 ILGenerator ig = ec.ig;
3640 int count = arguments.Count - idx;
3641 Argument a = (Argument) arguments [idx];
3642 Type t = a.expr.Type;
3643 string array_type = t.FullName + "[]";
3646 array = ig.DeclareLocal (Type.GetType (array_type));
3647 IntConstant.EmitInt (ig, count);
3648 ig.Emit (OpCodes.Newarr, t);
3649 ig.Emit (OpCodes.Stloc, array);
3651 int top = arguments.Count;
3652 for (int j = idx; j < top; j++){
3653 a = (Argument) arguments [j];
3655 ig.Emit (OpCodes.Ldloc, array);
3656 IntConstant.EmitInt (ig, j - idx);
3659 ArrayAccess.EmitStoreOpcode (ig, t);
3661 ig.Emit (OpCodes.Ldloc, array);
3665 /// Emits a list of resolved Arguments that are in the arguments
3668 /// The MethodBase argument might be null if the
3669 /// emission of the arguments is known not to contain
3670 /// a `params' field (for example in constructors or other routines
3671 /// that keep their arguments in this structure
3673 public static void EmitArguments (EmitContext ec, MethodBase mb, ArrayList arguments)
3677 pd = GetParameterData (mb);
3682 // If we are calling a params method with no arguments, special case it
3684 if (arguments == null){
3685 if (pd != null && pd.Count > 0 &&
3686 pd.ParameterModifier (0) == Parameter.Modifier.PARAMS){
3687 ILGenerator ig = ec.ig;
3689 IntConstant.EmitInt (ig, 0);
3690 ig.Emit (OpCodes.Newarr, pd.ParameterType (0).GetElementType ());
3696 int top = arguments.Count;
3698 for (int i = 0; i < top; i++){
3699 Argument a = (Argument) arguments [i];
3702 if (pd.ParameterModifier (i) == Parameter.Modifier.PARAMS){
3704 // Special case if we are passing the same data as the
3705 // params argument, do not put it in an array.
3707 if (pd.ParameterType (i) == a.Type)
3710 EmitParams (ec, i, arguments);
3720 /// is_base tells whether we want to force the use of the `call'
3721 /// opcode instead of using callvirt. Call is required to call
3722 /// a specific method, while callvirt will always use the most
3723 /// recent method in the vtable.
3725 /// is_static tells whether this is an invocation on a static method
3727 /// instance_expr is an expression that represents the instance
3728 /// it must be non-null if is_static is false.
3730 /// method is the method to invoke.
3732 /// Arguments is the list of arguments to pass to the method or constructor.
3734 public static void EmitCall (EmitContext ec, bool is_base,
3735 bool is_static, Expression instance_expr,
3736 MethodBase method, ArrayList Arguments)
3738 ILGenerator ig = ec.ig;
3739 bool struct_call = false;
3743 if (method.DeclaringType.IsValueType)
3746 // If this is ourselves, push "this"
3748 if (instance_expr == null){
3749 ig.Emit (OpCodes.Ldarg_0);
3752 // Push the instance expression
3754 if (instance_expr.Type.IsSubclassOf (TypeManager.value_type)){
3756 // Special case: calls to a function declared in a
3757 // reference-type with a value-type argument need
3758 // to have their value boxed.
3761 if (method.DeclaringType.IsValueType){
3763 // If the expression implements IMemoryLocation, then
3764 // we can optimize and use AddressOf on the
3767 // If not we have to use some temporary storage for
3769 if (instance_expr is IMemoryLocation){
3770 ((IMemoryLocation)instance_expr).
3771 AddressOf (ec, AddressOp.LoadStore);
3774 Type t = instance_expr.Type;
3776 instance_expr.Emit (ec);
3777 LocalBuilder temp = ig.DeclareLocal (t);
3778 ig.Emit (OpCodes.Stloc, temp);
3779 ig.Emit (OpCodes.Ldloca, temp);
3782 instance_expr.Emit (ec);
3783 ig.Emit (OpCodes.Box, instance_expr.Type);
3786 instance_expr.Emit (ec);
3790 EmitArguments (ec, method, Arguments);
3792 if (is_static || struct_call || is_base){
3793 if (method is MethodInfo)
3794 ig.Emit (OpCodes.Call, (MethodInfo) method);
3796 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
3798 if (method is MethodInfo)
3799 ig.Emit (OpCodes.Callvirt, (MethodInfo) method);
3801 ig.Emit (OpCodes.Callvirt, (ConstructorInfo) method);
3805 public override void Emit (EmitContext ec)
3807 MethodGroupExpr mg = (MethodGroupExpr) this.expr;
3809 EmitCall (ec, is_base, method.IsStatic, mg.InstanceExpression, method, Arguments);
3812 public override void EmitStatement (EmitContext ec)
3817 // Pop the return value if there is one
3819 if (method is MethodInfo){
3820 if (((MethodInfo)method).ReturnType != TypeManager.void_type)
3821 ec.ig.Emit (OpCodes.Pop);
3827 // This class is used to "disable" the code generation for the
3828 // temporary variable when initializing value types.
3830 class EmptyAddressOf : EmptyExpression, IMemoryLocation {
3831 public void AddressOf (EmitContext ec, AddressOp Mode)
3838 /// Implements the new expression
3840 public class New : ExpressionStatement {
3841 public readonly ArrayList Arguments;
3842 public readonly string RequestedType;
3845 MethodBase method = null;
3848 // If set, the new expression is for a value_target, and
3849 // we will not leave anything on the stack.
3851 Expression value_target;
3853 public New (string requested_type, ArrayList arguments, Location l)
3855 RequestedType = requested_type;
3856 Arguments = arguments;
3860 public Expression ValueTypeVariable {
3862 return value_target;
3866 value_target = value;
3871 // This function is used to disable the following code sequence for
3872 // value type initialization:
3874 // AddressOf (temporary)
3878 // Instead the provide will have provided us with the address on the
3879 // stack to store the results.
3881 static Expression MyEmptyExpression;
3883 public void DisableTemporaryValueType ()
3885 if (MyEmptyExpression == null)
3886 MyEmptyExpression = new EmptyAddressOf ();
3889 // To enable this, look into:
3890 // test-34 and test-89 and self bootstrapping.
3892 // For instance, we can avoid a copy by using `newobj'
3893 // instead of Call + Push-temp on value types.
3894 // value_target = MyEmptyExpression;
3897 public override Expression DoResolve (EmitContext ec)
3899 type = RootContext.LookupType (ec.DeclSpace, RequestedType, false, loc);
3904 bool IsDelegate = TypeManager.IsDelegateType (type);
3907 return (new NewDelegate (type, Arguments, loc)).Resolve (ec);
3909 bool is_struct = false;
3910 is_struct = type.IsSubclassOf (TypeManager.value_type);
3911 eclass = ExprClass.Value;
3914 // SRE returns a match for .ctor () on structs (the object constructor),
3915 // so we have to manually ignore it.
3917 if (is_struct && Arguments == null)
3921 ml = MemberLookup (ec, type, ".ctor",
3922 MemberTypes.Constructor,
3923 AllBindingFlags | BindingFlags.DeclaredOnly, loc);
3925 if (! (ml is MethodGroupExpr)){
3927 report118 (loc, ml, "method group");
3933 if (Arguments != null){
3934 for (int i = Arguments.Count; i > 0;){
3936 Argument a = (Argument) Arguments [i];
3938 if (!a.Resolve (ec, loc))
3943 method = Invocation.OverloadResolve (ec, (MethodGroupExpr) ml,
3948 if (method == null && !is_struct) {
3950 "New invocation: Can not find a constructor for " +
3951 "this argument list");
3958 // This DoEmit can be invoked in two contexts:
3959 // * As a mechanism that will leave a value on the stack (new object)
3960 // * As one that wont (init struct)
3962 // You can control whether a value is required on the stack by passing
3963 // need_value_on_stack. The code *might* leave a value on the stack
3964 // so it must be popped manually
3966 // If we are dealing with a ValueType, we have a few
3967 // situations to deal with:
3969 // * The target is a ValueType, and we have been provided
3970 // the instance (this is easy, we are being assigned).
3972 // * The target of New is being passed as an argument,
3973 // to a boxing operation or a function that takes a
3976 // In this case, we need to create a temporary variable
3977 // that is the argument of New.
3979 // Returns whether a value is left on the stack
3981 bool DoEmit (EmitContext ec, bool need_value_on_stack)
3983 bool is_value_type = type.IsSubclassOf (TypeManager.value_type);
3984 ILGenerator ig = ec.ig;
3989 if (value_target == null)
3990 value_target = new LocalTemporary (ec, type);
3992 ml = (IMemoryLocation) value_target;
3993 ml.AddressOf (ec, AddressOp.Store);
3997 Invocation.EmitArguments (ec, method, Arguments);
4001 ig.Emit (OpCodes.Initobj, type);
4003 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
4004 if (need_value_on_stack){
4005 value_target.Emit (ec);
4010 ig.Emit (OpCodes.Newobj, (ConstructorInfo) method);
4015 public override void Emit (EmitContext ec)
4020 public override void EmitStatement (EmitContext ec)
4022 if (DoEmit (ec, false))
4023 ec.ig.Emit (OpCodes.Pop);
4028 /// Represents an array creation expression.
4032 /// There are two possible scenarios here: one is an array creation
4033 /// expression that specifies the dimensions and optionally the
4034 /// initialization data and the other which does not need dimensions
4035 /// specified but where initialization data is mandatory.
4037 public class ArrayCreation : ExpressionStatement {
4038 string RequestedType;
4040 ArrayList Initializers;
4044 // The list of Argument types.
4045 // This is used to constrcut the `newarray' or constructor signature
4047 ArrayList Arguments;
4049 MethodBase method = null;
4050 Type array_element_type;
4051 bool IsOneDimensional = false;
4052 bool IsBuiltinType = false;
4053 bool ExpectInitializers = false;
4056 Type underlying_type;
4058 ArrayList ArrayData;
4063 // The number of array initializers that we can handle
4064 // via the InitializeArray method - through EmitStaticInitializers
4066 int num_automatic_initializers;
4068 public ArrayCreation (string requested_type, ArrayList exprs,
4069 string rank, ArrayList initializers, Location l)
4071 RequestedType = requested_type;
4073 Initializers = initializers;
4076 Arguments = new ArrayList ();
4078 foreach (Expression e in exprs)
4079 Arguments.Add (new Argument (e, Argument.AType.Expression));
4082 public ArrayCreation (string requested_type, string rank, ArrayList initializers, Location l)
4084 RequestedType = requested_type;
4085 Initializers = initializers;
4088 Rank = rank.Substring (0, rank.LastIndexOf ("["));
4090 string tmp = rank.Substring (rank.LastIndexOf ("["));
4092 dimensions = tmp.Length - 1;
4093 ExpectInitializers = true;
4096 public static string FormArrayType (string base_type, int idx_count, string rank)
4098 StringBuilder sb = new StringBuilder (base_type);
4103 for (int i = 1; i < idx_count; i++)
4108 return sb.ToString ();
4111 public static string FormElementType (string base_type, int idx_count, string rank)
4113 StringBuilder sb = new StringBuilder (base_type);
4116 for (int i = 1; i < idx_count; i++)
4123 string val = sb.ToString ();
4125 return val.Substring (0, val.LastIndexOf ("["));
4130 Report.Error (178, loc, "Incorrectly structured array initializer");
4133 public bool CheckIndices (EmitContext ec, ArrayList probe, int idx, bool specified_dims)
4135 if (specified_dims) {
4136 Argument a = (Argument) Arguments [idx];
4138 if (!a.Resolve (ec, loc))
4141 if (!(a.Expr is Constant)) {
4142 Report.Error (150, loc, "A constant value is expected");
4146 int value = (int) ((Constant) a.Expr).GetValue ();
4148 if (value != probe.Count) {
4153 Bounds [idx] = value;
4156 foreach (object o in probe) {
4157 if (o is ArrayList) {
4158 bool ret = CheckIndices (ec, (ArrayList) o, idx + 1, specified_dims);
4162 Expression tmp = (Expression) o;
4163 tmp = tmp.Resolve (ec);
4167 // Handle initialization from vars, fields etc.
4169 Expression conv = ConvertImplicitRequired (
4170 ec, tmp, underlying_type, loc);
4175 if (conv is StringConstant)
4176 ArrayData.Add (conv);
4177 else if (conv is Constant) {
4178 ArrayData.Add (conv);
4179 num_automatic_initializers++;
4181 ArrayData.Add (conv);
4188 public void UpdateIndices (EmitContext ec)
4191 for (ArrayList probe = Initializers; probe != null;) {
4192 if (probe.Count > 0 && probe [0] is ArrayList) {
4193 Expression e = new IntConstant (probe.Count);
4194 Arguments.Add (new Argument (e, Argument.AType.Expression));
4196 Bounds [i++] = probe.Count;
4198 probe = (ArrayList) probe [0];
4201 Expression e = new IntConstant (probe.Count);
4202 Arguments.Add (new Argument (e, Argument.AType.Expression));
4204 Bounds [i++] = probe.Count;
4211 public bool ValidateInitializers (EmitContext ec)
4213 if (Initializers == null) {
4214 if (ExpectInitializers)
4220 underlying_type = RootContext.LookupType (
4221 ec.DeclSpace, RequestedType, false, loc);
4224 // We use this to store all the date values in the order in which we
4225 // will need to store them in the byte blob later
4227 ArrayData = new ArrayList ();
4228 Bounds = new Hashtable ();
4232 if (Arguments != null) {
4233 ret = CheckIndices (ec, Initializers, 0, true);
4237 Arguments = new ArrayList ();
4239 ret = CheckIndices (ec, Initializers, 0, false);
4246 if (Arguments.Count != dimensions) {
4255 public override Expression DoResolve (EmitContext ec)
4260 // First step is to validate the initializers and fill
4261 // in any missing bits
4263 if (!ValidateInitializers (ec))
4266 if (Arguments == null)
4269 arg_count = Arguments.Count;
4270 for (int i = 0; i < arg_count; i++){
4271 Argument a = (Argument) Arguments [i];
4273 if (!a.Resolve (ec, loc))
4277 // Now, convert that to an integer
4279 Expression real_arg;
4280 bool old_checked = ec.CheckState;
4281 ec.CheckState = true;
4283 real_arg = ConvertExplicit (
4284 ec, a.expr, TypeManager.uint32_type, loc);
4285 ec.CheckState = old_checked;
4286 if (real_arg == null)
4293 string array_type = FormArrayType (RequestedType, arg_count, Rank);
4294 string element_type = FormElementType (RequestedType, arg_count, Rank);
4296 type = RootContext.LookupType (ec.DeclSpace, array_type, false, loc);
4298 array_element_type = RootContext.LookupType (
4299 ec.DeclSpace, element_type, false, loc);
4304 if (arg_count == 1) {
4305 IsOneDimensional = true;
4306 eclass = ExprClass.Value;
4310 IsBuiltinType = TypeManager.IsBuiltinType (type);
4312 if (IsBuiltinType) {
4316 ml = MemberLookup (ec, type, ".ctor", MemberTypes.Constructor,
4317 AllBindingFlags, loc);
4319 if (!(ml is MethodGroupExpr)){
4320 report118 (loc, ml, "method group");
4325 Report.Error (-6, loc, "New invocation: Can not find a constructor for " +
4326 "this argument list");
4330 method = Invocation.OverloadResolve (ec, (MethodGroupExpr) ml, Arguments, loc);
4332 if (method == null) {
4333 Report.Error (-6, loc, "New invocation: Can not find a constructor for " +
4334 "this argument list");
4338 eclass = ExprClass.Value;
4343 ModuleBuilder mb = CodeGen.ModuleBuilder;
4345 ArrayList args = new ArrayList ();
4346 if (Arguments != null){
4347 for (int i = arg_count; i > 0;){
4349 Argument a = (Argument) Arguments [i];
4351 args.Add (TypeManager.int32_type);
4355 Type [] arg_types = null;
4358 arg_types = new Type [args.Count];
4360 args.CopyTo (arg_types, 0);
4362 method = mb.GetArrayMethod (type, ".ctor", CallingConventions.HasThis, null,
4365 if (method == null) {
4366 Report.Error (-6, loc, "New invocation: Can not find a constructor for " +
4367 "this argument list");
4371 eclass = ExprClass.Value;
4377 public static byte [] MakeByteBlob (ArrayList ArrayData, Type underlying_type, Location loc)
4382 int count = ArrayData.Count;
4384 factor = GetTypeSize (underlying_type);
4388 data = new byte [(count * factor + 4) & ~3];
4391 for (int i = 0; i < count; ++i) {
4392 object v = ArrayData [i];
4394 if (v is EnumConstant)
4395 v = ((EnumConstant) v).Child;
4397 if (v is Constant && !(v is StringConstant))
4398 v = ((Constant) v).GetValue ();
4404 if (underlying_type == TypeManager.int64_type){
4405 if (!(v is Expression)){
4406 long val = (long) v;
4408 for (int j = 0; j < factor; ++j) {
4409 data [idx + j] = (byte) (val & 0xFF);
4413 } else if (underlying_type == TypeManager.uint64_type){
4414 if (!(v is Expression)){
4415 ulong val = (ulong) v;
4417 for (int j = 0; j < factor; ++j) {
4418 data [idx + j] = (byte) (val & 0xFF);
4422 } else if (underlying_type == TypeManager.float_type) {
4423 if (!(v is Expression)){
4424 element = BitConverter.GetBytes ((float) v);
4426 for (int j = 0; j < factor; ++j)
4427 data [idx + j] = element [j];
4429 } else if (underlying_type == TypeManager.double_type) {
4430 if (!(v is Expression)){
4431 element = BitConverter.GetBytes ((double) v);
4433 for (int j = 0; j < factor; ++j)
4434 data [idx + j] = element [j];
4436 } else if (underlying_type == TypeManager.char_type){
4437 if (!(v is Expression)){
4438 int val = (int) ((char) v);
4440 data [idx] = (byte) (val & 0xff);
4441 data [idx+1] = (byte) (val >> 8);
4443 } else if (underlying_type == TypeManager.short_type){
4444 if (!(v is Expression)){
4445 int val = (int) ((short) v);
4447 data [idx] = (byte) (val & 0xff);
4448 data [idx+1] = (byte) (val >> 8);
4450 } else if (underlying_type == TypeManager.ushort_type){
4451 if (!(v is Expression)){
4452 int val = (int) ((ushort) v);
4454 data [idx] = (byte) (val & 0xff);
4455 data [idx+1] = (byte) (val >> 8);
4457 } else if (underlying_type == TypeManager.int32_type) {
4458 if (!(v is Expression)){
4461 data [idx] = (byte) (val & 0xff);
4462 data [idx+1] = (byte) ((val >> 8) & 0xff);
4463 data [idx+2] = (byte) ((val >> 16) & 0xff);
4464 data [idx+3] = (byte) (val >> 24);
4466 } else if (underlying_type == TypeManager.uint32_type) {
4467 if (!(v is Expression)){
4468 uint val = (uint) v;
4470 data [idx] = (byte) (val & 0xff);
4471 data [idx+1] = (byte) ((val >> 8) & 0xff);
4472 data [idx+2] = (byte) ((val >> 16) & 0xff);
4473 data [idx+3] = (byte) (val >> 24);
4475 } else if (underlying_type == TypeManager.sbyte_type) {
4476 if (!(v is Expression)){
4477 sbyte val = (sbyte) v;
4478 data [idx] = (byte) val;
4480 } else if (underlying_type == TypeManager.byte_type) {
4481 if (!(v is Expression)){
4482 byte val = (byte) v;
4483 data [idx] = (byte) val;
4486 throw new Exception ("Unrecognized type in MakeByteBlob");
4495 // Emits the initializers for the array
4497 void EmitStaticInitializers (EmitContext ec, bool is_expression)
4500 // First, the static data
4503 ILGenerator ig = ec.ig;
4505 byte [] data = MakeByteBlob (ArrayData, underlying_type, loc);
4508 fb = RootContext.MakeStaticData (data);
4511 ig.Emit (OpCodes.Dup);
4512 ig.Emit (OpCodes.Ldtoken, fb);
4513 ig.Emit (OpCodes.Call,
4514 TypeManager.void_initializearray_array_fieldhandle);
4519 // Emits pieces of the array that can not be computed at compile
4520 // time (variables and string locations).
4522 // This always expect the top value on the stack to be the array
4524 void EmitDynamicInitializers (EmitContext ec, bool is_expression)
4526 ILGenerator ig = ec.ig;
4527 int dims = Bounds.Count;
4528 int [] current_pos = new int [dims];
4529 int top = ArrayData.Count;
4530 LocalBuilder temp = ig.DeclareLocal (type);
4532 ig.Emit (OpCodes.Stloc, temp);
4534 MethodInfo set = null;
4538 ModuleBuilder mb = null;
4539 mb = CodeGen.ModuleBuilder;
4540 args = new Type [dims + 1];
4543 for (j = 0; j < dims; j++)
4544 args [j] = TypeManager.int32_type;
4546 args [j] = array_element_type;
4548 set = mb.GetArrayMethod (
4550 CallingConventions.HasThis | CallingConventions.Standard,
4551 TypeManager.void_type, args);
4554 for (int i = 0; i < top; i++){
4556 Expression e = null;
4558 if (ArrayData [i] is Expression)
4559 e = (Expression) ArrayData [i];
4563 // Basically we do this for string literals and
4564 // other non-literal expressions
4566 if (e is StringConstant || !(e is Constant) ||
4567 num_automatic_initializers <= 2) {
4568 Type etype = e.Type;
4570 ig.Emit (OpCodes.Ldloc, temp);
4572 for (int idx = dims; idx > 0; ) {
4574 IntConstant.EmitInt (ig, current_pos [idx]);
4578 // If we are dealing with a struct, get the
4579 // address of it, so we can store it.
4581 if (etype.IsSubclassOf (TypeManager.value_type) &&
4582 !TypeManager.IsBuiltinType (etype)){
4587 // Let new know that we are providing
4588 // the address where to store the results
4590 n.DisableTemporaryValueType ();
4593 ig.Emit (OpCodes.Ldelema, etype);
4599 ArrayAccess.EmitStoreOpcode (ig, array_element_type);
4601 ig.Emit (OpCodes.Call, set);
4608 for (int j = 0; j < dims; j++){
4610 if (current_pos [j] < (int) Bounds [j])
4612 current_pos [j] = 0;
4617 ig.Emit (OpCodes.Ldloc, temp);
4620 void EmitArrayArguments (EmitContext ec)
4622 foreach (Argument a in Arguments)
4626 void DoEmit (EmitContext ec, bool is_statement)
4628 ILGenerator ig = ec.ig;
4630 EmitArrayArguments (ec);
4631 if (IsOneDimensional)
4632 ig.Emit (OpCodes.Newarr, array_element_type);
4635 ig.Emit (OpCodes.Newobj, (ConstructorInfo) method);
4637 ig.Emit (OpCodes.Newobj, (MethodInfo) method);
4640 if (Initializers != null){
4642 // FIXME: Set this variable correctly.
4644 bool dynamic_initializers = true;
4646 if (underlying_type != TypeManager.string_type &&
4647 underlying_type != TypeManager.object_type) {
4648 if (num_automatic_initializers > 2)
4649 EmitStaticInitializers (ec, dynamic_initializers || !is_statement);
4652 if (dynamic_initializers)
4653 EmitDynamicInitializers (ec, !is_statement);
4657 public override void Emit (EmitContext ec)
4662 public override void EmitStatement (EmitContext ec)
4670 /// Represents the `this' construct
4672 public class This : Expression, IAssignMethod, IMemoryLocation {
4675 public This (Location loc)
4680 public override Expression DoResolve (EmitContext ec)
4682 eclass = ExprClass.Variable;
4683 type = ec.ContainerType;
4686 Report.Error (26, loc,
4687 "Keyword this not valid in static code");
4694 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
4698 if (ec.TypeContainer is Class){
4699 Report.Error (1604, loc, "Cannot assign to `this'");
4706 public override void Emit (EmitContext ec)
4708 ec.ig.Emit (OpCodes.Ldarg_0);
4711 public void EmitAssign (EmitContext ec, Expression source)
4714 ec.ig.Emit (OpCodes.Starg, 0);
4717 public void AddressOf (EmitContext ec, AddressOp mode)
4719 ec.ig.Emit (OpCodes.Ldarg_0);
4722 // FIGURE OUT WHY LDARG_S does not work
4724 // consider: struct X { int val; int P { set { val = value; }}}
4726 // Yes, this looks very bad. Look at `NOTAS' for
4728 // ec.ig.Emit (OpCodes.Ldarga_S, (byte) 0);
4733 /// Implements the typeof operator
4735 public class TypeOf : Expression {
4736 public readonly string QueriedType;
4740 public TypeOf (string queried_type, Location l)
4742 QueriedType = queried_type;
4746 public override Expression DoResolve (EmitContext ec)
4748 typearg = RootContext.LookupType (
4749 ec.DeclSpace, QueriedType, false, loc);
4751 if (typearg == null)
4754 type = TypeManager.type_type;
4755 eclass = ExprClass.Type;
4759 public override void Emit (EmitContext ec)
4761 ec.ig.Emit (OpCodes.Ldtoken, typearg);
4762 ec.ig.Emit (OpCodes.Call, TypeManager.system_type_get_type_from_handle);
4765 public Type TypeArg {
4766 get { return typearg; }
4771 /// Implements the sizeof expression
4773 public class SizeOf : Expression {
4774 public readonly string QueriedType;
4778 public SizeOf (string queried_type, Location l)
4780 this.QueriedType = queried_type;
4784 public override Expression DoResolve (EmitContext ec)
4786 type_queried = RootContext.LookupType (
4787 ec.DeclSpace, QueriedType, false, loc);
4788 if (type_queried == null)
4791 type = TypeManager.int32_type;
4792 eclass = ExprClass.Value;
4796 public override void Emit (EmitContext ec)
4798 int size = GetTypeSize (type_queried);
4801 ec.ig.Emit (OpCodes.Sizeof, type_queried);
4803 IntConstant.EmitInt (ec.ig, size);
4808 /// Implements the member access expression
4810 public class MemberAccess : Expression {
4811 public readonly string Identifier;
4813 Expression member_lookup;
4816 public MemberAccess (Expression expr, string id, Location l)
4823 public Expression Expr {
4829 static void error176 (Location loc, string name)
4831 Report.Error (176, loc, "Static member `" +
4832 name + "' cannot be accessed " +
4833 "with an instance reference, qualify with a " +
4834 "type name instead");
4837 static bool IdenticalNameAndTypeName (EmitContext ec, Expression left_original, Location loc)
4839 if (left_original == null)
4842 if (!(left_original is SimpleName))
4845 SimpleName sn = (SimpleName) left_original;
4847 Type t = RootContext.LookupType (ec.DeclSpace, sn.Name, true, loc);
4854 public static Expression ResolveMemberAccess (EmitContext ec, Expression member_lookup,
4855 Expression left, Location loc,
4856 Expression left_original)
4861 if (member_lookup is MethodGroupExpr){
4862 MethodGroupExpr mg = (MethodGroupExpr) member_lookup;
4867 if (left is TypeExpr){
4868 if (!mg.RemoveInstanceMethods ()){
4869 SimpleName.Error120 (loc, mg.Methods [0].Name);
4873 return member_lookup;
4877 // Instance.MethodGroup
4879 if (IdenticalNameAndTypeName (ec, left_original, loc)){
4880 if (mg.RemoveInstanceMethods ())
4881 return member_lookup;
4884 if (!mg.RemoveStaticMethods ()){
4885 error176 (loc, mg.Methods [0].Name);
4889 mg.InstanceExpression = left;
4890 return member_lookup;
4892 if (!mg.RemoveStaticMethods ()){
4893 if (IdenticalNameAndTypeName (ec, left_original, loc)){
4894 if (!mg.RemoveInstanceMethods ()){
4895 SimpleName.Error120 (loc, mg.Methods [0].Name);
4898 return member_lookup;
4901 error176 (loc, mg.Methods [0].Name);
4905 mg.InstanceExpression = left;
4907 return member_lookup;
4911 if (member_lookup is FieldExpr){
4912 FieldExpr fe = (FieldExpr) member_lookup;
4913 FieldInfo fi = fe.FieldInfo;
4914 Type decl_type = fi.DeclaringType;
4916 if (fi is FieldBuilder) {
4917 Const c = TypeManager.LookupConstant ((FieldBuilder) fi);
4920 object o = c.LookupConstantValue (ec);
4921 object real_value = ((Constant) c.Expr).GetValue ();
4923 return Constantify (real_value, fi.FieldType);
4928 Type t = fi.FieldType;
4932 if (fi is FieldBuilder)
4933 o = TypeManager.GetValue ((FieldBuilder) fi);
4935 o = fi.GetValue (fi);
4937 if (decl_type.IsSubclassOf (TypeManager.enum_type)) {
4938 Expression enum_member = MemberLookup (
4939 ec, decl_type, "value__", MemberTypes.Field,
4940 AllBindingFlags, loc);
4942 Enum en = TypeManager.LookupEnum (decl_type);
4946 c = Constantify (o, en.UnderlyingType);
4948 c = Constantify (o, enum_member.Type);
4950 return new EnumConstant (c, decl_type);
4953 Expression exp = Constantify (o, t);
4955 if (!(left is TypeExpr)) {
4956 error176 (loc, fe.FieldInfo.Name);
4963 if (fi.FieldType.IsPointer && !ec.InUnsafe){
4968 if (left is TypeExpr){
4969 // and refers to a type name or an
4970 if (!fe.FieldInfo.IsStatic){
4971 error176 (loc, fe.FieldInfo.Name);
4974 return member_lookup;
4976 if (fe.FieldInfo.IsStatic){
4977 if (IdenticalNameAndTypeName (ec, left_original, loc))
4978 return member_lookup;
4980 error176 (loc, fe.FieldInfo.Name);
4983 fe.InstanceExpression = left;
4989 if (member_lookup is PropertyExpr){
4990 PropertyExpr pe = (PropertyExpr) member_lookup;
4992 if (left is TypeExpr){
4994 SimpleName.Error120 (loc, pe.PropertyInfo.Name);
5000 if (IdenticalNameAndTypeName (ec, left_original, loc))
5001 return member_lookup;
5002 error176 (loc, pe.PropertyInfo.Name);
5005 pe.InstanceExpression = left;
5011 if (member_lookup is EventExpr) {
5013 EventExpr ee = (EventExpr) member_lookup;
5016 // If the event is local to this class, we transform ourselves into
5020 Expression ml = MemberLookup (
5021 ec, ec.ContainerType,
5022 ee.EventInfo.Name, MemberTypes.Event, AllBindingFlags, loc);
5025 MemberInfo mi = ec.TypeContainer.GetFieldFromEvent ((EventExpr) ml);
5029 // If this happens, then we have an event with its own
5030 // accessors and private field etc so there's no need
5031 // to transform ourselves : we should instead flag an error
5033 Assign.error70 (ee.EventInfo, loc);
5037 ml = ExprClassFromMemberInfo (ec, mi, loc);
5040 Report.Error (-200, loc, "Internal error!!");
5043 return ResolveMemberAccess (ec, ml, left, loc, left_original);
5046 if (left is TypeExpr) {
5048 SimpleName.Error120 (loc, ee.EventInfo.Name);
5056 if (IdenticalNameAndTypeName (ec, left_original, loc))
5059 error176 (loc, ee.EventInfo.Name);
5063 ee.InstanceExpression = left;
5069 if (member_lookup is TypeExpr){
5070 member_lookup.Resolve (ec);
5071 return member_lookup;
5074 Console.WriteLine ("Left is: " + left);
5075 Report.Error (-100, loc, "Support for [" + member_lookup + "] is not present yet");
5076 Environment.Exit (0);
5080 public override Expression DoResolve (EmitContext ec)
5083 // We are the sole users of ResolveWithSimpleName (ie, the only
5084 // ones that can cope with it
5086 Expression original = expr;
5087 expr = expr.ResolveWithSimpleName (ec);
5092 if (expr is SimpleName){
5093 SimpleName child_expr = (SimpleName) expr;
5095 expr = new SimpleName (child_expr.Name + "." + Identifier, loc);
5097 return expr.ResolveWithSimpleName (ec);
5101 // TODO: I mailed Ravi about this, and apparently we can get rid
5102 // of this and put it in the right place.
5104 // Handle enums here when they are in transit.
5105 // Note that we cannot afford to hit MemberLookup in this case because
5106 // it will fail to find any members at all
5109 Type expr_type = expr.Type;
5110 if ((expr is TypeExpr) && (expr_type.IsSubclassOf (TypeManager.enum_type))){
5112 Enum en = TypeManager.LookupEnum (expr_type);
5115 object value = en.LookupEnumValue (ec, Identifier, loc);
5118 Constant c = Constantify (value, en.UnderlyingType);
5119 return new EnumConstant (c, expr_type);
5124 if (expr_type.IsPointer){
5125 Report.Error (23, loc,
5126 "The `.' operator can not be applied to pointer operands (" +
5127 TypeManager.CSharpName (expr_type) + ")");
5131 member_lookup = MemberLookup (ec, expr_type, Identifier, loc);
5133 if (member_lookup == null){
5134 Report.Error (117, loc, "`" + expr_type + "' does not contain a " +
5135 "definition for `" + Identifier + "'");
5140 return ResolveMemberAccess (ec, member_lookup, expr, loc, original);
5143 public override void Emit (EmitContext ec)
5145 throw new Exception ("Should not happen");
5150 /// Implements checked expressions
5152 public class CheckedExpr : Expression {
5154 public Expression Expr;
5156 public CheckedExpr (Expression e)
5161 public override Expression DoResolve (EmitContext ec)
5163 bool last_const_check = ec.ConstantCheckState;
5165 ec.ConstantCheckState = true;
5166 Expr = Expr.Resolve (ec);
5167 ec.ConstantCheckState = last_const_check;
5172 eclass = Expr.eclass;
5177 public override void Emit (EmitContext ec)
5179 bool last_check = ec.CheckState;
5180 bool last_const_check = ec.ConstantCheckState;
5182 ec.CheckState = true;
5183 ec.ConstantCheckState = true;
5185 ec.CheckState = last_check;
5186 ec.ConstantCheckState = last_const_check;
5192 /// Implements the unchecked expression
5194 public class UnCheckedExpr : Expression {
5196 public Expression Expr;
5198 public UnCheckedExpr (Expression e)
5203 public override Expression DoResolve (EmitContext ec)
5205 bool last_const_check = ec.ConstantCheckState;
5207 ec.ConstantCheckState = false;
5208 Expr = Expr.Resolve (ec);
5209 ec.ConstantCheckState = last_const_check;
5214 eclass = Expr.eclass;
5219 public override void Emit (EmitContext ec)
5221 bool last_check = ec.CheckState;
5222 bool last_const_check = ec.ConstantCheckState;
5224 ec.CheckState = false;
5225 ec.ConstantCheckState = false;
5227 ec.CheckState = last_check;
5228 ec.ConstantCheckState = last_const_check;
5234 /// An Element Access expression.
5236 /// During semantic analysis these are transformed into
5237 /// IndexerAccess or ArrayAccess
5239 public class ElementAccess : Expression {
5240 public ArrayList Arguments;
5241 public Expression Expr;
5242 public Location loc;
5244 public ElementAccess (Expression e, ArrayList e_list, Location l)
5253 Arguments = new ArrayList ();
5254 foreach (Expression tmp in e_list)
5255 Arguments.Add (new Argument (tmp, Argument.AType.Expression));
5259 bool CommonResolve (EmitContext ec)
5261 Expr = Expr.Resolve (ec);
5266 if (Arguments == null)
5269 for (int i = Arguments.Count; i > 0;){
5271 Argument a = (Argument) Arguments [i];
5273 if (!a.Resolve (ec, loc))
5280 Expression MakePointerAccess ()
5284 if (t == TypeManager.void_ptr_type){
5287 "The array index operation is not valid for void pointers");
5290 if (Arguments.Count != 1){
5293 "A pointer must be indexed by a single value");
5296 Expression p = new PointerArithmetic (true, Expr, ((Argument)Arguments [0]).Expr, t);
5297 return new Indirection (p);
5300 public override Expression DoResolve (EmitContext ec)
5302 if (!CommonResolve (ec))
5306 // We perform some simple tests, and then to "split" the emit and store
5307 // code we create an instance of a different class, and return that.
5309 // I am experimenting with this pattern.
5313 if (t.IsSubclassOf (TypeManager.array_type))
5314 return (new ArrayAccess (this)).Resolve (ec);
5315 else if (t.IsPointer)
5316 return MakePointerAccess ();
5318 return (new IndexerAccess (this)).Resolve (ec);
5321 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
5323 if (!CommonResolve (ec))
5327 if (t.IsSubclassOf (TypeManager.array_type))
5328 return (new ArrayAccess (this)).ResolveLValue (ec, right_side);
5329 else if (t.IsPointer)
5330 return MakePointerAccess ();
5332 return (new IndexerAccess (this)).ResolveLValue (ec, right_side);
5335 public override void Emit (EmitContext ec)
5337 throw new Exception ("Should never be reached");
5342 /// Implements array access
5344 public class ArrayAccess : Expression, IAssignMethod, IMemoryLocation {
5346 // Points to our "data" repository
5350 public ArrayAccess (ElementAccess ea_data)
5353 eclass = ExprClass.Variable;
5356 public override Expression DoResolve (EmitContext ec)
5358 ExprClass eclass = ea.Expr.eclass;
5360 if (!(eclass == ExprClass.Variable || eclass == ExprClass.Value)) {
5361 report118 (ea.loc, ea.Expr, "variable or value");
5365 Type t = ea.Expr.Type;
5366 if (t.GetArrayRank () != ea.Arguments.Count){
5367 Report.Error (22, ea.loc,
5368 "Incorrect number of indexes for array " +
5369 " expected: " + t.GetArrayRank () + " got: " +
5370 ea.Arguments.Count);
5373 type = t.GetElementType ();
5374 if (type.IsPointer && !ec.InUnsafe){
5375 UnsafeError (ea.loc);
5379 eclass = ExprClass.Variable;
5385 /// Emits the right opcode to load an object of Type `t'
5386 /// from an array of T
5388 static public void EmitLoadOpcode (ILGenerator ig, Type type)
5390 if (type == TypeManager.byte_type || type == TypeManager.bool_type)
5391 ig.Emit (OpCodes.Ldelem_I1);
5392 else if (type == TypeManager.sbyte_type)
5393 ig.Emit (OpCodes.Ldelem_U1);
5394 else if (type == TypeManager.short_type)
5395 ig.Emit (OpCodes.Ldelem_I2);
5396 else if (type == TypeManager.ushort_type)
5397 ig.Emit (OpCodes.Ldelem_U2);
5398 else if (type == TypeManager.int32_type)
5399 ig.Emit (OpCodes.Ldelem_I4);
5400 else if (type == TypeManager.uint32_type)
5401 ig.Emit (OpCodes.Ldelem_U4);
5402 else if (type == TypeManager.uint64_type)
5403 ig.Emit (OpCodes.Ldelem_I8);
5404 else if (type == TypeManager.int64_type)
5405 ig.Emit (OpCodes.Ldelem_I8);
5406 else if (type == TypeManager.float_type)
5407 ig.Emit (OpCodes.Ldelem_R4);
5408 else if (type == TypeManager.double_type)
5409 ig.Emit (OpCodes.Ldelem_R8);
5410 else if (type == TypeManager.intptr_type)
5411 ig.Emit (OpCodes.Ldelem_I);
5412 else if (type.IsValueType){
5413 ig.Emit (OpCodes.Ldelema, type);
5414 ig.Emit (OpCodes.Ldobj, type);
5416 ig.Emit (OpCodes.Ldelem_Ref);
5420 /// Emits the right opcode to store an object of Type `t'
5421 /// from an array of T.
5423 static public void EmitStoreOpcode (ILGenerator ig, Type t)
5425 if (t == TypeManager.byte_type || t == TypeManager.sbyte_type ||
5426 t == TypeManager.bool_type)
5427 ig.Emit (OpCodes.Stelem_I1);
5428 else if (t == TypeManager.short_type || t == TypeManager.ushort_type || t == TypeManager.char_type)
5429 ig.Emit (OpCodes.Stelem_I2);
5430 else if (t == TypeManager.int32_type || t == TypeManager.uint32_type)
5431 ig.Emit (OpCodes.Stelem_I4);
5432 else if (t == TypeManager.int64_type || t == TypeManager.uint64_type)
5433 ig.Emit (OpCodes.Stelem_I8);
5434 else if (t == TypeManager.float_type)
5435 ig.Emit (OpCodes.Stelem_R4);
5436 else if (t == TypeManager.double_type)
5437 ig.Emit (OpCodes.Stelem_R8);
5438 else if (t == TypeManager.intptr_type)
5439 ig.Emit (OpCodes.Stelem_I);
5440 else if (t.IsValueType)
5441 ig.Emit (OpCodes.Stobj, t);
5443 ig.Emit (OpCodes.Stelem_Ref);
5446 MethodInfo FetchGetMethod ()
5448 ModuleBuilder mb = CodeGen.ModuleBuilder;
5449 int arg_count = ea.Arguments.Count;
5450 Type [] args = new Type [arg_count];
5453 for (int i = 0; i < arg_count; i++){
5454 //args [i++] = a.Type;
5455 args [i] = TypeManager.int32_type;
5458 get = mb.GetArrayMethod (
5459 ea.Expr.Type, "Get",
5460 CallingConventions.HasThis |
5461 CallingConventions.Standard,
5467 MethodInfo FetchAddressMethod ()
5469 ModuleBuilder mb = CodeGen.ModuleBuilder;
5470 int arg_count = ea.Arguments.Count;
5471 Type [] args = new Type [arg_count];
5473 string ptr_type_name;
5476 ptr_type_name = type.FullName + "&";
5477 ret_type = Type.GetType (ptr_type_name);
5480 // It is a type defined by the source code we are compiling
5482 if (ret_type == null){
5483 ret_type = mb.GetType (ptr_type_name);
5486 for (int i = 0; i < arg_count; i++){
5487 //args [i++] = a.Type;
5488 args [i] = TypeManager.int32_type;
5491 address = mb.GetArrayMethod (
5492 ea.Expr.Type, "Address",
5493 CallingConventions.HasThis |
5494 CallingConventions.Standard,
5500 public override void Emit (EmitContext ec)
5502 int rank = ea.Expr.Type.GetArrayRank ();
5503 ILGenerator ig = ec.ig;
5507 foreach (Argument a in ea.Arguments)
5511 EmitLoadOpcode (ig, type);
5515 method = FetchGetMethod ();
5516 ig.Emit (OpCodes.Call, method);
5520 public void EmitAssign (EmitContext ec, Expression source)
5522 int rank = ea.Expr.Type.GetArrayRank ();
5523 ILGenerator ig = ec.ig;
5527 foreach (Argument a in ea.Arguments)
5530 Type t = source.Type;
5533 // The stobj opcode used by value types will need
5534 // an address on the stack, not really an array/array
5538 if (t.IsValueType && !TypeManager.IsBuiltinType (t))
5539 ig.Emit (OpCodes.Ldelema, t);
5545 EmitStoreOpcode (ig, t);
5547 ModuleBuilder mb = CodeGen.ModuleBuilder;
5548 int arg_count = ea.Arguments.Count;
5549 Type [] args = new Type [arg_count + 1];
5552 for (int i = 0; i < arg_count; i++){
5553 //args [i++] = a.Type;
5554 args [i] = TypeManager.int32_type;
5557 args [arg_count] = type;
5559 set = mb.GetArrayMethod (
5560 ea.Expr.Type, "Set",
5561 CallingConventions.HasThis |
5562 CallingConventions.Standard,
5563 TypeManager.void_type, args);
5565 ig.Emit (OpCodes.Call, set);
5569 public void AddressOf (EmitContext ec, AddressOp mode)
5571 int rank = ea.Expr.Type.GetArrayRank ();
5572 ILGenerator ig = ec.ig;
5576 foreach (Argument a in ea.Arguments)
5580 ig.Emit (OpCodes.Ldelema, type);
5582 MethodInfo address = FetchAddressMethod ();
5583 ig.Emit (OpCodes.Call, address);
5590 public ArrayList getters, setters;
5591 static Hashtable map;
5595 map = new Hashtable ();
5598 Indexers (MemberInfo [] mi)
5600 foreach (PropertyInfo property in mi){
5601 MethodInfo get, set;
5603 get = property.GetGetMethod (true);
5605 if (getters == null)
5606 getters = new ArrayList ();
5611 set = property.GetSetMethod (true);
5613 if (setters == null)
5614 setters = new ArrayList ();
5620 static public Indexers GetIndexersForType (Type t, Location loc)
5622 Indexers ix = (Indexers) map [t];
5623 string p_name = TypeManager.IndexerPropertyName (t);
5628 MemberInfo [] mi = TypeManager.FindMembers (
5629 t, MemberTypes.Property,
5630 BindingFlags.Public | BindingFlags.Instance,
5631 Type.FilterName, p_name);
5633 if (mi == null || mi.Length == 0){
5634 Report.Error (21, loc,
5635 "Type `" + TypeManager.CSharpName (t) + "' does not have " +
5636 "any indexers defined");
5640 ix = new Indexers (mi);
5648 /// Expressions that represent an indexer call.
5650 public class IndexerAccess : Expression, IAssignMethod {
5652 // Points to our "data" repository
5655 MethodInfo get, set;
5657 ArrayList set_arguments;
5659 public IndexerAccess (ElementAccess ea_data)
5662 eclass = ExprClass.Value;
5665 public override Expression DoResolve (EmitContext ec)
5667 Type indexer_type = ea.Expr.Type;
5670 // Step 1: Query for all `Item' *properties*. Notice
5671 // that the actual methods are pointed from here.
5673 // This is a group of properties, piles of them.
5676 ilist = Indexers.GetIndexersForType (
5677 indexer_type, ea.loc);
5681 // Step 2: find the proper match
5683 if (ilist != null && ilist.getters != null && ilist.getters.Count > 0){
5684 Location loc = ea.loc;
5686 get = (MethodInfo) Invocation.OverloadResolve (
5687 ec, new MethodGroupExpr (ilist.getters, loc), ea.Arguments, loc);
5691 Report.Error (154, ea.loc,
5692 "indexer can not be used in this context, because " +
5693 "it lacks a `get' accessor");
5697 type = get.ReturnType;
5698 if (type.IsPointer && !ec.InUnsafe){
5699 UnsafeError (ea.loc);
5703 eclass = ExprClass.IndexerAccess;
5707 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
5709 Type indexer_type = ea.Expr.Type;
5710 Type right_type = right_side.Type;
5713 ilist = Indexers.GetIndexersForType (
5714 indexer_type, ea.loc);
5716 if (ilist != null && ilist.setters != null && ilist.setters.Count > 0){
5717 Location loc = ea.loc;
5719 set_arguments = (ArrayList) ea.Arguments.Clone ();
5720 set_arguments.Add (new Argument (right_side, Argument.AType.Expression));
5722 set = (MethodInfo) Invocation.OverloadResolve (
5723 ec, new MethodGroupExpr (ilist.setters, loc), set_arguments, loc);
5727 Report.Error (200, ea.loc,
5728 "indexer X.this [" + TypeManager.CSharpName (right_type) +
5729 "] lacks a `set' accessor");
5733 type = TypeManager.void_type;
5734 eclass = ExprClass.IndexerAccess;
5738 public override void Emit (EmitContext ec)
5740 Invocation.EmitCall (ec, false, false, ea.Expr, get, ea.Arguments);
5744 // source is ignored, because we already have a copy of it from the
5745 // LValue resolution and we have already constructed a pre-cached
5746 // version of the arguments (ea.set_arguments);
5748 public void EmitAssign (EmitContext ec, Expression source)
5750 Invocation.EmitCall (ec, false, false, ea.Expr, set, set_arguments);
5755 /// The base operator for method names
5757 public class BaseAccess : Expression {
5761 public BaseAccess (string member, Location l)
5763 this.member = member;
5767 public override Expression DoResolve (EmitContext ec)
5769 Expression member_lookup;
5770 Type current_type = ec.ContainerType;
5771 Type base_type = current_type.BaseType;
5775 Report.Error (1511, loc,
5776 "Keyword base is not allowed in static method");
5780 member_lookup = MemberLookup (ec, base_type, member, loc);
5781 if (member_lookup == null)
5787 left = new TypeExpr (base_type);
5791 e = MemberAccess.ResolveMemberAccess (ec, member_lookup, left, loc, null);
5792 if (e is PropertyExpr){
5793 PropertyExpr pe = (PropertyExpr) e;
5801 public override void Emit (EmitContext ec)
5803 throw new Exception ("Should never be called");
5808 /// The base indexer operator
5810 public class BaseIndexerAccess : Expression {
5811 ArrayList Arguments;
5814 public BaseIndexerAccess (ArrayList args, Location l)
5820 public override Expression DoResolve (EmitContext ec)
5822 Type current_type = ec.ContainerType;
5823 Type base_type = current_type.BaseType;
5824 Expression member_lookup;
5827 Report.Error (1511, loc,
5828 "Keyword base is not allowed in static method");
5832 member_lookup = MemberLookup (ec, base_type, "get_Item", MemberTypes.Method, AllBindingFlags, loc);
5833 if (member_lookup == null)
5836 return MemberAccess.ResolveMemberAccess (ec, member_lookup, ec.This, loc, null);
5839 public override void Emit (EmitContext ec)
5841 throw new Exception ("Should never be called");
5846 /// This class exists solely to pass the Type around and to be a dummy
5847 /// that can be passed to the conversion functions (this is used by
5848 /// foreach implementation to typecast the object return value from
5849 /// get_Current into the proper type. All code has been generated and
5850 /// we only care about the side effect conversions to be performed
5852 /// This is also now used as a placeholder where a no-action expression
5853 /// is needed (the `New' class).
5855 public class EmptyExpression : Expression {
5856 public EmptyExpression ()
5858 type = TypeManager.object_type;
5859 eclass = ExprClass.Value;
5862 public EmptyExpression (Type t)
5865 eclass = ExprClass.Value;
5868 public override Expression DoResolve (EmitContext ec)
5873 public override void Emit (EmitContext ec)
5875 // nothing, as we only exist to not do anything.
5879 // This is just because we might want to reuse this bad boy
5880 // instead of creating gazillions of EmptyExpressions.
5881 // (CanConvertImplicit uses it)
5883 public void SetType (Type t)
5889 public class UserCast : Expression {
5893 public UserCast (MethodInfo method, Expression source)
5895 this.method = method;
5896 this.source = source;
5897 type = method.ReturnType;
5898 eclass = ExprClass.Value;
5901 public override Expression DoResolve (EmitContext ec)
5904 // We are born fully resolved
5909 public override void Emit (EmitContext ec)
5911 ILGenerator ig = ec.ig;
5915 if (method is MethodInfo)
5916 ig.Emit (OpCodes.Call, (MethodInfo) method);
5918 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
5924 // This class is used to "construct" the type during a typecast
5925 // operation. Since the Type.GetType class in .NET can parse
5926 // the type specification, we just use this to construct the type
5927 // one bit at a time.
5929 public class ComposedCast : Expression {
5934 public ComposedCast (Expression left, string dim, Location l)
5941 public override Expression DoResolve (EmitContext ec)
5943 left = left.Resolve (ec);
5947 if (left.eclass != ExprClass.Type){
5948 report118 (loc, left, "type");
5952 type = RootContext.LookupType (
5953 ec.DeclSpace, left.Type.FullName + dim, false, loc);
5957 if (!ec.InUnsafe && type.IsPointer){
5962 eclass = ExprClass.Type;
5966 public override void Emit (EmitContext ec)
5968 throw new Exception ("This should never be called");
5973 // This class is used to represent the address of an array, used
5974 // only by the Fixed statement, this is like the C "&a [0]" construct.
5976 public class ArrayPtr : Expression {
5979 public ArrayPtr (Expression array)
5981 Type array_type = array.Type.GetElementType ();
5985 string array_ptr_type_name = array_type.FullName + "*";
5987 type = Type.GetType (array_ptr_type_name);
5989 ModuleBuilder mb = CodeGen.ModuleBuilder;
5991 type = mb.GetType (array_ptr_type_name);
5994 eclass = ExprClass.Value;
5997 public override void Emit (EmitContext ec)
5999 ILGenerator ig = ec.ig;
6002 IntLiteral.EmitInt (ig, 0);
6003 ig.Emit (OpCodes.Ldelema, array.Type.GetElementType ());
6006 public override Expression DoResolve (EmitContext ec)
6009 // We are born fully resolved
6016 // Used by the fixed statement
6018 public class StringPtr : Expression {
6021 public StringPtr (LocalBuilder b)
6024 eclass = ExprClass.Value;
6025 type = TypeManager.char_ptr_type;
6028 public override Expression DoResolve (EmitContext ec)
6030 // This should never be invoked, we are born in fully
6031 // initialized state.
6036 public override void Emit (EmitContext ec)
6038 ILGenerator ig = ec.ig;
6040 ig.Emit (OpCodes.Ldloc, b);
6041 ig.Emit (OpCodes.Conv_I);
6042 ig.Emit (OpCodes.Call, TypeManager.int_get_offset_to_string_data);
6043 ig.Emit (OpCodes.Add);
6048 // Implements the `stackalloc' keyword
6050 public class StackAlloc : Expression {
6056 public StackAlloc (string type, Expression count, Location l)
6063 public override Expression DoResolve (EmitContext ec)
6065 count = count.Resolve (ec);
6069 if (count.Type != TypeManager.int32_type){
6070 count = ConvertImplicitRequired (ec, count, TypeManager.int32_type, loc);
6075 if (ec.InCatch || ec.InFinally){
6076 Report.Error (255, loc,
6077 "stackalloc can not be used in a catch or finally block");
6081 otype = RootContext.LookupType (ec.DeclSpace, t, false, loc);
6086 if (!TypeManager.VerifyUnManaged (otype, loc))
6089 string ptr_name = otype.FullName + "*";
6090 type = Type.GetType (ptr_name);
6092 ModuleBuilder mb = CodeGen.ModuleBuilder;
6094 type = mb.GetType (ptr_name);
6096 eclass = ExprClass.Value;
6101 public override void Emit (EmitContext ec)
6103 int size = GetTypeSize (otype);
6104 ILGenerator ig = ec.ig;
6107 ig.Emit (OpCodes.Sizeof, otype);
6109 IntConstant.EmitInt (ig, size);
6111 ig.Emit (OpCodes.Mul);
6112 ig.Emit (OpCodes.Localloc);