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 {
740 Expression target_type;
744 public Cast (Expression cast_type, Expression expr, Location loc)
746 this.target_type = cast_type;
751 public Expression TargetType {
757 public Expression Expr {
766 public override Expression DoResolve (EmitContext ec)
768 expr = expr.Resolve (ec);
772 target_type = target_type.Resolve (ec);
773 if (target_type == null)
776 if (target_type.ExprClass != ExprClass.Type){
777 report118 (loc, target_type, "class");
781 type = target_type.Type;
782 eclass = ExprClass.Value;
787 expr = ConvertExplicit (ec, expr, type, loc);
791 public override void Emit (EmitContext ec)
794 // This one will never happen
796 throw new Exception ("Should not happen");
803 public class Binary : Expression {
804 public enum Operator : byte {
805 Multiply, Division, Modulus,
806 Addition, Subtraction,
807 LeftShift, RightShift,
808 LessThan, GreaterThan, LessThanOrEqual, GreaterThanOrEqual,
809 Equality, Inequality,
818 Expression left, right;
824 public Binary (Operator oper, Expression left, Expression right, Location loc)
832 public Operator Oper {
841 public Expression Left {
850 public Expression Right {
861 /// Returns a stringified representation of the Operator
866 case Operator.Multiply:
868 case Operator.Division:
870 case Operator.Modulus:
872 case Operator.Addition:
874 case Operator.Subtraction:
876 case Operator.LeftShift:
878 case Operator.RightShift:
880 case Operator.LessThan:
882 case Operator.GreaterThan:
884 case Operator.LessThanOrEqual:
886 case Operator.GreaterThanOrEqual:
888 case Operator.Equality:
890 case Operator.Inequality:
892 case Operator.BitwiseAnd:
894 case Operator.BitwiseOr:
896 case Operator.ExclusiveOr:
898 case Operator.LogicalOr:
900 case Operator.LogicalAnd:
904 return oper.ToString ();
907 Expression ForceConversion (EmitContext ec, Expression expr, Type target_type)
909 if (expr.Type == target_type)
912 return ConvertImplicit (ec, expr, target_type, new Location (-1));
916 // Note that handling the case l == Decimal || r == Decimal
917 // is taken care of by the Step 1 Operator Overload resolution.
919 bool DoNumericPromotions (EmitContext ec, Type l, Type r)
921 if (l == TypeManager.double_type || r == TypeManager.double_type){
923 // If either operand is of type double, the other operand is
924 // conveted to type double.
926 if (r != TypeManager.double_type)
927 right = ConvertImplicit (ec, right, TypeManager.double_type, loc);
928 if (l != TypeManager.double_type)
929 left = ConvertImplicit (ec, left, TypeManager.double_type, loc);
931 type = TypeManager.double_type;
932 } else if (l == TypeManager.float_type || r == TypeManager.float_type){
934 // if either operand is of type float, th eother operand is
935 // converd to type float.
937 if (r != TypeManager.double_type)
938 right = ConvertImplicit (ec, right, TypeManager.float_type, loc);
939 if (l != TypeManager.double_type)
940 left = ConvertImplicit (ec, left, TypeManager.float_type, loc);
941 type = TypeManager.float_type;
942 } else if (l == TypeManager.uint64_type || r == TypeManager.uint64_type){
946 // If either operand is of type ulong, the other operand is
947 // converted to type ulong. or an error ocurrs if the other
948 // operand is of type sbyte, short, int or long
951 if (l == TypeManager.uint64_type){
952 if (r != TypeManager.uint64_type && right is IntLiteral){
953 e = TryImplicitIntConversion (l, (IntLiteral) right);
959 if (left is IntLiteral){
960 e = TryImplicitIntConversion (r, (IntLiteral) left);
967 if ((other == TypeManager.sbyte_type) ||
968 (other == TypeManager.short_type) ||
969 (other == TypeManager.int32_type) ||
970 (other == TypeManager.int64_type)){
971 string oper = OperName ();
973 Error (34, loc, "Operator `" + OperName ()
974 + "' is ambiguous on operands of type `"
975 + TypeManager.CSharpName (l) + "' "
976 + "and `" + TypeManager.CSharpName (r)
979 type = TypeManager.uint64_type;
980 } else if (l == TypeManager.int64_type || r == TypeManager.int64_type){
982 // If either operand is of type long, the other operand is converted
985 if (l != TypeManager.int64_type)
986 left = ConvertImplicit (ec, left, TypeManager.int64_type, loc);
987 if (r != TypeManager.int64_type)
988 right = ConvertImplicit (ec, right, TypeManager.int64_type, loc);
990 type = TypeManager.int64_type;
991 } else if (l == TypeManager.uint32_type || r == TypeManager.uint32_type){
993 // If either operand is of type uint, and the other
994 // operand is of type sbyte, short or int, othe operands are
995 // converted to type long.
999 if (l == TypeManager.uint32_type)
1001 else if (r == TypeManager.uint32_type)
1004 if ((other == TypeManager.sbyte_type) ||
1005 (other == TypeManager.short_type) ||
1006 (other == TypeManager.int32_type)){
1007 left = ForceConversion (ec, left, TypeManager.int64_type);
1008 right = ForceConversion (ec, right, TypeManager.int64_type);
1009 type = TypeManager.int64_type;
1012 // if either operand is of type uint, the other
1013 // operand is converd to type uint
1015 left = ForceConversion (ec, left, TypeManager.uint32_type);
1016 right = ForceConversion (ec, right, TypeManager.uint32_type);
1017 type = TypeManager.uint32_type;
1019 } else if (l == TypeManager.decimal_type || r == TypeManager.decimal_type){
1020 if (l != TypeManager.decimal_type)
1021 left = ConvertImplicit (ec, left, TypeManager.decimal_type, loc);
1022 if (r != TypeManager.decimal_type)
1023 right = ConvertImplicit (ec, right, TypeManager.decimal_type, loc);
1025 type = TypeManager.decimal_type;
1027 Expression l_tmp, r_tmp;
1029 l_tmp = ForceConversion (ec, left, TypeManager.int32_type);
1033 r_tmp = ForceConversion (ec, right, TypeManager.int32_type);
1040 type = TypeManager.int32_type;
1049 "Operator " + OperName () + " cannot be applied to operands of type `" +
1050 TypeManager.CSharpName (left.Type) + "' and `" +
1051 TypeManager.CSharpName (right.Type) + "'");
1055 Expression CheckShiftArguments (EmitContext ec)
1059 Type r = right.Type;
1061 e = ForceConversion (ec, right, TypeManager.int32_type);
1068 if (((e = ConvertImplicit (ec, left, TypeManager.int32_type, loc)) != null) ||
1069 ((e = ConvertImplicit (ec, left, TypeManager.uint32_type, loc)) != null) ||
1070 ((e = ConvertImplicit (ec, left, TypeManager.int64_type, loc)) != null) ||
1071 ((e = ConvertImplicit (ec, left, TypeManager.uint64_type, loc)) != null)){
1081 Expression ResolveOperator (EmitContext ec)
1084 Type r = right.Type;
1087 // Step 1: Perform Operator Overload location
1089 Expression left_expr, right_expr;
1091 string op = "op_" + oper;
1093 left_expr = MemberLookup (ec, l, op, false, loc);
1094 if (left_expr == null && l.BaseType != null)
1095 left_expr = MemberLookup (ec, l.BaseType, op, false, loc);
1097 right_expr = MemberLookup (ec, r, op, false, loc);
1098 if (right_expr == null && r.BaseType != null)
1099 right_expr = MemberLookup (ec, r.BaseType, op, false, loc);
1101 MethodGroupExpr union = Invocation.MakeUnionSet (left_expr, right_expr);
1103 if (union != null) {
1104 Arguments = new ArrayList ();
1105 Arguments.Add (new Argument (left, Argument.AType.Expression));
1106 Arguments.Add (new Argument (right, Argument.AType.Expression));
1108 method = Invocation.OverloadResolve (ec, union, Arguments, loc);
1109 if (method != null) {
1110 MethodInfo mi = (MethodInfo) method;
1111 type = mi.ReturnType;
1120 // Step 2: Default operations on CLI native types.
1123 // Only perform numeric promotions on:
1124 // +, -, *, /, %, &, |, ^, ==, !=, <, >, <=, >=
1126 if (oper == Operator.Addition){
1128 // If any of the arguments is a string, cast to string
1130 if (l == TypeManager.string_type){
1131 if (r == TypeManager.string_type){
1132 if (left is Literal && right is Literal){
1133 StringLiteral ls = (StringLiteral) left;
1134 StringLiteral rs = (StringLiteral) right;
1136 return new StringLiteral (ls.Value + rs.Value);
1140 method = TypeManager.string_concat_string_string;
1143 method = TypeManager.string_concat_object_object;
1144 right = ConvertImplicit (ec, right,
1145 TypeManager.object_type, loc);
1147 type = TypeManager.string_type;
1149 Arguments = new ArrayList ();
1150 Arguments.Add (new Argument (left, Argument.AType.Expression));
1151 Arguments.Add (new Argument (right, Argument.AType.Expression));
1155 } else if (r == TypeManager.string_type){
1157 method = TypeManager.string_concat_object_object;
1158 Arguments = new ArrayList ();
1159 Arguments.Add (new Argument (left, Argument.AType.Expression));
1160 Arguments.Add (new Argument (right, Argument.AType.Expression));
1162 left = ConvertImplicit (ec, left, TypeManager.object_type, loc);
1163 type = TypeManager.string_type;
1169 // FIXME: is Delegate operator + (D x, D y) handled?
1173 if (oper == Operator.LeftShift || oper == Operator.RightShift)
1174 return CheckShiftArguments (ec);
1176 if (oper == Operator.LogicalOr || oper == Operator.LogicalAnd){
1177 if (l != TypeManager.bool_type || r != TypeManager.bool_type){
1182 type = TypeManager.bool_type;
1186 if (oper == Operator.Equality || oper == Operator.Inequality){
1187 if (l == TypeManager.bool_type || r == TypeManager.bool_type){
1188 if (r != TypeManager.bool_type || l != TypeManager.bool_type){
1193 type = TypeManager.bool_type;
1200 // We are dealing with numbers
1203 if (!DoNumericPromotions (ec, l, r)){
1206 // operator != (object a, object b)
1207 // operator == (object a, object b)
1210 if (oper == Operator.Equality || oper == Operator.Inequality){
1212 li = ConvertImplicit (ec, left, TypeManager.object_type, loc);
1214 ri = ConvertImplicit (ec, right, TypeManager.object_type,
1220 type = TypeManager.bool_type;
1230 if (left == null || right == null)
1234 // reload our cached types if required
1239 if (oper == Operator.BitwiseAnd ||
1240 oper == Operator.BitwiseOr ||
1241 oper == Operator.ExclusiveOr){
1243 if (l.IsSubclassOf (TypeManager.enum_type) ||
1244 !((l == TypeManager.int32_type) ||
1245 (l == TypeManager.uint32_type) ||
1246 (l == TypeManager.int64_type) ||
1247 (l == TypeManager.uint64_type)))
1255 if (oper == Operator.Equality ||
1256 oper == Operator.Inequality ||
1257 oper == Operator.LessThanOrEqual ||
1258 oper == Operator.LessThan ||
1259 oper == Operator.GreaterThanOrEqual ||
1260 oper == Operator.GreaterThan){
1261 type = TypeManager.bool_type;
1267 public override Expression DoResolve (EmitContext ec)
1269 left = left.Resolve (ec);
1270 right = right.Resolve (ec);
1272 if (left == null || right == null)
1275 if (left.Type == null)
1276 throw new Exception (
1277 "Resolve returned non null, but did not set the type! (" +
1278 left + ") at Line: " + loc.Row);
1279 if (right.Type == null)
1280 throw new Exception (
1281 "Resolve returned non null, but did not set the type! (" +
1282 right + ") at Line: "+ loc.Row);
1284 eclass = ExprClass.Value;
1286 return ResolveOperator (ec);
1289 public bool IsBranchable ()
1291 if (oper == Operator.Equality ||
1292 oper == Operator.Inequality ||
1293 oper == Operator.LessThan ||
1294 oper == Operator.GreaterThan ||
1295 oper == Operator.LessThanOrEqual ||
1296 oper == Operator.GreaterThanOrEqual){
1303 /// This entry point is used by routines that might want
1304 /// to emit a brfalse/brtrue after an expression, and instead
1305 /// they could use a more compact notation.
1307 /// Typically the code would generate l.emit/r.emit, followed
1308 /// by the comparission and then a brtrue/brfalse. The comparissions
1309 /// are sometimes inneficient (there are not as complete as the branches
1310 /// look for the hacks in Emit using double ceqs).
1312 /// So for those cases we provide EmitBranchable that can emit the
1313 /// branch with the test
1315 public void EmitBranchable (EmitContext ec, int target)
1318 bool close_target = false;
1319 ILGenerator ig = ec.ig;
1322 // short-circuit operators
1324 if (oper == Operator.LogicalAnd){
1326 ig.Emit (OpCodes.Brfalse, target);
1328 ig.Emit (OpCodes.Brfalse, target);
1329 } else if (oper == Operator.LogicalOr){
1331 ig.Emit (OpCodes.Brtrue, target);
1333 ig.Emit (OpCodes.Brfalse, target);
1340 case Operator.Equality:
1342 opcode = OpCodes.Beq_S;
1344 opcode = OpCodes.Beq;
1347 case Operator.Inequality:
1349 opcode = OpCodes.Bne_Un_S;
1351 opcode = OpCodes.Bne_Un;
1354 case Operator.LessThan:
1356 opcode = OpCodes.Blt_S;
1358 opcode = OpCodes.Blt;
1361 case Operator.GreaterThan:
1363 opcode = OpCodes.Bgt_S;
1365 opcode = OpCodes.Bgt;
1368 case Operator.LessThanOrEqual:
1370 opcode = OpCodes.Ble_S;
1372 opcode = OpCodes.Ble;
1375 case Operator.GreaterThanOrEqual:
1377 opcode = OpCodes.Bge_S;
1379 opcode = OpCodes.Ble;
1383 throw new Exception ("EmitBranchable called on non-EmitBranchable operator: "
1384 + oper.ToString ());
1387 ig.Emit (opcode, target);
1390 public override void Emit (EmitContext ec)
1392 ILGenerator ig = ec.ig;
1394 Type r = right.Type;
1397 if (method != null) {
1399 // Note that operators are static anyway
1401 if (Arguments != null)
1402 Invocation.EmitArguments (ec, method, Arguments);
1404 if (method is MethodInfo)
1405 ig.Emit (OpCodes.Call, (MethodInfo) method);
1407 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
1413 // Handle short-circuit operators differently
1416 if (oper == Operator.LogicalAnd){
1417 Label load_zero = ig.DefineLabel ();
1418 Label end = ig.DefineLabel ();
1421 ig.Emit (OpCodes.Brfalse, load_zero);
1423 ig.Emit (OpCodes.Br, end);
1424 ig.MarkLabel (load_zero);
1425 ig.Emit (OpCodes.Ldc_I4_0);
1428 } else if (oper == Operator.LogicalOr){
1429 Label load_one = ig.DefineLabel ();
1430 Label end = ig.DefineLabel ();
1433 ig.Emit (OpCodes.Brtrue, load_one);
1435 ig.Emit (OpCodes.Br, end);
1436 ig.MarkLabel (load_one);
1437 ig.Emit (OpCodes.Ldc_I4_1);
1446 case Operator.Multiply:
1448 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
1449 opcode = OpCodes.Mul_Ovf;
1450 else if (l==TypeManager.uint32_type || l==TypeManager.uint64_type)
1451 opcode = OpCodes.Mul_Ovf_Un;
1453 opcode = OpCodes.Mul;
1455 opcode = OpCodes.Mul;
1459 case Operator.Division:
1460 if (l == TypeManager.uint32_type || l == TypeManager.uint64_type)
1461 opcode = OpCodes.Div_Un;
1463 opcode = OpCodes.Div;
1466 case Operator.Modulus:
1467 if (l == TypeManager.uint32_type || l == TypeManager.uint64_type)
1468 opcode = OpCodes.Rem_Un;
1470 opcode = OpCodes.Rem;
1473 case Operator.Addition:
1475 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
1476 opcode = OpCodes.Add_Ovf;
1477 else if (l==TypeManager.uint32_type || l==TypeManager.uint64_type)
1478 opcode = OpCodes.Add_Ovf_Un;
1480 opcode = OpCodes.Mul;
1482 opcode = OpCodes.Add;
1485 case Operator.Subtraction:
1487 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
1488 opcode = OpCodes.Sub_Ovf;
1489 else if (l==TypeManager.uint32_type || l==TypeManager.uint64_type)
1490 opcode = OpCodes.Sub_Ovf_Un;
1492 opcode = OpCodes.Sub;
1494 opcode = OpCodes.Sub;
1497 case Operator.RightShift:
1498 opcode = OpCodes.Shr;
1501 case Operator.LeftShift:
1502 opcode = OpCodes.Shl;
1505 case Operator.Equality:
1506 opcode = OpCodes.Ceq;
1509 case Operator.Inequality:
1510 ec.ig.Emit (OpCodes.Ceq);
1511 ec.ig.Emit (OpCodes.Ldc_I4_0);
1513 opcode = OpCodes.Ceq;
1516 case Operator.LessThan:
1517 opcode = OpCodes.Clt;
1520 case Operator.GreaterThan:
1521 opcode = OpCodes.Cgt;
1524 case Operator.LessThanOrEqual:
1525 ec.ig.Emit (OpCodes.Cgt);
1526 ec.ig.Emit (OpCodes.Ldc_I4_0);
1528 opcode = OpCodes.Ceq;
1531 case Operator.GreaterThanOrEqual:
1532 ec.ig.Emit (OpCodes.Clt);
1533 ec.ig.Emit (OpCodes.Ldc_I4_1);
1535 opcode = OpCodes.Sub;
1538 case Operator.BitwiseOr:
1539 opcode = OpCodes.Or;
1542 case Operator.BitwiseAnd:
1543 opcode = OpCodes.And;
1546 case Operator.ExclusiveOr:
1547 opcode = OpCodes.Xor;
1551 throw new Exception ("This should not happen: Operator = "
1552 + oper.ToString ());
1559 /// Constant expression reducer for binary operations
1561 public override Expression Reduce (EmitContext ec)
1564 left = left.Reduce (ec);
1565 right = right.Reduce (ec);
1567 if (!(left is Literal && right is Literal))
1570 if (method == TypeManager.string_concat_string_string){
1571 StringLiteral ls = (StringLiteral) left;
1572 StringLiteral rs = (StringLiteral) right;
1574 return new StringLiteral (ls.Value + rs.Value);
1583 public class Conditional : Expression {
1584 Expression expr, trueExpr, falseExpr;
1587 public Conditional (Expression expr, Expression trueExpr, Expression falseExpr, Location l)
1590 this.trueExpr = trueExpr;
1591 this.falseExpr = falseExpr;
1595 public Expression Expr {
1601 public Expression TrueExpr {
1607 public Expression FalseExpr {
1613 public override Expression DoResolve (EmitContext ec)
1615 expr = expr.Resolve (ec);
1617 if (expr.Type != TypeManager.bool_type)
1618 expr = Expression.ConvertImplicitRequired (
1619 ec, expr, TypeManager.bool_type, loc);
1621 trueExpr = trueExpr.Resolve (ec);
1622 falseExpr = falseExpr.Resolve (ec);
1624 if (expr == null || trueExpr == null || falseExpr == null)
1627 if (trueExpr.Type == falseExpr.Type)
1628 type = trueExpr.Type;
1633 // First, if an implicit conversion exists from trueExpr
1634 // to falseExpr, then the result type is of type falseExpr.Type
1636 conv = ConvertImplicit (ec, trueExpr, falseExpr.Type, loc);
1638 type = falseExpr.Type;
1640 } else if ((conv = ConvertImplicit(ec, falseExpr,trueExpr.Type,loc))!= null){
1641 type = trueExpr.Type;
1644 Error (173, loc, "The type of the conditional expression can " +
1645 "not be computed because there is no implicit conversion" +
1646 " from `" + TypeManager.CSharpName (trueExpr.Type) + "'" +
1647 " and `" + TypeManager.CSharpName (falseExpr.Type) + "'");
1652 if (expr is BoolLiteral){
1653 BoolLiteral bl = (BoolLiteral) expr;
1661 eclass = ExprClass.Value;
1665 public override void Emit (EmitContext ec)
1667 ILGenerator ig = ec.ig;
1668 Label false_target = ig.DefineLabel ();
1669 Label end_target = ig.DefineLabel ();
1672 ig.Emit (OpCodes.Brfalse, false_target);
1674 ig.Emit (OpCodes.Br, end_target);
1675 ig.MarkLabel (false_target);
1676 falseExpr.Emit (ec);
1677 ig.MarkLabel (end_target);
1680 public override Expression Reduce (EmitContext ec)
1682 expr = expr.Reduce (ec);
1683 trueExpr = trueExpr.Reduce (ec);
1684 falseExpr = falseExpr.Reduce (ec);
1686 if (!(expr is Literal && trueExpr is Literal && falseExpr is Literal))
1689 BoolLiteral bl = (BoolLiteral) expr;
1698 public class LocalVariableReference : Expression, IAssignMethod, IMemoryLocation {
1699 public readonly string Name;
1700 public readonly Block Block;
1702 VariableInfo variable_info;
1704 public LocalVariableReference (Block block, string name)
1708 eclass = ExprClass.Variable;
1711 public VariableInfo VariableInfo {
1713 if (variable_info == null)
1714 variable_info = Block.GetVariableInfo (Name);
1715 return variable_info;
1719 public override Expression DoResolve (EmitContext ec)
1721 VariableInfo vi = VariableInfo;
1723 type = vi.VariableType;
1727 public override void Emit (EmitContext ec)
1729 VariableInfo vi = VariableInfo;
1730 ILGenerator ig = ec.ig;
1737 ig.Emit (OpCodes.Ldloc_0);
1741 ig.Emit (OpCodes.Ldloc_1);
1745 ig.Emit (OpCodes.Ldloc_2);
1749 ig.Emit (OpCodes.Ldloc_3);
1754 ig.Emit (OpCodes.Ldloc_S, (byte) idx);
1756 ig.Emit (OpCodes.Ldloc, idx);
1761 public static void Store (ILGenerator ig, int idx)
1765 ig.Emit (OpCodes.Stloc_0);
1769 ig.Emit (OpCodes.Stloc_1);
1773 ig.Emit (OpCodes.Stloc_2);
1777 ig.Emit (OpCodes.Stloc_3);
1782 ig.Emit (OpCodes.Stloc_S, (byte) idx);
1784 ig.Emit (OpCodes.Stloc, idx);
1789 public void EmitAssign (EmitContext ec, Expression source)
1791 ILGenerator ig = ec.ig;
1792 VariableInfo vi = VariableInfo;
1798 // Funny seems the code below generates optimal code for us, but
1799 // seems to take too long to generate what we need.
1800 // ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
1805 public void AddressOf (EmitContext ec)
1807 VariableInfo vi = VariableInfo;
1814 ec.ig.Emit (OpCodes.Ldloca_S, (byte) idx);
1816 ec.ig.Emit (OpCodes.Ldloca, idx);
1821 /// This represents a reference to a parameter in the intermediate
1824 public class ParameterReference : Expression, IAssignMethod, IMemoryLocation {
1825 public readonly Parameters Pars;
1826 public readonly String Name;
1827 public readonly int Idx;
1830 public ParameterReference (Parameters pars, int idx, string name)
1835 eclass = ExprClass.Variable;
1838 public override Expression DoResolve (EmitContext ec)
1840 Type [] types = Pars.GetParameterInfo (ec.TypeContainer);
1851 public override void Emit (EmitContext ec)
1854 ec.ig.Emit (OpCodes.Ldarg_S, (byte) arg_idx);
1856 ec.ig.Emit (OpCodes.Ldarg, arg_idx);
1859 public void EmitAssign (EmitContext ec, Expression source)
1864 ec.ig.Emit (OpCodes.Starg_S, (byte) arg_idx);
1866 ec.ig.Emit (OpCodes.Starg, arg_idx);
1870 public void AddressOf (EmitContext ec)
1873 ec.ig.Emit (OpCodes.Ldarga_S, (byte) arg_idx);
1875 ec.ig.Emit (OpCodes.Ldarga, arg_idx);
1880 /// Used for arguments to New(), Invocation()
1882 public class Argument {
1883 public enum AType : byte {
1889 public readonly AType ArgType;
1890 public Expression expr;
1892 public Argument (Expression expr, AType type)
1895 this.ArgType = type;
1898 public Expression Expr {
1914 public Parameter.Modifier GetParameterModifier ()
1916 if (ArgType == AType.Ref)
1917 return Parameter.Modifier.REF;
1919 if (ArgType == AType.Out)
1920 return Parameter.Modifier.OUT;
1922 return Parameter.Modifier.NONE;
1925 public static string FullDesc (Argument a)
1927 return (a.ArgType == AType.Ref ? "ref " :
1928 (a.ArgType == AType.Out ? "out " : "")) +
1929 TypeManager.CSharpName (a.Expr.Type);
1932 public bool Resolve (EmitContext ec, Location loc)
1934 expr = expr.Resolve (ec);
1936 if (ArgType == AType.Expression)
1937 return expr != null;
1939 if (expr.ExprClass != ExprClass.Variable){
1940 Report.Error (206, loc,
1941 "A property or indexer can not be passed as an out or ref " +
1946 return expr != null;
1949 public void Emit (EmitContext ec)
1951 if (ArgType == AType.Ref || ArgType == AType.Out)
1952 ((IMemoryLocation)expr).AddressOf (ec);
1959 /// Invocation of methods or delegates.
1961 public class Invocation : ExpressionStatement {
1962 public readonly ArrayList Arguments;
1966 MethodBase method = null;
1968 static Hashtable method_parameter_cache;
1970 static Invocation ()
1972 method_parameter_cache = new Hashtable ();
1976 // arguments is an ArrayList, but we do not want to typecast,
1977 // as it might be null.
1979 // FIXME: only allow expr to be a method invocation or a
1980 // delegate invocation (7.5.5)
1982 public Invocation (Expression expr, ArrayList arguments, Location l)
1985 Arguments = arguments;
1989 public Expression Expr {
1996 /// Returns the Parameters (a ParameterData interface) for the
1999 public static ParameterData GetParameterData (MethodBase mb)
2001 object pd = method_parameter_cache [mb];
2005 return (ParameterData) pd;
2008 ip = TypeContainer.LookupParametersByBuilder (mb);
2010 method_parameter_cache [mb] = ip;
2012 return (ParameterData) ip;
2014 ParameterInfo [] pi = mb.GetParameters ();
2015 ReflectionParameters rp = new ReflectionParameters (pi);
2016 method_parameter_cache [mb] = rp;
2018 return (ParameterData) rp;
2023 /// Tells whether a user defined conversion from Type `from' to
2024 /// Type `to' exists.
2026 /// FIXME: we could implement a cache here.
2028 static bool ConversionExists (EmitContext ec, Type from, Type to, Location loc)
2030 // Locate user-defined implicit operators
2034 mg = MemberLookup (ec, to, "op_Implicit", false, loc);
2037 MethodGroupExpr me = (MethodGroupExpr) mg;
2039 for (int i = me.Methods.Length; i > 0;) {
2041 MethodBase mb = me.Methods [i];
2042 ParameterData pd = GetParameterData (mb);
2044 if (from == pd.ParameterType (0))
2049 mg = MemberLookup (ec, from, "op_Implicit", false, loc);
2052 MethodGroupExpr me = (MethodGroupExpr) mg;
2054 for (int i = me.Methods.Length; i > 0;) {
2056 MethodBase mb = me.Methods [i];
2057 MethodInfo mi = (MethodInfo) mb;
2059 if (mi.ReturnType == to)
2068 /// Determines "better conversion" as specified in 7.4.2.3
2069 /// Returns : 1 if a->p is better
2070 /// 0 if a->q or neither is better
2072 static int BetterConversion (EmitContext ec, Argument a, Type p, Type q, bool use_standard,
2075 Type argument_type = a.Type;
2076 Expression argument_expr = a.Expr;
2078 if (argument_type == null)
2079 throw new Exception ("Expression of type " + a.Expr + " does not resolve its type");
2084 if (argument_type == p)
2087 if (argument_type == q)
2091 // Now probe whether an implicit constant expression conversion
2094 // An implicit constant expression conversion permits the following
2097 // * A constant-expression of type `int' can be converted to type
2098 // sbyte, byute, short, ushort, uint, ulong provided the value of
2099 // of the expression is withing the range of the destination type.
2101 // * A constant-expression of type long can be converted to type
2102 // ulong, provided the value of the constant expression is not negative
2104 // FIXME: Note that this assumes that constant folding has
2105 // taken place. We dont do constant folding yet.
2108 if (argument_expr is IntLiteral){
2109 IntLiteral ei = (IntLiteral) argument_expr;
2110 int value = ei.Value;
2112 if (p == TypeManager.sbyte_type){
2113 if (value >= SByte.MinValue && value <= SByte.MaxValue)
2115 } else if (p == TypeManager.byte_type){
2116 if (Byte.MinValue >= 0 && value <= Byte.MaxValue)
2118 } else if (p == TypeManager.short_type){
2119 if (value >= Int16.MinValue && value <= Int16.MaxValue)
2121 } else if (p == TypeManager.ushort_type){
2122 if (value >= UInt16.MinValue && value <= UInt16.MaxValue)
2124 } else if (p == TypeManager.uint32_type){
2126 // we can optimize this case: a positive int32
2127 // always fits on a uint32
2131 } else if (p == TypeManager.uint64_type){
2133 // we can optimize this case: a positive int32
2134 // always fits on a uint64
2139 } else if (argument_type == TypeManager.int64_type && argument_expr is LongLiteral){
2140 LongLiteral ll = (LongLiteral) argument_expr;
2142 if (p == TypeManager.uint64_type){
2153 tmp = ConvertImplicitStandard (ec, argument_expr, p, loc);
2155 tmp = ConvertImplicit (ec, argument_expr, p, loc);
2164 if (ConversionExists (ec, p, q, loc) == true &&
2165 ConversionExists (ec, q, p, loc) == false)
2168 if (p == TypeManager.sbyte_type)
2169 if (q == TypeManager.byte_type || q == TypeManager.ushort_type ||
2170 q == TypeManager.uint32_type || q == TypeManager.uint64_type)
2173 if (p == TypeManager.short_type)
2174 if (q == TypeManager.ushort_type || q == TypeManager.uint32_type ||
2175 q == TypeManager.uint64_type)
2178 if (p == TypeManager.int32_type)
2179 if (q == TypeManager.uint32_type || q == TypeManager.uint64_type)
2182 if (p == TypeManager.int64_type)
2183 if (q == TypeManager.uint64_type)
2190 /// Determines "Better function"
2193 /// and returns an integer indicating :
2194 /// 0 if candidate ain't better
2195 /// 1 if candidate is better than the current best match
2197 static int BetterFunction (EmitContext ec, ArrayList args,
2198 MethodBase candidate, MethodBase best,
2199 bool use_standard, Location loc)
2201 ParameterData candidate_pd = GetParameterData (candidate);
2202 ParameterData best_pd;
2208 argument_count = args.Count;
2210 if (candidate_pd.Count == 0 && argument_count == 0)
2214 if (candidate_pd.Count == argument_count) {
2216 for (int j = argument_count; j > 0;) {
2219 Argument a = (Argument) args [j];
2221 x = BetterConversion (
2222 ec, a, candidate_pd.ParameterType (j), null,
2238 best_pd = GetParameterData (best);
2240 if (candidate_pd.Count == argument_count && best_pd.Count == argument_count) {
2241 int rating1 = 0, rating2 = 0;
2243 for (int j = argument_count; j > 0;) {
2247 Argument a = (Argument) args [j];
2249 x = BetterConversion (ec, a, candidate_pd.ParameterType (j),
2250 best_pd.ParameterType (j), use_standard, loc);
2251 y = BetterConversion (ec, a, best_pd.ParameterType (j),
2252 candidate_pd.ParameterType (j), use_standard,
2259 if (rating1 > rating2)
2268 public static string FullMethodDesc (MethodBase mb)
2270 StringBuilder sb = new StringBuilder (mb.Name);
2271 ParameterData pd = GetParameterData (mb);
2273 int count = pd.Count;
2276 for (int i = count; i > 0; ) {
2279 sb.Append (pd.ParameterDesc (count - i - 1));
2285 return sb.ToString ();
2288 public static MethodGroupExpr MakeUnionSet (Expression mg1, Expression mg2)
2290 MemberInfo [] miset;
2291 MethodGroupExpr union;
2293 if (mg1 != null && mg2 != null) {
2295 MethodGroupExpr left_set = null, right_set = null;
2296 int length1 = 0, length2 = 0;
2298 left_set = (MethodGroupExpr) mg1;
2299 length1 = left_set.Methods.Length;
2301 right_set = (MethodGroupExpr) mg2;
2302 length2 = right_set.Methods.Length;
2304 ArrayList common = new ArrayList ();
2306 for (int i = 0; i < left_set.Methods.Length; i++) {
2307 for (int j = 0; j < right_set.Methods.Length; j++) {
2308 if (left_set.Methods [i] == right_set.Methods [j])
2309 common.Add (left_set.Methods [i]);
2313 miset = new MemberInfo [length1 + length2 - common.Count];
2315 left_set.Methods.CopyTo (miset, 0);
2319 for (int j = 0; j < right_set.Methods.Length; j++)
2320 if (!common.Contains (right_set.Methods [j]))
2321 miset [length1 + k++] = right_set.Methods [j];
2323 union = new MethodGroupExpr (miset);
2327 } else if (mg1 == null && mg2 != null) {
2329 MethodGroupExpr me = (MethodGroupExpr) mg2;
2331 miset = new MemberInfo [me.Methods.Length];
2332 me.Methods.CopyTo (miset, 0);
2334 union = new MethodGroupExpr (miset);
2338 } else if (mg2 == null && mg1 != null) {
2340 MethodGroupExpr me = (MethodGroupExpr) mg1;
2342 miset = new MemberInfo [me.Methods.Length];
2343 me.Methods.CopyTo (miset, 0);
2345 union = new MethodGroupExpr (miset);
2354 /// Determines is the candidate method, if a params method, is applicable
2355 /// in its expanded form to the given set of arguments
2357 static bool IsParamsMethodApplicable (ArrayList arguments, MethodBase candidate)
2361 if (arguments == null)
2364 arg_count = arguments.Count;
2366 ParameterData pd = GetParameterData (candidate);
2368 int pd_count = pd.Count;
2370 if (pd.ParameterModifier (pd_count - 1) != Parameter.Modifier.PARAMS)
2373 if (pd_count - 1 > arg_count)
2376 // If we have come this far, the case which remains is when the number of parameters
2377 // is less than or equal to the argument count. So, we now check if the element type
2378 // of the params array is compatible with each argument type
2381 Type element_type = pd.ParameterType (pd_count - 1).GetElementType ();
2383 for (int i = pd_count - 1; i < arg_count - 1; i++) {
2384 Argument a = (Argument) arguments [i];
2385 if (!StandardConversionExists (a.Type, element_type))
2393 /// Determines if the candidate method is applicable (section 14.4.2.1)
2394 /// to the given set of arguments
2396 static bool IsApplicable (ArrayList arguments, MethodBase candidate)
2400 if (arguments == null)
2403 arg_count = arguments.Count;
2405 ParameterData pd = GetParameterData (candidate);
2407 int pd_count = pd.Count;
2409 if (arg_count != pd.Count)
2412 for (int i = arg_count; i > 0; ) {
2415 Argument a = (Argument) arguments [i];
2417 Parameter.Modifier a_mod = a.GetParameterModifier ();
2418 Parameter.Modifier p_mod = pd.ParameterModifier (i);
2420 if (a_mod == p_mod) {
2422 if (a_mod == Parameter.Modifier.NONE)
2423 if (!StandardConversionExists (a.Type, pd.ParameterType (i)))
2426 if (a_mod == Parameter.Modifier.REF ||
2427 a_mod == Parameter.Modifier.OUT)
2428 if (pd.ParameterType (i) != a.Type)
2440 /// Find the Applicable Function Members (7.4.2.1)
2442 /// me: Method Group expression with the members to select.
2443 /// it might contain constructors or methods (or anything
2444 /// that maps to a method).
2446 /// Arguments: ArrayList containing resolved Argument objects.
2448 /// loc: The location if we want an error to be reported, or a Null
2449 /// location for "probing" purposes.
2451 /// use_standard: controls whether OverloadResolve should use the
2452 /// ConvertImplicit or ConvertImplicitStandard during overload resolution.
2454 /// Returns: The MethodBase (either a ConstructorInfo or a MethodInfo)
2455 /// that is the best match of me on Arguments.
2458 public static MethodBase OverloadResolve (EmitContext ec, MethodGroupExpr me,
2459 ArrayList Arguments, Location loc,
2462 ArrayList afm = new ArrayList ();
2463 int best_match_idx = -1;
2464 MethodBase method = null;
2467 for (int i = me.Methods.Length; i > 0; ){
2469 MethodBase candidate = me.Methods [i];
2472 // Check if candidate is applicable (section 14.4.2.1)
2473 if (!IsApplicable (Arguments, candidate))
2476 x = BetterFunction (ec, Arguments, candidate, method, use_standard, loc);
2482 method = me.Methods [best_match_idx];
2486 if (Arguments == null)
2489 argument_count = Arguments.Count;
2492 // Now we see if we can find params functions, applicable in their expanded form
2493 // since if they were applicable in their normal form, they would have been selected
2496 if (best_match_idx == -1) {
2498 for (int i = me.Methods.Length; i > 0; ) {
2500 MethodBase candidate = me.Methods [i];
2502 if (IsParamsMethodApplicable (Arguments, candidate)) {
2504 method = me.Methods [best_match_idx];
2511 // Now we see if we can at least find a method with the same number of arguments
2515 if (best_match_idx == -1) {
2517 for (int i = me.Methods.Length; i > 0;) {
2519 MethodBase mb = me.Methods [i];
2520 pd = GetParameterData (mb);
2522 if (pd.Count == argument_count) {
2524 method = me.Methods [best_match_idx];
2534 // And now convert implicitly, each argument to the required type
2536 pd = GetParameterData (method);
2537 int pd_count = pd.Count;
2539 for (int j = 0; j < argument_count; j++) {
2541 Argument a = (Argument) Arguments [j];
2542 Expression a_expr = a.Expr;
2543 Type parameter_type = pd.ParameterType (j);
2546 // Note that we need to compare against the element type
2547 // when we have a params method
2549 if (pd.ParameterModifier (pd_count - 1) == Parameter.Modifier.PARAMS) {
2550 if (j >= pd_count - 1)
2551 parameter_type = pd.ParameterType (pd_count - 1).GetElementType ();
2554 if (a.Type != parameter_type){
2558 conv = ConvertImplicitStandard (ec, a_expr, parameter_type, Location.Null);
2560 conv = ConvertImplicit (ec, a_expr, parameter_type, Location.Null);
2563 if (!Location.IsNull (loc)) {
2565 "The best overloaded match for method '" + FullMethodDesc (method)+
2566 "' has some invalid arguments");
2568 "Argument " + (j+1) +
2569 ": Cannot convert from '" + Argument.FullDesc (a)
2570 + "' to '" + pd.ParameterDesc (j) + "'");
2578 // Update the argument with the implicit conversion
2583 // FIXME : For the case of params methods, we need to actually instantiate
2584 // an array and initialize it with the argument values etc etc.
2588 if (a.GetParameterModifier () != pd.ParameterModifier (j) &&
2589 pd.ParameterModifier (j) != Parameter.Modifier.PARAMS) {
2590 if (!Location.IsNull (loc)) {
2592 "The best overloaded match for method '" + FullMethodDesc (method)+
2593 "' has some invalid arguments");
2595 "Argument " + (j+1) +
2596 ": Cannot convert from '" + Argument.FullDesc (a)
2597 + "' to '" + pd.ParameterDesc (j) + "'");
2608 public static MethodBase OverloadResolve (EmitContext ec, MethodGroupExpr me,
2609 ArrayList Arguments, Location loc)
2611 return OverloadResolve (ec, me, Arguments, loc, false);
2614 public override Expression DoResolve (EmitContext ec)
2617 // First, resolve the expression that is used to
2618 // trigger the invocation
2620 expr = expr.Resolve (ec);
2624 if (!(expr is MethodGroupExpr)) {
2625 Type expr_type = expr.Type;
2627 if (expr_type != null){
2628 bool IsDelegate = TypeManager.IsDelegateType (expr_type);
2630 return (new DelegateInvocation (
2631 this.expr, Arguments, loc)).Resolve (ec);
2635 if (!(expr is MethodGroupExpr)){
2636 report118 (loc, this.expr, "method group");
2641 // Next, evaluate all the expressions in the argument list
2643 if (Arguments != null){
2644 for (int i = Arguments.Count; i > 0;){
2646 Argument a = (Argument) Arguments [i];
2648 if (!a.Resolve (ec, loc))
2653 method = OverloadResolve (ec, (MethodGroupExpr) this.expr, Arguments, loc);
2655 if (method == null){
2657 "Could not find any applicable function for this argument list");
2661 if (method is MethodInfo)
2662 type = ((MethodInfo)method).ReturnType;
2664 eclass = ExprClass.Value;
2669 // Emits the list of arguments as an array
2671 static void EmitParams (EmitContext ec, int idx, ArrayList arguments)
2673 ILGenerator ig = ec.ig;
2674 int count = arguments.Count - idx;
2675 Argument a = (Argument) arguments [idx];
2676 Type t = a.expr.Type;
2677 string array_type = t.FullName + "[]";
2680 array = ig.DeclareLocal (Type.GetType (array_type));
2681 IntLiteral.EmitInt (ig, count);
2682 ig.Emit (OpCodes.Newarr, t);
2683 ig.Emit (OpCodes.Stloc, array);
2685 int top = arguments.Count;
2686 for (int j = idx; j < top; j++){
2687 a = (Argument) arguments [j];
2689 ig.Emit (OpCodes.Ldloc, array);
2690 IntLiteral.EmitInt (ig, j - idx);
2693 ArrayAccess.EmitStoreOpcode (ig, t);
2695 ig.Emit (OpCodes.Ldloc, array);
2699 /// Emits a list of resolved Arguments that are in the arguments
2702 /// The MethodBase argument might be null if the
2703 /// emission of the arguments is known not to contain
2704 /// a `params' field (for example in constructors or other routines
2705 /// that keep their arguments in this structure
2707 public static void EmitArguments (EmitContext ec, MethodBase mb, ArrayList arguments)
2709 ParameterData pd = null;
2712 if (arguments != null)
2713 top = arguments.Count;
2718 pd = GetParameterData (mb);
2720 for (int i = 0; i < top; i++){
2721 Argument a = (Argument) arguments [i];
2724 if (pd.ParameterModifier (i) == Parameter.Modifier.PARAMS){
2725 EmitParams (ec, i, arguments);
2734 public static void EmitCall (EmitContext ec,
2735 bool is_static, Expression instance_expr,
2736 MethodBase method, ArrayList Arguments)
2738 ILGenerator ig = ec.ig;
2739 bool struct_call = false;
2743 // If this is ourselves, push "this"
2745 if (instance_expr == null){
2746 ig.Emit (OpCodes.Ldarg_0);
2749 // Push the instance expression
2751 if (instance_expr.Type.IsSubclassOf (TypeManager.value_type)){
2756 // If the expression implements IMemoryLocation, then
2757 // we can optimize and use AddressOf on the
2760 // If not we have to use some temporary storage for
2762 if (instance_expr is IMemoryLocation)
2763 ((IMemoryLocation) instance_expr).AddressOf (ec);
2765 Type t = instance_expr.Type;
2767 instance_expr.Emit (ec);
2768 LocalBuilder temp = ig.DeclareLocal (t);
2769 ig.Emit (OpCodes.Stloc, temp);
2770 ig.Emit (OpCodes.Ldloca, temp);
2773 instance_expr.Emit (ec);
2777 if (Arguments != null)
2778 EmitArguments (ec, method, Arguments);
2780 if (is_static || struct_call){
2781 if (method is MethodInfo)
2782 ig.Emit (OpCodes.Call, (MethodInfo) method);
2784 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
2786 if (method is MethodInfo)
2787 ig.Emit (OpCodes.Callvirt, (MethodInfo) method);
2789 ig.Emit (OpCodes.Callvirt, (ConstructorInfo) method);
2793 public override void Emit (EmitContext ec)
2795 MethodGroupExpr mg = (MethodGroupExpr) this.expr;
2796 EmitCall (ec, method.IsStatic, mg.InstanceExpression, method, Arguments);
2799 public override void EmitStatement (EmitContext ec)
2804 // Pop the return value if there is one
2806 if (method is MethodInfo){
2807 if (((MethodInfo)method).ReturnType != TypeManager.void_type)
2808 ec.ig.Emit (OpCodes.Pop);
2814 /// Implements the new expression
2816 public class New : ExpressionStatement {
2817 public readonly ArrayList Arguments;
2818 public readonly string RequestedType;
2821 MethodBase method = null;
2824 // If set, the new expression is for a value_target, and
2825 // we will not leave anything on the stack.
2827 Expression value_target;
2829 public New (string requested_type, ArrayList arguments, Location l)
2831 RequestedType = requested_type;
2832 Arguments = arguments;
2836 public Expression ValueTypeVariable {
2838 return value_target;
2842 value_target = value;
2846 public override Expression DoResolve (EmitContext ec)
2848 type = ec.TypeContainer.LookupType (RequestedType, false);
2853 bool IsDelegate = TypeManager.IsDelegateType (type);
2856 return (new NewDelegate (type, Arguments, loc)).Resolve (ec);
2860 ml = MemberLookup (ec, type, ".ctor", false,
2861 MemberTypes.Constructor, AllBindingsFlags, loc);
2863 bool is_struct = false;
2864 is_struct = type.IsSubclassOf (TypeManager.value_type);
2866 if (! (ml is MethodGroupExpr)){
2868 report118 (loc, ml, "method group");
2874 if (Arguments != null){
2875 for (int i = Arguments.Count; i > 0;){
2877 Argument a = (Argument) Arguments [i];
2879 if (!a.Resolve (ec, loc))
2884 method = Invocation.OverloadResolve (ec, (MethodGroupExpr) ml,
2888 if (method == null && !is_struct) {
2890 "New invocation: Can not find a constructor for " +
2891 "this argument list");
2895 eclass = ExprClass.Value;
2900 // This DoEmit can be invoked in two contexts:
2901 // * As a mechanism that will leave a value on the stack (new object)
2902 // * As one that wont (init struct)
2904 // You can control whether a value is required on the stack by passing
2905 // need_value_on_stack. The code *might* leave a value on the stack
2906 // so it must be popped manually
2908 // Returns whether a value is left on the stack
2910 bool DoEmit (EmitContext ec, bool need_value_on_stack)
2912 if (method == null){
2913 IMemoryLocation ml = (IMemoryLocation) value_target;
2917 Invocation.EmitArguments (ec, method, Arguments);
2918 ec.ig.Emit (OpCodes.Newobj, (ConstructorInfo) method);
2923 // It must be a value type, sanity check
2925 if (value_target != null){
2926 ec.ig.Emit (OpCodes.Initobj, type);
2928 if (need_value_on_stack){
2929 value_target.Emit (ec);
2935 throw new Exception ("No method and no value type");
2938 public override void Emit (EmitContext ec)
2943 public override void EmitStatement (EmitContext ec)
2945 if (DoEmit (ec, false))
2946 ec.ig.Emit (OpCodes.Pop);
2951 /// Represents an array creation expression.
2955 /// There are two possible scenarios here: one is an array creation
2956 /// expression that specifies the dimensions and optionally the
2957 /// initialization data
2959 public class ArrayCreation : ExpressionStatement {
2960 string RequestedType;
2962 ArrayList Initializers;
2964 ArrayList Arguments;
2966 MethodBase method = null;
2967 Type array_element_type;
2968 bool IsOneDimensional = false;
2969 bool IsBuiltinType = false;
2970 bool ExpectInitializers = false;
2973 Type underlying_type;
2975 ArrayList ArrayData;
2979 public ArrayCreation (string requested_type, ArrayList exprs,
2980 string rank, ArrayList initializers, Location l)
2982 RequestedType = requested_type;
2984 Initializers = initializers;
2987 Arguments = new ArrayList ();
2989 foreach (Expression e in exprs)
2990 Arguments.Add (new Argument (e, Argument.AType.Expression));
2994 public ArrayCreation (string requested_type, string rank, ArrayList initializers, Location l)
2996 RequestedType = requested_type;
2997 Initializers = initializers;
3000 Rank = rank.Substring (0, rank.LastIndexOf ("["));
3002 string tmp = rank.Substring (rank.LastIndexOf ("["));
3004 dimensions = tmp.Length - 1;
3005 ExpectInitializers = true;
3008 public static string FormArrayType (string base_type, int idx_count, string rank)
3010 StringBuilder sb = new StringBuilder (base_type);
3015 for (int i = 1; i < idx_count; i++)
3019 return sb.ToString ();
3022 public static string FormElementType (string base_type, int idx_count, string rank)
3024 StringBuilder sb = new StringBuilder (base_type);
3027 for (int i = 1; i < idx_count; i++)
3033 string val = sb.ToString ();
3035 return val.Substring (0, val.LastIndexOf ("["));
3040 Report.Error (178, loc, "Incorrectly structured array initializer");
3043 public bool CheckIndices (EmitContext ec, ArrayList probe, int idx, bool specified_dims)
3045 if (specified_dims) {
3046 Argument a = (Argument) Arguments [idx];
3048 if (!a.Resolve (ec, loc))
3051 Expression e = Expression.Reduce (ec, a.Expr);
3053 if (!(e is Literal)) {
3054 Report.Error (150, loc, "A constant value is expected");
3058 int value = (int) ((Literal) e).GetValue ();
3060 if (value != probe.Count) {
3065 Bounds [idx] = value;
3068 foreach (object o in probe) {
3069 if (o is ArrayList) {
3070 bool ret = CheckIndices (ec, (ArrayList) o, idx + 1, specified_dims);
3074 Expression tmp = (Expression) o;
3075 tmp = tmp.Resolve (ec);
3079 tmp = Expression.Reduce (ec, tmp);
3081 // Handle initialization from vars, fields etc.
3083 Expression conv = ConvertImplicitRequired (ec, tmp, underlying_type, loc);
3089 ArrayData.Add (((Literal) tmp).GetValue ());
3091 ArrayData.Add (tmp);
3098 public void UpdateIndices (EmitContext ec)
3101 for (ArrayList probe = Initializers; probe != null;) {
3103 if (probe [0] is ArrayList) {
3104 Expression e = new IntLiteral (probe.Count);
3105 Arguments.Add (new Argument (e, Argument.AType.Expression));
3107 Bounds [i++] = probe.Count;
3109 probe = (ArrayList) probe [0];
3112 Expression e = new IntLiteral (probe.Count);
3113 Arguments.Add (new Argument (e, Argument.AType.Expression));
3115 Bounds [i++] = probe.Count;
3122 public bool ValidateInitializers (EmitContext ec)
3124 if (Initializers == null) {
3125 if (ExpectInitializers)
3131 underlying_type = ec.TypeContainer.LookupType (RequestedType, false);
3134 // We use this to store all the date values in the order in which we
3135 // will need to store them in the byte blob later
3137 ArrayData = new ArrayList ();
3138 Bounds = new Hashtable ();
3142 if (Arguments != null) {
3143 ret = CheckIndices (ec, Initializers, 0, true);
3147 Arguments = new ArrayList ();
3149 ret = CheckIndices (ec, Initializers, 0, false);
3156 if (Arguments.Count != dimensions) {
3165 public override Expression DoResolve (EmitContext ec)
3169 if (!ValidateInitializers (ec))
3172 if (Arguments == null)
3175 arg_count = Arguments.Count;
3177 string array_type = FormArrayType (RequestedType, arg_count, Rank);
3178 string element_type = FormElementType (RequestedType, arg_count, Rank);
3180 type = ec.TypeContainer.LookupType (array_type, false);
3182 array_element_type = ec.TypeContainer.LookupType (element_type, false);
3187 if (arg_count == 1) {
3188 IsOneDimensional = true;
3189 eclass = ExprClass.Value;
3193 IsBuiltinType = TypeManager.IsBuiltinType (type);
3195 if (IsBuiltinType) {
3199 ml = MemberLookup (ec, type, ".ctor", false, MemberTypes.Constructor,
3200 AllBindingsFlags, loc);
3202 if (!(ml is MethodGroupExpr)){
3203 report118 (loc, ml, "method group");
3208 Report.Error (-6, loc, "New invocation: Can not find a constructor for " +
3209 "this argument list");
3213 if (Arguments != null) {
3214 for (int i = arg_count; i > 0;){
3216 Argument a = (Argument) Arguments [i];
3218 if (!a.Resolve (ec, loc))
3223 method = Invocation.OverloadResolve (ec, (MethodGroupExpr) ml, Arguments, loc);
3225 if (method == null) {
3226 Report.Error (-6, loc, "New invocation: Can not find a constructor for " +
3227 "this argument list");
3231 eclass = ExprClass.Value;
3236 ModuleBuilder mb = ec.TypeContainer.RootContext.ModuleBuilder;
3238 ArrayList args = new ArrayList ();
3239 if (Arguments != null){
3240 for (int i = arg_count; i > 0;){
3242 Argument a = (Argument) Arguments [i];
3244 if (!a.Resolve (ec, loc))
3251 Type [] arg_types = null;
3254 arg_types = new Type [args.Count];
3256 args.CopyTo (arg_types, 0);
3258 method = mb.GetArrayMethod (type, ".ctor", CallingConventions.HasThis, null,
3261 if (method == null) {
3262 Report.Error (-6, loc, "New invocation: Can not find a constructor for " +
3263 "this argument list");
3267 eclass = ExprClass.Value;
3273 public static byte [] MakeByteBlob (ArrayList ArrayData, Type underlying_type, Location loc)
3278 int count = ArrayData.Count;
3280 if (underlying_type == TypeManager.int32_type ||
3281 underlying_type == TypeManager.uint32_type ||
3282 underlying_type == TypeManager.float_type)
3284 else if (underlying_type == TypeManager.int64_type ||
3285 underlying_type == TypeManager.uint64_type ||
3286 underlying_type == TypeManager.double_type)
3288 else if (underlying_type == TypeManager.byte_type ||
3289 underlying_type == TypeManager.sbyte_type ||
3290 underlying_type == TypeManager.char_type ||
3291 underlying_type == TypeManager.bool_type)
3293 else if (underlying_type == TypeManager.short_type ||
3294 underlying_type == TypeManager.ushort_type)
3297 Report.Error (-100, loc, "Unhandled type in MakeByteBlob!!");
3301 data = new byte [count * factor];
3303 for (int i = 0; i < count; ++i) {
3305 if (underlying_type == TypeManager.int64_type ||
3306 underlying_type == TypeManager.uint64_type){
3309 if (!(ArrayData [i] is Expression))
3310 val = (long) ArrayData [i];
3312 for (int j = 0; j < factor; ++j) {
3313 data [(i * factor) + j] = (byte) (val & 0xFF);
3317 } else if (underlying_type == TypeManager.float_type) {
3319 // FIXME : How does one get the bits out ?
3321 } else if (underlying_type == TypeManager.double_type) {
3323 // FIXME : Same here. '&' and '>>' don't work !
3329 if (!(ArrayData [i] is Expression))
3330 val = (int) ArrayData [i];
3332 for (int j = 0; j < factor; ++j) {
3333 data [(i * factor) + j] = (byte) (val & 0xFF);
3343 // Emits the initializers for the array
3345 void EmitStaticInitializers (EmitContext ec, bool is_expression)
3348 // First, the static data
3350 if (underlying_type != TypeManager.string_type) {
3352 ILGenerator ig = ec.ig;
3354 byte [] data = MakeByteBlob (ArrayData, underlying_type, loc);
3357 fb = ec.TypeContainer.RootContext.MakeStaticData (data);
3360 ig.Emit (OpCodes.Dup);
3361 ig.Emit (OpCodes.Ldtoken, fb);
3362 ig.Emit (OpCodes.Call,
3363 TypeManager.void_initializearray_array_fieldhandle);
3369 // Emits pieces of the array that can not be computed at compile
3370 // time (variables and string locations).
3372 // This always expect the top value on the stack to be the array
3374 void EmitDynamicInitializers (EmitContext ec, bool is_expression)
3376 ILGenerator ig = ec.ig;
3377 int dims = Bounds.Count;
3378 int [] current_pos = new int [dims];
3379 int top = ArrayData.Count;
3380 LocalBuilder temp = ig.DeclareLocal (type);
3382 ig.Emit (OpCodes.Stloc, temp);
3384 MethodInfo set = null;
3388 ModuleBuilder mb = null;
3389 mb = ec.TypeContainer.RootContext.ModuleBuilder;
3390 args = new Type [dims + 1];
3393 for (j = 0; j < dims; j++)
3394 args [j] = TypeManager.int32_type;
3396 args [j] = array_element_type;
3398 set = mb.GetArrayMethod (
3400 CallingConventions.HasThis | CallingConventions.Standard,
3401 TypeManager.void_type, args);
3404 for (int i = 0; i < top; i++){
3406 Expression e = null;
3407 if (ArrayData [i] is Expression)
3408 e = (Expression) ArrayData [i];
3411 if (!(e is Literal && !(e is StringLiteral))){
3413 ig.Emit (OpCodes.Ldloc, temp);
3415 for (int idx = dims; idx > 0; ) {
3417 IntLiteral.EmitInt (ig, current_pos [idx]);
3423 ArrayAccess.EmitStoreOpcode (ig, array_element_type);
3425 ig.Emit (OpCodes.Call, set);
3433 for (int j = 0; j < dims; j++){
3435 if (current_pos [j] < (int) Bounds [j])
3437 current_pos [j] = 0;
3442 ig.Emit (OpCodes.Ldloc, temp);
3445 void DoEmit (EmitContext ec, bool is_statement)
3447 ILGenerator ig = ec.ig;
3449 if (IsOneDimensional) {
3450 Invocation.EmitArguments (ec, null, Arguments);
3451 ig.Emit (OpCodes.Newarr, array_element_type);
3454 Invocation.EmitArguments (ec, null, Arguments);
3457 ig.Emit (OpCodes.Newobj, (ConstructorInfo) method);
3459 ig.Emit (OpCodes.Newobj, (MethodInfo) method);
3462 if (Initializers != null){
3464 // FIXME: Set this variable correctly.
3466 bool dynamic_initializers = true;
3467 EmitStaticInitializers (ec, dynamic_initializers || !is_statement);
3469 if (dynamic_initializers)
3470 EmitDynamicInitializers (ec, !is_statement);
3474 public override void Emit (EmitContext ec)
3479 public override void EmitStatement (EmitContext ec)
3487 /// Represents the `this' construct
3489 public class This : Expression, IAssignMethod, IMemoryLocation {
3492 public This (Location loc)
3497 public override Expression DoResolve (EmitContext ec)
3499 eclass = ExprClass.Variable;
3500 type = ec.TypeContainer.TypeBuilder;
3503 Report.Error (26, loc,
3504 "Keyword this not valid in static code");
3511 public Expression DoResolveLValue (EmitContext ec)
3515 if (ec.TypeContainer is Class){
3516 Report.Error (1604, loc, "Cannot assign to `this'");
3523 public override void Emit (EmitContext ec)
3525 ec.ig.Emit (OpCodes.Ldarg_0);
3528 public void EmitAssign (EmitContext ec, Expression source)
3531 ec.ig.Emit (OpCodes.Starg, 0);
3534 public void AddressOf (EmitContext ec)
3536 ec.ig.Emit (OpCodes.Ldarga_S, (byte) 0);
3541 /// Implements the typeof operator
3543 public class TypeOf : Expression {
3544 public readonly string QueriedType;
3547 public TypeOf (string queried_type)
3549 QueriedType = queried_type;
3552 public override Expression DoResolve (EmitContext ec)
3554 typearg = ec.TypeContainer.LookupType (QueriedType, false);
3556 if (typearg == null)
3559 type = TypeManager.type_type;
3560 eclass = ExprClass.Type;
3564 public override void Emit (EmitContext ec)
3566 ec.ig.Emit (OpCodes.Ldtoken, typearg);
3567 ec.ig.Emit (OpCodes.Call, TypeManager.system_type_get_type_from_handle);
3572 /// Implements the sizeof expression
3574 public class SizeOf : Expression {
3575 public readonly string QueriedType;
3577 public SizeOf (string queried_type)
3579 this.QueriedType = queried_type;
3582 public override Expression DoResolve (EmitContext ec)
3584 // FIXME: Implement;
3585 throw new Exception ("Unimplemented");
3589 public override void Emit (EmitContext ec)
3591 throw new Exception ("Implement me");
3596 /// Implements the member access expression
3598 public class MemberAccess : Expression {
3599 public readonly string Identifier;
3601 Expression member_lookup;
3604 public MemberAccess (Expression expr, string id, Location l)
3611 public Expression Expr {
3617 void error176 (Location loc, string name)
3619 Report.Error (176, loc, "Static member `" +
3620 name + "' cannot be accessed " +
3621 "with an instance reference, qualify with a " +
3622 "type name instead");
3625 public override Expression DoResolve (EmitContext ec)
3628 // We are the sole users of ResolveWithSimpleName (ie, the only
3629 // ones that can cope with it
3631 expr = expr.ResolveWithSimpleName (ec);
3636 if (expr is SimpleName){
3637 SimpleName child_expr = (SimpleName) expr;
3639 expr = new SimpleName (child_expr.Name + "." + Identifier, loc);
3641 return expr.Resolve (ec);
3644 member_lookup = MemberLookup (ec, expr.Type, Identifier, false, loc);
3646 if (member_lookup == null)
3652 if (member_lookup is MethodGroupExpr){
3653 MethodGroupExpr mg = (MethodGroupExpr) member_lookup;
3658 if (expr is TypeExpr){
3659 if (!mg.RemoveInstanceMethods ()){
3660 SimpleName.Error120 (loc, mg.Methods [0].Name);
3664 return member_lookup;
3668 // Instance.MethodGroup
3670 if (!mg.RemoveStaticMethods ()){
3671 error176 (loc, mg.Methods [0].Name);
3675 mg.InstanceExpression = expr;
3677 return member_lookup;
3680 if (member_lookup is FieldExpr){
3681 FieldExpr fe = (FieldExpr) member_lookup;
3682 FieldInfo fi = fe.FieldInfo;
3685 Type t = fi.FieldType;
3686 Type decl_type = fi.DeclaringType;
3689 if (fi is FieldBuilder)
3690 o = TypeManager.GetValue ((FieldBuilder) fi);
3692 o = fi.GetValue (fi);
3694 if (decl_type.IsSubclassOf (TypeManager.enum_type)) {
3695 Expression enum_member = MemberLookup (ec, decl_type, "value__",
3698 Enum en = TypeManager.LookupEnum (decl_type);
3702 e = Literalize (o, en.UnderlyingType);
3704 e = Literalize (o, enum_member.Type);
3707 return new EnumLiteral (e, decl_type);
3710 Expression exp = Literalize (o, t);
3716 if (expr is TypeExpr){
3717 if (!fe.FieldInfo.IsStatic){
3718 error176 (loc, fe.FieldInfo.Name);
3721 return member_lookup;
3723 if (fe.FieldInfo.IsStatic){
3724 error176 (loc, fe.FieldInfo.Name);
3727 fe.InstanceExpression = expr;
3733 if (member_lookup is PropertyExpr){
3734 PropertyExpr pe = (PropertyExpr) member_lookup;
3736 if (expr is TypeExpr){
3738 SimpleName.Error120 (loc, pe.PropertyInfo.Name);
3744 error176 (loc, pe.PropertyInfo.Name);
3747 pe.InstanceExpression = expr;
3753 Console.WriteLine ("Support for [" + member_lookup + "] is not present yet");
3754 Environment.Exit (0);
3758 public override void Emit (EmitContext ec)
3760 throw new Exception ("Should not happen I think");
3765 /// Implements checked expressions
3767 public class CheckedExpr : Expression {
3769 public Expression Expr;
3771 public CheckedExpr (Expression e)
3776 public override Expression DoResolve (EmitContext ec)
3778 Expr = Expr.Resolve (ec);
3783 eclass = Expr.ExprClass;
3788 public override void Emit (EmitContext ec)
3790 bool last_check = ec.CheckState;
3792 ec.CheckState = true;
3794 ec.CheckState = last_check;
3800 /// Implements the unchecked expression
3802 public class UnCheckedExpr : Expression {
3804 public Expression Expr;
3806 public UnCheckedExpr (Expression e)
3811 public override Expression DoResolve (EmitContext ec)
3813 Expr = Expr.Resolve (ec);
3818 eclass = Expr.ExprClass;
3823 public override void Emit (EmitContext ec)
3825 bool last_check = ec.CheckState;
3827 ec.CheckState = false;
3829 ec.CheckState = last_check;
3835 /// An Element Access expression. During semantic
3836 /// analysis these are transformed into IndexerAccess or
3837 /// ArrayAccess expressions
3839 public class ElementAccess : Expression {
3840 public ArrayList Arguments;
3841 public Expression Expr;
3842 public Location loc;
3844 public ElementAccess (Expression e, ArrayList e_list, Location l)
3848 Arguments = new ArrayList ();
3849 foreach (Expression tmp in e_list)
3850 Arguments.Add (new Argument (tmp, Argument.AType.Expression));
3855 bool CommonResolve (EmitContext ec)
3857 Expr = Expr.Resolve (ec);
3862 if (Arguments == null)
3865 for (int i = Arguments.Count; i > 0;){
3867 Argument a = (Argument) Arguments [i];
3869 if (!a.Resolve (ec, loc))
3876 public override Expression DoResolve (EmitContext ec)
3878 if (!CommonResolve (ec))
3882 // We perform some simple tests, and then to "split" the emit and store
3883 // code we create an instance of a different class, and return that.
3885 // I am experimenting with this pattern.
3887 if (Expr.Type.IsSubclassOf (TypeManager.array_type))
3888 return (new ArrayAccess (this)).Resolve (ec);
3890 return (new IndexerAccess (this)).Resolve (ec);
3893 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
3895 if (!CommonResolve (ec))
3898 if (Expr.Type.IsSubclassOf (TypeManager.array_type))
3899 return (new ArrayAccess (this)).ResolveLValue (ec, right_side);
3901 return (new IndexerAccess (this)).ResolveLValue (ec, right_side);
3904 public override void Emit (EmitContext ec)
3906 throw new Exception ("Should never be reached");
3911 /// Implements array access
3913 public class ArrayAccess : Expression, IAssignMethod {
3915 // Points to our "data" repository
3919 public ArrayAccess (ElementAccess ea_data)
3922 eclass = ExprClass.Variable;
3925 public override Expression DoResolve (EmitContext ec)
3927 if (ea.Expr.ExprClass != ExprClass.Variable) {
3928 report118 (ea.loc, ea.Expr, "variable");
3932 Type t = ea.Expr.Type;
3934 if (t.GetArrayRank () != ea.Arguments.Count){
3935 Report.Error (22, ea.loc,
3936 "Incorrect number of indexes for array " +
3937 " expected: " + t.GetArrayRank () + " got: " +
3938 ea.Arguments.Count);
3941 type = t.GetElementType ();
3942 eclass = ExprClass.Variable;
3948 /// Emits the right opcode to load an object of Type `t'
3949 /// from an array of T
3951 static public void EmitLoadOpcode (ILGenerator ig, Type type)
3953 if (type == TypeManager.byte_type)
3954 ig.Emit (OpCodes.Ldelem_I1);
3955 else if (type == TypeManager.sbyte_type)
3956 ig.Emit (OpCodes.Ldelem_U1);
3957 else if (type == TypeManager.short_type)
3958 ig.Emit (OpCodes.Ldelem_I2);
3959 else if (type == TypeManager.ushort_type)
3960 ig.Emit (OpCodes.Ldelem_U2);
3961 else if (type == TypeManager.int32_type)
3962 ig.Emit (OpCodes.Ldelem_I4);
3963 else if (type == TypeManager.uint32_type)
3964 ig.Emit (OpCodes.Ldelem_U4);
3965 else if (type == TypeManager.uint64_type)
3966 ig.Emit (OpCodes.Ldelem_I8);
3967 else if (type == TypeManager.int64_type)
3968 ig.Emit (OpCodes.Ldelem_I8);
3969 else if (type == TypeManager.float_type)
3970 ig.Emit (OpCodes.Ldelem_R4);
3971 else if (type == TypeManager.double_type)
3972 ig.Emit (OpCodes.Ldelem_R8);
3973 else if (type == TypeManager.intptr_type)
3974 ig.Emit (OpCodes.Ldelem_I);
3976 ig.Emit (OpCodes.Ldelem_Ref);
3980 /// Emits the right opcode to store an object of Type `t'
3981 /// from an array of T.
3983 static public void EmitStoreOpcode (ILGenerator ig, Type t)
3985 if (t == TypeManager.byte_type || t == TypeManager.sbyte_type)
3986 ig.Emit (OpCodes.Stelem_I1);
3987 else if (t == TypeManager.short_type || t == TypeManager.ushort_type)
3988 ig.Emit (OpCodes.Stelem_I2);
3989 else if (t == TypeManager.int32_type || t == TypeManager.uint32_type)
3990 ig.Emit (OpCodes.Stelem_I4);
3991 else if (t == TypeManager.int64_type || t == TypeManager.uint64_type)
3992 ig.Emit (OpCodes.Stelem_I8);
3993 else if (t == TypeManager.float_type)
3994 ig.Emit (OpCodes.Stelem_R4);
3995 else if (t == TypeManager.double_type)
3996 ig.Emit (OpCodes.Stelem_R8);
3997 else if (t == TypeManager.intptr_type)
3998 ig.Emit (OpCodes.Stelem_I);
4000 ig.Emit (OpCodes.Stelem_Ref);
4003 public override void Emit (EmitContext ec)
4005 int rank = ea.Expr.Type.GetArrayRank ();
4006 ILGenerator ig = ec.ig;
4010 foreach (Argument a in ea.Arguments)
4014 EmitLoadOpcode (ig, type);
4016 ModuleBuilder mb = ec.TypeContainer.RootContext.ModuleBuilder;
4017 Type [] args = new Type [ea.Arguments.Count];
4022 foreach (Argument a in ea.Arguments)
4023 args [i++] = a.Type;
4025 get = mb.GetArrayMethod (
4026 ea.Expr.Type, "Get",
4027 CallingConventions.HasThis |
4028 CallingConventions.Standard,
4031 ig.Emit (OpCodes.Call, get);
4035 public void EmitAssign (EmitContext ec, Expression source)
4037 int rank = ea.Expr.Type.GetArrayRank ();
4038 ILGenerator ig = ec.ig;
4042 foreach (Argument a in ea.Arguments)
4047 Type t = source.Type;
4050 EmitStoreOpcode (ig, t);
4052 ModuleBuilder mb = ec.TypeContainer.RootContext.ModuleBuilder;
4053 Type [] args = new Type [ea.Arguments.Count + 1];
4058 foreach (Argument a in ea.Arguments)
4059 args [i++] = a.Type;
4063 set = mb.GetArrayMethod (
4064 ea.Expr.Type, "Set",
4065 CallingConventions.HasThis |
4066 CallingConventions.Standard,
4067 TypeManager.void_type, args);
4069 ig.Emit (OpCodes.Call, set);
4076 public ArrayList getters, setters;
4077 static Hashtable map;
4081 map = new Hashtable ();
4084 Indexers (MemberInfo [] mi)
4086 foreach (PropertyInfo property in mi){
4087 MethodInfo get, set;
4089 get = property.GetGetMethod (true);
4091 if (getters == null)
4092 getters = new ArrayList ();
4097 set = property.GetSetMethod (true);
4099 if (setters == null)
4100 setters = new ArrayList ();
4106 static public Indexers GetIndexersForType (Type t, TypeManager tm, Location loc)
4108 Indexers ix = (Indexers) map [t];
4109 string p_name = TypeManager.IndexerPropertyName (t);
4114 MemberInfo [] mi = tm.FindMembers (
4115 t, MemberTypes.Property,
4116 BindingFlags.Public | BindingFlags.Instance,
4117 Type.FilterName, p_name);
4119 if (mi == null || mi.Length == 0){
4120 Report.Error (21, loc,
4121 "Type `" + TypeManager.CSharpName (t) + "' does not have " +
4122 "any indexers defined");
4126 ix = new Indexers (mi);
4134 /// Expressions that represent an indexer call.
4136 public class IndexerAccess : Expression, IAssignMethod {
4138 // Points to our "data" repository
4141 MethodInfo get, set;
4143 ArrayList set_arguments;
4145 public IndexerAccess (ElementAccess ea_data)
4148 eclass = ExprClass.Value;
4151 public override Expression DoResolve (EmitContext ec)
4153 Type indexer_type = ea.Expr.Type;
4156 // Step 1: Query for all `Item' *properties*. Notice
4157 // that the actual methods are pointed from here.
4159 // This is a group of properties, piles of them.
4162 ilist = Indexers.GetIndexersForType (
4163 indexer_type, ec.TypeContainer.RootContext.TypeManager, ea.loc);
4167 // Step 2: find the proper match
4169 if (ilist != null && ilist.getters != null && ilist.getters.Count > 0)
4170 get = (MethodInfo) Invocation.OverloadResolve (
4171 ec, new MethodGroupExpr (ilist.getters), ea.Arguments, ea.loc);
4174 Report.Error (154, ea.loc,
4175 "indexer can not be used in this context, because " +
4176 "it lacks a `get' accessor");
4180 type = get.ReturnType;
4181 eclass = ExprClass.IndexerAccess;
4185 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
4187 Type indexer_type = ea.Expr.Type;
4188 Type right_type = right_side.Type;
4191 ilist = Indexers.GetIndexersForType (
4192 indexer_type, ec.TypeContainer.RootContext.TypeManager, ea.loc);
4194 if (ilist != null && ilist.setters != null && ilist.setters.Count > 0){
4195 set_arguments = (ArrayList) ea.Arguments.Clone ();
4196 set_arguments.Add (new Argument (right_side, Argument.AType.Expression));
4198 set = (MethodInfo) Invocation.OverloadResolve (
4199 ec, new MethodGroupExpr (ilist.setters), set_arguments, ea.loc);
4203 Report.Error (200, ea.loc,
4204 "indexer X.this [" + TypeManager.CSharpName (right_type) +
4205 "] lacks a `set' accessor");
4209 type = TypeManager.void_type;
4210 eclass = ExprClass.IndexerAccess;
4214 public override void Emit (EmitContext ec)
4216 Invocation.EmitCall (ec, false, ea.Expr, get, ea.Arguments);
4220 // source is ignored, because we already have a copy of it from the
4221 // LValue resolution and we have already constructed a pre-cached
4222 // version of the arguments (ea.set_arguments);
4224 public void EmitAssign (EmitContext ec, Expression source)
4226 Invocation.EmitCall (ec, false, ea.Expr, set, set_arguments);
4230 public class BaseAccess : Expression {
4232 public enum BaseAccessType : byte {
4237 public readonly BaseAccessType BAType;
4238 public readonly string Member;
4239 public readonly ArrayList Arguments;
4241 public BaseAccess (BaseAccessType t, string member, ArrayList args)
4249 public override Expression DoResolve (EmitContext ec)
4251 // FIXME: Implement;
4252 throw new Exception ("Unimplemented");
4256 public override void Emit (EmitContext ec)
4258 throw new Exception ("Unimplemented");
4263 /// This class exists solely to pass the Type around and to be a dummy
4264 /// that can be passed to the conversion functions (this is used by
4265 /// foreach implementation to typecast the object return value from
4266 /// get_Current into the proper type. All code has been generated and
4267 /// we only care about the side effect conversions to be performed
4269 public class EmptyExpression : Expression {
4270 public EmptyExpression ()
4272 type = TypeManager.object_type;
4273 eclass = ExprClass.Value;
4276 public EmptyExpression (Type t)
4279 eclass = ExprClass.Value;
4282 public override Expression DoResolve (EmitContext ec)
4287 public override void Emit (EmitContext ec)
4289 // nothing, as we only exist to not do anything.
4293 public class UserCast : Expression {
4297 public UserCast (MethodInfo method, Expression source)
4299 this.method = method;
4300 this.source = source;
4301 type = method.ReturnType;
4302 eclass = ExprClass.Value;
4305 public override Expression DoResolve (EmitContext ec)
4308 // We are born fully resolved
4313 public override void Emit (EmitContext ec)
4315 ILGenerator ig = ec.ig;
4319 if (method is MethodInfo)
4320 ig.Emit (OpCodes.Call, (MethodInfo) method);
4322 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
4329 // This class is used to "construct" the type during a typecast
4330 // operation. Since the Type.GetType class in .NET can parse
4331 // the type specification, we just use this to construct the type
4332 // one bit at a time.
4334 public class ComposedCast : Expression {
4339 public ComposedCast (Expression left, string dim, Location l)
4346 public override Expression DoResolve (EmitContext ec)
4348 left = left.Resolve (ec);
4352 if (left.ExprClass != ExprClass.Type){
4353 report118 (loc, left, "type");
4357 type = ec.TypeContainer.LookupType (left.Type.FullName + dim, false);
4361 eclass = ExprClass.Type;
4365 public override void Emit (EmitContext ec)
4367 throw new Exception ("This should never be called");