2 // expression.cs: Expression representation for the IL tree.
5 // Miguel de Icaza (miguel@ximian.com)
7 // (C) 2001 Ximian, Inc.
11 namespace Mono.CSharp {
13 using System.Collections;
14 using System.Diagnostics;
15 using System.Reflection;
16 using System.Reflection.Emit;
20 /// This is just a helper class, it is generated by Unary, UnaryMutator
21 /// when an overloaded method has been found. It just emits the code for a
24 public class StaticCallExpr : ExpressionStatement {
28 StaticCallExpr (MethodInfo m, ArrayList a)
34 eclass = ExprClass.Value;
37 public override Expression DoResolve (EmitContext ec)
40 // We are born fully resolved
45 public override void Emit (EmitContext ec)
48 Invocation.EmitArguments (ec, mi, args);
50 ec.ig.Emit (OpCodes.Call, mi);
54 static public Expression MakeSimpleCall (EmitContext ec, MethodGroupExpr mg,
55 Expression e, Location loc)
60 args = new ArrayList (1);
61 args.Add (new Argument (e, Argument.AType.Expression));
62 method = Invocation.OverloadResolve (ec, (MethodGroupExpr) mg, args, loc);
67 return new StaticCallExpr ((MethodInfo) method, args);
70 public override void EmitStatement (EmitContext ec)
73 if (type != TypeManager.void_type)
74 ec.ig.Emit (OpCodes.Pop);
79 /// Unary expressions.
83 /// Unary implements unary expressions. It derives from
84 /// ExpressionStatement becuase the pre/post increment/decrement
85 /// operators can be used in a statement context.
87 public class Unary : Expression {
88 public enum Operator : byte {
89 UnaryPlus, UnaryNegation, LogicalNot, OnesComplement,
90 Indirection, AddressOf,
97 public Unary (Operator op, Expression expr, Location loc)
104 public Expression Expr {
114 public Operator Oper {
125 /// Returns a stringified representation of the Operator
130 case Operator.UnaryPlus:
132 case Operator.UnaryNegation:
134 case Operator.LogicalNot:
136 case Operator.OnesComplement:
138 case Operator.AddressOf:
140 case Operator.Indirection:
144 return oper.ToString ();
147 void error23 (Type t)
150 23, loc, "Operator " + OperName () +
151 " cannot be applied to operand of type `" +
152 TypeManager.CSharpName (t) + "'");
155 static Expression TryReduceNegative (Expression expr)
159 if (expr is IntLiteral)
160 e = new IntLiteral (-((IntLiteral) expr).Value);
161 else if (expr is UIntLiteral)
162 e = new LongLiteral (-((UIntLiteral) expr).Value);
163 else if (expr is LongLiteral)
164 e = new LongLiteral (-((LongLiteral) expr).Value);
165 else if (expr is FloatLiteral)
166 e = new FloatLiteral (-((FloatLiteral) expr).Value);
167 else if (expr is DoubleLiteral)
168 e = new DoubleLiteral (-((DoubleLiteral) expr).Value);
169 else if (expr is DecimalLiteral)
170 e = new DecimalLiteral (-((DecimalLiteral) expr).Value);
175 Expression ResolveOperator (EmitContext ec)
177 Type expr_type = expr.Type;
180 // Step 1: Perform Operator Overload location
185 op_name = "op_" + oper;
187 mg = MemberLookup (ec, expr_type, op_name, false, loc);
189 if (mg == null && expr_type.BaseType != null)
190 mg = MemberLookup (ec, expr_type.BaseType, op_name, false, loc);
193 Expression e = StaticCallExpr.MakeSimpleCall (
194 ec, (MethodGroupExpr) mg, expr, loc);
205 // Step 2: Default operations on CLI native types.
208 // Only perform numeric promotions on:
211 if (expr_type == null)
214 if (oper == Operator.LogicalNot){
215 if (expr_type != TypeManager.bool_type) {
220 type = TypeManager.bool_type;
224 if (oper == Operator.OnesComplement) {
225 if (!((expr_type == TypeManager.int32_type) ||
226 (expr_type == TypeManager.uint32_type) ||
227 (expr_type == TypeManager.int64_type) ||
228 (expr_type == TypeManager.uint64_type) ||
229 (expr_type.IsSubclassOf (TypeManager.enum_type)))){
237 if (oper == Operator.UnaryPlus) {
239 // A plus in front of something is just a no-op, so return the child.
245 // Deals with -literals
246 // int operator- (int x)
247 // long operator- (long x)
248 // float operator- (float f)
249 // double operator- (double d)
250 // decimal operator- (decimal d)
252 if (oper == Operator.UnaryNegation){
254 // Fold a "- Constant" into a negative constant
260 // Is this a constant?
262 e = TryReduceNegative (expr);
270 // Not a constant we can optimize, perform numeric
271 // promotions to int, long, double.
274 // The following is inneficient, because we call
275 // ConvertImplicit too many times.
277 // It is also not clear if we should convert to Float
278 // or Double initially.
280 if (expr_type == TypeManager.uint32_type){
282 // FIXME: handle exception to this rule that
283 // permits the int value -2147483648 (-2^31) to
284 // bt written as a decimal interger literal
286 type = TypeManager.int64_type;
287 expr = ConvertImplicit (ec, expr, type, loc);
291 if (expr_type == TypeManager.uint64_type){
293 // FIXME: Handle exception of `long value'
294 // -92233720368547758087 (-2^63) to be written as
295 // decimal integer literal.
301 e = ConvertImplicit (ec, expr, TypeManager.int32_type, loc);
308 e = ConvertImplicit (ec, expr, TypeManager.int64_type, loc);
315 e = ConvertImplicit (ec, expr, TypeManager.double_type, loc);
326 if (oper == Operator.AddressOf){
327 if (expr.ExprClass != ExprClass.Variable){
328 Error (211, loc, "Cannot take the address of non-variables");
331 type = Type.GetType (expr.Type.ToString () + "*");
336 Error (187, loc, "No such operator '" + OperName () + "' defined for type '" +
337 TypeManager.CSharpName (expr_type) + "'");
341 public override Expression DoResolve (EmitContext ec)
343 expr = expr.Resolve (ec);
348 eclass = ExprClass.Value;
349 return ResolveOperator (ec);
352 public override void Emit (EmitContext ec)
354 ILGenerator ig = ec.ig;
355 Type expr_type = expr.Type;
358 case Operator.UnaryPlus:
359 throw new Exception ("This should be caught by Resolve");
361 case Operator.UnaryNegation:
363 ig.Emit (OpCodes.Neg);
366 case Operator.LogicalNot:
368 ig.Emit (OpCodes.Ldc_I4_0);
369 ig.Emit (OpCodes.Ceq);
372 case Operator.OnesComplement:
374 ig.Emit (OpCodes.Not);
377 case Operator.AddressOf:
378 ((IMemoryLocation)expr).AddressOf (ec);
381 case Operator.Indirection:
382 throw new Exception ("Not implemented yet");
385 throw new Exception ("This should not happen: Operator = "
391 /// This will emit the child expression for `ec' avoiding the logical
392 /// not. The parent will take care of changing brfalse/brtrue
394 public void EmitLogicalNot (EmitContext ec)
396 if (oper != Operator.LogicalNot)
397 throw new Exception ("EmitLogicalNot can only be called with !expr");
402 public override Expression Reduce (EmitContext ec)
407 // First, reduce our child. Note that although we handle
409 expr = expr.Reduce (ec);
410 if (!(expr is Literal))
414 case Operator.UnaryPlus:
417 case Operator.UnaryNegation:
418 e = TryReduceNegative (expr);
423 case Operator.LogicalNot:
424 BoolLiteral b = (BoolLiteral) expr;
426 return new BoolLiteral (!(b.Value));
428 case Operator.OnesComplement:
431 if (et == TypeManager.int32_type)
432 return new IntLiteral (~ ((IntLiteral) expr).Value);
433 if (et == TypeManager.uint32_type)
434 return new UIntLiteral (~ ((UIntLiteral) expr).Value);
435 if (et == TypeManager.int64_type)
436 return new LongLiteral (~ ((LongLiteral) expr).Value);
437 if (et == TypeManager.uint64_type)
438 return new ULongLiteral (~ ((ULongLiteral) expr).Value);
446 /// Unary Mutator expressions (pre and post ++ and --)
450 /// UnaryMutator implements ++ and -- expressions. It derives from
451 /// ExpressionStatement becuase the pre/post increment/decrement
452 /// operators can be used in a statement context.
454 /// FIXME: Idea, we could split this up in two classes, one simpler
455 /// for the common case, and one with the extra fields for more complex
456 /// classes (indexers require temporary access; overloaded require method)
458 /// Maybe we should have classes PreIncrement, PostIncrement, PreDecrement,
459 /// PostDecrement, that way we could save the `Mode' byte as well.
461 public class UnaryMutator : ExpressionStatement {
462 public enum Mode : byte {
463 PreIncrement, PreDecrement, PostIncrement, PostDecrement
469 LocalTemporary temp_storage;
472 // This is expensive for the simplest case.
476 public UnaryMutator (Mode m, Expression e, Location l)
485 return (mode == Mode.PreIncrement || mode == Mode.PostIncrement) ?
489 void error23 (Type t)
492 23, loc, "Operator " + OperName () +
493 " cannot be applied to operand of type `" +
494 TypeManager.CSharpName (t) + "'");
498 /// Returns whether an object of type `t' can be incremented
499 /// or decremented with add/sub (ie, basically whether we can
500 /// use pre-post incr-decr operations on it, but it is not a
501 /// System.Decimal, which we require operator overloading to catch)
503 static bool IsIncrementableNumber (Type t)
505 return (t == TypeManager.sbyte_type) ||
506 (t == TypeManager.byte_type) ||
507 (t == TypeManager.short_type) ||
508 (t == TypeManager.ushort_type) ||
509 (t == TypeManager.int32_type) ||
510 (t == TypeManager.uint32_type) ||
511 (t == TypeManager.int64_type) ||
512 (t == TypeManager.uint64_type) ||
513 (t == TypeManager.char_type) ||
514 (t.IsSubclassOf (TypeManager.enum_type)) ||
515 (t == TypeManager.float_type) ||
516 (t == TypeManager.double_type);
519 Expression ResolveOperator (EmitContext ec)
521 Type expr_type = expr.Type;
524 // Step 1: Perform Operator Overload location
529 if (mode == Mode.PreIncrement || mode == Mode.PostIncrement)
530 op_name = "op_Increment";
532 op_name = "op_Decrement";
534 mg = MemberLookup (ec, expr_type, op_name, false, loc);
536 if (mg == null && expr_type.BaseType != null)
537 mg = MemberLookup (ec, expr_type.BaseType, op_name, false, loc);
540 method = StaticCallExpr.MakeSimpleCall (
541 ec, (MethodGroupExpr) mg, expr, loc);
548 // The operand of the prefix/postfix increment decrement operators
549 // should be an expression that is classified as a variable,
550 // a property access or an indexer access
553 if (expr.ExprClass == ExprClass.Variable){
554 if (IsIncrementableNumber (expr_type) ||
555 expr_type == TypeManager.decimal_type){
558 } else if (expr.ExprClass == ExprClass.IndexerAccess){
559 IndexerAccess ia = (IndexerAccess) expr;
561 temp_storage = new LocalTemporary (ec, expr.Type);
563 expr = ia.ResolveLValue (ec, temp_storage);
568 } else if (expr.ExprClass == ExprClass.PropertyAccess){
569 PropertyExpr pe = (PropertyExpr) expr;
571 if (pe.VerifyAssignable ())
576 report118 (loc, expr, "variable, indexer or property access");
580 Error (187, loc, "No such operator '" + OperName () + "' defined for type '" +
581 TypeManager.CSharpName (expr_type) + "'");
585 public override Expression DoResolve (EmitContext ec)
587 expr = expr.Resolve (ec);
592 eclass = ExprClass.Value;
593 return ResolveOperator (ec);
598 // FIXME: We need some way of avoiding the use of temp_storage
599 // for some types of storage (parameters, local variables,
600 // static fields) and single-dimension array access.
602 void EmitCode (EmitContext ec, bool is_expr)
604 ILGenerator ig = ec.ig;
605 IAssignMethod ia = (IAssignMethod) expr;
607 if (temp_storage == null)
608 temp_storage = new LocalTemporary (ec, expr.Type);
611 case Mode.PreIncrement:
612 case Mode.PreDecrement:
616 ig.Emit (OpCodes.Ldc_I4_1);
618 if (mode == Mode.PreDecrement)
619 ig.Emit (OpCodes.Sub);
621 ig.Emit (OpCodes.Add);
625 temp_storage.Store (ec);
626 ia.EmitAssign (ec, temp_storage);
628 temp_storage.Emit (ec);
631 case Mode.PostIncrement:
632 case Mode.PostDecrement:
640 ig.Emit (OpCodes.Dup);
642 ig.Emit (OpCodes.Ldc_I4_1);
644 if (mode == Mode.PostDecrement)
645 ig.Emit (OpCodes.Sub);
647 ig.Emit (OpCodes.Add);
652 temp_storage.Store (ec);
653 ia.EmitAssign (ec, temp_storage);
658 public override void Emit (EmitContext ec)
664 public override void EmitStatement (EmitContext ec)
666 EmitCode (ec, false);
672 /// Implements the `is' and `as' tests.
676 /// FIXME: Split this in two, and we get to save the `Operator' Oper
679 public class Probe : Expression {
680 public readonly string ProbeType;
681 public readonly Operator Oper;
685 public enum Operator : byte {
689 public Probe (Operator oper, Expression expr, string probe_type)
692 ProbeType = probe_type;
696 public Expression Expr {
702 public override Expression DoResolve (EmitContext ec)
704 probe_type = ec.TypeContainer.LookupType (ProbeType, false);
706 if (probe_type == null)
709 expr = expr.Resolve (ec);
711 type = TypeManager.bool_type;
712 eclass = ExprClass.Value;
717 public override void Emit (EmitContext ec)
719 ILGenerator ig = ec.ig;
723 if (Oper == Operator.Is){
724 ig.Emit (OpCodes.Isinst, probe_type);
725 ig.Emit (OpCodes.Ldnull);
726 ig.Emit (OpCodes.Cgt_Un);
728 ig.Emit (OpCodes.Isinst, probe_type);
734 /// This represents a typecast in the source language.
736 /// FIXME: Cast expressions have an unusual set of parsing
737 /// rules, we need to figure those out.
739 public class Cast : Expression {
744 public Cast (string cast_type, Expression expr, Location loc)
746 this.target_type = cast_type;
751 public string TargetType {
757 public Expression Expr {
766 public override Expression DoResolve (EmitContext ec)
768 expr = expr.Resolve (ec);
772 type = ec.TypeContainer.LookupType (target_type, false);
773 eclass = ExprClass.Value;
778 expr = ConvertExplicit (ec, expr, type, loc);
782 public override void Emit (EmitContext ec)
785 // This one will never happen
787 throw new Exception ("Should not happen");
794 public class Binary : Expression {
795 public enum Operator : byte {
796 Multiply, Division, Modulus,
797 Addition, Subtraction,
798 LeftShift, RightShift,
799 LessThan, GreaterThan, LessThanOrEqual, GreaterThanOrEqual,
800 Equality, Inequality,
809 Expression left, right;
815 public Binary (Operator oper, Expression left, Expression right, Location loc)
823 public Operator Oper {
832 public Expression Left {
841 public Expression Right {
852 /// Returns a stringified representation of the Operator
857 case Operator.Multiply:
859 case Operator.Division:
861 case Operator.Modulus:
863 case Operator.Addition:
865 case Operator.Subtraction:
867 case Operator.LeftShift:
869 case Operator.RightShift:
871 case Operator.LessThan:
873 case Operator.GreaterThan:
875 case Operator.LessThanOrEqual:
877 case Operator.GreaterThanOrEqual:
879 case Operator.Equality:
881 case Operator.Inequality:
883 case Operator.BitwiseAnd:
885 case Operator.BitwiseOr:
887 case Operator.ExclusiveOr:
889 case Operator.LogicalOr:
891 case Operator.LogicalAnd:
895 return oper.ToString ();
898 Expression ForceConversion (EmitContext ec, Expression expr, Type target_type)
900 if (expr.Type == target_type)
903 return ConvertImplicit (ec, expr, target_type, new Location (-1));
907 // Note that handling the case l == Decimal || r == Decimal
908 // is taken care of by the Step 1 Operator Overload resolution.
910 bool DoNumericPromotions (EmitContext ec, Type l, Type r)
912 if (l == TypeManager.double_type || r == TypeManager.double_type){
914 // If either operand is of type double, the other operand is
915 // conveted to type double.
917 if (r != TypeManager.double_type)
918 right = ConvertImplicit (ec, right, TypeManager.double_type, loc);
919 if (l != TypeManager.double_type)
920 left = ConvertImplicit (ec, left, TypeManager.double_type, loc);
922 type = TypeManager.double_type;
923 } else if (l == TypeManager.float_type || r == TypeManager.float_type){
925 // if either operand is of type float, th eother operand is
926 // converd to type float.
928 if (r != TypeManager.double_type)
929 right = ConvertImplicit (ec, right, TypeManager.float_type, loc);
930 if (l != TypeManager.double_type)
931 left = ConvertImplicit (ec, left, TypeManager.float_type, loc);
932 type = TypeManager.float_type;
933 } else if (l == TypeManager.uint64_type || r == TypeManager.uint64_type){
937 // If either operand is of type ulong, the other operand is
938 // converted to type ulong. or an error ocurrs if the other
939 // operand is of type sbyte, short, int or long
942 if (l == TypeManager.uint64_type){
943 if (r != TypeManager.uint64_type && right is IntLiteral){
944 e = TryImplicitIntConversion (l, (IntLiteral) right);
950 if (left is IntLiteral){
951 e = TryImplicitIntConversion (r, (IntLiteral) left);
958 if ((other == TypeManager.sbyte_type) ||
959 (other == TypeManager.short_type) ||
960 (other == TypeManager.int32_type) ||
961 (other == TypeManager.int64_type)){
962 string oper = OperName ();
964 Error (34, loc, "Operator `" + OperName ()
965 + "' is ambiguous on operands of type `"
966 + TypeManager.CSharpName (l) + "' "
967 + "and `" + TypeManager.CSharpName (r)
970 type = TypeManager.uint64_type;
971 } else if (l == TypeManager.int64_type || r == TypeManager.int64_type){
973 // If either operand is of type long, the other operand is converted
976 if (l != TypeManager.int64_type)
977 left = ConvertImplicit (ec, left, TypeManager.int64_type, loc);
978 if (r != TypeManager.int64_type)
979 right = ConvertImplicit (ec, right, TypeManager.int64_type, loc);
981 type = TypeManager.int64_type;
982 } else if (l == TypeManager.uint32_type || r == TypeManager.uint32_type){
984 // If either operand is of type uint, and the other
985 // operand is of type sbyte, short or int, othe operands are
986 // converted to type long.
990 if (l == TypeManager.uint32_type)
992 else if (r == TypeManager.uint32_type)
995 if ((other == TypeManager.sbyte_type) ||
996 (other == TypeManager.short_type) ||
997 (other == TypeManager.int32_type)){
998 left = ForceConversion (ec, left, TypeManager.int64_type);
999 right = ForceConversion (ec, right, TypeManager.int64_type);
1000 type = TypeManager.int64_type;
1003 // if either operand is of type uint, the other
1004 // operand is converd to type uint
1006 left = ForceConversion (ec, left, TypeManager.uint32_type);
1007 right = ForceConversion (ec, right, TypeManager.uint32_type);
1008 type = TypeManager.uint32_type;
1010 } else if (l == TypeManager.decimal_type || r == TypeManager.decimal_type){
1011 if (l != TypeManager.decimal_type)
1012 left = ConvertImplicit (ec, left, TypeManager.decimal_type, loc);
1013 if (r != TypeManager.decimal_type)
1014 right = ConvertImplicit (ec, right, TypeManager.decimal_type, loc);
1016 type = TypeManager.decimal_type;
1018 Expression l_tmp, r_tmp;
1020 l_tmp = ForceConversion (ec, left, TypeManager.int32_type);
1024 r_tmp = ForceConversion (ec, right, TypeManager.int32_type);
1031 type = TypeManager.int32_type;
1040 "Operator " + OperName () + " cannot be applied to operands of type `" +
1041 TypeManager.CSharpName (left.Type) + "' and `" +
1042 TypeManager.CSharpName (right.Type) + "'");
1046 Expression CheckShiftArguments (EmitContext ec)
1050 Type r = right.Type;
1052 e = ForceConversion (ec, right, TypeManager.int32_type);
1059 if (((e = ConvertImplicit (ec, left, TypeManager.int32_type, loc)) != null) ||
1060 ((e = ConvertImplicit (ec, left, TypeManager.uint32_type, loc)) != null) ||
1061 ((e = ConvertImplicit (ec, left, TypeManager.int64_type, loc)) != null) ||
1062 ((e = ConvertImplicit (ec, left, TypeManager.uint64_type, loc)) != null)){
1072 Expression ResolveOperator (EmitContext ec)
1075 Type r = right.Type;
1078 // Step 1: Perform Operator Overload location
1080 Expression left_expr, right_expr;
1082 string op = "op_" + oper;
1084 left_expr = MemberLookup (ec, l, op, false, loc);
1085 if (left_expr == null && l.BaseType != null)
1086 left_expr = MemberLookup (ec, l.BaseType, op, false, loc);
1088 right_expr = MemberLookup (ec, r, op, false, loc);
1089 if (right_expr == null && r.BaseType != null)
1090 right_expr = MemberLookup (ec, r.BaseType, op, false, loc);
1092 MethodGroupExpr union = Invocation.MakeUnionSet (left_expr, right_expr);
1094 if (union != null) {
1095 Arguments = new ArrayList ();
1096 Arguments.Add (new Argument (left, Argument.AType.Expression));
1097 Arguments.Add (new Argument (right, Argument.AType.Expression));
1099 method = Invocation.OverloadResolve (ec, union, Arguments, loc);
1100 if (method != null) {
1101 MethodInfo mi = (MethodInfo) method;
1102 type = mi.ReturnType;
1111 // Step 2: Default operations on CLI native types.
1114 // Only perform numeric promotions on:
1115 // +, -, *, /, %, &, |, ^, ==, !=, <, >, <=, >=
1117 if (oper == Operator.Addition){
1119 // If any of the arguments is a string, cast to string
1121 if (l == TypeManager.string_type){
1122 if (r == TypeManager.string_type){
1123 if (left is Literal && right is Literal){
1124 StringLiteral ls = (StringLiteral) left;
1125 StringLiteral rs = (StringLiteral) right;
1127 return new StringLiteral (ls.Value + rs.Value);
1131 method = TypeManager.string_concat_string_string;
1134 method = TypeManager.string_concat_object_object;
1135 right = ConvertImplicit (ec, right,
1136 TypeManager.object_type, loc);
1138 type = TypeManager.string_type;
1140 Arguments = new ArrayList ();
1141 Arguments.Add (new Argument (left, Argument.AType.Expression));
1142 Arguments.Add (new Argument (right, Argument.AType.Expression));
1146 } else if (r == TypeManager.string_type){
1148 method = TypeManager.string_concat_object_object;
1149 Arguments = new ArrayList ();
1150 Arguments.Add (new Argument (left, Argument.AType.Expression));
1151 Arguments.Add (new Argument (right, Argument.AType.Expression));
1153 left = ConvertImplicit (ec, left, TypeManager.object_type, loc);
1154 type = TypeManager.string_type;
1160 // FIXME: is Delegate operator + (D x, D y) handled?
1164 if (oper == Operator.LeftShift || oper == Operator.RightShift)
1165 return CheckShiftArguments (ec);
1167 if (oper == Operator.LogicalOr || oper == Operator.LogicalAnd){
1168 if (l != TypeManager.bool_type || r != TypeManager.bool_type){
1173 type = TypeManager.bool_type;
1177 if (oper == Operator.Equality || oper == Operator.Inequality){
1178 if (l == TypeManager.bool_type || r == TypeManager.bool_type){
1179 if (r != TypeManager.bool_type || l != TypeManager.bool_type){
1184 type = TypeManager.bool_type;
1191 // We are dealing with numbers
1194 if (!DoNumericPromotions (ec, l, r)){
1197 // operator != (object a, object b)
1198 // operator == (object a, object b)
1201 if (oper == Operator.Equality || oper == Operator.Inequality){
1203 li = ConvertImplicit (ec, left, TypeManager.object_type, loc);
1205 ri = ConvertImplicit (ec, right, TypeManager.object_type,
1211 type = TypeManager.bool_type;
1221 if (left == null || right == null)
1225 // reload our cached types if required
1230 if (oper == Operator.BitwiseAnd ||
1231 oper == Operator.BitwiseOr ||
1232 oper == Operator.ExclusiveOr){
1234 if (l.IsSubclassOf (TypeManager.enum_type) ||
1235 !((l == TypeManager.int32_type) ||
1236 (l == TypeManager.uint32_type) ||
1237 (l == TypeManager.int64_type) ||
1238 (l == TypeManager.uint64_type)))
1246 if (oper == Operator.Equality ||
1247 oper == Operator.Inequality ||
1248 oper == Operator.LessThanOrEqual ||
1249 oper == Operator.LessThan ||
1250 oper == Operator.GreaterThanOrEqual ||
1251 oper == Operator.GreaterThan){
1252 type = TypeManager.bool_type;
1258 public override Expression DoResolve (EmitContext ec)
1260 left = left.Resolve (ec);
1261 right = right.Resolve (ec);
1263 if (left == null || right == null)
1266 if (left.Type == null)
1267 throw new Exception (
1268 "Resolve returned non null, but did not set the type! (" +
1269 left + ") at Line: " + loc.Row);
1270 if (right.Type == null)
1271 throw new Exception (
1272 "Resolve returned non null, but did not set the type! (" +
1273 right + ") at Line: "+ loc.Row);
1275 eclass = ExprClass.Value;
1277 return ResolveOperator (ec);
1280 public bool IsBranchable ()
1282 if (oper == Operator.Equality ||
1283 oper == Operator.Inequality ||
1284 oper == Operator.LessThan ||
1285 oper == Operator.GreaterThan ||
1286 oper == Operator.LessThanOrEqual ||
1287 oper == Operator.GreaterThanOrEqual){
1294 /// This entry point is used by routines that might want
1295 /// to emit a brfalse/brtrue after an expression, and instead
1296 /// they could use a more compact notation.
1298 /// Typically the code would generate l.emit/r.emit, followed
1299 /// by the comparission and then a brtrue/brfalse. The comparissions
1300 /// are sometimes inneficient (there are not as complete as the branches
1301 /// look for the hacks in Emit using double ceqs).
1303 /// So for those cases we provide EmitBranchable that can emit the
1304 /// branch with the test
1306 public void EmitBranchable (EmitContext ec, int target)
1309 bool close_target = false;
1315 case Operator.Equality:
1317 opcode = OpCodes.Beq_S;
1319 opcode = OpCodes.Beq;
1322 case Operator.Inequality:
1324 opcode = OpCodes.Bne_Un_S;
1326 opcode = OpCodes.Bne_Un;
1329 case Operator.LessThan:
1331 opcode = OpCodes.Blt_S;
1333 opcode = OpCodes.Blt;
1336 case Operator.GreaterThan:
1338 opcode = OpCodes.Bgt_S;
1340 opcode = OpCodes.Bgt;
1343 case Operator.LessThanOrEqual:
1345 opcode = OpCodes.Ble_S;
1347 opcode = OpCodes.Ble;
1350 case Operator.GreaterThanOrEqual:
1352 opcode = OpCodes.Bge_S;
1354 opcode = OpCodes.Ble;
1358 throw new Exception ("EmitBranchable called on non-EmitBranchable operator: "
1359 + oper.ToString ());
1362 ec.ig.Emit (opcode, target);
1365 public override void Emit (EmitContext ec)
1367 ILGenerator ig = ec.ig;
1369 Type r = right.Type;
1372 if (method != null) {
1374 // Note that operators are static anyway
1376 if (Arguments != null)
1377 Invocation.EmitArguments (ec, method, Arguments);
1379 if (method is MethodInfo)
1380 ig.Emit (OpCodes.Call, (MethodInfo) method);
1382 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
1391 case Operator.Multiply:
1393 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
1394 opcode = OpCodes.Mul_Ovf;
1395 else if (l==TypeManager.uint32_type || l==TypeManager.uint64_type)
1396 opcode = OpCodes.Mul_Ovf_Un;
1398 opcode = OpCodes.Mul;
1400 opcode = OpCodes.Mul;
1404 case Operator.Division:
1405 if (l == TypeManager.uint32_type || l == TypeManager.uint64_type)
1406 opcode = OpCodes.Div_Un;
1408 opcode = OpCodes.Div;
1411 case Operator.Modulus:
1412 if (l == TypeManager.uint32_type || l == TypeManager.uint64_type)
1413 opcode = OpCodes.Rem_Un;
1415 opcode = OpCodes.Rem;
1418 case Operator.Addition:
1420 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
1421 opcode = OpCodes.Add_Ovf;
1422 else if (l==TypeManager.uint32_type || l==TypeManager.uint64_type)
1423 opcode = OpCodes.Add_Ovf_Un;
1425 opcode = OpCodes.Mul;
1427 opcode = OpCodes.Add;
1430 case Operator.Subtraction:
1432 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
1433 opcode = OpCodes.Sub_Ovf;
1434 else if (l==TypeManager.uint32_type || l==TypeManager.uint64_type)
1435 opcode = OpCodes.Sub_Ovf_Un;
1437 opcode = OpCodes.Sub;
1439 opcode = OpCodes.Sub;
1442 case Operator.RightShift:
1443 opcode = OpCodes.Shr;
1446 case Operator.LeftShift:
1447 opcode = OpCodes.Shl;
1450 case Operator.Equality:
1451 opcode = OpCodes.Ceq;
1454 case Operator.Inequality:
1455 ec.ig.Emit (OpCodes.Ceq);
1456 ec.ig.Emit (OpCodes.Ldc_I4_0);
1458 opcode = OpCodes.Ceq;
1461 case Operator.LessThan:
1462 opcode = OpCodes.Clt;
1465 case Operator.GreaterThan:
1466 opcode = OpCodes.Cgt;
1469 case Operator.LessThanOrEqual:
1470 ec.ig.Emit (OpCodes.Cgt);
1471 ec.ig.Emit (OpCodes.Ldc_I4_0);
1473 opcode = OpCodes.Ceq;
1476 case Operator.GreaterThanOrEqual:
1477 ec.ig.Emit (OpCodes.Clt);
1478 ec.ig.Emit (OpCodes.Ldc_I4_1);
1480 opcode = OpCodes.Sub;
1483 case Operator.LogicalOr:
1484 case Operator.BitwiseOr:
1485 opcode = OpCodes.Or;
1488 case Operator.LogicalAnd:
1489 case Operator.BitwiseAnd:
1490 opcode = OpCodes.And;
1493 case Operator.ExclusiveOr:
1494 opcode = OpCodes.Xor;
1498 throw new Exception ("This should not happen: Operator = "
1499 + oper.ToString ());
1506 /// Constant expression reducer for binary operations
1508 public override Expression Reduce (EmitContext ec)
1511 left = left.Reduce (ec);
1512 right = right.Reduce (ec);
1514 if (!(left is Literal && right is Literal))
1517 if (method == TypeManager.string_concat_string_string){
1518 StringLiteral ls = (StringLiteral) left;
1519 StringLiteral rs = (StringLiteral) right;
1521 return new StringLiteral (ls.Value + rs.Value);
1530 public class Conditional : Expression {
1531 Expression expr, trueExpr, falseExpr;
1534 public Conditional (Expression expr, Expression trueExpr, Expression falseExpr, Location l)
1537 this.trueExpr = trueExpr;
1538 this.falseExpr = falseExpr;
1542 public Expression Expr {
1548 public Expression TrueExpr {
1554 public Expression FalseExpr {
1560 public override Expression DoResolve (EmitContext ec)
1562 expr = expr.Resolve (ec);
1564 if (expr.Type != TypeManager.bool_type)
1565 expr = Expression.ConvertImplicitRequired (
1566 ec, expr, TypeManager.bool_type, loc);
1568 trueExpr = trueExpr.Resolve (ec);
1569 falseExpr = falseExpr.Resolve (ec);
1571 if (expr == null || trueExpr == null || falseExpr == null)
1574 if (trueExpr.Type == falseExpr.Type)
1575 type = trueExpr.Type;
1580 // First, if an implicit conversion exists from trueExpr
1581 // to falseExpr, then the result type is of type falseExpr.Type
1583 conv = ConvertImplicit (ec, trueExpr, falseExpr.Type, loc);
1585 type = falseExpr.Type;
1587 } else if ((conv = ConvertImplicit(ec, falseExpr,trueExpr.Type,loc))!= null){
1588 type = trueExpr.Type;
1591 Error (173, loc, "The type of the conditional expression can " +
1592 "not be computed because there is no implicit conversion" +
1593 " from `" + TypeManager.CSharpName (trueExpr.Type) + "'" +
1594 " and `" + TypeManager.CSharpName (falseExpr.Type) + "'");
1599 if (expr is BoolLiteral){
1600 BoolLiteral bl = (BoolLiteral) expr;
1608 eclass = ExprClass.Value;
1612 public override void Emit (EmitContext ec)
1614 ILGenerator ig = ec.ig;
1615 Label false_target = ig.DefineLabel ();
1616 Label end_target = ig.DefineLabel ();
1619 ig.Emit (OpCodes.Brfalse, false_target);
1621 ig.Emit (OpCodes.Br, end_target);
1622 ig.MarkLabel (false_target);
1623 falseExpr.Emit (ec);
1624 ig.MarkLabel (end_target);
1627 public override Expression Reduce (EmitContext ec)
1629 expr = expr.Reduce (ec);
1630 trueExpr = trueExpr.Reduce (ec);
1631 falseExpr = falseExpr.Reduce (ec);
1633 if (!(expr is Literal && trueExpr is Literal && falseExpr is Literal))
1636 BoolLiteral bl = (BoolLiteral) expr;
1645 public class LocalVariableReference : Expression, IAssignMethod, IMemoryLocation {
1646 public readonly string Name;
1647 public readonly Block Block;
1649 VariableInfo variable_info;
1651 public LocalVariableReference (Block block, string name)
1655 eclass = ExprClass.Variable;
1658 public VariableInfo VariableInfo {
1660 if (variable_info == null)
1661 variable_info = Block.GetVariableInfo (Name);
1662 return variable_info;
1666 public override Expression DoResolve (EmitContext ec)
1668 VariableInfo vi = VariableInfo;
1670 type = vi.VariableType;
1674 public override void Emit (EmitContext ec)
1676 VariableInfo vi = VariableInfo;
1677 ILGenerator ig = ec.ig;
1684 ig.Emit (OpCodes.Ldloc_0);
1688 ig.Emit (OpCodes.Ldloc_1);
1692 ig.Emit (OpCodes.Ldloc_2);
1696 ig.Emit (OpCodes.Ldloc_3);
1701 ig.Emit (OpCodes.Ldloc_S, (byte) idx);
1703 ig.Emit (OpCodes.Ldloc, idx);
1708 public static void Store (ILGenerator ig, int idx)
1712 ig.Emit (OpCodes.Stloc_0);
1716 ig.Emit (OpCodes.Stloc_1);
1720 ig.Emit (OpCodes.Stloc_2);
1724 ig.Emit (OpCodes.Stloc_3);
1729 ig.Emit (OpCodes.Stloc_S, (byte) idx);
1731 ig.Emit (OpCodes.Stloc, idx);
1736 public void EmitAssign (EmitContext ec, Expression source)
1738 ILGenerator ig = ec.ig;
1739 VariableInfo vi = VariableInfo;
1745 // Funny seems the code below generates optimal code for us, but
1746 // seems to take too long to generate what we need.
1747 // ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
1752 public void AddressOf (EmitContext ec)
1754 VariableInfo vi = VariableInfo;
1761 ec.ig.Emit (OpCodes.Ldloca_S, (byte) idx);
1763 ec.ig.Emit (OpCodes.Ldloca, idx);
1768 /// This represents a reference to a parameter in the intermediate
1771 public class ParameterReference : Expression, IAssignMethod, IMemoryLocation {
1772 public readonly Parameters Pars;
1773 public readonly String Name;
1774 public readonly int Idx;
1777 public ParameterReference (Parameters pars, int idx, string name)
1782 eclass = ExprClass.Variable;
1785 public override Expression DoResolve (EmitContext ec)
1787 Type [] types = Pars.GetParameterInfo (ec.TypeContainer);
1798 public override void Emit (EmitContext ec)
1801 ec.ig.Emit (OpCodes.Ldarg_S, (byte) arg_idx);
1803 ec.ig.Emit (OpCodes.Ldarg, arg_idx);
1806 public void EmitAssign (EmitContext ec, Expression source)
1811 ec.ig.Emit (OpCodes.Starg_S, (byte) arg_idx);
1813 ec.ig.Emit (OpCodes.Starg, arg_idx);
1817 public void AddressOf (EmitContext ec)
1820 ec.ig.Emit (OpCodes.Ldarga_S, (byte) arg_idx);
1822 ec.ig.Emit (OpCodes.Ldarga, arg_idx);
1827 /// Used for arguments to New(), Invocation()
1829 public class Argument {
1830 public enum AType : byte {
1836 public readonly AType ArgType;
1837 public Expression expr;
1839 public Argument (Expression expr, AType type)
1842 this.ArgType = type;
1845 public Expression Expr {
1861 public Parameter.Modifier GetParameterModifier ()
1863 if (ArgType == AType.Ref)
1864 return Parameter.Modifier.REF;
1866 if (ArgType == AType.Out)
1867 return Parameter.Modifier.OUT;
1869 return Parameter.Modifier.NONE;
1872 public static string FullDesc (Argument a)
1874 return (a.ArgType == AType.Ref ? "ref " :
1875 (a.ArgType == AType.Out ? "out " : "")) +
1876 TypeManager.CSharpName (a.Expr.Type);
1879 public bool Resolve (EmitContext ec, Location loc)
1881 expr = expr.Resolve (ec);
1883 if (ArgType == AType.Expression)
1884 return expr != null;
1886 if (expr.ExprClass != ExprClass.Variable){
1887 Report.Error (206, loc,
1888 "A property or indexer can not be passed as an out or ref " +
1893 return expr != null;
1896 public void Emit (EmitContext ec)
1898 if (ArgType == AType.Ref || ArgType == AType.Out)
1899 ((IMemoryLocation)expr).AddressOf (ec);
1906 /// Invocation of methods or delegates.
1908 public class Invocation : ExpressionStatement {
1909 public readonly ArrayList Arguments;
1913 MethodBase method = null;
1915 static Hashtable method_parameter_cache;
1917 static Invocation ()
1919 method_parameter_cache = new Hashtable ();
1923 // arguments is an ArrayList, but we do not want to typecast,
1924 // as it might be null.
1926 // FIXME: only allow expr to be a method invocation or a
1927 // delegate invocation (7.5.5)
1929 public Invocation (Expression expr, ArrayList arguments, Location l)
1932 Arguments = arguments;
1936 public Expression Expr {
1943 /// Returns the Parameters (a ParameterData interface) for the
1946 public static ParameterData GetParameterData (MethodBase mb)
1948 object pd = method_parameter_cache [mb];
1952 return (ParameterData) pd;
1955 ip = TypeContainer.LookupParametersByBuilder (mb);
1957 method_parameter_cache [mb] = ip;
1959 return (ParameterData) ip;
1961 ParameterInfo [] pi = mb.GetParameters ();
1962 ReflectionParameters rp = new ReflectionParameters (pi);
1963 method_parameter_cache [mb] = rp;
1965 return (ParameterData) rp;
1970 /// Tells whether a user defined conversion from Type `from' to
1971 /// Type `to' exists.
1973 /// FIXME: we could implement a cache here.
1975 static bool ConversionExists (EmitContext ec, Type from, Type to, Location loc)
1977 // Locate user-defined implicit operators
1981 mg = MemberLookup (ec, to, "op_Implicit", false, loc);
1984 MethodGroupExpr me = (MethodGroupExpr) mg;
1986 for (int i = me.Methods.Length; i > 0;) {
1988 MethodBase mb = me.Methods [i];
1989 ParameterData pd = GetParameterData (mb);
1991 if (from == pd.ParameterType (0))
1996 mg = MemberLookup (ec, from, "op_Implicit", false, loc);
1999 MethodGroupExpr me = (MethodGroupExpr) mg;
2001 for (int i = me.Methods.Length; i > 0;) {
2003 MethodBase mb = me.Methods [i];
2004 MethodInfo mi = (MethodInfo) mb;
2006 if (mi.ReturnType == to)
2015 /// Determines "better conversion" as specified in 7.4.2.3
2016 /// Returns : 1 if a->p is better
2017 /// 0 if a->q or neither is better
2019 static int BetterConversion (EmitContext ec, Argument a, Type p, Type q, bool use_standard,
2022 Type argument_type = a.Type;
2023 Expression argument_expr = a.Expr;
2025 if (argument_type == null)
2026 throw new Exception ("Expression of type " + a.Expr + " does not resolve its type");
2031 if (argument_type == p)
2034 if (argument_type == q)
2038 // Now probe whether an implicit constant expression conversion
2041 // An implicit constant expression conversion permits the following
2044 // * A constant-expression of type `int' can be converted to type
2045 // sbyte, byute, short, ushort, uint, ulong provided the value of
2046 // of the expression is withing the range of the destination type.
2048 // * A constant-expression of type long can be converted to type
2049 // ulong, provided the value of the constant expression is not negative
2051 // FIXME: Note that this assumes that constant folding has
2052 // taken place. We dont do constant folding yet.
2055 if (argument_expr is IntLiteral){
2056 IntLiteral ei = (IntLiteral) argument_expr;
2057 int value = ei.Value;
2059 if (p == TypeManager.sbyte_type){
2060 if (value >= SByte.MinValue && value <= SByte.MaxValue)
2062 } else if (p == TypeManager.byte_type){
2063 if (Byte.MinValue >= 0 && value <= Byte.MaxValue)
2065 } else if (p == TypeManager.short_type){
2066 if (value >= Int16.MinValue && value <= Int16.MaxValue)
2068 } else if (p == TypeManager.ushort_type){
2069 if (value >= UInt16.MinValue && value <= UInt16.MaxValue)
2071 } else if (p == TypeManager.uint32_type){
2073 // we can optimize this case: a positive int32
2074 // always fits on a uint32
2078 } else if (p == TypeManager.uint64_type){
2080 // we can optimize this case: a positive int32
2081 // always fits on a uint64
2086 } else if (argument_type == TypeManager.int64_type && argument_expr is LongLiteral){
2087 LongLiteral ll = (LongLiteral) argument_expr;
2089 if (p == TypeManager.uint64_type){
2100 tmp = ConvertImplicitStandard (ec, argument_expr, p, loc);
2102 tmp = ConvertImplicit (ec, argument_expr, p, loc);
2111 if (ConversionExists (ec, p, q, loc) == true &&
2112 ConversionExists (ec, q, p, loc) == false)
2115 if (p == TypeManager.sbyte_type)
2116 if (q == TypeManager.byte_type || q == TypeManager.ushort_type ||
2117 q == TypeManager.uint32_type || q == TypeManager.uint64_type)
2120 if (p == TypeManager.short_type)
2121 if (q == TypeManager.ushort_type || q == TypeManager.uint32_type ||
2122 q == TypeManager.uint64_type)
2125 if (p == TypeManager.int32_type)
2126 if (q == TypeManager.uint32_type || q == TypeManager.uint64_type)
2129 if (p == TypeManager.int64_type)
2130 if (q == TypeManager.uint64_type)
2137 /// Determines "Better function"
2140 /// and returns an integer indicating :
2141 /// 0 if candidate ain't better
2142 /// 1 if candidate is better than the current best match
2144 static int BetterFunction (EmitContext ec, ArrayList args,
2145 MethodBase candidate, MethodBase best,
2146 bool use_standard, Location loc)
2148 ParameterData candidate_pd = GetParameterData (candidate);
2149 ParameterData best_pd;
2155 argument_count = args.Count;
2157 if (candidate_pd.Count == 0 && argument_count == 0)
2161 if (candidate_pd.Count == argument_count) {
2163 for (int j = argument_count; j > 0;) {
2166 Argument a = (Argument) args [j];
2168 x = BetterConversion (
2169 ec, a, candidate_pd.ParameterType (j), null,
2185 best_pd = GetParameterData (best);
2187 if (candidate_pd.Count == argument_count && best_pd.Count == argument_count) {
2188 int rating1 = 0, rating2 = 0;
2190 for (int j = argument_count; j > 0;) {
2194 Argument a = (Argument) args [j];
2196 x = BetterConversion (ec, a, candidate_pd.ParameterType (j),
2197 best_pd.ParameterType (j), use_standard, loc);
2198 y = BetterConversion (ec, a, best_pd.ParameterType (j),
2199 candidate_pd.ParameterType (j), use_standard,
2206 if (rating1 > rating2)
2215 public static string FullMethodDesc (MethodBase mb)
2217 StringBuilder sb = new StringBuilder (mb.Name);
2218 ParameterData pd = GetParameterData (mb);
2220 int count = pd.Count;
2223 for (int i = count; i > 0; ) {
2226 sb.Append (pd.ParameterDesc (count - i - 1));
2232 return sb.ToString ();
2235 public static MethodGroupExpr MakeUnionSet (Expression mg1, Expression mg2)
2237 MemberInfo [] miset;
2238 MethodGroupExpr union;
2240 if (mg1 != null && mg2 != null) {
2242 MethodGroupExpr left_set = null, right_set = null;
2243 int length1 = 0, length2 = 0;
2245 left_set = (MethodGroupExpr) mg1;
2246 length1 = left_set.Methods.Length;
2248 right_set = (MethodGroupExpr) mg2;
2249 length2 = right_set.Methods.Length;
2251 ArrayList common = new ArrayList ();
2253 for (int i = 0; i < left_set.Methods.Length; i++) {
2254 for (int j = 0; j < right_set.Methods.Length; j++) {
2255 if (left_set.Methods [i] == right_set.Methods [j])
2256 common.Add (left_set.Methods [i]);
2260 miset = new MemberInfo [length1 + length2 - common.Count];
2262 left_set.Methods.CopyTo (miset, 0);
2266 for (int j = 0; j < right_set.Methods.Length; j++)
2267 if (!common.Contains (right_set.Methods [j]))
2268 miset [length1 + k++] = right_set.Methods [j];
2270 union = new MethodGroupExpr (miset);
2274 } else if (mg1 == null && mg2 != null) {
2276 MethodGroupExpr me = (MethodGroupExpr) mg2;
2278 miset = new MemberInfo [me.Methods.Length];
2279 me.Methods.CopyTo (miset, 0);
2281 union = new MethodGroupExpr (miset);
2285 } else if (mg2 == null && mg1 != null) {
2287 MethodGroupExpr me = (MethodGroupExpr) mg1;
2289 miset = new MemberInfo [me.Methods.Length];
2290 me.Methods.CopyTo (miset, 0);
2292 union = new MethodGroupExpr (miset);
2301 /// Determines is the candidate method, if a params method, is applicable
2302 /// in its expanded form to the given set of arguments
2304 static bool IsParamsMethodApplicable (ArrayList arguments, MethodBase candidate)
2308 if (arguments == null)
2311 arg_count = arguments.Count;
2313 ParameterData pd = GetParameterData (candidate);
2315 int pd_count = pd.Count;
2317 if (pd.ParameterModifier (pd_count - 1) != Parameter.Modifier.PARAMS)
2320 if (pd_count - 1 > arg_count)
2323 // If we have come this far, the case which remains is when the number of parameters
2324 // is less than or equal to the argument count. So, we now check if the element type
2325 // of the params array is compatible with each argument type
2328 Type element_type = pd.ParameterType (pd_count - 1).GetElementType ();
2330 for (int i = pd_count - 1; i < arg_count - 1; i++) {
2331 Argument a = (Argument) arguments [i];
2332 if (!StandardConversionExists (a.Type, element_type))
2340 /// Determines if the candidate method is applicable (section 14.4.2.1)
2341 /// to the given set of arguments
2343 static bool IsApplicable (ArrayList arguments, MethodBase candidate)
2347 if (arguments == null)
2350 arg_count = arguments.Count;
2352 ParameterData pd = GetParameterData (candidate);
2354 int pd_count = pd.Count;
2356 if (arg_count != pd.Count)
2359 for (int i = arg_count; i > 0; ) {
2362 Argument a = (Argument) arguments [i];
2364 Parameter.Modifier a_mod = a.GetParameterModifier ();
2365 Parameter.Modifier p_mod = pd.ParameterModifier (i);
2367 if (a_mod == p_mod) {
2369 if (a_mod == Parameter.Modifier.NONE)
2370 if (!StandardConversionExists (a.Type, pd.ParameterType (i)))
2373 if (a_mod == Parameter.Modifier.REF ||
2374 a_mod == Parameter.Modifier.OUT)
2375 if (pd.ParameterType (i) != a.Type)
2387 /// Find the Applicable Function Members (7.4.2.1)
2389 /// me: Method Group expression with the members to select.
2390 /// it might contain constructors or methods (or anything
2391 /// that maps to a method).
2393 /// Arguments: ArrayList containing resolved Argument objects.
2395 /// loc: The location if we want an error to be reported, or a Null
2396 /// location for "probing" purposes.
2398 /// use_standard: controls whether OverloadResolve should use the
2399 /// ConvertImplicit or ConvertImplicitStandard during overload resolution.
2401 /// Returns: The MethodBase (either a ConstructorInfo or a MethodInfo)
2402 /// that is the best match of me on Arguments.
2405 public static MethodBase OverloadResolve (EmitContext ec, MethodGroupExpr me,
2406 ArrayList Arguments, Location loc,
2409 ArrayList afm = new ArrayList ();
2410 int best_match_idx = -1;
2411 MethodBase method = null;
2414 for (int i = me.Methods.Length; i > 0; ){
2416 MethodBase candidate = me.Methods [i];
2419 // Check if candidate is applicable (section 14.4.2.1)
2420 if (!IsApplicable (Arguments, candidate))
2423 x = BetterFunction (ec, Arguments, candidate, method, use_standard, loc);
2429 method = me.Methods [best_match_idx];
2433 if (Arguments == null)
2436 argument_count = Arguments.Count;
2439 // Now we see if we can find params functions, applicable in their expanded form
2440 // since if they were applicable in their normal form, they would have been selected
2443 if (best_match_idx == -1) {
2445 for (int i = me.Methods.Length; i > 0; ) {
2447 MethodBase candidate = me.Methods [i];
2449 if (IsParamsMethodApplicable (Arguments, candidate)) {
2451 method = me.Methods [best_match_idx];
2458 // Now we see if we can at least find a method with the same number of arguments
2462 if (best_match_idx == -1) {
2464 for (int i = me.Methods.Length; i > 0;) {
2466 MethodBase mb = me.Methods [i];
2467 pd = GetParameterData (mb);
2469 if (pd.Count == argument_count) {
2471 method = me.Methods [best_match_idx];
2481 // And now convert implicitly, each argument to the required type
2483 pd = GetParameterData (method);
2484 int pd_count = pd.Count;
2486 for (int j = 0; j < argument_count; j++) {
2488 Argument a = (Argument) Arguments [j];
2489 Expression a_expr = a.Expr;
2490 Type parameter_type = pd.ParameterType (j);
2493 // Note that we need to compare against the element type
2494 // when we have a params method
2496 if (pd.ParameterModifier (pd_count - 1) == Parameter.Modifier.PARAMS) {
2497 if (j >= pd_count - 1)
2498 parameter_type = pd.ParameterType (pd_count - 1).GetElementType ();
2501 if (a.Type != parameter_type){
2505 conv = ConvertImplicitStandard (ec, a_expr, parameter_type, Location.Null);
2507 conv = ConvertImplicit (ec, a_expr, parameter_type, Location.Null);
2510 if (!Location.IsNull (loc)) {
2512 "The best overloaded match for method '" + FullMethodDesc (method)+
2513 "' has some invalid arguments");
2515 "Argument " + (j+1) +
2516 ": Cannot convert from '" + Argument.FullDesc (a)
2517 + "' to '" + pd.ParameterDesc (j) + "'");
2525 // Update the argument with the implicit conversion
2530 // FIXME : For the case of params methods, we need to actually instantiate
2531 // an array and initialize it with the argument values etc etc.
2535 if (a.GetParameterModifier () != pd.ParameterModifier (j) &&
2536 pd.ParameterModifier (j) != Parameter.Modifier.PARAMS) {
2537 if (!Location.IsNull (loc)) {
2539 "The best overloaded match for method '" + FullMethodDesc (method)+
2540 "' has some invalid arguments");
2542 "Argument " + (j+1) +
2543 ": Cannot convert from '" + Argument.FullDesc (a)
2544 + "' to '" + pd.ParameterDesc (j) + "'");
2555 public static MethodBase OverloadResolve (EmitContext ec, MethodGroupExpr me,
2556 ArrayList Arguments, Location loc)
2558 return OverloadResolve (ec, me, Arguments, loc, false);
2561 public override Expression DoResolve (EmitContext ec)
2564 // First, resolve the expression that is used to
2565 // trigger the invocation
2567 expr = expr.Resolve (ec);
2571 if (!(expr is MethodGroupExpr)) {
2572 Type expr_type = expr.Type;
2574 if (expr_type != null){
2575 bool IsDelegate = TypeManager.IsDelegateType (expr_type);
2577 return (new DelegateInvocation (
2578 this.expr, Arguments, loc)).Resolve (ec);
2582 if (!(expr is MethodGroupExpr)){
2583 report118 (loc, this.expr, "method group");
2588 // Next, evaluate all the expressions in the argument list
2590 if (Arguments != null){
2591 for (int i = Arguments.Count; i > 0;){
2593 Argument a = (Argument) Arguments [i];
2595 if (!a.Resolve (ec, loc))
2600 method = OverloadResolve (ec, (MethodGroupExpr) this.expr, Arguments, loc);
2602 if (method == null){
2604 "Could not find any applicable function for this argument list");
2608 if (method is MethodInfo)
2609 type = ((MethodInfo)method).ReturnType;
2611 eclass = ExprClass.Value;
2616 // Emits the list of arguments as an array
2618 static void EmitParams (EmitContext ec, int idx, ArrayList arguments)
2620 ILGenerator ig = ec.ig;
2621 int count = arguments.Count - idx;
2622 Argument a = (Argument) arguments [idx];
2623 Type t = a.expr.Type;
2624 string array_type = t.FullName + "[]";
2627 array = ig.DeclareLocal (Type.GetType (array_type));
2628 IntLiteral.EmitInt (ig, count);
2629 ig.Emit (OpCodes.Newarr, t);
2630 ig.Emit (OpCodes.Stloc, array);
2632 int top = arguments.Count;
2633 for (int j = idx; j < top; j++){
2634 a = (Argument) arguments [j];
2636 ig.Emit (OpCodes.Ldloc, array);
2637 IntLiteral.EmitInt (ig, j - idx);
2640 ArrayAccess.EmitStoreOpcode (ig, t);
2642 ig.Emit (OpCodes.Ldloc, array);
2646 /// Emits a list of resolved Arguments that are in the arguments
2649 /// The MethodBase argument might be null if the
2650 /// emission of the arguments is known not to contain
2651 /// a `params' field (for example in constructors or other routines
2652 /// that keep their arguments in this structure
2654 public static void EmitArguments (EmitContext ec, MethodBase mb, ArrayList arguments)
2656 ParameterData pd = null;
2659 if (arguments != null)
2660 top = arguments.Count;
2665 pd = GetParameterData (mb);
2667 for (int i = 0; i < top; i++){
2668 Argument a = (Argument) arguments [i];
2671 if (pd.ParameterModifier (i) == Parameter.Modifier.PARAMS){
2672 EmitParams (ec, i, arguments);
2681 public static void EmitCall (EmitContext ec,
2682 bool is_static, Expression instance_expr,
2683 MethodBase method, ArrayList Arguments)
2685 ILGenerator ig = ec.ig;
2686 bool struct_call = false;
2690 // If this is ourselves, push "this"
2692 if (instance_expr == null){
2693 ig.Emit (OpCodes.Ldarg_0);
2696 // Push the instance expression
2698 if (instance_expr.Type.IsSubclassOf (TypeManager.value_type)){
2703 // If the expression implements IMemoryLocation, then
2704 // we can optimize and use AddressOf on the
2707 // If not we have to use some temporary storage for
2709 if (instance_expr is IMemoryLocation)
2710 ((IMemoryLocation) instance_expr).AddressOf (ec);
2712 Type t = instance_expr.Type;
2714 instance_expr.Emit (ec);
2715 LocalBuilder temp = ig.DeclareLocal (t);
2716 ig.Emit (OpCodes.Stloc, temp);
2717 ig.Emit (OpCodes.Ldloca, temp);
2720 instance_expr.Emit (ec);
2724 if (Arguments != null)
2725 EmitArguments (ec, method, Arguments);
2727 if (is_static || struct_call){
2728 if (method is MethodInfo)
2729 ig.Emit (OpCodes.Call, (MethodInfo) method);
2731 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
2733 if (method is MethodInfo)
2734 ig.Emit (OpCodes.Callvirt, (MethodInfo) method);
2736 ig.Emit (OpCodes.Callvirt, (ConstructorInfo) method);
2740 public override void Emit (EmitContext ec)
2742 MethodGroupExpr mg = (MethodGroupExpr) this.expr;
2743 EmitCall (ec, method.IsStatic, mg.InstanceExpression, method, Arguments);
2746 public override void EmitStatement (EmitContext ec)
2751 // Pop the return value if there is one
2753 if (method is MethodInfo){
2754 if (((MethodInfo)method).ReturnType != TypeManager.void_type)
2755 ec.ig.Emit (OpCodes.Pop);
2761 /// Implements the new expression
2763 public class New : ExpressionStatement {
2764 public readonly ArrayList Arguments;
2765 public readonly string RequestedType;
2768 MethodBase method = null;
2771 // If set, the new expression is for a value_target, and
2772 // we will not leave anything on the stack.
2774 Expression value_target;
2776 public New (string requested_type, ArrayList arguments, Location l)
2778 RequestedType = requested_type;
2779 Arguments = arguments;
2783 public Expression ValueTypeVariable {
2785 return value_target;
2789 value_target = value;
2793 public override Expression DoResolve (EmitContext ec)
2795 type = ec.TypeContainer.LookupType (RequestedType, false);
2800 bool IsDelegate = TypeManager.IsDelegateType (type);
2803 return (new NewDelegate (type, Arguments, loc)).Resolve (ec);
2807 ml = MemberLookup (ec, type, ".ctor", false,
2808 MemberTypes.Constructor, AllBindingsFlags, loc);
2810 bool is_struct = false;
2811 is_struct = type.IsSubclassOf (TypeManager.value_type);
2813 if (! (ml is MethodGroupExpr)){
2815 report118 (loc, ml, "method group");
2821 if (Arguments != null){
2822 for (int i = Arguments.Count; i > 0;){
2824 Argument a = (Argument) Arguments [i];
2826 if (!a.Resolve (ec, loc))
2831 method = Invocation.OverloadResolve (ec, (MethodGroupExpr) ml,
2835 if (method == null && !is_struct) {
2837 "New invocation: Can not find a constructor for " +
2838 "this argument list");
2842 eclass = ExprClass.Value;
2847 // This DoEmit can be invoked in two contexts:
2848 // * As a mechanism that will leave a value on the stack (new object)
2849 // * As one that wont (init struct)
2851 // You can control whether a value is required on the stack by passing
2852 // need_value_on_stack. The code *might* leave a value on the stack
2853 // so it must be popped manually
2855 // Returns whether a value is left on the stack
2857 bool DoEmit (EmitContext ec, bool need_value_on_stack)
2859 if (method == null){
2860 IMemoryLocation ml = (IMemoryLocation) value_target;
2864 Invocation.EmitArguments (ec, method, Arguments);
2865 ec.ig.Emit (OpCodes.Newobj, (ConstructorInfo) method);
2870 // It must be a value type, sanity check
2872 if (value_target != null){
2873 ec.ig.Emit (OpCodes.Initobj, type);
2875 if (need_value_on_stack){
2876 value_target.Emit (ec);
2882 throw new Exception ("No method and no value type");
2885 public override void Emit (EmitContext ec)
2890 public override void EmitStatement (EmitContext ec)
2892 if (DoEmit (ec, false))
2893 ec.ig.Emit (OpCodes.Pop);
2898 /// Represents an array creation expression.
2902 /// There are two possible scenarios here: one is an array creation
2903 /// expression that specifies the dimensions and optionally the
2904 /// initialization data
2906 public class ArrayCreation : ExpressionStatement {
2908 string RequestedType;
2910 ArrayList Initializers;
2912 ArrayList Arguments;
2914 MethodBase method = null;
2915 Type array_element_type;
2916 bool IsOneDimensional = false;
2918 bool IsBuiltinType = false;
2921 Type underlying_type;
2923 ArrayList ArrayData;
2925 public ArrayCreation (string requested_type, ArrayList exprs,
2926 string rank, ArrayList initializers, Location l)
2928 RequestedType = requested_type;
2930 Initializers = initializers;
2933 Arguments = new ArrayList ();
2935 foreach (Expression e in exprs)
2936 Arguments.Add (new Argument (e, Argument.AType.Expression));
2940 public ArrayCreation (string requested_type, string rank, ArrayList initializers, Location l)
2942 RequestedType = requested_type;
2943 Initializers = initializers;
2946 Rank = rank.Substring (0, rank.LastIndexOf ("["));
2948 string tmp = rank.Substring (rank.LastIndexOf ("["));
2950 dimensions = tmp.Length - 1;
2953 public static string FormArrayType (string base_type, int idx_count, string rank)
2955 StringBuilder sb = new StringBuilder (base_type);
2960 for (int i = 1; i < idx_count; i++)
2964 return sb.ToString ();
2967 public static string FormElementType (string base_type, int idx_count, string rank)
2969 StringBuilder sb = new StringBuilder (base_type);
2972 for (int i = 1; i < idx_count; i++)
2978 string val = sb.ToString ();
2980 return val.Substring (0, val.LastIndexOf ("["));
2985 Report.Error (178, loc, "Incorrectly structured array initializer");
2988 public bool CheckIndices (EmitContext ec, ArrayList probe, int idx,
2989 bool require_constant, bool specified_dims)
2991 foreach (object o in probe) {
2993 if (o is ArrayList) {
2995 if (specified_dims) {
2996 Argument a = (Argument) Arguments [idx];
2998 if (!a.Resolve (ec, loc))
3001 Expression e = Expression.Reduce (ec, a.Expr);
3003 if (!(e is Literal) && require_constant) {
3004 Report.Error (150, loc, "A constant value is expected");
3008 int value = (int) ((Literal) e).GetValue ();
3010 if (value != probe.Count) {
3016 bool ret = CheckIndices (ec, (ArrayList) o, ++idx,
3017 require_constant, specified_dims);
3023 Expression tmp = (Expression) o;
3024 tmp = tmp.Resolve (ec);
3025 tmp = Expression.Reduce (ec, tmp);
3027 if (!(tmp is Literal) && require_constant) {
3028 Report.Error (150, loc, "A constant value is expected");
3032 Expression conv = ConvertImplicitRequired (ec, tmp,
3033 underlying_type, loc);
3038 ArrayData.Add (((Literal) tmp).GetValue ());
3045 public void UpdateIndices (EmitContext ec)
3047 for (ArrayList probe = Initializers; probe != null;) {
3049 if (probe [0] is ArrayList) {
3050 Expression e = new IntLiteral (probe.Count);
3051 Arguments.Add (new Argument (e, Argument.AType.Expression));
3053 probe = (ArrayList) probe [0];
3056 Expression e = new IntLiteral (probe.Count);
3057 Arguments.Add (new Argument (e, Argument.AType.Expression));
3065 public bool ValidateInitializers (EmitContext ec)
3067 if (Initializers == null)
3070 underlying_type = ec.TypeContainer.LookupType (RequestedType, false);
3073 // We use this to store all the date values in the order in which we
3074 // will need to store them in the byte blob later
3076 ArrayData = new ArrayList ();
3080 if (Arguments != null) {
3081 ret = CheckIndices (ec, Initializers, 0, true, true);
3085 Arguments = new ArrayList ();
3087 ret = CheckIndices (ec, Initializers, 0, true, false);
3094 if (Arguments.Count != dimensions) {
3103 public override Expression DoResolve (EmitContext ec)
3107 if (!ValidateInitializers (ec))
3110 if (Arguments == null)
3113 arg_count = Arguments.Count;
3115 string array_type = FormArrayType (RequestedType, arg_count, Rank);
3117 string element_type = FormElementType (RequestedType, arg_count, Rank);
3119 type = ec.TypeContainer.LookupType (array_type, false);
3121 array_element_type = ec.TypeContainer.LookupType (element_type, false);
3126 if (arg_count == 1) {
3127 IsOneDimensional = true;
3128 eclass = ExprClass.Value;
3132 IsBuiltinType = TypeManager.IsBuiltinType (type);
3134 if (IsBuiltinType) {
3138 ml = MemberLookup (ec, type, ".ctor", false, MemberTypes.Constructor,
3139 AllBindingsFlags, loc);
3141 if (!(ml is MethodGroupExpr)){
3142 report118 (loc, ml, "method group");
3147 Report.Error (-6, loc, "New invocation: Can not find a constructor for " +
3148 "this argument list");
3152 if (Arguments != null) {
3153 for (int i = arg_count; i > 0;){
3155 Argument a = (Argument) Arguments [i];
3157 if (!a.Resolve (ec, loc))
3162 method = Invocation.OverloadResolve (ec, (MethodGroupExpr) ml, Arguments, loc);
3164 if (method == null) {
3165 Report.Error (-6, loc, "New invocation: Can not find a constructor for " +
3166 "this argument list");
3170 eclass = ExprClass.Value;
3175 ModuleBuilder mb = ec.TypeContainer.RootContext.ModuleBuilder;
3177 ArrayList args = new ArrayList ();
3178 if (Arguments != null){
3179 for (int i = arg_count; i > 0;){
3181 Argument a = (Argument) Arguments [i];
3183 if (!a.Resolve (ec, loc))
3190 Type [] arg_types = null;
3193 arg_types = new Type [args.Count];
3195 args.CopyTo (arg_types, 0);
3197 method = mb.GetArrayMethod (type, ".ctor", CallingConventions.HasThis, null,
3200 if (method == null) {
3201 Report.Error (-6, loc, "New invocation: Can not find a constructor for " +
3202 "this argument list");
3206 eclass = ExprClass.Value;
3212 public static byte [] MakeByteBlob (ArrayList ArrayData, Type underlying_type, Location loc)
3217 int count = ArrayData.Count;
3219 if (underlying_type == TypeManager.int32_type ||
3220 underlying_type == TypeManager.uint32_type ||
3221 underlying_type == TypeManager.float_type)
3223 else if (underlying_type == TypeManager.int64_type ||
3224 underlying_type == TypeManager.uint64_type ||
3225 underlying_type == TypeManager.double_type)
3227 else if (underlying_type == TypeManager.byte_type ||
3228 underlying_type == TypeManager.sbyte_type ||
3229 underlying_type == TypeManager.char_type ||
3230 underlying_type == TypeManager.bool_type)
3232 else if (underlying_type == TypeManager.short_type ||
3233 underlying_type == TypeManager.ushort_type)
3236 Report.Error (-100, loc, "Unhandled type in MakeByteBlob!!");
3240 data = new byte [count * factor];
3242 for (int i = 0; i < count; ++i) {
3243 int val = (int) ArrayData [i];
3244 for (int j = 0; j < factor; ++j) {
3245 data [(i * factor) + j] = (byte) (val & 0xFF);
3253 public override void Emit (EmitContext ec)
3255 ILGenerator ig = ec.ig;
3257 if (IsOneDimensional) {
3258 Invocation.EmitArguments (ec, null, Arguments);
3259 ig.Emit (OpCodes.Newarr, array_element_type);
3262 Invocation.EmitArguments (ec, null, Arguments);
3265 ig.Emit (OpCodes.Newobj, (ConstructorInfo) method);
3267 ig.Emit (OpCodes.Newobj, (MethodInfo) method);
3270 if (Initializers != null) {
3273 byte [] data = MakeByteBlob (ArrayData, underlying_type, loc);
3276 fb = ec.TypeContainer.RootContext.MakeStaticData (data);
3278 ig.Emit (OpCodes.Dup);
3279 ig.Emit (OpCodes.Ldtoken, fb);
3280 ig.Emit (OpCodes.Call, TypeManager.void_initializearray_array_fieldhandle);
3285 public override void EmitStatement (EmitContext ec)
3288 ec.ig.Emit (OpCodes.Pop);
3294 /// Represents the `this' construct
3296 public class This : Expression, IAssignMethod, IMemoryLocation {
3299 public This (Location loc)
3304 public override Expression DoResolve (EmitContext ec)
3306 eclass = ExprClass.Variable;
3307 type = ec.TypeContainer.TypeBuilder;
3310 Report.Error (26, loc,
3311 "Keyword this not valid in static code");
3318 public Expression DoResolveLValue (EmitContext ec)
3322 if (ec.TypeContainer is Class){
3323 Report.Error (1604, loc, "Cannot assign to `this'");
3330 public override void Emit (EmitContext ec)
3332 ec.ig.Emit (OpCodes.Ldarg_0);
3335 public void EmitAssign (EmitContext ec, Expression source)
3338 ec.ig.Emit (OpCodes.Starg, 0);
3341 public void AddressOf (EmitContext ec)
3343 ec.ig.Emit (OpCodes.Ldarga_S, (byte) 0);
3348 /// Implements the typeof operator
3350 public class TypeOf : Expression {
3351 public readonly string QueriedType;
3354 public TypeOf (string queried_type)
3356 QueriedType = queried_type;
3359 public override Expression DoResolve (EmitContext ec)
3361 typearg = ec.TypeContainer.LookupType (QueriedType, false);
3363 if (typearg == null)
3366 type = TypeManager.type_type;
3367 eclass = ExprClass.Type;
3371 public override void Emit (EmitContext ec)
3373 ec.ig.Emit (OpCodes.Ldtoken, typearg);
3374 ec.ig.Emit (OpCodes.Call, TypeManager.system_type_get_type_from_handle);
3379 /// Implements the sizeof expression
3381 public class SizeOf : Expression {
3382 public readonly string QueriedType;
3384 public SizeOf (string queried_type)
3386 this.QueriedType = queried_type;
3389 public override Expression DoResolve (EmitContext ec)
3391 // FIXME: Implement;
3392 throw new Exception ("Unimplemented");
3396 public override void Emit (EmitContext ec)
3398 throw new Exception ("Implement me");
3403 /// Implements the member access expression
3405 public class MemberAccess : Expression {
3406 public readonly string Identifier;
3408 Expression member_lookup;
3411 public MemberAccess (Expression expr, string id, Location l)
3418 public Expression Expr {
3424 void error176 (Location loc, string name)
3426 Report.Error (176, loc, "Static member `" +
3427 name + "' cannot be accessed " +
3428 "with an instance reference, qualify with a " +
3429 "type name instead");
3432 public override Expression DoResolve (EmitContext ec)
3435 // We are the sole users of ResolveWithSimpleName (ie, the only
3436 // ones that can cope with it
3438 expr = expr.ResolveWithSimpleName (ec);
3443 if (expr is SimpleName){
3444 SimpleName child_expr = (SimpleName) expr;
3446 expr = new SimpleName (child_expr.Name + "." + Identifier, loc);
3448 return expr.Resolve (ec);
3451 member_lookup = MemberLookup (ec, expr.Type, Identifier, false, loc);
3453 if (member_lookup == null)
3459 if (member_lookup is MethodGroupExpr){
3460 MethodGroupExpr mg = (MethodGroupExpr) member_lookup;
3465 if (expr is TypeExpr){
3466 if (!mg.RemoveInstanceMethods ()){
3467 SimpleName.Error120 (loc, mg.Methods [0].Name);
3471 return member_lookup;
3475 // Instance.MethodGroup
3477 if (!mg.RemoveStaticMethods ()){
3478 error176 (loc, mg.Methods [0].Name);
3482 mg.InstanceExpression = expr;
3484 return member_lookup;
3487 if (member_lookup is FieldExpr){
3488 FieldExpr fe = (FieldExpr) member_lookup;
3489 FieldInfo fi = fe.FieldInfo;
3492 Type t = fi.FieldType;
3493 Type decl_type = fi.DeclaringType;
3496 if (fi is FieldBuilder)
3497 o = TypeManager.GetValue ((FieldBuilder) fi);
3499 o = fi.GetValue (fi);
3501 if (decl_type.IsSubclassOf (TypeManager.enum_type)) {
3502 Expression enum_member = MemberLookup (ec, decl_type, "value__",
3505 Enum en = TypeManager.LookupEnum (decl_type);
3509 e = Literalize (o, en.UnderlyingType);
3511 e = Literalize (o, enum_member.Type);
3514 return new EnumLiteral (e, decl_type);
3517 Expression exp = Literalize (o, t);
3523 if (expr is TypeExpr){
3524 if (!fe.FieldInfo.IsStatic){
3525 error176 (loc, fe.FieldInfo.Name);
3528 return member_lookup;
3530 if (fe.FieldInfo.IsStatic){
3531 error176 (loc, fe.FieldInfo.Name);
3534 fe.InstanceExpression = expr;
3540 if (member_lookup is PropertyExpr){
3541 PropertyExpr pe = (PropertyExpr) member_lookup;
3543 if (expr is TypeExpr){
3545 SimpleName.Error120 (loc, pe.PropertyInfo.Name);
3551 error176 (loc, pe.PropertyInfo.Name);
3554 pe.InstanceExpression = expr;
3560 Console.WriteLine ("Support for [" + member_lookup + "] is not present yet");
3561 Environment.Exit (0);
3565 public override void Emit (EmitContext ec)
3567 throw new Exception ("Should not happen I think");
3572 /// Implements checked expressions
3574 public class CheckedExpr : Expression {
3576 public Expression Expr;
3578 public CheckedExpr (Expression e)
3583 public override Expression DoResolve (EmitContext ec)
3585 Expr = Expr.Resolve (ec);
3590 eclass = Expr.ExprClass;
3595 public override void Emit (EmitContext ec)
3597 bool last_check = ec.CheckState;
3599 ec.CheckState = true;
3601 ec.CheckState = last_check;
3607 /// Implements the unchecked expression
3609 public class UnCheckedExpr : Expression {
3611 public Expression Expr;
3613 public UnCheckedExpr (Expression e)
3618 public override Expression DoResolve (EmitContext ec)
3620 Expr = Expr.Resolve (ec);
3625 eclass = Expr.ExprClass;
3630 public override void Emit (EmitContext ec)
3632 bool last_check = ec.CheckState;
3634 ec.CheckState = false;
3636 ec.CheckState = last_check;
3642 /// An Element Access expression. During semantic
3643 /// analysis these are transformed into IndexerAccess or
3644 /// ArrayAccess expressions
3646 public class ElementAccess : Expression {
3647 public ArrayList Arguments;
3648 public Expression Expr;
3649 public Location loc;
3651 public ElementAccess (Expression e, ArrayList e_list, Location l)
3655 Arguments = new ArrayList ();
3656 foreach (Expression tmp in e_list)
3657 Arguments.Add (new Argument (tmp, Argument.AType.Expression));
3662 bool CommonResolve (EmitContext ec)
3664 Expr = Expr.Resolve (ec);
3669 if (Arguments == null)
3672 for (int i = Arguments.Count; i > 0;){
3674 Argument a = (Argument) Arguments [i];
3676 if (!a.Resolve (ec, loc))
3683 public override Expression DoResolve (EmitContext ec)
3685 if (!CommonResolve (ec))
3689 // We perform some simple tests, and then to "split" the emit and store
3690 // code we create an instance of a different class, and return that.
3692 // I am experimenting with this pattern.
3694 if (Expr.Type.IsSubclassOf (TypeManager.array_type))
3695 return (new ArrayAccess (this)).Resolve (ec);
3697 return (new IndexerAccess (this)).Resolve (ec);
3700 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
3702 if (!CommonResolve (ec))
3705 if (Expr.Type.IsSubclassOf (TypeManager.array_type))
3706 return (new ArrayAccess (this)).ResolveLValue (ec, right_side);
3708 return (new IndexerAccess (this)).ResolveLValue (ec, right_side);
3711 public override void Emit (EmitContext ec)
3713 throw new Exception ("Should never be reached");
3718 /// Implements array access
3720 public class ArrayAccess : Expression, IAssignMethod {
3722 // Points to our "data" repository
3726 public ArrayAccess (ElementAccess ea_data)
3729 eclass = ExprClass.Variable;
3732 public override Expression DoResolve (EmitContext ec)
3734 if (ea.Expr.ExprClass != ExprClass.Variable) {
3735 report118 (ea.loc, ea.Expr, "variable");
3739 Type t = ea.Expr.Type;
3741 if (t.GetArrayRank () != ea.Arguments.Count){
3742 Report.Error (22, ea.loc,
3743 "Incorrect number of indexes for array " +
3744 " expected: " + t.GetArrayRank () + " got: " +
3745 ea.Arguments.Count);
3748 type = t.GetElementType ();
3749 eclass = ExprClass.Variable;
3755 /// Emits the right opcode to load an object of Type `t'
3756 /// from an array of T
3758 static public void EmitLoadOpcode (ILGenerator ig, Type type)
3760 if (type == TypeManager.byte_type)
3761 ig.Emit (OpCodes.Ldelem_I1);
3762 else if (type == TypeManager.sbyte_type)
3763 ig.Emit (OpCodes.Ldelem_U1);
3764 else if (type == TypeManager.short_type)
3765 ig.Emit (OpCodes.Ldelem_I2);
3766 else if (type == TypeManager.ushort_type)
3767 ig.Emit (OpCodes.Ldelem_U2);
3768 else if (type == TypeManager.int32_type)
3769 ig.Emit (OpCodes.Ldelem_I4);
3770 else if (type == TypeManager.uint32_type)
3771 ig.Emit (OpCodes.Ldelem_U4);
3772 else if (type == TypeManager.uint64_type)
3773 ig.Emit (OpCodes.Ldelem_I8);
3774 else if (type == TypeManager.int64_type)
3775 ig.Emit (OpCodes.Ldelem_I8);
3776 else if (type == TypeManager.float_type)
3777 ig.Emit (OpCodes.Ldelem_R4);
3778 else if (type == TypeManager.double_type)
3779 ig.Emit (OpCodes.Ldelem_R8);
3780 else if (type == TypeManager.intptr_type)
3781 ig.Emit (OpCodes.Ldelem_I);
3783 ig.Emit (OpCodes.Ldelem_Ref);
3787 /// Emits the right opcode to store an object of Type `t'
3788 /// from an array of T.
3790 static public void EmitStoreOpcode (ILGenerator ig, Type t)
3792 if (t == TypeManager.byte_type || t == TypeManager.sbyte_type)
3793 ig.Emit (OpCodes.Stelem_I1);
3794 else if (t == TypeManager.short_type || t == TypeManager.ushort_type)
3795 ig.Emit (OpCodes.Stelem_I2);
3796 else if (t == TypeManager.int32_type || t == TypeManager.uint32_type)
3797 ig.Emit (OpCodes.Stelem_I4);
3798 else if (t == TypeManager.int64_type || t == TypeManager.uint64_type)
3799 ig.Emit (OpCodes.Stelem_I8);
3800 else if (t == TypeManager.float_type)
3801 ig.Emit (OpCodes.Stelem_R4);
3802 else if (t == TypeManager.double_type)
3803 ig.Emit (OpCodes.Stelem_R8);
3804 else if (t == TypeManager.intptr_type)
3805 ig.Emit (OpCodes.Stelem_I);
3807 ig.Emit (OpCodes.Stelem_Ref);
3810 public override void Emit (EmitContext ec)
3812 int rank = ea.Expr.Type.GetArrayRank ();
3813 ILGenerator ig = ec.ig;
3817 foreach (Argument a in ea.Arguments)
3821 EmitLoadOpcode (ig, type);
3823 ModuleBuilder mb = ec.TypeContainer.RootContext.ModuleBuilder;
3824 Type [] args = new Type [ea.Arguments.Count];
3829 foreach (Argument a in ea.Arguments)
3830 args [i++] = a.Type;
3832 get = mb.GetArrayMethod (
3833 ea.Expr.Type, "Get",
3834 CallingConventions.HasThis |
3835 CallingConventions.Standard,
3838 ig.Emit (OpCodes.Call, get);
3842 public void EmitAssign (EmitContext ec, Expression source)
3844 int rank = ea.Expr.Type.GetArrayRank ();
3845 ILGenerator ig = ec.ig;
3849 foreach (Argument a in ea.Arguments)
3854 Type t = source.Type;
3856 EmitStoreOpcode (ig, t);
3858 ModuleBuilder mb = ec.TypeContainer.RootContext.ModuleBuilder;
3859 Type [] args = new Type [ea.Arguments.Count + 1];
3864 foreach (Argument a in ea.Arguments)
3865 args [i++] = a.Type;
3869 set = mb.GetArrayMethod (
3870 ea.Expr.Type, "Set",
3871 CallingConventions.HasThis |
3872 CallingConventions.Standard,
3873 TypeManager.void_type, args);
3875 ig.Emit (OpCodes.Call, set);
3882 public ArrayList getters, setters;
3883 static Hashtable map;
3887 map = new Hashtable ();
3890 Indexers (MemberInfo [] mi)
3892 foreach (PropertyInfo property in mi){
3893 MethodInfo get, set;
3895 get = property.GetGetMethod (true);
3897 if (getters == null)
3898 getters = new ArrayList ();
3903 set = property.GetSetMethod (true);
3905 if (setters == null)
3906 setters = new ArrayList ();
3912 static public Indexers GetIndexersForType (Type t, TypeManager tm, Location loc)
3914 Indexers ix = (Indexers) map [t];
3915 string p_name = TypeManager.IndexerPropertyName (t);
3920 MemberInfo [] mi = tm.FindMembers (
3921 t, MemberTypes.Property,
3922 BindingFlags.Public | BindingFlags.Instance,
3923 Type.FilterName, p_name);
3925 if (mi == null || mi.Length == 0){
3926 Report.Error (21, loc,
3927 "Type `" + TypeManager.CSharpName (t) + "' does not have " +
3928 "any indexers defined");
3932 ix = new Indexers (mi);
3940 /// Expressions that represent an indexer call.
3942 public class IndexerAccess : Expression, IAssignMethod {
3944 // Points to our "data" repository
3947 MethodInfo get, set;
3949 ArrayList set_arguments;
3951 public IndexerAccess (ElementAccess ea_data)
3954 eclass = ExprClass.Value;
3957 public override Expression DoResolve (EmitContext ec)
3959 Type indexer_type = ea.Expr.Type;
3962 // Step 1: Query for all `Item' *properties*. Notice
3963 // that the actual methods are pointed from here.
3965 // This is a group of properties, piles of them.
3968 ilist = Indexers.GetIndexersForType (
3969 indexer_type, ec.TypeContainer.RootContext.TypeManager, ea.loc);
3973 // Step 2: find the proper match
3975 if (ilist != null && ilist.getters != null && ilist.getters.Count > 0)
3976 get = (MethodInfo) Invocation.OverloadResolve (
3977 ec, new MethodGroupExpr (ilist.getters), ea.Arguments, ea.loc);
3980 Report.Error (154, ea.loc,
3981 "indexer can not be used in this context, because " +
3982 "it lacks a `get' accessor");
3986 type = get.ReturnType;
3987 eclass = ExprClass.IndexerAccess;
3991 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
3993 Type indexer_type = ea.Expr.Type;
3994 Type right_type = right_side.Type;
3997 ilist = Indexers.GetIndexersForType (
3998 indexer_type, ec.TypeContainer.RootContext.TypeManager, ea.loc);
4000 if (ilist != null && ilist.setters != null && ilist.setters.Count > 0){
4001 set_arguments = (ArrayList) ea.Arguments.Clone ();
4002 set_arguments.Add (new Argument (right_side, Argument.AType.Expression));
4004 set = (MethodInfo) Invocation.OverloadResolve (
4005 ec, new MethodGroupExpr (ilist.setters), set_arguments, ea.loc);
4009 Report.Error (200, ea.loc,
4010 "indexer X.this [" + TypeManager.CSharpName (right_type) +
4011 "] lacks a `set' accessor");
4015 type = TypeManager.void_type;
4016 eclass = ExprClass.IndexerAccess;
4020 public override void Emit (EmitContext ec)
4022 Invocation.EmitCall (ec, false, ea.Expr, get, ea.Arguments);
4026 // source is ignored, because we already have a copy of it from the
4027 // LValue resolution and we have already constructed a pre-cached
4028 // version of the arguments (ea.set_arguments);
4030 public void EmitAssign (EmitContext ec, Expression source)
4032 Invocation.EmitCall (ec, false, ea.Expr, set, set_arguments);
4036 public class BaseAccess : Expression {
4038 public enum BaseAccessType : byte {
4043 public readonly BaseAccessType BAType;
4044 public readonly string Member;
4045 public readonly ArrayList Arguments;
4047 public BaseAccess (BaseAccessType t, string member, ArrayList args)
4055 public override Expression DoResolve (EmitContext ec)
4057 // FIXME: Implement;
4058 throw new Exception ("Unimplemented");
4062 public override void Emit (EmitContext ec)
4064 throw new Exception ("Unimplemented");
4069 /// This class exists solely to pass the Type around and to be a dummy
4070 /// that can be passed to the conversion functions (this is used by
4071 /// foreach implementation to typecast the object return value from
4072 /// get_Current into the proper type. All code has been generated and
4073 /// we only care about the side effect conversions to be performed
4075 public class EmptyExpression : Expression {
4076 public EmptyExpression ()
4078 type = TypeManager.object_type;
4079 eclass = ExprClass.Value;
4082 public EmptyExpression (Type t)
4085 eclass = ExprClass.Value;
4088 public override Expression DoResolve (EmitContext ec)
4093 public override void Emit (EmitContext ec)
4095 // nothing, as we only exist to not do anything.
4099 public class UserCast : Expression {
4103 public UserCast (MethodInfo method, Expression source)
4105 this.method = method;
4106 this.source = source;
4107 type = method.ReturnType;
4108 eclass = ExprClass.Value;
4111 public override Expression DoResolve (EmitContext ec)
4114 // We are born fully resolved
4119 public override void Emit (EmitContext ec)
4121 ILGenerator ig = ec.ig;
4125 if (method is MethodInfo)
4126 ig.Emit (OpCodes.Call, (MethodInfo) method);
4128 ig.Emit (OpCodes.Call, (ConstructorInfo) method);