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 TypeManager.LookupType (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) {
3286 // Note that the ParameterType () does not return the appropriate
3287 // modifier in the case of ref/out parameters so we take care
3290 Type pt = TypeManager.LookupType (pd.ParameterType (i).ToString () + "&");
3300 Type element_type = pd.ParameterType (pd_count - 1).GetElementType ();
3302 for (int i = pd_count - 1; i < arg_count; i++) {
3303 Argument a = (Argument) arguments [i];
3305 if (!StandardConversionExists (a.Expr, element_type))
3313 /// Determines if the candidate method is applicable (section 14.4.2.1)
3314 /// to the given set of arguments
3316 static bool IsApplicable (ArrayList arguments, MethodBase candidate)
3320 if (arguments == null)
3323 arg_count = arguments.Count;
3325 ParameterData pd = GetParameterData (candidate);
3327 int pd_count = pd.Count;
3329 if (arg_count != pd.Count)
3332 for (int i = arg_count; i > 0; ) {
3335 Argument a = (Argument) arguments [i];
3337 Parameter.Modifier a_mod = a.GetParameterModifier ();
3338 Parameter.Modifier p_mod = pd.ParameterModifier (i);
3340 if (a_mod == p_mod) {
3341 if (a_mod == Parameter.Modifier.NONE)
3342 if (!StandardConversionExists (a.Expr, pd.ParameterType (i)))
3345 if (a_mod == Parameter.Modifier.REF ||
3346 a_mod == Parameter.Modifier.OUT) {
3348 // Note that the ParameterType () does not return the appropriate
3349 // modifier in the case of ref/out parameters so we take care
3352 Type pt = TypeManager.LookupType (pd.ParameterType (i).ToString () + "&");
3367 /// Find the Applicable Function Members (7.4.2.1)
3369 /// me: Method Group expression with the members to select.
3370 /// it might contain constructors or methods (or anything
3371 /// that maps to a method).
3373 /// Arguments: ArrayList containing resolved Argument objects.
3375 /// loc: The location if we want an error to be reported, or a Null
3376 /// location for "probing" purposes.
3378 /// Returns: The MethodBase (either a ConstructorInfo or a MethodInfo)
3379 /// that is the best match of me on Arguments.
3382 public static MethodBase OverloadResolve (EmitContext ec, MethodGroupExpr me,
3383 ArrayList Arguments, Location loc)
3385 ArrayList afm = new ArrayList ();
3386 int best_match_idx = -1;
3387 MethodBase method = null;
3389 ArrayList candidates = new ArrayList ();
3391 for (int i = me.Methods.Length; i > 0; ){
3393 MethodBase candidate = me.Methods [i];
3396 // Check if candidate is applicable (section 14.4.2.1)
3397 if (!IsApplicable (Arguments, candidate))
3400 candidates.Add (candidate);
3401 x = BetterFunction (ec, Arguments, candidate, method, false, loc);
3407 method = me.Methods [best_match_idx];
3411 if (Arguments == null)
3414 argument_count = Arguments.Count;
3417 // Now we see if we can find params functions, applicable in their expanded form
3418 // since if they were applicable in their normal form, they would have been selected
3421 bool chose_params_expanded = false;
3423 if (best_match_idx == -1) {
3425 candidates = new ArrayList ();
3426 for (int i = me.Methods.Length; i > 0; ) {
3428 MethodBase candidate = me.Methods [i];
3430 if (!IsParamsMethodApplicable (Arguments, candidate))
3433 candidates.Add (candidate);
3435 int x = BetterFunction (ec, Arguments, candidate, method, true, loc);
3441 method = me.Methods [best_match_idx];
3442 chose_params_expanded = true;
3448 // Now we see if we can at least find a method with the same number of arguments
3452 if (best_match_idx == -1) {
3454 for (int i = me.Methods.Length; i > 0;) {
3456 MethodBase mb = me.Methods [i];
3457 pd = GetParameterData (mb);
3459 if (pd.Count == argument_count) {
3461 method = me.Methods [best_match_idx];
3471 // Now check that there are no ambiguities i.e the selected method
3472 // should be better than all the others
3475 for (int i = 0; i < candidates.Count; ++i) {
3476 MethodBase candidate = (MethodBase) candidates [i];
3478 if (candidate == method)
3482 // If a normal method is applicable in the sense that it has the same
3483 // number of arguments, then the expanded params method is never applicable
3484 // so we debar the params method.
3486 if (IsParamsMethodApplicable (Arguments, candidate) &&
3487 IsApplicable (Arguments, method))
3490 int x = BetterFunction (ec, Arguments, method, candidate,
3491 chose_params_expanded, loc);
3496 "Ambiguous call when selecting function due to implicit casts");
3502 // And now check if the arguments are all compatible, perform conversions
3503 // if necessary etc. and return if everything is all right
3506 if (VerifyArgumentsCompat (ec, Arguments, argument_count, method,
3507 chose_params_expanded, null, loc))
3513 public static bool VerifyArgumentsCompat (EmitContext ec, ArrayList Arguments,
3516 bool chose_params_expanded,
3520 ParameterData pd = GetParameterData (method);
3521 int pd_count = pd.Count;
3523 for (int j = 0; j < argument_count; j++) {
3524 Argument a = (Argument) Arguments [j];
3525 Expression a_expr = a.Expr;
3526 Type parameter_type = pd.ParameterType (j);
3528 if (pd.ParameterModifier (j) == Parameter.Modifier.PARAMS && chose_params_expanded)
3529 parameter_type = parameter_type.GetElementType ();
3531 if (a.Type != parameter_type){
3534 conv = ConvertImplicitStandard (ec, a_expr, parameter_type, loc);
3537 if (!Location.IsNull (loc)) {
3538 if (delegate_type == null)
3540 "The best overloaded match for method '" +
3541 FullMethodDesc (method) +
3542 "' has some invalid arguments");
3544 Report.Error (1594, loc,
3545 "Delegate '" + delegate_type.ToString () +
3546 "' has some invalid arguments.");
3548 "Argument " + (j+1) +
3549 ": Cannot convert from '" + Argument.FullDesc (a)
3550 + "' to '" + pd.ParameterDesc (j) + "'");
3557 // Update the argument with the implicit conversion
3563 if (a.GetParameterModifier () != pd.ParameterModifier (j) &&
3564 pd.ParameterModifier (pd_count - 1) != Parameter.Modifier.PARAMS) {
3565 if (!Location.IsNull (loc)) {
3566 Console.WriteLine ("A:P: " + a.GetParameterModifier ());
3567 Console.WriteLine ("PP:: " + pd.ParameterModifier (j));
3568 Console.WriteLine ("PT: " + parameter_type.IsByRef);
3570 "The best overloaded match for method '" + FullMethodDesc (method)+
3571 "' has some invalid arguments");
3573 "Argument " + (j+1) +
3574 ": Cannot convert from '" + Argument.FullDesc (a)
3575 + "' to '" + pd.ParameterDesc (j) + "'");
3585 public override Expression DoResolve (EmitContext ec)
3588 // First, resolve the expression that is used to
3589 // trigger the invocation
3591 if (expr is BaseAccess)
3594 expr = expr.Resolve (ec);
3598 if (!(expr is MethodGroupExpr)) {
3599 Type expr_type = expr.Type;
3601 if (expr_type != null){
3602 bool IsDelegate = TypeManager.IsDelegateType (expr_type);
3604 return (new DelegateInvocation (
3605 this.expr, Arguments, loc)).Resolve (ec);
3609 if (!(expr is MethodGroupExpr)){
3610 report118 (loc, this.expr, "method group");
3615 // Next, evaluate all the expressions in the argument list
3617 if (Arguments != null){
3618 for (int i = Arguments.Count; i > 0;){
3620 Argument a = (Argument) Arguments [i];
3622 if (!a.Resolve (ec, loc))
3627 method = OverloadResolve (ec, (MethodGroupExpr) this.expr, Arguments, loc);
3629 if (method == null){
3631 "Could not find any applicable function for this argument list");
3635 if (method is MethodInfo)
3636 type = ((MethodInfo)method).ReturnType;
3638 if (type.IsPointer){
3645 eclass = ExprClass.Value;
3650 // Emits the list of arguments as an array
3652 static void EmitParams (EmitContext ec, int idx, ArrayList arguments)
3654 ILGenerator ig = ec.ig;
3655 int count = arguments.Count - idx;
3656 Argument a = (Argument) arguments [idx];
3657 Type t = a.expr.Type;
3658 string array_type = t.FullName + "[]";
3661 array = ig.DeclareLocal (Type.GetType (array_type));
3662 IntConstant.EmitInt (ig, count);
3663 ig.Emit (OpCodes.Newarr, t);
3664 ig.Emit (OpCodes.Stloc, array);
3666 int top = arguments.Count;
3667 for (int j = idx; j < top; j++){
3668 a = (Argument) arguments [j];
3670 ig.Emit (OpCodes.Ldloc, array);
3671 IntConstant.EmitInt (ig, j - idx);
3674 ArrayAccess.EmitStoreOpcode (ig, t);
3676 ig.Emit (OpCodes.Ldloc, array);
3680 /// Emits a list of resolved Arguments that are in the arguments
3683 /// The MethodBase argument might be null if the
3684 /// emission of the arguments is known not to contain
3685 /// a `params' field (for example in constructors or other routines
3686 /// that keep their arguments in this structure
3688 public static void EmitArguments (EmitContext ec, MethodBase mb, ArrayList arguments)
3692 pd = GetParameterData (mb);
3697 // If we are calling a params method with no arguments, special case it
3699 if (arguments == null){
3700 if (pd != null && pd.Count > 0 &&
3701 pd.ParameterModifier (0) == Parameter.Modifier.PARAMS){
3702 ILGenerator ig = ec.ig;
3704 IntConstant.EmitInt (ig, 0);
3705 ig.Emit (OpCodes.Newarr, pd.ParameterType (0).GetElementType ());
3711 int top = arguments.Count;
3713 for (int i = 0; i < top; i++){
3714 Argument a = (Argument) arguments [i];
3717 if (pd.ParameterModifier (i) == Parameter.Modifier.PARAMS){
3719 // Special case if we are passing the same data as the
3720 // params argument, do not put it in an array.
3722 if (pd.ParameterType (i) == a.Type)
3725 EmitParams (ec, i, arguments);
3735 /// is_base tells whether we want to force the use of the `call'
3736 /// opcode instead of using callvirt. Call is required to call
3737 /// a specific method, while callvirt will always use the most
3738 /// recent method in the vtable.
3740 /// is_static tells whether this is an invocation on a static method
3742 /// instance_expr is an expression that represents the instance
3743 /// it must be non-null if is_static is false.
3745 /// method is the method to invoke.
3747 /// Arguments is the list of arguments to pass to the method or constructor.
3749 public static void EmitCall (EmitContext ec, bool is_base,
3750 bool is_static, Expression instance_expr,
3751 MethodBase method, ArrayList Arguments)
3753 ILGenerator ig = ec.ig;
3754 bool struct_call = false;
3758 if (method.DeclaringType.IsValueType)
3761 // If this is ourselves, push "this"
3763 if (instance_expr == null){
3764 ig.Emit (OpCodes.Ldarg_0);
3767 // Push the instance expression
3769 if (instance_expr.Type.IsSubclassOf (TypeManager.value_type)){
3771 // Special case: calls to a function declared in a
3772 // reference-type with a value-type argument need
3773 // to have their value boxed.
3776 if (method.DeclaringType.IsValueType){
3778 // If the expression implements IMemoryLocation, then
3779 // we can optimize and use AddressOf on the
3782 // If not we have to use some temporary storage for
3784 if (instance_expr is IMemoryLocation){
3785 ((IMemoryLocation)instance_expr).
3786 AddressOf (ec, AddressOp.LoadStore);
3789 Type t = instance_expr.Type;
3791 instance_expr.Emit (ec);
3792 LocalBuilder temp = ig.DeclareLocal (t);
3793 ig.Emit (OpCodes.Stloc, temp);
3794 ig.Emit (OpCodes.Ldloca, temp);
3797 instance_expr.Emit (ec);
3798 ig.Emit (OpCodes.Box, instance_expr.Type);
3801 instance_expr.Emit (ec);
3805 EmitArguments (ec, method, Arguments);
3807 if (is_static || struct_call || is_base){
3808 if (method is MethodInfo)
3809 ig.Emit (OpCodes.Call, (MethodInfo) method);
3811 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
3813 if (method is MethodInfo)
3814 ig.Emit (OpCodes.Callvirt, (MethodInfo) method);
3816 ig.Emit (OpCodes.Callvirt, (ConstructorInfo) method);
3820 public override void Emit (EmitContext ec)
3822 MethodGroupExpr mg = (MethodGroupExpr) this.expr;
3824 EmitCall (ec, is_base, method.IsStatic, mg.InstanceExpression, method, Arguments);
3827 public override void EmitStatement (EmitContext ec)
3832 // Pop the return value if there is one
3834 if (method is MethodInfo){
3835 if (((MethodInfo)method).ReturnType != TypeManager.void_type)
3836 ec.ig.Emit (OpCodes.Pop);
3842 // This class is used to "disable" the code generation for the
3843 // temporary variable when initializing value types.
3845 class EmptyAddressOf : EmptyExpression, IMemoryLocation {
3846 public void AddressOf (EmitContext ec, AddressOp Mode)
3853 /// Implements the new expression
3855 public class New : ExpressionStatement {
3856 public readonly ArrayList Arguments;
3857 public readonly string RequestedType;
3860 MethodBase method = null;
3863 // If set, the new expression is for a value_target, and
3864 // we will not leave anything on the stack.
3866 Expression value_target;
3868 public New (string requested_type, ArrayList arguments, Location l)
3870 RequestedType = requested_type;
3871 Arguments = arguments;
3875 public Expression ValueTypeVariable {
3877 return value_target;
3881 value_target = value;
3886 // This function is used to disable the following code sequence for
3887 // value type initialization:
3889 // AddressOf (temporary)
3893 // Instead the provide will have provided us with the address on the
3894 // stack to store the results.
3896 static Expression MyEmptyExpression;
3898 public void DisableTemporaryValueType ()
3900 if (MyEmptyExpression == null)
3901 MyEmptyExpression = new EmptyAddressOf ();
3904 // To enable this, look into:
3905 // test-34 and test-89 and self bootstrapping.
3907 // For instance, we can avoid a copy by using `newobj'
3908 // instead of Call + Push-temp on value types.
3909 // value_target = MyEmptyExpression;
3912 public override Expression DoResolve (EmitContext ec)
3914 type = RootContext.LookupType (ec.DeclSpace, RequestedType, false, loc);
3919 bool IsDelegate = TypeManager.IsDelegateType (type);
3922 return (new NewDelegate (type, Arguments, loc)).Resolve (ec);
3924 bool is_struct = false;
3925 is_struct = type.IsSubclassOf (TypeManager.value_type);
3926 eclass = ExprClass.Value;
3929 // SRE returns a match for .ctor () on structs (the object constructor),
3930 // so we have to manually ignore it.
3932 if (is_struct && Arguments == null)
3936 ml = MemberLookup (ec, type, ".ctor",
3937 MemberTypes.Constructor,
3938 AllBindingFlags | BindingFlags.DeclaredOnly, loc);
3940 if (! (ml is MethodGroupExpr)){
3942 report118 (loc, ml, "method group");
3948 if (Arguments != null){
3949 for (int i = Arguments.Count; i > 0;){
3951 Argument a = (Argument) Arguments [i];
3953 if (!a.Resolve (ec, loc))
3958 method = Invocation.OverloadResolve (ec, (MethodGroupExpr) ml,
3963 if (method == null && !is_struct) {
3965 "New invocation: Can not find a constructor for " +
3966 "this argument list");
3973 // This DoEmit can be invoked in two contexts:
3974 // * As a mechanism that will leave a value on the stack (new object)
3975 // * As one that wont (init struct)
3977 // You can control whether a value is required on the stack by passing
3978 // need_value_on_stack. The code *might* leave a value on the stack
3979 // so it must be popped manually
3981 // If we are dealing with a ValueType, we have a few
3982 // situations to deal with:
3984 // * The target is a ValueType, and we have been provided
3985 // the instance (this is easy, we are being assigned).
3987 // * The target of New is being passed as an argument,
3988 // to a boxing operation or a function that takes a
3991 // In this case, we need to create a temporary variable
3992 // that is the argument of New.
3994 // Returns whether a value is left on the stack
3996 bool DoEmit (EmitContext ec, bool need_value_on_stack)
3998 bool is_value_type = type.IsSubclassOf (TypeManager.value_type);
3999 ILGenerator ig = ec.ig;
4004 if (value_target == null)
4005 value_target = new LocalTemporary (ec, type);
4007 ml = (IMemoryLocation) value_target;
4008 ml.AddressOf (ec, AddressOp.Store);
4012 Invocation.EmitArguments (ec, method, Arguments);
4016 ig.Emit (OpCodes.Initobj, type);
4018 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
4019 if (need_value_on_stack){
4020 value_target.Emit (ec);
4025 ig.Emit (OpCodes.Newobj, (ConstructorInfo) method);
4030 public override void Emit (EmitContext ec)
4035 public override void EmitStatement (EmitContext ec)
4037 if (DoEmit (ec, false))
4038 ec.ig.Emit (OpCodes.Pop);
4043 /// Represents an array creation expression.
4047 /// There are two possible scenarios here: one is an array creation
4048 /// expression that specifies the dimensions and optionally the
4049 /// initialization data and the other which does not need dimensions
4050 /// specified but where initialization data is mandatory.
4052 public class ArrayCreation : ExpressionStatement {
4053 string RequestedType;
4055 ArrayList Initializers;
4059 // The list of Argument types.
4060 // This is used to constrcut the `newarray' or constructor signature
4062 ArrayList Arguments;
4064 MethodBase method = null;
4065 Type array_element_type;
4066 bool IsOneDimensional = false;
4067 bool IsBuiltinType = false;
4068 bool ExpectInitializers = false;
4071 Type underlying_type;
4073 ArrayList ArrayData;
4078 // The number of array initializers that we can handle
4079 // via the InitializeArray method - through EmitStaticInitializers
4081 int num_automatic_initializers;
4083 public ArrayCreation (string requested_type, ArrayList exprs,
4084 string rank, ArrayList initializers, Location l)
4086 RequestedType = requested_type;
4088 Initializers = initializers;
4091 Arguments = new ArrayList ();
4093 foreach (Expression e in exprs)
4094 Arguments.Add (new Argument (e, Argument.AType.Expression));
4097 public ArrayCreation (string requested_type, string rank, ArrayList initializers, Location l)
4099 RequestedType = requested_type;
4100 Initializers = initializers;
4103 Rank = rank.Substring (0, rank.LastIndexOf ("["));
4105 string tmp = rank.Substring (rank.LastIndexOf ("["));
4107 dimensions = tmp.Length - 1;
4108 ExpectInitializers = true;
4111 public static string FormArrayType (string base_type, int idx_count, string rank)
4113 StringBuilder sb = new StringBuilder (base_type);
4118 for (int i = 1; i < idx_count; i++)
4123 return sb.ToString ();
4126 public static string FormElementType (string base_type, int idx_count, string rank)
4128 StringBuilder sb = new StringBuilder (base_type);
4131 for (int i = 1; i < idx_count; i++)
4138 string val = sb.ToString ();
4140 return val.Substring (0, val.LastIndexOf ("["));
4145 Report.Error (178, loc, "Incorrectly structured array initializer");
4148 public bool CheckIndices (EmitContext ec, ArrayList probe, int idx, bool specified_dims)
4150 if (specified_dims) {
4151 Argument a = (Argument) Arguments [idx];
4153 if (!a.Resolve (ec, loc))
4156 if (!(a.Expr is Constant)) {
4157 Report.Error (150, loc, "A constant value is expected");
4161 int value = (int) ((Constant) a.Expr).GetValue ();
4163 if (value != probe.Count) {
4168 Bounds [idx] = value;
4171 foreach (object o in probe) {
4172 if (o is ArrayList) {
4173 bool ret = CheckIndices (ec, (ArrayList) o, idx + 1, specified_dims);
4177 Expression tmp = (Expression) o;
4178 tmp = tmp.Resolve (ec);
4182 // Handle initialization from vars, fields etc.
4184 Expression conv = ConvertImplicitRequired (
4185 ec, tmp, underlying_type, loc);
4190 if (conv is StringConstant)
4191 ArrayData.Add (conv);
4192 else if (conv is Constant) {
4193 ArrayData.Add (conv);
4194 num_automatic_initializers++;
4196 ArrayData.Add (conv);
4203 public void UpdateIndices (EmitContext ec)
4206 for (ArrayList probe = Initializers; probe != null;) {
4207 if (probe.Count > 0 && probe [0] is ArrayList) {
4208 Expression e = new IntConstant (probe.Count);
4209 Arguments.Add (new Argument (e, Argument.AType.Expression));
4211 Bounds [i++] = probe.Count;
4213 probe = (ArrayList) probe [0];
4216 Expression e = new IntConstant (probe.Count);
4217 Arguments.Add (new Argument (e, Argument.AType.Expression));
4219 Bounds [i++] = probe.Count;
4226 public bool ValidateInitializers (EmitContext ec)
4228 if (Initializers == null) {
4229 if (ExpectInitializers)
4235 underlying_type = RootContext.LookupType (
4236 ec.DeclSpace, RequestedType, false, loc);
4239 // We use this to store all the date values in the order in which we
4240 // will need to store them in the byte blob later
4242 ArrayData = new ArrayList ();
4243 Bounds = new Hashtable ();
4247 if (Arguments != null) {
4248 ret = CheckIndices (ec, Initializers, 0, true);
4252 Arguments = new ArrayList ();
4254 ret = CheckIndices (ec, Initializers, 0, false);
4261 if (Arguments.Count != dimensions) {
4270 public override Expression DoResolve (EmitContext ec)
4275 // First step is to validate the initializers and fill
4276 // in any missing bits
4278 if (!ValidateInitializers (ec))
4281 if (Arguments == null)
4284 arg_count = Arguments.Count;
4285 for (int i = 0; i < arg_count; i++){
4286 Argument a = (Argument) Arguments [i];
4288 if (!a.Resolve (ec, loc))
4292 // Now, convert that to an integer
4294 Expression real_arg;
4295 bool old_checked = ec.CheckState;
4296 ec.CheckState = true;
4298 real_arg = ConvertExplicit (
4299 ec, a.expr, TypeManager.uint32_type, loc);
4300 ec.CheckState = old_checked;
4301 if (real_arg == null)
4308 string array_type = FormArrayType (RequestedType, arg_count, Rank);
4309 string element_type = FormElementType (RequestedType, arg_count, Rank);
4311 type = RootContext.LookupType (ec.DeclSpace, array_type, false, loc);
4313 array_element_type = RootContext.LookupType (
4314 ec.DeclSpace, element_type, false, loc);
4319 if (arg_count == 1) {
4320 IsOneDimensional = true;
4321 eclass = ExprClass.Value;
4325 IsBuiltinType = TypeManager.IsBuiltinType (type);
4327 if (IsBuiltinType) {
4331 ml = MemberLookup (ec, type, ".ctor", MemberTypes.Constructor,
4332 AllBindingFlags, loc);
4334 if (!(ml is MethodGroupExpr)){
4335 report118 (loc, ml, "method group");
4340 Report.Error (-6, loc, "New invocation: Can not find a constructor for " +
4341 "this argument list");
4345 method = Invocation.OverloadResolve (ec, (MethodGroupExpr) ml, Arguments, loc);
4347 if (method == null) {
4348 Report.Error (-6, loc, "New invocation: Can not find a constructor for " +
4349 "this argument list");
4353 eclass = ExprClass.Value;
4358 ModuleBuilder mb = CodeGen.ModuleBuilder;
4360 ArrayList args = new ArrayList ();
4361 if (Arguments != null){
4362 for (int i = arg_count; i > 0;){
4364 Argument a = (Argument) Arguments [i];
4366 args.Add (TypeManager.int32_type);
4370 Type [] arg_types = null;
4373 arg_types = new Type [args.Count];
4375 args.CopyTo (arg_types, 0);
4377 method = mb.GetArrayMethod (type, ".ctor", CallingConventions.HasThis, null,
4380 if (method == null) {
4381 Report.Error (-6, loc, "New invocation: Can not find a constructor for " +
4382 "this argument list");
4386 eclass = ExprClass.Value;
4392 public static byte [] MakeByteBlob (ArrayList ArrayData, Type underlying_type, Location loc)
4397 int count = ArrayData.Count;
4399 factor = GetTypeSize (underlying_type);
4403 data = new byte [(count * factor + 4) & ~3];
4406 for (int i = 0; i < count; ++i) {
4407 object v = ArrayData [i];
4409 if (v is EnumConstant)
4410 v = ((EnumConstant) v).Child;
4412 if (v is Constant && !(v is StringConstant))
4413 v = ((Constant) v).GetValue ();
4419 if (underlying_type == TypeManager.int64_type){
4420 if (!(v is Expression)){
4421 long val = (long) v;
4423 for (int j = 0; j < factor; ++j) {
4424 data [idx + j] = (byte) (val & 0xFF);
4428 } else if (underlying_type == TypeManager.uint64_type){
4429 if (!(v is Expression)){
4430 ulong val = (ulong) v;
4432 for (int j = 0; j < factor; ++j) {
4433 data [idx + j] = (byte) (val & 0xFF);
4437 } else if (underlying_type == TypeManager.float_type) {
4438 if (!(v is Expression)){
4439 element = BitConverter.GetBytes ((float) v);
4441 for (int j = 0; j < factor; ++j)
4442 data [idx + j] = element [j];
4444 } else if (underlying_type == TypeManager.double_type) {
4445 if (!(v is Expression)){
4446 element = BitConverter.GetBytes ((double) v);
4448 for (int j = 0; j < factor; ++j)
4449 data [idx + j] = element [j];
4451 } else if (underlying_type == TypeManager.char_type){
4452 if (!(v is Expression)){
4453 int val = (int) ((char) v);
4455 data [idx] = (byte) (val & 0xff);
4456 data [idx+1] = (byte) (val >> 8);
4458 } else if (underlying_type == TypeManager.short_type){
4459 if (!(v is Expression)){
4460 int val = (int) ((short) v);
4462 data [idx] = (byte) (val & 0xff);
4463 data [idx+1] = (byte) (val >> 8);
4465 } else if (underlying_type == TypeManager.ushort_type){
4466 if (!(v is Expression)){
4467 int val = (int) ((ushort) v);
4469 data [idx] = (byte) (val & 0xff);
4470 data [idx+1] = (byte) (val >> 8);
4472 } else if (underlying_type == TypeManager.int32_type) {
4473 if (!(v is Expression)){
4476 data [idx] = (byte) (val & 0xff);
4477 data [idx+1] = (byte) ((val >> 8) & 0xff);
4478 data [idx+2] = (byte) ((val >> 16) & 0xff);
4479 data [idx+3] = (byte) (val >> 24);
4481 } else if (underlying_type == TypeManager.uint32_type) {
4482 if (!(v is Expression)){
4483 uint val = (uint) v;
4485 data [idx] = (byte) (val & 0xff);
4486 data [idx+1] = (byte) ((val >> 8) & 0xff);
4487 data [idx+2] = (byte) ((val >> 16) & 0xff);
4488 data [idx+3] = (byte) (val >> 24);
4490 } else if (underlying_type == TypeManager.sbyte_type) {
4491 if (!(v is Expression)){
4492 sbyte val = (sbyte) v;
4493 data [idx] = (byte) val;
4495 } else if (underlying_type == TypeManager.byte_type) {
4496 if (!(v is Expression)){
4497 byte val = (byte) v;
4498 data [idx] = (byte) val;
4500 } else if (underlying_type == TypeManager.bool_type) {
4501 if (!(v is Expression)){
4502 bool val = (bool) v;
4503 data [idx] = (byte) (val ? 1 : 0);
4506 throw new Exception ("Unrecognized type in MakeByteBlob");
4515 // Emits the initializers for the array
4517 void EmitStaticInitializers (EmitContext ec, bool is_expression)
4520 // First, the static data
4523 ILGenerator ig = ec.ig;
4525 byte [] data = MakeByteBlob (ArrayData, underlying_type, loc);
4528 fb = RootContext.MakeStaticData (data);
4531 ig.Emit (OpCodes.Dup);
4532 ig.Emit (OpCodes.Ldtoken, fb);
4533 ig.Emit (OpCodes.Call,
4534 TypeManager.void_initializearray_array_fieldhandle);
4539 // Emits pieces of the array that can not be computed at compile
4540 // time (variables and string locations).
4542 // This always expect the top value on the stack to be the array
4544 void EmitDynamicInitializers (EmitContext ec, bool is_expression)
4546 ILGenerator ig = ec.ig;
4547 int dims = Bounds.Count;
4548 int [] current_pos = new int [dims];
4549 int top = ArrayData.Count;
4550 LocalBuilder temp = ig.DeclareLocal (type);
4552 ig.Emit (OpCodes.Stloc, temp);
4554 MethodInfo set = null;
4558 ModuleBuilder mb = null;
4559 mb = CodeGen.ModuleBuilder;
4560 args = new Type [dims + 1];
4563 for (j = 0; j < dims; j++)
4564 args [j] = TypeManager.int32_type;
4566 args [j] = array_element_type;
4568 set = mb.GetArrayMethod (
4570 CallingConventions.HasThis | CallingConventions.Standard,
4571 TypeManager.void_type, args);
4574 for (int i = 0; i < top; i++){
4576 Expression e = null;
4578 if (ArrayData [i] is Expression)
4579 e = (Expression) ArrayData [i];
4583 // Basically we do this for string literals and
4584 // other non-literal expressions
4586 if (e is StringConstant || !(e is Constant) ||
4587 num_automatic_initializers <= 2) {
4588 Type etype = e.Type;
4590 ig.Emit (OpCodes.Ldloc, temp);
4592 for (int idx = dims; idx > 0; ) {
4594 IntConstant.EmitInt (ig, current_pos [idx]);
4598 // If we are dealing with a struct, get the
4599 // address of it, so we can store it.
4601 if (etype.IsSubclassOf (TypeManager.value_type) &&
4602 !TypeManager.IsBuiltinType (etype)){
4607 // Let new know that we are providing
4608 // the address where to store the results
4610 n.DisableTemporaryValueType ();
4613 ig.Emit (OpCodes.Ldelema, etype);
4619 ArrayAccess.EmitStoreOpcode (ig, array_element_type);
4621 ig.Emit (OpCodes.Call, set);
4628 for (int j = 0; j < dims; j++){
4630 if (current_pos [j] < (int) Bounds [j])
4632 current_pos [j] = 0;
4637 ig.Emit (OpCodes.Ldloc, temp);
4640 void EmitArrayArguments (EmitContext ec)
4642 foreach (Argument a in Arguments)
4646 void DoEmit (EmitContext ec, bool is_statement)
4648 ILGenerator ig = ec.ig;
4650 EmitArrayArguments (ec);
4651 if (IsOneDimensional)
4652 ig.Emit (OpCodes.Newarr, array_element_type);
4655 ig.Emit (OpCodes.Newobj, (ConstructorInfo) method);
4657 ig.Emit (OpCodes.Newobj, (MethodInfo) method);
4660 if (Initializers != null){
4662 // FIXME: Set this variable correctly.
4664 bool dynamic_initializers = true;
4666 if (underlying_type != TypeManager.string_type &&
4667 underlying_type != TypeManager.object_type) {
4668 if (num_automatic_initializers > 2)
4669 EmitStaticInitializers (ec, dynamic_initializers || !is_statement);
4672 if (dynamic_initializers)
4673 EmitDynamicInitializers (ec, !is_statement);
4677 public override void Emit (EmitContext ec)
4682 public override void EmitStatement (EmitContext ec)
4690 /// Represents the `this' construct
4692 public class This : Expression, IAssignMethod, IMemoryLocation {
4695 public This (Location loc)
4700 public override Expression DoResolve (EmitContext ec)
4702 eclass = ExprClass.Variable;
4703 type = ec.ContainerType;
4706 Report.Error (26, loc,
4707 "Keyword this not valid in static code");
4714 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
4718 if (ec.TypeContainer is Class){
4719 Report.Error (1604, loc, "Cannot assign to `this'");
4726 public override void Emit (EmitContext ec)
4728 ec.ig.Emit (OpCodes.Ldarg_0);
4731 public void EmitAssign (EmitContext ec, Expression source)
4734 ec.ig.Emit (OpCodes.Starg, 0);
4737 public void AddressOf (EmitContext ec, AddressOp mode)
4739 ec.ig.Emit (OpCodes.Ldarg_0);
4742 // FIGURE OUT WHY LDARG_S does not work
4744 // consider: struct X { int val; int P { set { val = value; }}}
4746 // Yes, this looks very bad. Look at `NOTAS' for
4748 // ec.ig.Emit (OpCodes.Ldarga_S, (byte) 0);
4753 /// Implements the typeof operator
4755 public class TypeOf : Expression {
4756 public readonly string QueriedType;
4760 public TypeOf (string queried_type, Location l)
4762 QueriedType = queried_type;
4766 public override Expression DoResolve (EmitContext ec)
4768 typearg = RootContext.LookupType (
4769 ec.DeclSpace, QueriedType, false, loc);
4771 if (typearg == null)
4774 type = TypeManager.type_type;
4775 eclass = ExprClass.Type;
4779 public override void Emit (EmitContext ec)
4781 ec.ig.Emit (OpCodes.Ldtoken, typearg);
4782 ec.ig.Emit (OpCodes.Call, TypeManager.system_type_get_type_from_handle);
4785 public Type TypeArg {
4786 get { return typearg; }
4791 /// Implements the sizeof expression
4793 public class SizeOf : Expression {
4794 public readonly string QueriedType;
4798 public SizeOf (string queried_type, Location l)
4800 this.QueriedType = queried_type;
4804 public override Expression DoResolve (EmitContext ec)
4806 type_queried = RootContext.LookupType (
4807 ec.DeclSpace, QueriedType, false, loc);
4808 if (type_queried == null)
4811 type = TypeManager.int32_type;
4812 eclass = ExprClass.Value;
4816 public override void Emit (EmitContext ec)
4818 int size = GetTypeSize (type_queried);
4821 ec.ig.Emit (OpCodes.Sizeof, type_queried);
4823 IntConstant.EmitInt (ec.ig, size);
4828 /// Implements the member access expression
4830 public class MemberAccess : Expression {
4831 public readonly string Identifier;
4833 Expression member_lookup;
4836 public MemberAccess (Expression expr, string id, Location l)
4843 public Expression Expr {
4849 static void error176 (Location loc, string name)
4851 Report.Error (176, loc, "Static member `" +
4852 name + "' cannot be accessed " +
4853 "with an instance reference, qualify with a " +
4854 "type name instead");
4857 static bool IdenticalNameAndTypeName (EmitContext ec, Expression left_original, Location loc)
4859 if (left_original == null)
4862 if (!(left_original is SimpleName))
4865 SimpleName sn = (SimpleName) left_original;
4867 Type t = RootContext.LookupType (ec.DeclSpace, sn.Name, true, loc);
4874 public static Expression ResolveMemberAccess (EmitContext ec, Expression member_lookup,
4875 Expression left, Location loc,
4876 Expression left_original)
4881 if (member_lookup is MethodGroupExpr){
4882 MethodGroupExpr mg = (MethodGroupExpr) member_lookup;
4887 if (left is TypeExpr){
4888 if (!mg.RemoveInstanceMethods ()){
4889 SimpleName.Error120 (loc, mg.Methods [0].Name);
4893 return member_lookup;
4897 // Instance.MethodGroup
4899 if (IdenticalNameAndTypeName (ec, left_original, loc)){
4900 if (mg.RemoveInstanceMethods ())
4901 return member_lookup;
4904 if (!mg.RemoveStaticMethods ()){
4905 error176 (loc, mg.Methods [0].Name);
4909 mg.InstanceExpression = left;
4910 return member_lookup;
4912 if (!mg.RemoveStaticMethods ()){
4913 if (IdenticalNameAndTypeName (ec, left_original, loc)){
4914 if (!mg.RemoveInstanceMethods ()){
4915 SimpleName.Error120 (loc, mg.Methods [0].Name);
4918 return member_lookup;
4921 error176 (loc, mg.Methods [0].Name);
4925 mg.InstanceExpression = left;
4927 return member_lookup;
4931 if (member_lookup is FieldExpr){
4932 FieldExpr fe = (FieldExpr) member_lookup;
4933 FieldInfo fi = fe.FieldInfo;
4934 Type decl_type = fi.DeclaringType;
4936 if (fi is FieldBuilder) {
4937 Const c = TypeManager.LookupConstant ((FieldBuilder) fi);
4940 object o = c.LookupConstantValue (ec);
4941 object real_value = ((Constant) c.Expr).GetValue ();
4943 return Constantify (real_value, fi.FieldType);
4948 Type t = fi.FieldType;
4952 if (fi is FieldBuilder)
4953 o = TypeManager.GetValue ((FieldBuilder) fi);
4955 o = fi.GetValue (fi);
4957 if (decl_type.IsSubclassOf (TypeManager.enum_type)) {
4958 Expression enum_member = MemberLookup (
4959 ec, decl_type, "value__", MemberTypes.Field,
4960 AllBindingFlags, loc);
4962 Enum en = TypeManager.LookupEnum (decl_type);
4966 c = Constantify (o, en.UnderlyingType);
4968 c = Constantify (o, enum_member.Type);
4970 return new EnumConstant (c, decl_type);
4973 Expression exp = Constantify (o, t);
4975 if (!(left is TypeExpr)) {
4976 error176 (loc, fe.FieldInfo.Name);
4983 if (fi.FieldType.IsPointer && !ec.InUnsafe){
4988 if (left is TypeExpr){
4989 // and refers to a type name or an
4990 if (!fe.FieldInfo.IsStatic){
4991 error176 (loc, fe.FieldInfo.Name);
4994 return member_lookup;
4996 if (fe.FieldInfo.IsStatic){
4997 if (IdenticalNameAndTypeName (ec, left_original, loc))
4998 return member_lookup;
5000 error176 (loc, fe.FieldInfo.Name);
5003 fe.InstanceExpression = left;
5009 if (member_lookup is PropertyExpr){
5010 PropertyExpr pe = (PropertyExpr) member_lookup;
5012 if (left is TypeExpr){
5014 SimpleName.Error120 (loc, pe.PropertyInfo.Name);
5020 if (IdenticalNameAndTypeName (ec, left_original, loc))
5021 return member_lookup;
5022 error176 (loc, pe.PropertyInfo.Name);
5025 pe.InstanceExpression = left;
5031 if (member_lookup is EventExpr) {
5033 EventExpr ee = (EventExpr) member_lookup;
5036 // If the event is local to this class, we transform ourselves into
5040 Expression ml = MemberLookup (
5041 ec, ec.ContainerType,
5042 ee.EventInfo.Name, MemberTypes.Event, AllBindingFlags, loc);
5045 MemberInfo mi = ec.TypeContainer.GetFieldFromEvent ((EventExpr) ml);
5049 // If this happens, then we have an event with its own
5050 // accessors and private field etc so there's no need
5051 // to transform ourselves : we should instead flag an error
5053 Assign.error70 (ee.EventInfo, loc);
5057 ml = ExprClassFromMemberInfo (ec, mi, loc);
5060 Report.Error (-200, loc, "Internal error!!");
5063 return ResolveMemberAccess (ec, ml, left, loc, left_original);
5066 if (left is TypeExpr) {
5068 SimpleName.Error120 (loc, ee.EventInfo.Name);
5076 if (IdenticalNameAndTypeName (ec, left_original, loc))
5079 error176 (loc, ee.EventInfo.Name);
5083 ee.InstanceExpression = left;
5089 if (member_lookup is TypeExpr){
5090 member_lookup.Resolve (ec);
5091 return member_lookup;
5094 Console.WriteLine ("Left is: " + left);
5095 Report.Error (-100, loc, "Support for [" + member_lookup + "] is not present yet");
5096 Environment.Exit (0);
5100 public override Expression DoResolve (EmitContext ec)
5103 // We are the sole users of ResolveWithSimpleName (ie, the only
5104 // ones that can cope with it
5106 Expression original = expr;
5107 expr = expr.ResolveWithSimpleName (ec);
5112 if (expr is SimpleName){
5113 SimpleName child_expr = (SimpleName) expr;
5115 expr = new SimpleName (child_expr.Name + "." + Identifier, loc);
5117 return expr.ResolveWithSimpleName (ec);
5121 // TODO: I mailed Ravi about this, and apparently we can get rid
5122 // of this and put it in the right place.
5124 // Handle enums here when they are in transit.
5125 // Note that we cannot afford to hit MemberLookup in this case because
5126 // it will fail to find any members at all
5129 Type expr_type = expr.Type;
5130 if ((expr is TypeExpr) && (expr_type.IsSubclassOf (TypeManager.enum_type))){
5132 Enum en = TypeManager.LookupEnum (expr_type);
5135 object value = en.LookupEnumValue (ec, Identifier, loc);
5138 Constant c = Constantify (value, en.UnderlyingType);
5139 return new EnumConstant (c, expr_type);
5144 if (expr_type.IsPointer){
5145 Report.Error (23, loc,
5146 "The `.' operator can not be applied to pointer operands (" +
5147 TypeManager.CSharpName (expr_type) + ")");
5151 member_lookup = MemberLookup (ec, expr_type, Identifier, loc);
5153 if (member_lookup == null){
5154 Report.Error (117, loc, "`" + expr_type + "' does not contain a " +
5155 "definition for `" + Identifier + "'");
5160 return ResolveMemberAccess (ec, member_lookup, expr, loc, original);
5163 public override void Emit (EmitContext ec)
5165 throw new Exception ("Should not happen");
5170 /// Implements checked expressions
5172 public class CheckedExpr : Expression {
5174 public Expression Expr;
5176 public CheckedExpr (Expression e)
5181 public override Expression DoResolve (EmitContext ec)
5183 bool last_const_check = ec.ConstantCheckState;
5185 ec.ConstantCheckState = true;
5186 Expr = Expr.Resolve (ec);
5187 ec.ConstantCheckState = last_const_check;
5192 eclass = Expr.eclass;
5197 public override void Emit (EmitContext ec)
5199 bool last_check = ec.CheckState;
5200 bool last_const_check = ec.ConstantCheckState;
5202 ec.CheckState = true;
5203 ec.ConstantCheckState = true;
5205 ec.CheckState = last_check;
5206 ec.ConstantCheckState = last_const_check;
5212 /// Implements the unchecked expression
5214 public class UnCheckedExpr : Expression {
5216 public Expression Expr;
5218 public UnCheckedExpr (Expression e)
5223 public override Expression DoResolve (EmitContext ec)
5225 bool last_const_check = ec.ConstantCheckState;
5227 ec.ConstantCheckState = false;
5228 Expr = Expr.Resolve (ec);
5229 ec.ConstantCheckState = last_const_check;
5234 eclass = Expr.eclass;
5239 public override void Emit (EmitContext ec)
5241 bool last_check = ec.CheckState;
5242 bool last_const_check = ec.ConstantCheckState;
5244 ec.CheckState = false;
5245 ec.ConstantCheckState = false;
5247 ec.CheckState = last_check;
5248 ec.ConstantCheckState = last_const_check;
5254 /// An Element Access expression.
5256 /// During semantic analysis these are transformed into
5257 /// IndexerAccess or ArrayAccess
5259 public class ElementAccess : Expression {
5260 public ArrayList Arguments;
5261 public Expression Expr;
5262 public Location loc;
5264 public ElementAccess (Expression e, ArrayList e_list, Location l)
5273 Arguments = new ArrayList ();
5274 foreach (Expression tmp in e_list)
5275 Arguments.Add (new Argument (tmp, Argument.AType.Expression));
5279 bool CommonResolve (EmitContext ec)
5281 Expr = Expr.Resolve (ec);
5286 if (Arguments == null)
5289 for (int i = Arguments.Count; i > 0;){
5291 Argument a = (Argument) Arguments [i];
5293 if (!a.Resolve (ec, loc))
5300 Expression MakePointerAccess ()
5304 if (t == TypeManager.void_ptr_type){
5307 "The array index operation is not valid for void pointers");
5310 if (Arguments.Count != 1){
5313 "A pointer must be indexed by a single value");
5316 Expression p = new PointerArithmetic (true, Expr, ((Argument)Arguments [0]).Expr, t);
5317 return new Indirection (p);
5320 public override Expression DoResolve (EmitContext ec)
5322 if (!CommonResolve (ec))
5326 // We perform some simple tests, and then to "split" the emit and store
5327 // code we create an instance of a different class, and return that.
5329 // I am experimenting with this pattern.
5333 if (t.IsSubclassOf (TypeManager.array_type))
5334 return (new ArrayAccess (this)).Resolve (ec);
5335 else if (t.IsPointer)
5336 return MakePointerAccess ();
5338 return (new IndexerAccess (this)).Resolve (ec);
5341 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
5343 if (!CommonResolve (ec))
5347 if (t.IsSubclassOf (TypeManager.array_type))
5348 return (new ArrayAccess (this)).ResolveLValue (ec, right_side);
5349 else if (t.IsPointer)
5350 return MakePointerAccess ();
5352 return (new IndexerAccess (this)).ResolveLValue (ec, right_side);
5355 public override void Emit (EmitContext ec)
5357 throw new Exception ("Should never be reached");
5362 /// Implements array access
5364 public class ArrayAccess : Expression, IAssignMethod, IMemoryLocation {
5366 // Points to our "data" repository
5370 public ArrayAccess (ElementAccess ea_data)
5373 eclass = ExprClass.Variable;
5376 public override Expression DoResolve (EmitContext ec)
5378 ExprClass eclass = ea.Expr.eclass;
5381 // As long as the type is valid
5382 if (!(eclass == ExprClass.Variable || eclass == ExprClass.PropertyAccess ||
5383 eclass == ExprClass.Value)) {
5384 report118 (ea.loc, ea.Expr, "variable or value");
5389 Type t = ea.Expr.Type;
5390 if (t.GetArrayRank () != ea.Arguments.Count){
5391 Report.Error (22, ea.loc,
5392 "Incorrect number of indexes for array " +
5393 " expected: " + t.GetArrayRank () + " got: " +
5394 ea.Arguments.Count);
5397 type = t.GetElementType ();
5398 if (type.IsPointer && !ec.InUnsafe){
5399 UnsafeError (ea.loc);
5403 eclass = ExprClass.Variable;
5409 /// Emits the right opcode to load an object of Type `t'
5410 /// from an array of T
5412 static public void EmitLoadOpcode (ILGenerator ig, Type type)
5414 if (type == TypeManager.byte_type || type == TypeManager.bool_type)
5415 ig.Emit (OpCodes.Ldelem_I1);
5416 else if (type == TypeManager.sbyte_type)
5417 ig.Emit (OpCodes.Ldelem_U1);
5418 else if (type == TypeManager.short_type)
5419 ig.Emit (OpCodes.Ldelem_I2);
5420 else if (type == TypeManager.ushort_type)
5421 ig.Emit (OpCodes.Ldelem_U2);
5422 else if (type == TypeManager.int32_type)
5423 ig.Emit (OpCodes.Ldelem_I4);
5424 else if (type == TypeManager.uint32_type)
5425 ig.Emit (OpCodes.Ldelem_U4);
5426 else if (type == TypeManager.uint64_type)
5427 ig.Emit (OpCodes.Ldelem_I8);
5428 else if (type == TypeManager.int64_type)
5429 ig.Emit (OpCodes.Ldelem_I8);
5430 else if (type == TypeManager.float_type)
5431 ig.Emit (OpCodes.Ldelem_R4);
5432 else if (type == TypeManager.double_type)
5433 ig.Emit (OpCodes.Ldelem_R8);
5434 else if (type == TypeManager.intptr_type)
5435 ig.Emit (OpCodes.Ldelem_I);
5436 else if (type.IsValueType){
5437 ig.Emit (OpCodes.Ldelema, type);
5438 ig.Emit (OpCodes.Ldobj, type);
5440 ig.Emit (OpCodes.Ldelem_Ref);
5444 /// Emits the right opcode to store an object of Type `t'
5445 /// from an array of T.
5447 static public void EmitStoreOpcode (ILGenerator ig, Type t)
5449 if (t == TypeManager.byte_type || t == TypeManager.sbyte_type ||
5450 t == TypeManager.bool_type)
5451 ig.Emit (OpCodes.Stelem_I1);
5452 else if (t == TypeManager.short_type || t == TypeManager.ushort_type || t == TypeManager.char_type)
5453 ig.Emit (OpCodes.Stelem_I2);
5454 else if (t == TypeManager.int32_type || t == TypeManager.uint32_type)
5455 ig.Emit (OpCodes.Stelem_I4);
5456 else if (t == TypeManager.int64_type || t == TypeManager.uint64_type)
5457 ig.Emit (OpCodes.Stelem_I8);
5458 else if (t == TypeManager.float_type)
5459 ig.Emit (OpCodes.Stelem_R4);
5460 else if (t == TypeManager.double_type)
5461 ig.Emit (OpCodes.Stelem_R8);
5462 else if (t == TypeManager.intptr_type)
5463 ig.Emit (OpCodes.Stelem_I);
5464 else if (t.IsValueType)
5465 ig.Emit (OpCodes.Stobj, t);
5467 ig.Emit (OpCodes.Stelem_Ref);
5470 MethodInfo FetchGetMethod ()
5472 ModuleBuilder mb = CodeGen.ModuleBuilder;
5473 int arg_count = ea.Arguments.Count;
5474 Type [] args = new Type [arg_count];
5477 for (int i = 0; i < arg_count; i++){
5478 //args [i++] = a.Type;
5479 args [i] = TypeManager.int32_type;
5482 get = mb.GetArrayMethod (
5483 ea.Expr.Type, "Get",
5484 CallingConventions.HasThis |
5485 CallingConventions.Standard,
5491 MethodInfo FetchAddressMethod ()
5493 ModuleBuilder mb = CodeGen.ModuleBuilder;
5494 int arg_count = ea.Arguments.Count;
5495 Type [] args = new Type [arg_count];
5497 string ptr_type_name;
5500 ptr_type_name = type.FullName + "&";
5501 ret_type = Type.GetType (ptr_type_name);
5504 // It is a type defined by the source code we are compiling
5506 if (ret_type == null){
5507 ret_type = mb.GetType (ptr_type_name);
5510 for (int i = 0; i < arg_count; i++){
5511 //args [i++] = a.Type;
5512 args [i] = TypeManager.int32_type;
5515 address = mb.GetArrayMethod (
5516 ea.Expr.Type, "Address",
5517 CallingConventions.HasThis |
5518 CallingConventions.Standard,
5524 public override void Emit (EmitContext ec)
5526 int rank = ea.Expr.Type.GetArrayRank ();
5527 ILGenerator ig = ec.ig;
5531 foreach (Argument a in ea.Arguments)
5535 EmitLoadOpcode (ig, type);
5539 method = FetchGetMethod ();
5540 ig.Emit (OpCodes.Call, method);
5544 public void EmitAssign (EmitContext ec, Expression source)
5546 int rank = ea.Expr.Type.GetArrayRank ();
5547 ILGenerator ig = ec.ig;
5551 foreach (Argument a in ea.Arguments)
5554 Type t = source.Type;
5557 // The stobj opcode used by value types will need
5558 // an address on the stack, not really an array/array
5562 if (t.IsValueType && !TypeManager.IsBuiltinType (t))
5563 ig.Emit (OpCodes.Ldelema, t);
5569 EmitStoreOpcode (ig, t);
5571 ModuleBuilder mb = CodeGen.ModuleBuilder;
5572 int arg_count = ea.Arguments.Count;
5573 Type [] args = new Type [arg_count + 1];
5576 for (int i = 0; i < arg_count; i++){
5577 //args [i++] = a.Type;
5578 args [i] = TypeManager.int32_type;
5581 args [arg_count] = type;
5583 set = mb.GetArrayMethod (
5584 ea.Expr.Type, "Set",
5585 CallingConventions.HasThis |
5586 CallingConventions.Standard,
5587 TypeManager.void_type, args);
5589 ig.Emit (OpCodes.Call, set);
5593 public void AddressOf (EmitContext ec, AddressOp mode)
5595 int rank = ea.Expr.Type.GetArrayRank ();
5596 ILGenerator ig = ec.ig;
5600 foreach (Argument a in ea.Arguments)
5604 ig.Emit (OpCodes.Ldelema, type);
5606 MethodInfo address = FetchAddressMethod ();
5607 ig.Emit (OpCodes.Call, address);
5614 public ArrayList getters, setters;
5615 static Hashtable map;
5619 map = new Hashtable ();
5622 Indexers (MemberInfo [] mi)
5624 foreach (PropertyInfo property in mi){
5625 MethodInfo get, set;
5627 get = property.GetGetMethod (true);
5629 if (getters == null)
5630 getters = new ArrayList ();
5635 set = property.GetSetMethod (true);
5637 if (setters == null)
5638 setters = new ArrayList ();
5644 static public Indexers GetIndexersForType (Type caller_type, Type lookup_type, Location loc)
5646 Indexers ix = (Indexers) map [lookup_type];
5647 string p_name = TypeManager.IndexerPropertyName (lookup_type);
5652 MemberInfo [] mi = TypeManager.MemberLookup (
5653 caller_type, lookup_type, MemberTypes.Property,
5654 BindingFlags.Public | BindingFlags.Instance, p_name);
5656 if (mi == null || mi.Length == 0){
5657 Report.Error (21, loc,
5658 "Type `" + TypeManager.CSharpName (lookup_type) +
5659 "' does not have any indexers defined");
5663 ix = new Indexers (mi);
5664 map [lookup_type] = ix;
5671 /// Expressions that represent an indexer call.
5673 public class IndexerAccess : Expression, IAssignMethod {
5675 // Points to our "data" repository
5678 MethodInfo get, set;
5680 ArrayList set_arguments;
5682 public IndexerAccess (ElementAccess ea_data)
5685 eclass = ExprClass.Value;
5688 public override Expression DoResolve (EmitContext ec)
5690 Type indexer_type = ea.Expr.Type;
5693 // Step 1: Query for all `Item' *properties*. Notice
5694 // that the actual methods are pointed from here.
5696 // This is a group of properties, piles of them.
5699 ilist = Indexers.GetIndexersForType (
5700 ec.ContainerType, indexer_type, ea.loc);
5704 // Step 2: find the proper match
5706 if (ilist != null && ilist.getters != null && ilist.getters.Count > 0){
5707 Location loc = ea.loc;
5709 get = (MethodInfo) Invocation.OverloadResolve (
5710 ec, new MethodGroupExpr (ilist.getters, loc), ea.Arguments, loc);
5714 Report.Error (154, ea.loc,
5715 "indexer can not be used in this context, because " +
5716 "it lacks a `get' accessor");
5720 type = get.ReturnType;
5721 if (type.IsPointer && !ec.InUnsafe){
5722 UnsafeError (ea.loc);
5726 eclass = ExprClass.IndexerAccess;
5730 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
5732 Type indexer_type = ea.Expr.Type;
5733 Type right_type = right_side.Type;
5736 ilist = Indexers.GetIndexersForType (
5737 ec.ContainerType, indexer_type, ea.loc);
5739 if (ilist != null && ilist.setters != null && ilist.setters.Count > 0){
5740 Location loc = ea.loc;
5742 set_arguments = (ArrayList) ea.Arguments.Clone ();
5743 set_arguments.Add (new Argument (right_side, Argument.AType.Expression));
5745 set = (MethodInfo) Invocation.OverloadResolve (
5746 ec, new MethodGroupExpr (ilist.setters, loc), set_arguments, loc);
5750 Report.Error (200, ea.loc,
5751 "indexer X.this [" + TypeManager.CSharpName (right_type) +
5752 "] lacks a `set' accessor");
5756 type = TypeManager.void_type;
5757 eclass = ExprClass.IndexerAccess;
5761 public override void Emit (EmitContext ec)
5763 Invocation.EmitCall (ec, false, false, ea.Expr, get, ea.Arguments);
5767 // source is ignored, because we already have a copy of it from the
5768 // LValue resolution and we have already constructed a pre-cached
5769 // version of the arguments (ea.set_arguments);
5771 public void EmitAssign (EmitContext ec, Expression source)
5773 Invocation.EmitCall (ec, false, false, ea.Expr, set, set_arguments);
5778 /// The base operator for method names
5780 public class BaseAccess : Expression {
5784 public BaseAccess (string member, Location l)
5786 this.member = member;
5790 public override Expression DoResolve (EmitContext ec)
5792 Expression member_lookup;
5793 Type current_type = ec.ContainerType;
5794 Type base_type = current_type.BaseType;
5798 Report.Error (1511, loc,
5799 "Keyword base is not allowed in static method");
5803 member_lookup = MemberLookup (ec, base_type, member, loc);
5804 if (member_lookup == null)
5810 left = new TypeExpr (base_type);
5814 e = MemberAccess.ResolveMemberAccess (ec, member_lookup, left, loc, null);
5815 if (e is PropertyExpr){
5816 PropertyExpr pe = (PropertyExpr) e;
5824 public override void Emit (EmitContext ec)
5826 throw new Exception ("Should never be called");
5831 /// The base indexer operator
5833 public class BaseIndexerAccess : Expression {
5834 ArrayList Arguments;
5837 public BaseIndexerAccess (ArrayList args, Location l)
5843 public override Expression DoResolve (EmitContext ec)
5845 Type current_type = ec.ContainerType;
5846 Type base_type = current_type.BaseType;
5847 Expression member_lookup;
5850 Report.Error (1511, loc,
5851 "Keyword base is not allowed in static method");
5855 member_lookup = MemberLookup (ec, base_type, "get_Item", MemberTypes.Method, AllBindingFlags, loc);
5856 if (member_lookup == null)
5859 return MemberAccess.ResolveMemberAccess (ec, member_lookup, ec.This, loc, null);
5862 public override void Emit (EmitContext ec)
5864 throw new Exception ("Should never be called");
5869 /// This class exists solely to pass the Type around and to be a dummy
5870 /// that can be passed to the conversion functions (this is used by
5871 /// foreach implementation to typecast the object return value from
5872 /// get_Current into the proper type. All code has been generated and
5873 /// we only care about the side effect conversions to be performed
5875 /// This is also now used as a placeholder where a no-action expression
5876 /// is needed (the `New' class).
5878 public class EmptyExpression : Expression {
5879 public EmptyExpression ()
5881 type = TypeManager.object_type;
5882 eclass = ExprClass.Value;
5885 public EmptyExpression (Type t)
5888 eclass = ExprClass.Value;
5891 public override Expression DoResolve (EmitContext ec)
5896 public override void Emit (EmitContext ec)
5898 // nothing, as we only exist to not do anything.
5902 // This is just because we might want to reuse this bad boy
5903 // instead of creating gazillions of EmptyExpressions.
5904 // (CanConvertImplicit uses it)
5906 public void SetType (Type t)
5912 public class UserCast : Expression {
5916 public UserCast (MethodInfo method, Expression source)
5918 this.method = method;
5919 this.source = source;
5920 type = method.ReturnType;
5921 eclass = ExprClass.Value;
5924 public override Expression DoResolve (EmitContext ec)
5927 // We are born fully resolved
5932 public override void Emit (EmitContext ec)
5934 ILGenerator ig = ec.ig;
5938 if (method is MethodInfo)
5939 ig.Emit (OpCodes.Call, (MethodInfo) method);
5941 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
5947 // This class is used to "construct" the type during a typecast
5948 // operation. Since the Type.GetType class in .NET can parse
5949 // the type specification, we just use this to construct the type
5950 // one bit at a time.
5952 public class ComposedCast : Expression {
5957 public ComposedCast (Expression left, string dim, Location l)
5964 public override Expression DoResolve (EmitContext ec)
5966 left = left.Resolve (ec);
5970 if (left.eclass != ExprClass.Type){
5971 report118 (loc, left, "type");
5975 type = RootContext.LookupType (
5976 ec.DeclSpace, left.Type.FullName + dim, false, loc);
5980 if (!ec.InUnsafe && type.IsPointer){
5985 eclass = ExprClass.Type;
5989 public override void Emit (EmitContext ec)
5991 throw new Exception ("This should never be called");
5996 // This class is used to represent the address of an array, used
5997 // only by the Fixed statement, this is like the C "&a [0]" construct.
5999 public class ArrayPtr : Expression {
6002 public ArrayPtr (Expression array)
6004 Type array_type = array.Type.GetElementType ();
6008 string array_ptr_type_name = array_type.FullName + "*";
6010 type = Type.GetType (array_ptr_type_name);
6012 ModuleBuilder mb = CodeGen.ModuleBuilder;
6014 type = mb.GetType (array_ptr_type_name);
6017 eclass = ExprClass.Value;
6020 public override void Emit (EmitContext ec)
6022 ILGenerator ig = ec.ig;
6025 IntLiteral.EmitInt (ig, 0);
6026 ig.Emit (OpCodes.Ldelema, array.Type.GetElementType ());
6029 public override Expression DoResolve (EmitContext ec)
6032 // We are born fully resolved
6039 // Used by the fixed statement
6041 public class StringPtr : Expression {
6044 public StringPtr (LocalBuilder b)
6047 eclass = ExprClass.Value;
6048 type = TypeManager.char_ptr_type;
6051 public override Expression DoResolve (EmitContext ec)
6053 // This should never be invoked, we are born in fully
6054 // initialized state.
6059 public override void Emit (EmitContext ec)
6061 ILGenerator ig = ec.ig;
6063 ig.Emit (OpCodes.Ldloc, b);
6064 ig.Emit (OpCodes.Conv_I);
6065 ig.Emit (OpCodes.Call, TypeManager.int_get_offset_to_string_data);
6066 ig.Emit (OpCodes.Add);
6071 // Implements the `stackalloc' keyword
6073 public class StackAlloc : Expression {
6079 public StackAlloc (string type, Expression count, Location l)
6086 public override Expression DoResolve (EmitContext ec)
6088 count = count.Resolve (ec);
6092 if (count.Type != TypeManager.int32_type){
6093 count = ConvertImplicitRequired (ec, count, TypeManager.int32_type, loc);
6098 if (ec.InCatch || ec.InFinally){
6099 Report.Error (255, loc,
6100 "stackalloc can not be used in a catch or finally block");
6104 otype = RootContext.LookupType (ec.DeclSpace, t, false, loc);
6109 if (!TypeManager.VerifyUnManaged (otype, loc))
6112 string ptr_name = otype.FullName + "*";
6113 type = Type.GetType (ptr_name);
6115 ModuleBuilder mb = CodeGen.ModuleBuilder;
6117 type = mb.GetType (ptr_name);
6119 eclass = ExprClass.Value;
6124 public override void Emit (EmitContext ec)
6126 int size = GetTypeSize (otype);
6127 ILGenerator ig = ec.ig;
6130 ig.Emit (OpCodes.Sizeof, otype);
6132 IntConstant.EmitInt (ig, size);
6134 ig.Emit (OpCodes.Mul);
6135 ig.Emit (OpCodes.Localloc);