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 if (oper == Operator.BitwiseAnd ||
1226 oper == Operator.BitwiseOr ||
1227 oper == Operator.ExclusiveOr){
1228 if (!((l == TypeManager.int32_type) ||
1229 (l == TypeManager.uint32_type) ||
1230 (l == TypeManager.int64_type) ||
1231 (l == TypeManager.uint64_type))){
1238 if (oper == Operator.Equality ||
1239 oper == Operator.Inequality ||
1240 oper == Operator.LessThanOrEqual ||
1241 oper == Operator.LessThan ||
1242 oper == Operator.GreaterThanOrEqual ||
1243 oper == Operator.GreaterThan){
1244 type = TypeManager.bool_type;
1250 public override Expression DoResolve (EmitContext ec)
1252 left = left.Resolve (ec);
1253 right = right.Resolve (ec);
1255 if (left == null || right == null)
1258 if (left.Type == null)
1259 throw new Exception (
1260 "Resolve returned non null, but did not set the type! (" +
1261 left + ") at Line: " + loc.Row);
1262 if (right.Type == null)
1263 throw new Exception (
1264 "Resolve returned non null, but did not set the type! (" +
1265 right + ") at Line: "+ loc.Row);
1267 eclass = ExprClass.Value;
1269 return ResolveOperator (ec);
1272 public bool IsBranchable ()
1274 if (oper == Operator.Equality ||
1275 oper == Operator.Inequality ||
1276 oper == Operator.LessThan ||
1277 oper == Operator.GreaterThan ||
1278 oper == Operator.LessThanOrEqual ||
1279 oper == Operator.GreaterThanOrEqual){
1286 /// This entry point is used by routines that might want
1287 /// to emit a brfalse/brtrue after an expression, and instead
1288 /// they could use a more compact notation.
1290 /// Typically the code would generate l.emit/r.emit, followed
1291 /// by the comparission and then a brtrue/brfalse. The comparissions
1292 /// are sometimes inneficient (there are not as complete as the branches
1293 /// look for the hacks in Emit using double ceqs).
1295 /// So for those cases we provide EmitBranchable that can emit the
1296 /// branch with the test
1298 public void EmitBranchable (EmitContext ec, int target)
1301 bool close_target = false;
1307 case Operator.Equality:
1309 opcode = OpCodes.Beq_S;
1311 opcode = OpCodes.Beq;
1314 case Operator.Inequality:
1316 opcode = OpCodes.Bne_Un_S;
1318 opcode = OpCodes.Bne_Un;
1321 case Operator.LessThan:
1323 opcode = OpCodes.Blt_S;
1325 opcode = OpCodes.Blt;
1328 case Operator.GreaterThan:
1330 opcode = OpCodes.Bgt_S;
1332 opcode = OpCodes.Bgt;
1335 case Operator.LessThanOrEqual:
1337 opcode = OpCodes.Ble_S;
1339 opcode = OpCodes.Ble;
1342 case Operator.GreaterThanOrEqual:
1344 opcode = OpCodes.Bge_S;
1346 opcode = OpCodes.Ble;
1350 throw new Exception ("EmitBranchable called on non-EmitBranchable operator: "
1351 + oper.ToString ());
1354 ec.ig.Emit (opcode, target);
1357 public override void Emit (EmitContext ec)
1359 ILGenerator ig = ec.ig;
1361 Type r = right.Type;
1364 if (method != null) {
1366 // Note that operators are static anyway
1368 if (Arguments != null)
1369 Invocation.EmitArguments (ec, method, Arguments);
1371 if (method is MethodInfo)
1372 ig.Emit (OpCodes.Call, (MethodInfo) method);
1374 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
1383 case Operator.Multiply:
1385 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
1386 opcode = OpCodes.Mul_Ovf;
1387 else if (l==TypeManager.uint32_type || l==TypeManager.uint64_type)
1388 opcode = OpCodes.Mul_Ovf_Un;
1390 opcode = OpCodes.Mul;
1392 opcode = OpCodes.Mul;
1396 case Operator.Division:
1397 if (l == TypeManager.uint32_type || l == TypeManager.uint64_type)
1398 opcode = OpCodes.Div_Un;
1400 opcode = OpCodes.Div;
1403 case Operator.Modulus:
1404 if (l == TypeManager.uint32_type || l == TypeManager.uint64_type)
1405 opcode = OpCodes.Rem_Un;
1407 opcode = OpCodes.Rem;
1410 case Operator.Addition:
1412 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
1413 opcode = OpCodes.Add_Ovf;
1414 else if (l==TypeManager.uint32_type || l==TypeManager.uint64_type)
1415 opcode = OpCodes.Add_Ovf_Un;
1417 opcode = OpCodes.Mul;
1419 opcode = OpCodes.Add;
1422 case Operator.Subtraction:
1424 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
1425 opcode = OpCodes.Sub_Ovf;
1426 else if (l==TypeManager.uint32_type || l==TypeManager.uint64_type)
1427 opcode = OpCodes.Sub_Ovf_Un;
1429 opcode = OpCodes.Sub;
1431 opcode = OpCodes.Sub;
1434 case Operator.RightShift:
1435 opcode = OpCodes.Shr;
1438 case Operator.LeftShift:
1439 opcode = OpCodes.Shl;
1442 case Operator.Equality:
1443 opcode = OpCodes.Ceq;
1446 case Operator.Inequality:
1447 ec.ig.Emit (OpCodes.Ceq);
1448 ec.ig.Emit (OpCodes.Ldc_I4_0);
1450 opcode = OpCodes.Ceq;
1453 case Operator.LessThan:
1454 opcode = OpCodes.Clt;
1457 case Operator.GreaterThan:
1458 opcode = OpCodes.Cgt;
1461 case Operator.LessThanOrEqual:
1462 ec.ig.Emit (OpCodes.Cgt);
1463 ec.ig.Emit (OpCodes.Ldc_I4_0);
1465 opcode = OpCodes.Ceq;
1468 case Operator.GreaterThanOrEqual:
1469 ec.ig.Emit (OpCodes.Clt);
1470 ec.ig.Emit (OpCodes.Ldc_I4_1);
1472 opcode = OpCodes.Sub;
1475 case Operator.LogicalOr:
1476 case Operator.BitwiseOr:
1477 opcode = OpCodes.Or;
1480 case Operator.LogicalAnd:
1481 case Operator.BitwiseAnd:
1482 opcode = OpCodes.And;
1485 case Operator.ExclusiveOr:
1486 opcode = OpCodes.Xor;
1490 throw new Exception ("This should not happen: Operator = "
1491 + oper.ToString ());
1498 /// Constant expression reducer for binary operations
1500 public override Expression Reduce (EmitContext ec)
1503 left = left.Reduce (ec);
1504 right = right.Reduce (ec);
1506 if (!(left is Literal && right is Literal))
1509 if (method == TypeManager.string_concat_string_string){
1510 StringLiteral ls = (StringLiteral) left;
1511 StringLiteral rs = (StringLiteral) right;
1513 return new StringLiteral (ls.Value + rs.Value);
1522 public class Conditional : Expression {
1523 Expression expr, trueExpr, falseExpr;
1526 public Conditional (Expression expr, Expression trueExpr, Expression falseExpr, Location l)
1529 this.trueExpr = trueExpr;
1530 this.falseExpr = falseExpr;
1534 public Expression Expr {
1540 public Expression TrueExpr {
1546 public Expression FalseExpr {
1552 public override Expression DoResolve (EmitContext ec)
1554 expr = expr.Resolve (ec);
1556 if (expr.Type != TypeManager.bool_type)
1557 expr = Expression.ConvertImplicitRequired (
1558 ec, expr, TypeManager.bool_type, loc);
1560 trueExpr = trueExpr.Resolve (ec);
1561 falseExpr = falseExpr.Resolve (ec);
1563 if (expr == null || trueExpr == null || falseExpr == null)
1566 if (trueExpr.Type == falseExpr.Type)
1567 type = trueExpr.Type;
1572 // First, if an implicit conversion exists from trueExpr
1573 // to falseExpr, then the result type is of type falseExpr.Type
1575 conv = ConvertImplicit (ec, trueExpr, falseExpr.Type, loc);
1577 type = falseExpr.Type;
1579 } else if ((conv = ConvertImplicit(ec, falseExpr,trueExpr.Type,loc))!= null){
1580 type = trueExpr.Type;
1583 Error (173, loc, "The type of the conditional expression can " +
1584 "not be computed because there is no implicit conversion" +
1585 " from `" + TypeManager.CSharpName (trueExpr.Type) + "'" +
1586 " and `" + TypeManager.CSharpName (falseExpr.Type) + "'");
1591 if (expr is BoolLiteral){
1592 BoolLiteral bl = (BoolLiteral) expr;
1600 eclass = ExprClass.Value;
1604 public override void Emit (EmitContext ec)
1606 ILGenerator ig = ec.ig;
1607 Label false_target = ig.DefineLabel ();
1608 Label end_target = ig.DefineLabel ();
1611 ig.Emit (OpCodes.Brfalse, false_target);
1613 ig.Emit (OpCodes.Br, end_target);
1614 ig.MarkLabel (false_target);
1615 falseExpr.Emit (ec);
1616 ig.MarkLabel (end_target);
1619 public override Expression Reduce (EmitContext ec)
1621 expr = expr.Reduce (ec);
1622 trueExpr = trueExpr.Reduce (ec);
1623 falseExpr = falseExpr.Reduce (ec);
1625 if (!(expr is Literal && trueExpr is Literal && falseExpr is Literal))
1628 BoolLiteral bl = (BoolLiteral) expr;
1637 public class LocalVariableReference : Expression, IAssignMethod, IMemoryLocation {
1638 public readonly string Name;
1639 public readonly Block Block;
1641 VariableInfo variable_info;
1643 public LocalVariableReference (Block block, string name)
1647 eclass = ExprClass.Variable;
1650 public VariableInfo VariableInfo {
1652 if (variable_info == null)
1653 variable_info = Block.GetVariableInfo (Name);
1654 return variable_info;
1658 public override Expression DoResolve (EmitContext ec)
1660 VariableInfo vi = VariableInfo;
1662 type = vi.VariableType;
1666 public override void Emit (EmitContext ec)
1668 VariableInfo vi = VariableInfo;
1669 ILGenerator ig = ec.ig;
1676 ig.Emit (OpCodes.Ldloc_0);
1680 ig.Emit (OpCodes.Ldloc_1);
1684 ig.Emit (OpCodes.Ldloc_2);
1688 ig.Emit (OpCodes.Ldloc_3);
1693 ig.Emit (OpCodes.Ldloc_S, (byte) idx);
1695 ig.Emit (OpCodes.Ldloc, idx);
1700 public static void Store (ILGenerator ig, int idx)
1704 ig.Emit (OpCodes.Stloc_0);
1708 ig.Emit (OpCodes.Stloc_1);
1712 ig.Emit (OpCodes.Stloc_2);
1716 ig.Emit (OpCodes.Stloc_3);
1721 ig.Emit (OpCodes.Stloc_S, (byte) idx);
1723 ig.Emit (OpCodes.Stloc, idx);
1728 public void EmitAssign (EmitContext ec, Expression source)
1730 ILGenerator ig = ec.ig;
1731 VariableInfo vi = VariableInfo;
1737 // Funny seems the code below generates optimal code for us, but
1738 // seems to take too long to generate what we need.
1739 // ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
1744 public void AddressOf (EmitContext ec)
1746 VariableInfo vi = VariableInfo;
1753 ec.ig.Emit (OpCodes.Ldloca_S, (byte) idx);
1755 ec.ig.Emit (OpCodes.Ldloca, idx);
1760 /// This represents a reference to a parameter in the intermediate
1763 public class ParameterReference : Expression, IAssignMethod, IMemoryLocation {
1764 public readonly Parameters Pars;
1765 public readonly String Name;
1766 public readonly int Idx;
1769 public ParameterReference (Parameters pars, int idx, string name)
1774 eclass = ExprClass.Variable;
1777 public override Expression DoResolve (EmitContext ec)
1779 Type [] types = Pars.GetParameterInfo (ec.TypeContainer);
1790 public override void Emit (EmitContext ec)
1793 ec.ig.Emit (OpCodes.Ldarg_S, (byte) arg_idx);
1795 ec.ig.Emit (OpCodes.Ldarg, arg_idx);
1798 public void EmitAssign (EmitContext ec, Expression source)
1803 ec.ig.Emit (OpCodes.Starg_S, (byte) arg_idx);
1805 ec.ig.Emit (OpCodes.Starg, arg_idx);
1809 public void AddressOf (EmitContext ec)
1812 ec.ig.Emit (OpCodes.Ldarga_S, (byte) arg_idx);
1814 ec.ig.Emit (OpCodes.Ldarga, arg_idx);
1819 /// Used for arguments to New(), Invocation()
1821 public class Argument {
1822 public enum AType : byte {
1828 public readonly AType ArgType;
1829 public Expression expr;
1831 public Argument (Expression expr, AType type)
1834 this.ArgType = type;
1837 public Expression Expr {
1853 public Parameter.Modifier GetParameterModifier ()
1855 if (ArgType == AType.Ref)
1856 return Parameter.Modifier.REF;
1858 if (ArgType == AType.Out)
1859 return Parameter.Modifier.OUT;
1861 return Parameter.Modifier.NONE;
1864 public static string FullDesc (Argument a)
1866 return (a.ArgType == AType.Ref ? "ref " :
1867 (a.ArgType == AType.Out ? "out " : "")) +
1868 TypeManager.CSharpName (a.Expr.Type);
1871 public bool Resolve (EmitContext ec, Location loc)
1873 expr = expr.Resolve (ec);
1875 if (ArgType == AType.Expression)
1876 return expr != null;
1878 if (expr.ExprClass != ExprClass.Variable){
1879 Report.Error (206, loc,
1880 "A property or indexer can not be passed as an out or ref " +
1885 return expr != null;
1888 public void Emit (EmitContext ec)
1890 if (ArgType == AType.Ref || ArgType == AType.Out)
1891 ((IMemoryLocation)expr).AddressOf (ec);
1898 /// Invocation of methods or delegates.
1900 public class Invocation : ExpressionStatement {
1901 public readonly ArrayList Arguments;
1905 MethodBase method = null;
1907 static Hashtable method_parameter_cache;
1909 static Invocation ()
1911 method_parameter_cache = new Hashtable ();
1915 // arguments is an ArrayList, but we do not want to typecast,
1916 // as it might be null.
1918 // FIXME: only allow expr to be a method invocation or a
1919 // delegate invocation (7.5.5)
1921 public Invocation (Expression expr, ArrayList arguments, Location l)
1924 Arguments = arguments;
1928 public Expression Expr {
1935 /// Returns the Parameters (a ParameterData interface) for the
1938 public static ParameterData GetParameterData (MethodBase mb)
1940 object pd = method_parameter_cache [mb];
1944 return (ParameterData) pd;
1947 ip = TypeContainer.LookupParametersByBuilder (mb);
1949 method_parameter_cache [mb] = ip;
1951 return (ParameterData) ip;
1953 ParameterInfo [] pi = mb.GetParameters ();
1954 ReflectionParameters rp = new ReflectionParameters (pi);
1955 method_parameter_cache [mb] = rp;
1957 return (ParameterData) rp;
1962 /// Tells whether a user defined conversion from Type `from' to
1963 /// Type `to' exists.
1965 /// FIXME: we could implement a cache here.
1967 static bool ConversionExists (EmitContext ec, Type from, Type to, Location loc)
1969 // Locate user-defined implicit operators
1973 mg = MemberLookup (ec, to, "op_Implicit", false, loc);
1976 MethodGroupExpr me = (MethodGroupExpr) mg;
1978 for (int i = me.Methods.Length; i > 0;) {
1980 MethodBase mb = me.Methods [i];
1981 ParameterData pd = GetParameterData (mb);
1983 if (from == pd.ParameterType (0))
1988 mg = MemberLookup (ec, from, "op_Implicit", false, loc);
1991 MethodGroupExpr me = (MethodGroupExpr) mg;
1993 for (int i = me.Methods.Length; i > 0;) {
1995 MethodBase mb = me.Methods [i];
1996 MethodInfo mi = (MethodInfo) mb;
1998 if (mi.ReturnType == to)
2007 /// Determines "better conversion" as specified in 7.4.2.3
2008 /// Returns : 1 if a->p is better
2009 /// 0 if a->q or neither is better
2011 static int BetterConversion (EmitContext ec, Argument a, Type p, Type q, bool use_standard,
2014 Type argument_type = a.Type;
2015 Expression argument_expr = a.Expr;
2017 if (argument_type == null)
2018 throw new Exception ("Expression of type " + a.Expr + " does not resolve its type");
2023 if (argument_type == p)
2026 if (argument_type == q)
2030 // Now probe whether an implicit constant expression conversion
2033 // An implicit constant expression conversion permits the following
2036 // * A constant-expression of type `int' can be converted to type
2037 // sbyte, byute, short, ushort, uint, ulong provided the value of
2038 // of the expression is withing the range of the destination type.
2040 // * A constant-expression of type long can be converted to type
2041 // ulong, provided the value of the constant expression is not negative
2043 // FIXME: Note that this assumes that constant folding has
2044 // taken place. We dont do constant folding yet.
2047 if (argument_expr is IntLiteral){
2048 IntLiteral ei = (IntLiteral) argument_expr;
2049 int value = ei.Value;
2051 if (p == TypeManager.sbyte_type){
2052 if (value >= SByte.MinValue && value <= SByte.MaxValue)
2054 } else if (p == TypeManager.byte_type){
2055 if (Byte.MinValue >= 0 && value <= Byte.MaxValue)
2057 } else if (p == TypeManager.short_type){
2058 if (value >= Int16.MinValue && value <= Int16.MaxValue)
2060 } else if (p == TypeManager.ushort_type){
2061 if (value >= UInt16.MinValue && value <= UInt16.MaxValue)
2063 } else if (p == TypeManager.uint32_type){
2065 // we can optimize this case: a positive int32
2066 // always fits on a uint32
2070 } else if (p == TypeManager.uint64_type){
2072 // we can optimize this case: a positive int32
2073 // always fits on a uint64
2078 } else if (argument_type == TypeManager.int64_type && argument_expr is LongLiteral){
2079 LongLiteral ll = (LongLiteral) argument_expr;
2081 if (p == TypeManager.uint64_type){
2092 tmp = ConvertImplicitStandard (ec, argument_expr, p, loc);
2094 tmp = ConvertImplicit (ec, argument_expr, p, loc);
2103 if (ConversionExists (ec, p, q, loc) == true &&
2104 ConversionExists (ec, q, p, loc) == false)
2107 if (p == TypeManager.sbyte_type)
2108 if (q == TypeManager.byte_type || q == TypeManager.ushort_type ||
2109 q == TypeManager.uint32_type || q == TypeManager.uint64_type)
2112 if (p == TypeManager.short_type)
2113 if (q == TypeManager.ushort_type || q == TypeManager.uint32_type ||
2114 q == TypeManager.uint64_type)
2117 if (p == TypeManager.int32_type)
2118 if (q == TypeManager.uint32_type || q == TypeManager.uint64_type)
2121 if (p == TypeManager.int64_type)
2122 if (q == TypeManager.uint64_type)
2129 /// Determines "Better function"
2132 /// and returns an integer indicating :
2133 /// 0 if candidate ain't better
2134 /// 1 if candidate is better than the current best match
2136 static int BetterFunction (EmitContext ec, ArrayList args,
2137 MethodBase candidate, MethodBase best,
2138 bool use_standard, Location loc)
2140 ParameterData candidate_pd = GetParameterData (candidate);
2141 ParameterData best_pd;
2147 argument_count = args.Count;
2149 if (candidate_pd.Count == 0 && argument_count == 0)
2153 if (candidate_pd.Count == argument_count) {
2155 for (int j = argument_count; j > 0;) {
2158 Argument a = (Argument) args [j];
2160 x = BetterConversion (
2161 ec, a, candidate_pd.ParameterType (j), null,
2177 best_pd = GetParameterData (best);
2179 if (candidate_pd.Count == argument_count && best_pd.Count == argument_count) {
2180 int rating1 = 0, rating2 = 0;
2182 for (int j = argument_count; j > 0;) {
2186 Argument a = (Argument) args [j];
2188 x = BetterConversion (ec, a, candidate_pd.ParameterType (j),
2189 best_pd.ParameterType (j), use_standard, loc);
2190 y = BetterConversion (ec, a, best_pd.ParameterType (j),
2191 candidate_pd.ParameterType (j), use_standard,
2198 if (rating1 > rating2)
2207 public static string FullMethodDesc (MethodBase mb)
2209 StringBuilder sb = new StringBuilder (mb.Name);
2210 ParameterData pd = GetParameterData (mb);
2212 int count = pd.Count;
2215 for (int i = count; i > 0; ) {
2218 sb.Append (pd.ParameterDesc (count - i - 1));
2224 return sb.ToString ();
2227 public static MethodGroupExpr MakeUnionSet (Expression mg1, Expression mg2)
2229 MemberInfo [] miset;
2230 MethodGroupExpr union;
2232 if (mg1 != null && mg2 != null) {
2234 MethodGroupExpr left_set = null, right_set = null;
2235 int length1 = 0, length2 = 0;
2237 left_set = (MethodGroupExpr) mg1;
2238 length1 = left_set.Methods.Length;
2240 right_set = (MethodGroupExpr) mg2;
2241 length2 = right_set.Methods.Length;
2243 ArrayList common = new ArrayList ();
2245 for (int i = 0; i < left_set.Methods.Length; i++) {
2246 for (int j = 0; j < right_set.Methods.Length; j++) {
2247 if (left_set.Methods [i] == right_set.Methods [j])
2248 common.Add (left_set.Methods [i]);
2252 miset = new MemberInfo [length1 + length2 - common.Count];
2254 left_set.Methods.CopyTo (miset, 0);
2258 for (int j = 0; j < right_set.Methods.Length; j++)
2259 if (!common.Contains (right_set.Methods [j]))
2260 miset [length1 + k++] = right_set.Methods [j];
2262 union = new MethodGroupExpr (miset);
2266 } else if (mg1 == null && mg2 != null) {
2268 MethodGroupExpr me = (MethodGroupExpr) mg2;
2270 miset = new MemberInfo [me.Methods.Length];
2271 me.Methods.CopyTo (miset, 0);
2273 union = new MethodGroupExpr (miset);
2277 } else if (mg2 == null && mg1 != null) {
2279 MethodGroupExpr me = (MethodGroupExpr) mg1;
2281 miset = new MemberInfo [me.Methods.Length];
2282 me.Methods.CopyTo (miset, 0);
2284 union = new MethodGroupExpr (miset);
2293 /// Determines is the candidate method, if a params method, is applicable
2294 /// in its expanded form to the given set of arguments
2296 static bool IsParamsMethodApplicable (ArrayList arguments, MethodBase candidate)
2300 if (arguments == null)
2303 arg_count = arguments.Count;
2305 ParameterData pd = GetParameterData (candidate);
2307 int pd_count = pd.Count;
2309 if (pd.ParameterModifier (pd_count - 1) != Parameter.Modifier.PARAMS)
2312 if (pd_count - 1 > arg_count)
2315 // If we have come this far, the case which remains is when the number of parameters
2316 // is less than or equal to the argument count. So, we now check if the element type
2317 // of the params array is compatible with each argument type
2320 Type element_type = pd.ParameterType (pd_count - 1).GetElementType ();
2322 for (int i = pd_count - 1; i < arg_count - 1; i++) {
2323 Argument a = (Argument) arguments [i];
2324 if (!StandardConversionExists (a.Type, element_type))
2332 /// Determines if the candidate method is applicable (section 14.4.2.1)
2333 /// to the given set of arguments
2335 static bool IsApplicable (ArrayList arguments, MethodBase candidate)
2339 if (arguments == null)
2342 arg_count = arguments.Count;
2344 ParameterData pd = GetParameterData (candidate);
2346 int pd_count = pd.Count;
2348 if (arg_count != pd.Count)
2351 for (int i = arg_count; i > 0; ) {
2354 Argument a = (Argument) arguments [i];
2356 Parameter.Modifier a_mod = a.GetParameterModifier ();
2357 Parameter.Modifier p_mod = pd.ParameterModifier (i);
2359 if (a_mod == p_mod) {
2361 if (a_mod == Parameter.Modifier.NONE)
2362 if (!StandardConversionExists (a.Type, pd.ParameterType (i)))
2365 if (a_mod == Parameter.Modifier.REF ||
2366 a_mod == Parameter.Modifier.OUT)
2367 if (pd.ParameterType (i) != a.Type)
2379 /// Find the Applicable Function Members (7.4.2.1)
2381 /// me: Method Group expression with the members to select.
2382 /// it might contain constructors or methods (or anything
2383 /// that maps to a method).
2385 /// Arguments: ArrayList containing resolved Argument objects.
2387 /// loc: The location if we want an error to be reported, or a Null
2388 /// location for "probing" purposes.
2390 /// use_standard: controls whether OverloadResolve should use the
2391 /// ConvertImplicit or ConvertImplicitStandard during overload resolution.
2393 /// Returns: The MethodBase (either a ConstructorInfo or a MethodInfo)
2394 /// that is the best match of me on Arguments.
2397 public static MethodBase OverloadResolve (EmitContext ec, MethodGroupExpr me,
2398 ArrayList Arguments, Location loc,
2401 ArrayList afm = new ArrayList ();
2402 int best_match_idx = -1;
2403 MethodBase method = null;
2406 for (int i = me.Methods.Length; i > 0; ){
2408 MethodBase candidate = me.Methods [i];
2411 // Check if candidate is applicable (section 14.4.2.1)
2412 if (!IsApplicable (Arguments, candidate))
2415 x = BetterFunction (ec, Arguments, candidate, method, use_standard, loc);
2421 method = me.Methods [best_match_idx];
2425 if (Arguments == null)
2428 argument_count = Arguments.Count;
2431 // Now we see if we can find params functions, applicable in their expanded form
2432 // since if they were applicable in their normal form, they would have been selected
2435 if (best_match_idx == -1) {
2437 for (int i = me.Methods.Length; i > 0; ) {
2439 MethodBase candidate = me.Methods [i];
2441 if (IsParamsMethodApplicable (Arguments, candidate)) {
2443 method = me.Methods [best_match_idx];
2450 // Now we see if we can at least find a method with the same number of arguments
2454 if (best_match_idx == -1) {
2456 for (int i = me.Methods.Length; i > 0;) {
2458 MethodBase mb = me.Methods [i];
2459 pd = GetParameterData (mb);
2461 if (pd.Count == argument_count) {
2463 method = me.Methods [best_match_idx];
2473 // And now convert implicitly, each argument to the required type
2475 pd = GetParameterData (method);
2476 int pd_count = pd.Count;
2478 for (int j = 0; j < argument_count; j++) {
2480 Argument a = (Argument) Arguments [j];
2481 Expression a_expr = a.Expr;
2482 Type parameter_type = pd.ParameterType (j);
2485 // Note that we need to compare against the element type
2486 // when we have a params method
2488 if (pd.ParameterModifier (pd_count - 1) == Parameter.Modifier.PARAMS) {
2489 if (j >= pd_count - 1)
2490 parameter_type = pd.ParameterType (pd_count - 1).GetElementType ();
2493 if (a.Type != parameter_type){
2497 conv = ConvertImplicitStandard (ec, a_expr, parameter_type, Location.Null);
2499 conv = ConvertImplicit (ec, a_expr, parameter_type, Location.Null);
2502 if (!Location.IsNull (loc)) {
2504 "The best overloaded match for method '" + FullMethodDesc (method)+
2505 "' has some invalid arguments");
2507 "Argument " + (j+1) +
2508 ": Cannot convert from '" + Argument.FullDesc (a)
2509 + "' to '" + pd.ParameterDesc (j) + "'");
2517 // Update the argument with the implicit conversion
2522 // FIXME : For the case of params methods, we need to actually instantiate
2523 // an array and initialize it with the argument values etc etc.
2527 if (a.GetParameterModifier () != pd.ParameterModifier (j) &&
2528 pd.ParameterModifier (j) != Parameter.Modifier.PARAMS) {
2529 if (!Location.IsNull (loc)) {
2531 "The best overloaded match for method '" + FullMethodDesc (method)+
2532 "' has some invalid arguments");
2534 "Argument " + (j+1) +
2535 ": Cannot convert from '" + Argument.FullDesc (a)
2536 + "' to '" + pd.ParameterDesc (j) + "'");
2547 public static MethodBase OverloadResolve (EmitContext ec, MethodGroupExpr me,
2548 ArrayList Arguments, Location loc)
2550 return OverloadResolve (ec, me, Arguments, loc, false);
2553 public override Expression DoResolve (EmitContext ec)
2556 // First, resolve the expression that is used to
2557 // trigger the invocation
2559 expr = expr.Resolve (ec);
2563 if (!(expr is MethodGroupExpr)) {
2564 Type expr_type = expr.Type;
2566 if (expr_type != null){
2567 bool IsDelegate = TypeManager.IsDelegateType (expr_type);
2569 return (new DelegateInvocation (
2570 this.expr, Arguments, loc)).Resolve (ec);
2574 if (!(expr is MethodGroupExpr)){
2575 report118 (loc, this.expr, "method group");
2580 // Next, evaluate all the expressions in the argument list
2582 if (Arguments != null){
2583 for (int i = Arguments.Count; i > 0;){
2585 Argument a = (Argument) Arguments [i];
2587 if (!a.Resolve (ec, loc))
2592 method = OverloadResolve (ec, (MethodGroupExpr) this.expr, Arguments, loc);
2594 if (method == null){
2596 "Could not find any applicable function for this argument list");
2600 if (method is MethodInfo)
2601 type = ((MethodInfo)method).ReturnType;
2603 eclass = ExprClass.Value;
2608 // Emits the list of arguments as an array
2610 static void EmitParams (EmitContext ec, int idx, ArrayList arguments)
2612 ILGenerator ig = ec.ig;
2613 int count = arguments.Count - idx;
2614 Argument a = (Argument) arguments [idx];
2615 Type t = a.expr.Type;
2616 string array_type = t.FullName + "[]";
2619 array = ig.DeclareLocal (Type.GetType (array_type));
2620 IntLiteral.EmitInt (ig, count);
2621 ig.Emit (OpCodes.Newarr, t);
2622 ig.Emit (OpCodes.Stloc, array);
2624 int top = arguments.Count;
2625 for (int j = idx; j < top; j++){
2626 a = (Argument) arguments [j];
2628 ig.Emit (OpCodes.Ldloc, array);
2629 IntLiteral.EmitInt (ig, j - idx);
2632 ArrayAccess.EmitStoreOpcode (ig, t);
2634 ig.Emit (OpCodes.Ldloc, array);
2638 /// Emits a list of resolved Arguments that are in the arguments
2641 /// The MethodBase argument might be null if the
2642 /// emission of the arguments is known not to contain
2643 /// a `params' field (for example in constructors or other routines
2644 /// that keep their arguments in this structure
2646 public static void EmitArguments (EmitContext ec, MethodBase mb, ArrayList arguments)
2648 ParameterData pd = null;
2651 if (arguments != null)
2652 top = arguments.Count;
2657 pd = GetParameterData (mb);
2659 for (int i = 0; i < top; i++){
2660 Argument a = (Argument) arguments [i];
2663 if (pd.ParameterModifier (i) == Parameter.Modifier.PARAMS){
2664 EmitParams (ec, i, arguments);
2673 public static void EmitCall (EmitContext ec,
2674 bool is_static, Expression instance_expr,
2675 MethodBase method, ArrayList Arguments)
2677 ILGenerator ig = ec.ig;
2678 bool struct_call = false;
2682 // If this is ourselves, push "this"
2684 if (instance_expr == null){
2685 ig.Emit (OpCodes.Ldarg_0);
2688 // Push the instance expression
2690 if (instance_expr.Type.IsSubclassOf (TypeManager.value_type)){
2695 // If the expression implements IMemoryLocation, then
2696 // we can optimize and use AddressOf on the
2699 // If not we have to use some temporary storage for
2701 if (instance_expr is IMemoryLocation)
2702 ((IMemoryLocation) instance_expr).AddressOf (ec);
2704 Type t = instance_expr.Type;
2706 instance_expr.Emit (ec);
2707 LocalBuilder temp = ig.DeclareLocal (t);
2708 ig.Emit (OpCodes.Stloc, temp);
2709 ig.Emit (OpCodes.Ldloca, temp);
2712 instance_expr.Emit (ec);
2716 if (Arguments != null)
2717 EmitArguments (ec, method, Arguments);
2719 if (is_static || struct_call){
2720 if (method is MethodInfo)
2721 ig.Emit (OpCodes.Call, (MethodInfo) method);
2723 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
2725 if (method is MethodInfo)
2726 ig.Emit (OpCodes.Callvirt, (MethodInfo) method);
2728 ig.Emit (OpCodes.Callvirt, (ConstructorInfo) method);
2732 public override void Emit (EmitContext ec)
2734 MethodGroupExpr mg = (MethodGroupExpr) this.expr;
2735 EmitCall (ec, method.IsStatic, mg.InstanceExpression, method, Arguments);
2738 public override void EmitStatement (EmitContext ec)
2743 // Pop the return value if there is one
2745 if (method is MethodInfo){
2746 if (((MethodInfo)method).ReturnType != TypeManager.void_type)
2747 ec.ig.Emit (OpCodes.Pop);
2753 /// Implements the new expression
2755 public class New : ExpressionStatement {
2756 public readonly ArrayList Arguments;
2757 public readonly string RequestedType;
2760 MethodBase method = null;
2763 // If set, the new expression is for a value_target, and
2764 // we will not leave anything on the stack.
2766 Expression value_target;
2768 public New (string requested_type, ArrayList arguments, Location l)
2770 RequestedType = requested_type;
2771 Arguments = arguments;
2775 public Expression ValueTypeVariable {
2777 return value_target;
2781 value_target = value;
2785 public override Expression DoResolve (EmitContext ec)
2787 type = ec.TypeContainer.LookupType (RequestedType, false);
2792 bool IsDelegate = TypeManager.IsDelegateType (type);
2795 return (new NewDelegate (type, Arguments, loc)).Resolve (ec);
2799 ml = MemberLookup (ec, type, ".ctor", false,
2800 MemberTypes.Constructor, AllBindingsFlags, loc);
2802 bool is_struct = false;
2803 is_struct = type.IsSubclassOf (TypeManager.value_type);
2805 if (! (ml is MethodGroupExpr)){
2807 report118 (loc, ml, "method group");
2813 if (Arguments != null){
2814 for (int i = Arguments.Count; i > 0;){
2816 Argument a = (Argument) Arguments [i];
2818 if (!a.Resolve (ec, loc))
2823 method = Invocation.OverloadResolve (ec, (MethodGroupExpr) ml,
2827 if (method == null && !is_struct) {
2829 "New invocation: Can not find a constructor for " +
2830 "this argument list");
2834 eclass = ExprClass.Value;
2839 // This DoEmit can be invoked in two contexts:
2840 // * As a mechanism that will leave a value on the stack (new object)
2841 // * As one that wont (init struct)
2843 // You can control whether a value is required on the stack by passing
2844 // need_value_on_stack. The code *might* leave a value on the stack
2845 // so it must be popped manually
2847 // Returns whether a value is left on the stack
2849 bool DoEmit (EmitContext ec, bool need_value_on_stack)
2851 if (method == null){
2852 IMemoryLocation ml = (IMemoryLocation) value_target;
2856 Invocation.EmitArguments (ec, method, Arguments);
2857 ec.ig.Emit (OpCodes.Newobj, (ConstructorInfo) method);
2862 // It must be a value type, sanity check
2864 if (value_target != null){
2865 ec.ig.Emit (OpCodes.Initobj, type);
2867 if (need_value_on_stack){
2868 value_target.Emit (ec);
2874 throw new Exception ("No method and no value type");
2877 public override void Emit (EmitContext ec)
2882 public override void EmitStatement (EmitContext ec)
2884 if (DoEmit (ec, false))
2885 ec.ig.Emit (OpCodes.Pop);
2890 /// Represents an array creation expression.
2894 /// There are two possible scenarios here: one is an array creation
2895 /// expression that specifies the dimensions and optionally the
2896 /// initialization data
2898 public class ArrayCreation : ExpressionStatement {
2900 string RequestedType;
2902 ArrayList Initializers;
2904 ArrayList Arguments;
2906 MethodBase method = null;
2907 Type array_element_type;
2908 bool IsOneDimensional = false;
2910 bool IsBuiltinType = false;
2913 Type underlying_type;
2915 ArrayList ArrayData;
2917 public ArrayCreation (string requested_type, ArrayList exprs,
2918 string rank, ArrayList initializers, Location l)
2920 RequestedType = requested_type;
2922 Initializers = initializers;
2925 Arguments = new ArrayList ();
2927 foreach (Expression e in exprs)
2928 Arguments.Add (new Argument (e, Argument.AType.Expression));
2932 public ArrayCreation (string requested_type, string rank, ArrayList initializers, Location l)
2934 RequestedType = requested_type;
2935 Initializers = initializers;
2938 Rank = rank.Substring (0, rank.LastIndexOf ("["));
2940 string tmp = rank.Substring (rank.LastIndexOf ("["));
2942 dimensions = tmp.Length - 1;
2945 public static string FormArrayType (string base_type, int idx_count, string rank)
2947 StringBuilder sb = new StringBuilder (base_type);
2952 for (int i = 1; i < idx_count; i++)
2956 return sb.ToString ();
2959 public static string FormElementType (string base_type, int idx_count, string rank)
2961 StringBuilder sb = new StringBuilder (base_type);
2964 for (int i = 1; i < idx_count; i++)
2970 string val = sb.ToString ();
2972 return val.Substring (0, val.LastIndexOf ("["));
2977 Report.Error (178, loc, "Incorrectly structured array initializer");
2980 public bool CheckIndices (EmitContext ec, ArrayList probe, int idx,
2981 bool require_constant, bool unspecified_dims)
2983 foreach (object o in probe) {
2985 if (o is ArrayList) {
2987 if (!unspecified_dims) {
2988 Argument a = (Argument) Arguments [idx];
2990 if (!a.Resolve (ec, loc))
2993 Expression e = Expression.Reduce (ec, a.Expr);
2995 if (!(e is Literal) && require_constant) {
2996 Report.Error (150, loc, "A constant value is expected");
3000 int value = (int) ((Literal) e).GetValue ();
3002 if (value != probe.Count) {
3008 bool ret = CheckIndices (ec, (ArrayList) o, ++idx,
3009 require_constant, unspecified_dims);
3015 Expression tmp = (Expression) o;
3016 tmp = tmp.Resolve (ec);
3017 tmp = Expression.Reduce (ec, tmp);
3019 if (!(tmp is Literal) && require_constant) {
3020 Report.Error (150, loc, "A constant value is expected");
3024 Expression conv = ConvertImplicitRequired (ec, tmp,
3025 underlying_type, loc);
3030 ArrayData.Add (((Literal) tmp).GetValue ());
3037 public void UpdateIndices (EmitContext ec)
3039 for (ArrayList probe = Initializers; probe != null;) {
3041 if (probe [0] is ArrayList) {
3042 Expression e = new IntLiteral (probe.Count);
3043 Arguments.Add (new Argument (e, Argument.AType.Expression));
3045 probe = (ArrayList) probe [0];
3048 Expression e = new IntLiteral (probe.Count);
3049 Arguments.Add (new Argument (e, Argument.AType.Expression));
3057 public bool ValidateInitializers (EmitContext ec)
3059 if (Initializers == null)
3062 underlying_type = ec.TypeContainer.LookupType (RequestedType, false);
3065 // We use this to store all the date values in the order in which we
3066 // will need to store them in the byte blob later
3068 ArrayData = new ArrayList ();
3072 if (Arguments != null) {
3073 ret = CheckIndices (ec, Initializers, 0, true, false);
3077 Arguments = new ArrayList ();
3079 ret = CheckIndices (ec, Initializers, 0, true, true);
3085 if (Arguments.Count != dimensions) {
3094 public override Expression DoResolve (EmitContext ec)
3098 if (!ValidateInitializers (ec))
3101 if (Arguments == null)
3104 arg_count = Arguments.Count;
3106 string array_type = FormArrayType (RequestedType, arg_count, Rank);
3108 string element_type = FormElementType (RequestedType, arg_count, Rank);
3110 type = ec.TypeContainer.LookupType (array_type, false);
3112 array_element_type = ec.TypeContainer.LookupType (element_type, false);
3117 if (arg_count == 1) {
3118 IsOneDimensional = true;
3119 eclass = ExprClass.Value;
3123 IsBuiltinType = TypeManager.IsBuiltinType (type);
3125 if (IsBuiltinType) {
3129 ml = MemberLookup (ec, type, ".ctor", false, MemberTypes.Constructor,
3130 AllBindingsFlags, loc);
3132 if (!(ml is MethodGroupExpr)){
3133 report118 (loc, ml, "method group");
3138 Report.Error (-6, loc, "New invocation: Can not find a constructor for " +
3139 "this argument list");
3143 if (Arguments != null) {
3144 for (int i = arg_count; i > 0;){
3146 Argument a = (Argument) Arguments [i];
3148 if (!a.Resolve (ec, loc))
3153 method = Invocation.OverloadResolve (ec, (MethodGroupExpr) ml, Arguments, loc);
3155 if (method == null) {
3156 Report.Error (-6, loc, "New invocation: Can not find a constructor for " +
3157 "this argument list");
3161 eclass = ExprClass.Value;
3166 ModuleBuilder mb = ec.TypeContainer.RootContext.ModuleBuilder;
3168 ArrayList args = new ArrayList ();
3169 if (Arguments != null){
3170 for (int i = arg_count; i > 0;){
3172 Argument a = (Argument) Arguments [i];
3174 if (!a.Resolve (ec, loc))
3181 Type [] arg_types = null;
3184 arg_types = new Type [args.Count];
3186 args.CopyTo (arg_types, 0);
3188 method = mb.GetArrayMethod (type, ".ctor", CallingConventions.HasThis, null,
3191 if (method == null) {
3192 Report.Error (-6, loc, "New invocation: Can not find a constructor for " +
3193 "this argument list");
3197 eclass = ExprClass.Value;
3203 public byte [] MakeByteBlob ()
3208 int count = ArrayData.Count;
3210 if (underlying_type == TypeManager.int32_type ||
3211 underlying_type == TypeManager.uint32_type ||
3212 underlying_type == TypeManager.float_type)
3214 else if (underlying_type == TypeManager.int64_type ||
3215 underlying_type == TypeManager.uint64_type ||
3216 underlying_type == TypeManager.double_type)
3218 else if (underlying_type == TypeManager.byte_type ||
3219 underlying_type == TypeManager.sbyte_type ||
3220 underlying_type == TypeManager.char_type ||
3221 underlying_type == TypeManager.bool_type)
3223 else if (underlying_type == TypeManager.short_type ||
3224 underlying_type == TypeManager.ushort_type)
3227 Report.Error (-100, loc, "Unhandled type in MakeByteBlob!!");
3231 data = new byte [count * factor];
3233 for (int i = 0; i < count; ++i) {
3234 int val = (int) ArrayData [i];
3235 for (int j = 0; j < factor; ++j) {
3236 data [(i * factor) + j] = (byte) (val & 0xFF);
3244 public override void Emit (EmitContext ec)
3246 ILGenerator ig = ec.ig;
3248 if (IsOneDimensional) {
3249 Invocation.EmitArguments (ec, null, Arguments);
3250 ig.Emit (OpCodes.Newarr, array_element_type);
3253 Invocation.EmitArguments (ec, null, Arguments);
3256 ig.Emit (OpCodes.Newobj, (ConstructorInfo) method);
3258 ig.Emit (OpCodes.Newobj, (MethodInfo) method);
3261 if (Initializers != null) {
3264 byte [] data = MakeByteBlob ();
3267 fb = ec.TypeContainer.RootContext.MakeStaticData (data);
3269 ig.Emit (OpCodes.Dup);
3270 ig.Emit (OpCodes.Ldtoken, fb);
3271 ig.Emit (OpCodes.Call, TypeManager.void_initializearray_array_fieldhandle);
3276 public override void EmitStatement (EmitContext ec)
3279 ec.ig.Emit (OpCodes.Pop);
3285 /// Represents the `this' construct
3287 public class This : Expression, IAssignMethod, IMemoryLocation {
3290 public This (Location loc)
3295 public override Expression DoResolve (EmitContext ec)
3297 eclass = ExprClass.Variable;
3298 type = ec.TypeContainer.TypeBuilder;
3301 Report.Error (26, loc,
3302 "Keyword this not valid in static code");
3309 public Expression DoResolveLValue (EmitContext ec)
3313 if (ec.TypeContainer is Class){
3314 Report.Error (1604, loc, "Cannot assign to `this'");
3321 public override void Emit (EmitContext ec)
3323 ec.ig.Emit (OpCodes.Ldarg_0);
3326 public void EmitAssign (EmitContext ec, Expression source)
3329 ec.ig.Emit (OpCodes.Starg, 0);
3332 public void AddressOf (EmitContext ec)
3334 ec.ig.Emit (OpCodes.Ldarga_S, (byte) 0);
3339 /// Implements the typeof operator
3341 public class TypeOf : Expression {
3342 public readonly string QueriedType;
3345 public TypeOf (string queried_type)
3347 QueriedType = queried_type;
3350 public override Expression DoResolve (EmitContext ec)
3352 typearg = ec.TypeContainer.LookupType (QueriedType, false);
3354 if (typearg == null)
3357 type = TypeManager.type_type;
3358 eclass = ExprClass.Type;
3362 public override void Emit (EmitContext ec)
3364 ec.ig.Emit (OpCodes.Ldtoken, typearg);
3365 ec.ig.Emit (OpCodes.Call, TypeManager.system_type_get_type_from_handle);
3370 /// Implements the sizeof expression
3372 public class SizeOf : Expression {
3373 public readonly string QueriedType;
3375 public SizeOf (string queried_type)
3377 this.QueriedType = queried_type;
3380 public override Expression DoResolve (EmitContext ec)
3382 // FIXME: Implement;
3383 throw new Exception ("Unimplemented");
3387 public override void Emit (EmitContext ec)
3389 throw new Exception ("Implement me");
3394 /// Implements the member access expression
3396 public class MemberAccess : Expression {
3397 public readonly string Identifier;
3399 Expression member_lookup;
3402 public MemberAccess (Expression expr, string id, Location l)
3409 public Expression Expr {
3415 void error176 (Location loc, string name)
3417 Report.Error (176, loc, "Static member `" +
3418 name + "' cannot be accessed " +
3419 "with an instance reference, qualify with a " +
3420 "type name instead");
3423 public override Expression DoResolve (EmitContext ec)
3426 // We are the sole users of ResolveWithSimpleName (ie, the only
3427 // ones that can cope with it
3429 expr = expr.ResolveWithSimpleName (ec);
3434 if (expr is SimpleName){
3435 SimpleName child_expr = (SimpleName) expr;
3437 expr = new SimpleName (child_expr.Name + "." + Identifier, loc);
3439 return expr.Resolve (ec);
3442 member_lookup = MemberLookup (ec, expr.Type, Identifier, false, loc);
3444 if (member_lookup == null)
3450 if (member_lookup is MethodGroupExpr){
3451 MethodGroupExpr mg = (MethodGroupExpr) member_lookup;
3456 if (expr is TypeExpr){
3457 if (!mg.RemoveInstanceMethods ()){
3458 SimpleName.Error120 (loc, mg.Methods [0].Name);
3462 return member_lookup;
3466 // Instance.MethodGroup
3468 if (!mg.RemoveStaticMethods ()){
3469 error176 (loc, mg.Methods [0].Name);
3473 mg.InstanceExpression = expr;
3475 return member_lookup;
3478 if (member_lookup is FieldExpr){
3479 FieldExpr fe = (FieldExpr) member_lookup;
3480 FieldInfo fi = fe.FieldInfo;
3483 Type t = fi.FieldType;
3486 if (fi is FieldBuilder)
3487 o = TypeManager.GetValue ((FieldBuilder) fi);
3489 o = fi.GetValue (fi);
3491 if (t.IsSubclassOf (TypeManager.enum_type)) {
3492 Expression enum_member = MemberLookup (ec, t, "value__", false, loc);
3493 Type underlying_type = enum_member.Type;
3495 Expression e = Literalize (o, underlying_type);
3498 return new EnumLiteral (e, t);
3501 Expression exp = Literalize (o, t);
3507 if (expr is TypeExpr){
3508 if (!fe.FieldInfo.IsStatic){
3509 error176 (loc, fe.FieldInfo.Name);
3512 return member_lookup;
3514 if (fe.FieldInfo.IsStatic){
3515 error176 (loc, fe.FieldInfo.Name);
3518 fe.InstanceExpression = expr;
3524 if (member_lookup is PropertyExpr){
3525 PropertyExpr pe = (PropertyExpr) member_lookup;
3527 if (expr is TypeExpr){
3529 SimpleName.Error120 (loc, pe.PropertyInfo.Name);
3535 error176 (loc, pe.PropertyInfo.Name);
3538 pe.InstanceExpression = expr;
3544 Console.WriteLine ("Support for [" + member_lookup + "] is not present yet");
3545 Environment.Exit (0);
3549 public override void Emit (EmitContext ec)
3551 throw new Exception ("Should not happen I think");
3556 /// Implements checked expressions
3558 public class CheckedExpr : Expression {
3560 public Expression Expr;
3562 public CheckedExpr (Expression e)
3567 public override Expression DoResolve (EmitContext ec)
3569 Expr = Expr.Resolve (ec);
3574 eclass = Expr.ExprClass;
3579 public override void Emit (EmitContext ec)
3581 bool last_check = ec.CheckState;
3583 ec.CheckState = true;
3585 ec.CheckState = last_check;
3591 /// Implements the unchecked expression
3593 public class UnCheckedExpr : Expression {
3595 public Expression Expr;
3597 public UnCheckedExpr (Expression e)
3602 public override Expression DoResolve (EmitContext ec)
3604 Expr = Expr.Resolve (ec);
3609 eclass = Expr.ExprClass;
3614 public override void Emit (EmitContext ec)
3616 bool last_check = ec.CheckState;
3618 ec.CheckState = false;
3620 ec.CheckState = last_check;
3626 /// An Element Access expression. During semantic
3627 /// analysis these are transformed into IndexerAccess or
3628 /// ArrayAccess expressions
3630 public class ElementAccess : Expression {
3631 public ArrayList Arguments;
3632 public Expression Expr;
3633 public Location loc;
3635 public ElementAccess (Expression e, ArrayList e_list, Location l)
3639 Arguments = new ArrayList ();
3640 foreach (Expression tmp in e_list)
3641 Arguments.Add (new Argument (tmp, Argument.AType.Expression));
3646 bool CommonResolve (EmitContext ec)
3648 Expr = Expr.Resolve (ec);
3653 if (Arguments == null)
3656 for (int i = Arguments.Count; i > 0;){
3658 Argument a = (Argument) Arguments [i];
3660 if (!a.Resolve (ec, loc))
3667 public override Expression DoResolve (EmitContext ec)
3669 if (!CommonResolve (ec))
3673 // We perform some simple tests, and then to "split" the emit and store
3674 // code we create an instance of a different class, and return that.
3676 // I am experimenting with this pattern.
3678 if (Expr.Type.IsSubclassOf (TypeManager.array_type))
3679 return (new ArrayAccess (this)).Resolve (ec);
3681 return (new IndexerAccess (this)).Resolve (ec);
3684 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
3686 if (!CommonResolve (ec))
3689 if (Expr.Type.IsSubclassOf (TypeManager.array_type))
3690 return (new ArrayAccess (this)).ResolveLValue (ec, right_side);
3692 return (new IndexerAccess (this)).ResolveLValue (ec, right_side);
3695 public override void Emit (EmitContext ec)
3697 throw new Exception ("Should never be reached");
3702 /// Implements array access
3704 public class ArrayAccess : Expression, IAssignMethod {
3706 // Points to our "data" repository
3710 public ArrayAccess (ElementAccess ea_data)
3713 eclass = ExprClass.Variable;
3716 public override Expression DoResolve (EmitContext ec)
3718 if (ea.Expr.ExprClass != ExprClass.Variable) {
3719 report118 (ea.loc, ea.Expr, "variable");
3723 Type t = ea.Expr.Type;
3725 if (t.GetArrayRank () != ea.Arguments.Count){
3726 Report.Error (22, ea.loc,
3727 "Incorrect number of indexes for array " +
3728 " expected: " + t.GetArrayRank () + " got: " +
3729 ea.Arguments.Count);
3732 type = t.GetElementType ();
3733 eclass = ExprClass.Variable;
3739 /// Emits the right opcode to load an object of Type `t'
3740 /// from an array of T
3742 static public void EmitLoadOpcode (ILGenerator ig, Type type)
3744 if (type == TypeManager.byte_type)
3745 ig.Emit (OpCodes.Ldelem_I1);
3746 else if (type == TypeManager.sbyte_type)
3747 ig.Emit (OpCodes.Ldelem_U1);
3748 else if (type == TypeManager.short_type)
3749 ig.Emit (OpCodes.Ldelem_I2);
3750 else if (type == TypeManager.ushort_type)
3751 ig.Emit (OpCodes.Ldelem_U2);
3752 else if (type == TypeManager.int32_type)
3753 ig.Emit (OpCodes.Ldelem_I4);
3754 else if (type == TypeManager.uint32_type)
3755 ig.Emit (OpCodes.Ldelem_U4);
3756 else if (type == TypeManager.uint64_type)
3757 ig.Emit (OpCodes.Ldelem_I8);
3758 else if (type == TypeManager.int64_type)
3759 ig.Emit (OpCodes.Ldelem_I8);
3760 else if (type == TypeManager.float_type)
3761 ig.Emit (OpCodes.Ldelem_R4);
3762 else if (type == TypeManager.double_type)
3763 ig.Emit (OpCodes.Ldelem_R8);
3764 else if (type == TypeManager.intptr_type)
3765 ig.Emit (OpCodes.Ldelem_I);
3767 ig.Emit (OpCodes.Ldelem_Ref);
3771 /// Emits the right opcode to store an object of Type `t'
3772 /// from an array of T.
3774 static public void EmitStoreOpcode (ILGenerator ig, Type t)
3776 if (t == TypeManager.byte_type || t == TypeManager.sbyte_type)
3777 ig.Emit (OpCodes.Stelem_I1);
3778 else if (t == TypeManager.short_type || t == TypeManager.ushort_type)
3779 ig.Emit (OpCodes.Stelem_I2);
3780 else if (t == TypeManager.int32_type || t == TypeManager.uint32_type)
3781 ig.Emit (OpCodes.Stelem_I4);
3782 else if (t == TypeManager.int64_type || t == TypeManager.uint64_type)
3783 ig.Emit (OpCodes.Stelem_I8);
3784 else if (t == TypeManager.float_type)
3785 ig.Emit (OpCodes.Stelem_R4);
3786 else if (t == TypeManager.double_type)
3787 ig.Emit (OpCodes.Stelem_R8);
3788 else if (t == TypeManager.intptr_type)
3789 ig.Emit (OpCodes.Stelem_I);
3791 ig.Emit (OpCodes.Stelem_Ref);
3794 public override void Emit (EmitContext ec)
3796 int rank = ea.Expr.Type.GetArrayRank ();
3797 ILGenerator ig = ec.ig;
3801 foreach (Argument a in ea.Arguments)
3805 EmitLoadOpcode (ig, type);
3807 ModuleBuilder mb = ec.TypeContainer.RootContext.ModuleBuilder;
3808 Type [] args = new Type [ea.Arguments.Count];
3813 foreach (Argument a in ea.Arguments)
3814 args [i++] = a.Type;
3816 get = mb.GetArrayMethod (
3817 ea.Expr.Type, "Get",
3818 CallingConventions.HasThis |
3819 CallingConventions.Standard,
3822 ig.Emit (OpCodes.Call, get);
3826 public void EmitAssign (EmitContext ec, Expression source)
3828 int rank = ea.Expr.Type.GetArrayRank ();
3829 ILGenerator ig = ec.ig;
3833 foreach (Argument a in ea.Arguments)
3838 Type t = source.Type;
3840 EmitStoreOpcode (ig, t);
3842 ModuleBuilder mb = ec.TypeContainer.RootContext.ModuleBuilder;
3843 Type [] args = new Type [ea.Arguments.Count + 1];
3848 foreach (Argument a in ea.Arguments)
3849 args [i++] = a.Type;
3853 set = mb.GetArrayMethod (
3854 ea.Expr.Type, "Set",
3855 CallingConventions.HasThis |
3856 CallingConventions.Standard,
3857 TypeManager.void_type, args);
3859 ig.Emit (OpCodes.Call, set);
3866 public ArrayList getters, setters;
3867 static Hashtable map;
3871 map = new Hashtable ();
3874 Indexers (MemberInfo [] mi)
3876 foreach (PropertyInfo property in mi){
3877 MethodInfo get, set;
3879 get = property.GetGetMethod (true);
3881 if (getters == null)
3882 getters = new ArrayList ();
3887 set = property.GetSetMethod (true);
3889 if (setters == null)
3890 setters = new ArrayList ();
3896 static public Indexers GetIndexersForType (Type t, TypeManager tm, Location loc)
3898 Indexers ix = (Indexers) map [t];
3899 string p_name = TypeManager.IndexerPropertyName (t);
3904 MemberInfo [] mi = tm.FindMembers (
3905 t, MemberTypes.Property,
3906 BindingFlags.Public | BindingFlags.Instance,
3907 Type.FilterName, p_name);
3909 if (mi == null || mi.Length == 0){
3910 Report.Error (21, loc,
3911 "Type `" + TypeManager.CSharpName (t) + "' does not have " +
3912 "any indexers defined");
3916 ix = new Indexers (mi);
3924 /// Expressions that represent an indexer call.
3926 public class IndexerAccess : Expression, IAssignMethod {
3928 // Points to our "data" repository
3931 MethodInfo get, set;
3933 ArrayList set_arguments;
3935 public IndexerAccess (ElementAccess ea_data)
3938 eclass = ExprClass.Value;
3941 public override Expression DoResolve (EmitContext ec)
3943 Type indexer_type = ea.Expr.Type;
3946 // Step 1: Query for all `Item' *properties*. Notice
3947 // that the actual methods are pointed from here.
3949 // This is a group of properties, piles of them.
3952 ilist = Indexers.GetIndexersForType (
3953 indexer_type, ec.TypeContainer.RootContext.TypeManager, ea.loc);
3957 // Step 2: find the proper match
3959 if (ilist != null && ilist.getters != null && ilist.getters.Count > 0)
3960 get = (MethodInfo) Invocation.OverloadResolve (
3961 ec, new MethodGroupExpr (ilist.getters), ea.Arguments, ea.loc);
3964 Report.Error (154, ea.loc,
3965 "indexer can not be used in this context, because " +
3966 "it lacks a `get' accessor");
3970 type = get.ReturnType;
3971 eclass = ExprClass.IndexerAccess;
3975 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
3977 Type indexer_type = ea.Expr.Type;
3978 Type right_type = right_side.Type;
3981 ilist = Indexers.GetIndexersForType (
3982 indexer_type, ec.TypeContainer.RootContext.TypeManager, ea.loc);
3984 if (ilist != null && ilist.setters != null && ilist.setters.Count > 0){
3985 set_arguments = (ArrayList) ea.Arguments.Clone ();
3986 set_arguments.Add (new Argument (right_side, Argument.AType.Expression));
3988 set = (MethodInfo) Invocation.OverloadResolve (
3989 ec, new MethodGroupExpr (ilist.setters), set_arguments, ea.loc);
3993 Report.Error (200, ea.loc,
3994 "indexer X.this [" + TypeManager.CSharpName (right_type) +
3995 "] lacks a `set' accessor");
3999 type = TypeManager.void_type;
4000 eclass = ExprClass.IndexerAccess;
4004 public override void Emit (EmitContext ec)
4006 Invocation.EmitCall (ec, false, ea.Expr, get, ea.Arguments);
4010 // source is ignored, because we already have a copy of it from the
4011 // LValue resolution and we have already constructed a pre-cached
4012 // version of the arguments (ea.set_arguments);
4014 public void EmitAssign (EmitContext ec, Expression source)
4016 Invocation.EmitCall (ec, false, ea.Expr, set, set_arguments);
4020 public class BaseAccess : Expression {
4022 public enum BaseAccessType : byte {
4027 public readonly BaseAccessType BAType;
4028 public readonly string Member;
4029 public readonly ArrayList Arguments;
4031 public BaseAccess (BaseAccessType t, string member, ArrayList args)
4039 public override Expression DoResolve (EmitContext ec)
4041 // FIXME: Implement;
4042 throw new Exception ("Unimplemented");
4046 public override void Emit (EmitContext ec)
4048 throw new Exception ("Unimplemented");
4053 /// This class exists solely to pass the Type around and to be a dummy
4054 /// that can be passed to the conversion functions (this is used by
4055 /// foreach implementation to typecast the object return value from
4056 /// get_Current into the proper type. All code has been generated and
4057 /// we only care about the side effect conversions to be performed
4059 public class EmptyExpression : Expression {
4060 public EmptyExpression ()
4062 type = TypeManager.object_type;
4063 eclass = ExprClass.Value;
4066 public EmptyExpression (Type t)
4069 eclass = ExprClass.Value;
4072 public override Expression DoResolve (EmitContext ec)
4077 public override void Emit (EmitContext ec)
4079 // nothing, as we only exist to not do anything.
4083 public class UserCast : Expression {
4087 public UserCast (MethodInfo method, Expression source)
4089 this.method = method;
4090 this.source = source;
4091 type = method.ReturnType;
4092 eclass = ExprClass.Value;
4095 public override Expression DoResolve (EmitContext ec)
4098 // We are born fully resolved
4103 public override void Emit (EmitContext ec)
4105 ILGenerator ig = ec.ig;
4109 if (method is MethodInfo)
4110 ig.Emit (OpCodes.Call, (MethodInfo) method);
4112 ig.Emit (OpCodes.Call, (ConstructorInfo) method);