2 // expression.cs: Expression representation for the IL tree.
5 // Miguel de Icaza (miguel@ximian.com)
7 // (C) 2001 Ximian, Inc.
13 using System.Collections;
14 using System.Diagnostics;
15 using System.Reflection;
16 using System.Reflection.Emit;
24 // Unary implements unary expressions. It derives from
25 // ExpressionStatement becuase the pre/post increment/decrement
26 // operators can be used in a statement context.
28 public class Unary : ExpressionStatement {
29 public enum Operator {
30 UnaryPlus, UnaryNegation, LogicalNot, OnesComplement,
31 Indirection, AddressOf, PreIncrement,
32 PreDecrement, PostIncrement, PostDecrement
41 public Unary (Operator op, Expression expr, Location loc)
48 public Expression Expr {
58 public Operator Oper {
69 // Returns a stringified representation of the Operator
74 case Operator.UnaryPlus:
76 case Operator.UnaryNegation:
78 case Operator.LogicalNot:
80 case Operator.OnesComplement:
82 case Operator.AddressOf:
84 case Operator.Indirection:
86 case Operator.PreIncrement : case Operator.PostIncrement :
88 case Operator.PreDecrement : case Operator.PostDecrement :
92 return oper.ToString ();
95 Expression ForceConversion (EmitContext ec, Expression expr, Type target_type)
97 if (expr.Type == target_type)
100 return ConvertImplicit (ec, expr, target_type, new Location (-1));
103 void error23 (Type t)
106 23, loc, "Operator " + OperName () +
107 " cannot be applied to operand of type `" +
108 TypeManager.CSharpName (t) + "'");
112 // Returns whether an object of type `t' can be incremented
113 // or decremented with add/sub (ie, basically whether we can
114 // use pre-post incr-decr operations on it, but it is not a
115 // System.Decimal, which we test elsewhere)
117 static bool IsIncrementableNumber (Type t)
119 return (t == TypeManager.sbyte_type) ||
120 (t == TypeManager.byte_type) ||
121 (t == TypeManager.short_type) ||
122 (t == TypeManager.ushort_type) ||
123 (t == TypeManager.int32_type) ||
124 (t == TypeManager.uint32_type) ||
125 (t == TypeManager.int64_type) ||
126 (t == TypeManager.uint64_type) ||
127 (t == TypeManager.char_type) ||
128 (t.IsSubclassOf (TypeManager.enum_type)) ||
129 (t == TypeManager.float_type) ||
130 (t == TypeManager.double_type);
133 static Expression TryReduceNegative (Expression expr)
137 if (expr is IntLiteral)
138 e = new IntLiteral (-((IntLiteral) expr).Value);
139 else if (expr is UIntLiteral)
140 e = new LongLiteral (-((UIntLiteral) expr).Value);
141 else if (expr is LongLiteral)
142 e = new LongLiteral (-((LongLiteral) expr).Value);
143 else if (expr is FloatLiteral)
144 e = new FloatLiteral (-((FloatLiteral) expr).Value);
145 else if (expr is DoubleLiteral)
146 e = new DoubleLiteral (-((DoubleLiteral) expr).Value);
147 else if (expr is DecimalLiteral)
148 e = new DecimalLiteral (-((DecimalLiteral) expr).Value);
153 Expression ResolveOperator (EmitContext ec)
155 Type expr_type = expr.Type;
158 // Step 1: Perform Operator Overload location
163 if (oper == Operator.PostIncrement || oper == Operator.PreIncrement)
164 op_name = "op_Increment";
165 else if (oper == Operator.PostDecrement || oper == Operator.PreDecrement)
166 op_name = "op_Decrement";
168 op_name = "op_" + oper;
170 mg = MemberLookup (ec, expr_type, op_name, false, loc);
172 if (mg == null && expr_type.BaseType != null)
173 mg = MemberLookup (ec, expr_type.BaseType, op_name, false, loc);
176 Arguments = new ArrayList ();
177 Arguments.Add (new Argument (expr, Argument.AType.Expression));
179 method = Invocation.OverloadResolve (ec, (MethodGroupExpr) mg,
181 if (method != null) {
182 MethodInfo mi = (MethodInfo) method;
183 type = mi.ReturnType;
193 // Step 2: Default operations on CLI native types.
196 // Only perform numeric promotions on:
199 if (expr_type == null)
202 if (oper == Operator.LogicalNot){
203 if (expr_type != TypeManager.bool_type) {
208 type = TypeManager.bool_type;
212 if (oper == Operator.OnesComplement) {
213 if (!((expr_type == TypeManager.int32_type) ||
214 (expr_type == TypeManager.uint32_type) ||
215 (expr_type == TypeManager.int64_type) ||
216 (expr_type == TypeManager.uint64_type) ||
217 (expr_type.IsSubclassOf (TypeManager.enum_type)))){
225 if (oper == Operator.UnaryPlus) {
227 // A plus in front of something is just a no-op, so return the child.
233 // Deals with -literals
234 // int operator- (int x)
235 // long operator- (long x)
236 // float operator- (float f)
237 // double operator- (double d)
238 // decimal operator- (decimal d)
240 if (oper == Operator.UnaryNegation){
242 // Fold a "- Constant" into a negative constant
248 // Is this a constant?
250 e = TryReduceNegative (expr);
258 // Not a constant we can optimize, perform numeric
259 // promotions to int, long, double.
262 // The following is inneficient, because we call
263 // ConvertImplicit too many times.
265 // It is also not clear if we should convert to Float
266 // or Double initially.
268 if (expr_type == TypeManager.uint32_type){
270 // FIXME: handle exception to this rule that
271 // permits the int value -2147483648 (-2^31) to
272 // bt written as a decimal interger literal
274 type = TypeManager.int64_type;
275 expr = ConvertImplicit (ec, expr, type, loc);
279 if (expr_type == TypeManager.uint64_type){
281 // FIXME: Handle exception of `long value'
282 // -92233720368547758087 (-2^63) to be written as
283 // decimal integer literal.
289 e = ConvertImplicit (ec, expr, TypeManager.int32_type, loc);
296 e = ConvertImplicit (ec, expr, TypeManager.int64_type, loc);
303 e = ConvertImplicit (ec, expr, TypeManager.double_type, loc);
315 // The operand of the prefix/postfix increment decrement operators
316 // should be an expression that is classified as a variable,
317 // a property access or an indexer access
319 if (oper == Operator.PreDecrement || oper == Operator.PreIncrement ||
320 oper == Operator.PostDecrement || oper == Operator.PostIncrement){
321 if (expr.ExprClass == ExprClass.Variable){
322 if (IsIncrementableNumber (expr_type) ||
323 expr_type == TypeManager.decimal_type){
327 } else if (expr.ExprClass == ExprClass.IndexerAccess){
329 // FIXME: Verify that we have both get and set methods
331 throw new Exception ("Implement me");
332 } else if (expr.ExprClass == ExprClass.PropertyAccess){
333 PropertyExpr pe = (PropertyExpr) expr;
335 if (pe.VerifyAssignable ())
339 report118 (loc, expr, "variable, indexer or property access");
343 if (oper == Operator.AddressOf){
344 if (expr.ExprClass != ExprClass.Variable){
345 Error (211, "Cannot take the address of non-variables");
348 type = Type.GetType (expr.Type.ToString () + "*");
351 Error (187, "No such operator '" + OperName () + "' defined for type '" +
352 TypeManager.CSharpName (expr_type) + "'");
357 public override Expression DoResolve (EmitContext ec)
359 expr = expr.Resolve (ec);
364 eclass = ExprClass.Value;
365 return ResolveOperator (ec);
368 public override void Emit (EmitContext ec)
370 ILGenerator ig = ec.ig;
371 Type expr_type = expr.Type;
374 if (method != null) {
376 // Note that operators are static anyway
378 if (Arguments != null)
379 Invocation.EmitArguments (ec, Arguments);
382 // Post increment/decrement operations need a copy at this
385 if (oper == Operator.PostDecrement || oper == Operator.PostIncrement)
386 ig.Emit (OpCodes.Dup);
389 ig.Emit (OpCodes.Call, (MethodInfo) method);
392 // Pre Increment and Decrement operators
394 if (oper == Operator.PreIncrement || oper == Operator.PreDecrement){
395 ig.Emit (OpCodes.Dup);
399 // Increment and Decrement should store the result
401 if (oper == Operator.PreDecrement || oper == Operator.PreIncrement ||
402 oper == Operator.PostDecrement || oper == Operator.PostIncrement){
403 ((IStackStore) expr).Store (ec);
409 case Operator.UnaryPlus:
410 throw new Exception ("This should be caught by Resolve");
412 case Operator.UnaryNegation:
414 ig.Emit (OpCodes.Neg);
417 case Operator.LogicalNot:
419 ig.Emit (OpCodes.Ldc_I4_0);
420 ig.Emit (OpCodes.Ceq);
423 case Operator.OnesComplement:
425 ig.Emit (OpCodes.Not);
428 case Operator.AddressOf:
429 ((IMemoryLocation)expr).AddressOf (ec);
432 case Operator.Indirection:
433 throw new Exception ("Not implemented yet");
435 case Operator.PreIncrement:
436 case Operator.PreDecrement:
437 if (expr.ExprClass == ExprClass.Variable){
439 // Resolve already verified that it is an "incrementable"
442 ig.Emit (OpCodes.Ldc_I4_1);
444 if (oper == Operator.PreDecrement)
445 ig.Emit (OpCodes.Sub);
447 ig.Emit (OpCodes.Add);
448 ig.Emit (OpCodes.Dup);
449 ((IStackStore) expr).Store (ec);
451 throw new Exception ("Handle Indexers and Properties here");
455 case Operator.PostIncrement:
456 case Operator.PostDecrement:
457 eclass = expr.ExprClass;
458 if (eclass == ExprClass.Variable){
460 // Resolve already verified that it is an "incrementable"
463 ig.Emit (OpCodes.Dup);
464 ig.Emit (OpCodes.Ldc_I4_1);
466 if (oper == Operator.PostDecrement)
467 ig.Emit (OpCodes.Sub);
469 ig.Emit (OpCodes.Add);
470 ((IStackStore) expr).Store (ec);
471 } else if (eclass == ExprClass.PropertyAccess){
472 throw new Exception ("Handle Properties here");
473 } else if (eclass == ExprClass.IndexerAccess) {
474 throw new Exception ("Handle Indexers here");
476 Console.WriteLine ("Unknown exprclass: " + eclass);
481 throw new Exception ("This should not happen: Operator = "
487 // This will emit the child expression for `ec' avoiding the logical
488 // not. The parent will take care of changing brfalse/brtrue
490 public void EmitLogicalNot (EmitContext ec)
492 if (oper != Operator.LogicalNot)
493 throw new Exception ("EmitLogicalNot can only be called with !expr");
498 public override void EmitStatement (EmitContext ec)
501 // FIXME: we should rewrite this code to generate
502 // better code for ++ and -- as we know we wont need
503 // the values on the stack
506 ec.ig.Emit (OpCodes.Pop);
509 public override Expression Reduce (EmitContext ec)
514 // We can not reduce expressions that invoke operator overloaded functions.
520 // First, reduce our child. Note that although we handle
522 expr = expr.Reduce (ec);
523 if (!(expr is Literal))
527 case Operator.UnaryPlus:
530 case Operator.UnaryNegation:
531 e = TryReduceNegative (expr);
536 case Operator.LogicalNot:
537 BoolLiteral b = (BoolLiteral) expr;
539 return new BoolLiteral (!(b.Value));
541 case Operator.OnesComplement:
544 if (et == TypeManager.int32_type)
545 return new IntLiteral (~ ((IntLiteral) expr).Value);
546 if (et == TypeManager.uint32_type)
547 return new UIntLiteral (~ ((UIntLiteral) expr).Value);
548 if (et == TypeManager.int64_type)
549 return new LongLiteral (~ ((LongLiteral) expr).Value);
550 if (et == TypeManager.uint64_type)
551 return new ULongLiteral (~ ((ULongLiteral) expr).Value);
558 public class Probe : Expression {
559 public readonly string ProbeType;
560 public readonly Operator Oper;
564 public enum Operator {
568 public Probe (Operator oper, Expression expr, string probe_type)
571 ProbeType = probe_type;
575 public Expression Expr {
581 public override Expression DoResolve (EmitContext ec)
583 probe_type = ec.TypeContainer.LookupType (ProbeType, false);
585 if (probe_type == null)
588 expr = expr.Resolve (ec);
590 type = TypeManager.bool_type;
591 eclass = ExprClass.Value;
596 public override void Emit (EmitContext ec)
598 ILGenerator ig = ec.ig;
602 if (Oper == Operator.Is){
603 ig.Emit (OpCodes.Isinst, probe_type);
604 ig.Emit (OpCodes.Ldnull);
605 ig.Emit (OpCodes.Cgt_Un);
607 ig.Emit (OpCodes.Isinst, probe_type);
613 // This represents a typecast in the source language.
615 // FIXME: Cast expressions have an unusual set of parsing
616 // rules, we need to figure those out.
618 public class Cast : Expression {
623 public Cast (string cast_type, Expression expr, Location loc)
625 this.target_type = cast_type;
630 public string TargetType {
636 public Expression Expr {
645 public override Expression DoResolve (EmitContext ec)
647 expr = expr.Resolve (ec);
651 type = ec.TypeContainer.LookupType (target_type, false);
652 eclass = ExprClass.Value;
657 expr = ConvertExplicit (ec, expr, type, loc);
662 public override void Emit (EmitContext ec)
665 // This one will never happen
667 throw new Exception ("Should not happen");
671 public class Binary : Expression {
672 public enum Operator {
673 Multiply, Division, Modulus,
674 Addition, Subtraction,
675 LeftShift, RightShift,
676 LessThan, GreaterThan, LessThanOrEqual, GreaterThanOrEqual,
677 Equality, Inequality,
686 Expression left, right;
692 public Binary (Operator oper, Expression left, Expression right, Location loc)
700 public Operator Oper {
709 public Expression Left {
718 public Expression Right {
729 // Returns a stringified representation of the Operator
734 case Operator.Multiply:
736 case Operator.Division:
738 case Operator.Modulus:
740 case Operator.Addition:
742 case Operator.Subtraction:
744 case Operator.LeftShift:
746 case Operator.RightShift:
748 case Operator.LessThan:
750 case Operator.GreaterThan:
752 case Operator.LessThanOrEqual:
754 case Operator.GreaterThanOrEqual:
756 case Operator.Equality:
758 case Operator.Inequality:
760 case Operator.BitwiseAnd:
762 case Operator.BitwiseOr:
764 case Operator.ExclusiveOr:
766 case Operator.LogicalOr:
768 case Operator.LogicalAnd:
772 return oper.ToString ();
775 Expression ForceConversion (EmitContext ec, Expression expr, Type target_type)
777 if (expr.Type == target_type)
780 return ConvertImplicit (ec, expr, target_type, new Location (-1));
784 // Note that handling the case l == Decimal || r == Decimal
785 // is taken care of by the Step 1 Operator Overload resolution.
787 void DoNumericPromotions (EmitContext ec, Type l, Type r)
789 if (l == TypeManager.double_type || r == TypeManager.double_type){
791 // If either operand is of type double, the other operand is
792 // conveted to type double.
794 if (r != TypeManager.double_type)
795 right = ConvertImplicit (ec, right, TypeManager.double_type, loc);
796 if (l != TypeManager.double_type)
797 left = ConvertImplicit (ec, left, TypeManager.double_type, loc);
799 type = TypeManager.double_type;
800 } else if (l == TypeManager.float_type || r == TypeManager.float_type){
802 // if either operand is of type float, th eother operand is
803 // converd to type float.
805 if (r != TypeManager.double_type)
806 right = ConvertImplicit (ec, right, TypeManager.float_type, loc);
807 if (l != TypeManager.double_type)
808 left = ConvertImplicit (ec, left, TypeManager.float_type, loc);
809 type = TypeManager.float_type;
810 } else if (l == TypeManager.uint64_type || r == TypeManager.uint64_type){
814 // If either operand is of type ulong, the other operand is
815 // converted to type ulong. or an error ocurrs if the other
816 // operand is of type sbyte, short, int or long
819 if (l == TypeManager.uint64_type){
820 if (r != TypeManager.uint64_type && right is IntLiteral){
821 e = TryImplicitIntConversion (l, (IntLiteral) right);
827 if (left is IntLiteral){
828 e = TryImplicitIntConversion (r, (IntLiteral) left);
835 if ((other == TypeManager.sbyte_type) ||
836 (other == TypeManager.short_type) ||
837 (other == TypeManager.int32_type) ||
838 (other == TypeManager.int64_type)){
839 string oper = OperName ();
841 Error (34, loc, "Operator `" + OperName ()
842 + "' is ambiguous on operands of type `"
843 + TypeManager.CSharpName (l) + "' "
844 + "and `" + TypeManager.CSharpName (r)
847 type = TypeManager.uint64_type;
848 } else if (l == TypeManager.int64_type || r == TypeManager.int64_type){
850 // If either operand is of type long, the other operand is converted
853 if (l != TypeManager.int64_type)
854 left = ConvertImplicit (ec, left, TypeManager.int64_type, loc);
855 if (r != TypeManager.int64_type)
856 right = ConvertImplicit (ec, right, TypeManager.int64_type, loc);
858 type = TypeManager.int64_type;
859 } else if (l == TypeManager.uint32_type || r == TypeManager.uint32_type){
861 // If either operand is of type uint, and the other
862 // operand is of type sbyte, short or int, othe operands are
863 // converted to type long.
867 if (l == TypeManager.uint32_type)
869 else if (r == TypeManager.uint32_type)
872 if ((other == TypeManager.sbyte_type) ||
873 (other == TypeManager.short_type) ||
874 (other == TypeManager.int32_type)){
875 left = ForceConversion (ec, left, TypeManager.int64_type);
876 right = ForceConversion (ec, right, TypeManager.int64_type);
877 type = TypeManager.int64_type;
880 // if either operand is of type uint, the other
881 // operand is converd to type uint
883 left = ForceConversion (ec, left, TypeManager.uint32_type);
884 right = ForceConversion (ec, right, TypeManager.uint32_type);
885 type = TypeManager.uint32_type;
887 } else if (l == TypeManager.decimal_type || r == TypeManager.decimal_type){
888 if (l != TypeManager.decimal_type)
889 left = ConvertImplicit (ec, left, TypeManager.decimal_type, loc);
890 if (r != TypeManager.decimal_type)
891 right = ConvertImplicit (ec, right, TypeManager.decimal_type, loc);
893 type = TypeManager.decimal_type;
895 Expression l_tmp, r_tmp;
897 l_tmp = ForceConversion (ec, left, TypeManager.int32_type);
904 r_tmp = ForceConversion (ec, right, TypeManager.int32_type);
911 type = TypeManager.int32_type;
918 "Operator " + OperName () + " cannot be applied to operands of type `" +
919 TypeManager.CSharpName (left.Type) + "' and `" +
920 TypeManager.CSharpName (right.Type) + "'");
924 Expression CheckShiftArguments (EmitContext ec)
930 e = ForceConversion (ec, right, TypeManager.int32_type);
937 if (((e = ConvertImplicit (ec, left, TypeManager.int32_type, loc)) != null) ||
938 ((e = ConvertImplicit (ec, left, TypeManager.uint32_type, loc)) != null) ||
939 ((e = ConvertImplicit (ec, left, TypeManager.int64_type, loc)) != null) ||
940 ((e = ConvertImplicit (ec, left, TypeManager.uint64_type, loc)) != null)){
950 Expression ResolveOperator (EmitContext ec)
956 // Step 1: Perform Operator Overload location
958 Expression left_expr, right_expr;
960 string op = "op_" + oper;
962 left_expr = MemberLookup (ec, l, op, false, loc);
963 if (left_expr == null && l.BaseType != null)
964 left_expr = MemberLookup (ec, l.BaseType, op, false, loc);
966 right_expr = MemberLookup (ec, r, op, false, loc);
967 if (right_expr == null && r.BaseType != null)
968 right_expr = MemberLookup (ec, r.BaseType, op, false, loc);
970 MethodGroupExpr union = Invocation.MakeUnionSet (left_expr, right_expr);
973 Arguments = new ArrayList ();
974 Arguments.Add (new Argument (left, Argument.AType.Expression));
975 Arguments.Add (new Argument (right, Argument.AType.Expression));
977 method = Invocation.OverloadResolve (ec, union, Arguments, loc);
978 if (method != null) {
979 MethodInfo mi = (MethodInfo) method;
980 type = mi.ReturnType;
989 // Step 2: Default operations on CLI native types.
992 // Only perform numeric promotions on:
993 // +, -, *, /, %, &, |, ^, ==, !=, <, >, <=, >=
995 if (oper == Operator.Addition){
997 // If any of the arguments is a string, cast to string
999 if (l == TypeManager.string_type){
1000 if (r == TypeManager.string_type){
1001 if (left is Literal && right is Literal){
1002 StringLiteral ls = (StringLiteral) left;
1003 StringLiteral rs = (StringLiteral) right;
1005 return new StringLiteral (ls.Value + rs.Value);
1009 method = TypeManager.string_concat_string_string;
1012 method = TypeManager.string_concat_object_object;
1013 right = ConvertImplicit (ec, right,
1014 TypeManager.object_type, loc);
1016 type = TypeManager.string_type;
1018 Arguments = new ArrayList ();
1019 Arguments.Add (new Argument (left, Argument.AType.Expression));
1020 Arguments.Add (new Argument (right, Argument.AType.Expression));
1024 } else if (r == TypeManager.string_type){
1026 method = TypeManager.string_concat_object_object;
1027 Arguments = new ArrayList ();
1028 Arguments.Add (new Argument (left, Argument.AType.Expression));
1029 Arguments.Add (new Argument (right, Argument.AType.Expression));
1031 left = ConvertImplicit (ec, left, TypeManager.object_type, loc);
1032 type = TypeManager.string_type;
1038 // FIXME: is Delegate operator + (D x, D y) handled?
1042 if (oper == Operator.LeftShift || oper == Operator.RightShift)
1043 return CheckShiftArguments (ec);
1045 if (oper == Operator.LogicalOr || oper == Operator.LogicalAnd){
1046 if (l != TypeManager.bool_type || r != TypeManager.bool_type){
1051 type = TypeManager.bool_type;
1055 if (oper == Operator.Equality || oper == Operator.Inequality){
1056 if (l == TypeManager.bool_type || r == TypeManager.bool_type){
1057 if (r != TypeManager.bool_type || l != TypeManager.bool_type){
1062 type = TypeManager.bool_type;
1071 // We are dealing with numbers
1074 DoNumericPromotions (ec, l, r);
1076 if (left == null || right == null)
1080 if (oper == Operator.BitwiseAnd ||
1081 oper == Operator.BitwiseOr ||
1082 oper == Operator.ExclusiveOr){
1083 if (!((l == TypeManager.int32_type) ||
1084 (l == TypeManager.uint32_type) ||
1085 (l == TypeManager.int64_type) ||
1086 (l == TypeManager.uint64_type))){
1093 if (oper == Operator.Equality ||
1094 oper == Operator.Inequality ||
1095 oper == Operator.LessThanOrEqual ||
1096 oper == Operator.LessThan ||
1097 oper == Operator.GreaterThanOrEqual ||
1098 oper == Operator.GreaterThan){
1099 type = TypeManager.bool_type;
1105 public override Expression DoResolve (EmitContext ec)
1107 left = left.Resolve (ec);
1108 right = right.Resolve (ec);
1110 if (left == null || right == null)
1113 if (left.Type == null)
1114 throw new Exception (
1115 "Resolve returned non null, but did not set the type! (" +
1116 left + ") at Line: " + loc.Row);
1117 if (right.Type == null)
1118 throw new Exception (
1119 "Resolve returned non null, but did not set the type! (" +
1120 right + ") at Line: "+ loc.Row);
1122 eclass = ExprClass.Value;
1124 return ResolveOperator (ec);
1127 public bool IsBranchable ()
1129 if (oper == Operator.Equality ||
1130 oper == Operator.Inequality ||
1131 oper == Operator.LessThan ||
1132 oper == Operator.GreaterThan ||
1133 oper == Operator.LessThanOrEqual ||
1134 oper == Operator.GreaterThanOrEqual){
1141 // This entry point is used by routines that might want
1142 // to emit a brfalse/brtrue after an expression, and instead
1143 // they could use a more compact notation.
1145 // Typically the code would generate l.emit/r.emit, followed
1146 // by the comparission and then a brtrue/brfalse. The comparissions
1147 // are sometimes inneficient (there are not as complete as the branches
1148 // look for the hacks in Emit using double ceqs).
1150 // So for those cases we provide EmitBranchable that can emit the
1151 // branch with the test
1153 public void EmitBranchable (EmitContext ec, int target)
1156 bool close_target = false;
1162 case Operator.Equality:
1164 opcode = OpCodes.Beq_S;
1166 opcode = OpCodes.Beq;
1169 case Operator.Inequality:
1171 opcode = OpCodes.Bne_Un_S;
1173 opcode = OpCodes.Bne_Un;
1176 case Operator.LessThan:
1178 opcode = OpCodes.Blt_S;
1180 opcode = OpCodes.Blt;
1183 case Operator.GreaterThan:
1185 opcode = OpCodes.Bgt_S;
1187 opcode = OpCodes.Bgt;
1190 case Operator.LessThanOrEqual:
1192 opcode = OpCodes.Ble_S;
1194 opcode = OpCodes.Ble;
1197 case Operator.GreaterThanOrEqual:
1199 opcode = OpCodes.Bge_S;
1201 opcode = OpCodes.Ble;
1205 throw new Exception ("EmitBranchable called on non-EmitBranchable operator: "
1206 + oper.ToString ());
1209 ec.ig.Emit (opcode, target);
1212 public override void Emit (EmitContext ec)
1214 ILGenerator ig = ec.ig;
1216 Type r = right.Type;
1219 if (method != null) {
1221 // Note that operators are static anyway
1223 if (Arguments != null)
1224 Invocation.EmitArguments (ec, Arguments);
1226 if (method is MethodInfo)
1227 ig.Emit (OpCodes.Call, (MethodInfo) method);
1229 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
1238 case Operator.Multiply:
1240 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
1241 opcode = OpCodes.Mul_Ovf;
1242 else if (l==TypeManager.uint32_type || l==TypeManager.uint64_type)
1243 opcode = OpCodes.Mul_Ovf_Un;
1245 opcode = OpCodes.Mul;
1247 opcode = OpCodes.Mul;
1251 case Operator.Division:
1252 if (l == TypeManager.uint32_type || l == TypeManager.uint64_type)
1253 opcode = OpCodes.Div_Un;
1255 opcode = OpCodes.Div;
1258 case Operator.Modulus:
1259 if (l == TypeManager.uint32_type || l == TypeManager.uint64_type)
1260 opcode = OpCodes.Rem_Un;
1262 opcode = OpCodes.Rem;
1265 case Operator.Addition:
1267 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
1268 opcode = OpCodes.Add_Ovf;
1269 else if (l==TypeManager.uint32_type || l==TypeManager.uint64_type)
1270 opcode = OpCodes.Add_Ovf_Un;
1272 opcode = OpCodes.Mul;
1274 opcode = OpCodes.Add;
1277 case Operator.Subtraction:
1279 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
1280 opcode = OpCodes.Sub_Ovf;
1281 else if (l==TypeManager.uint32_type || l==TypeManager.uint64_type)
1282 opcode = OpCodes.Sub_Ovf_Un;
1284 opcode = OpCodes.Sub;
1286 opcode = OpCodes.Sub;
1289 case Operator.RightShift:
1290 opcode = OpCodes.Shr;
1293 case Operator.LeftShift:
1294 opcode = OpCodes.Shl;
1297 case Operator.Equality:
1298 opcode = OpCodes.Ceq;
1301 case Operator.Inequality:
1302 ec.ig.Emit (OpCodes.Ceq);
1303 ec.ig.Emit (OpCodes.Ldc_I4_0);
1305 opcode = OpCodes.Ceq;
1308 case Operator.LessThan:
1309 opcode = OpCodes.Clt;
1312 case Operator.GreaterThan:
1313 opcode = OpCodes.Cgt;
1316 case Operator.LessThanOrEqual:
1317 ec.ig.Emit (OpCodes.Cgt);
1318 ec.ig.Emit (OpCodes.Ldc_I4_0);
1320 opcode = OpCodes.Ceq;
1323 case Operator.GreaterThanOrEqual:
1324 ec.ig.Emit (OpCodes.Clt);
1325 ec.ig.Emit (OpCodes.Ldc_I4_1);
1327 opcode = OpCodes.Sub;
1330 case Operator.LogicalOr:
1331 case Operator.BitwiseOr:
1332 opcode = OpCodes.Or;
1335 case Operator.LogicalAnd:
1336 case Operator.BitwiseAnd:
1337 opcode = OpCodes.And;
1340 case Operator.ExclusiveOr:
1341 opcode = OpCodes.Xor;
1345 throw new Exception ("This should not happen: Operator = "
1346 + oper.ToString ());
1353 // Constant expression reducer for binary operations
1355 public override Expression Reduce (EmitContext ec)
1357 Console.WriteLine ("Reduce called");
1359 left = left.Reduce (ec);
1360 right = right.Reduce (ec);
1362 if (!(left is Literal && right is Literal))
1365 if (method == TypeManager.string_concat_string_string){
1366 StringLiteral ls = (StringLiteral) left;
1367 StringLiteral rs = (StringLiteral) right;
1369 return new StringLiteral (ls.Value + rs.Value);
1378 public class Conditional : Expression {
1379 Expression expr, trueExpr, falseExpr;
1382 public Conditional (Expression expr, Expression trueExpr, Expression falseExpr, Location l)
1385 this.trueExpr = trueExpr;
1386 this.falseExpr = falseExpr;
1390 public Expression Expr {
1396 public Expression TrueExpr {
1402 public Expression FalseExpr {
1408 public override Expression DoResolve (EmitContext ec)
1410 expr = expr.Resolve (ec);
1412 if (expr.Type != TypeManager.bool_type)
1413 expr = Expression.ConvertImplicitRequired (
1414 ec, expr, TypeManager.bool_type, loc);
1416 trueExpr = trueExpr.Resolve (ec);
1417 falseExpr = falseExpr.Resolve (ec);
1419 if (expr == null || trueExpr == null || falseExpr == null)
1422 if (trueExpr.Type == falseExpr.Type)
1423 type = trueExpr.Type;
1428 // First, if an implicit conversion exists from trueExpr
1429 // to falseExpr, then the result type is of type falseExpr.Type
1431 conv = ConvertImplicit (ec, trueExpr, falseExpr.Type, loc);
1433 type = falseExpr.Type;
1435 } else if ((conv = ConvertImplicit(ec, falseExpr,trueExpr.Type,loc))!= null){
1436 type = trueExpr.Type;
1439 Error (173, loc, "The type of the conditional expression can " +
1440 "not be computed because there is no implicit conversion" +
1441 " from `" + TypeManager.CSharpName (trueExpr.Type) + "'" +
1442 " and `" + TypeManager.CSharpName (falseExpr.Type) + "'");
1447 if (expr is BoolLiteral){
1448 BoolLiteral bl = (BoolLiteral) expr;
1456 eclass = ExprClass.Value;
1460 public override void Emit (EmitContext ec)
1462 ILGenerator ig = ec.ig;
1463 Label false_target = ig.DefineLabel ();
1464 Label end_target = ig.DefineLabel ();
1467 ig.Emit (OpCodes.Brfalse, false_target);
1469 ig.Emit (OpCodes.Br, end_target);
1470 ig.MarkLabel (false_target);
1471 falseExpr.Emit (ec);
1472 ig.MarkLabel (end_target);
1475 public override Expression Reduce (EmitContext ec)
1477 expr = expr.Reduce (ec);
1478 trueExpr = trueExpr.Reduce (ec);
1479 falseExpr = falseExpr.Reduce (ec);
1481 if (!(expr is Literal && trueExpr is Literal && falseExpr is Literal))
1484 BoolLiteral bl = (BoolLiteral) expr;
1493 public class LocalVariableReference : Expression, IStackStore, IMemoryLocation {
1494 public readonly string Name;
1495 public readonly Block Block;
1497 VariableInfo variable_info;
1499 public LocalVariableReference (Block block, string name)
1503 eclass = ExprClass.Variable;
1506 public VariableInfo VariableInfo {
1508 if (variable_info == null)
1509 variable_info = Block.GetVariableInfo (Name);
1510 return variable_info;
1514 public override Expression DoResolve (EmitContext ec)
1516 VariableInfo vi = VariableInfo;
1518 type = vi.VariableType;
1522 public override void Emit (EmitContext ec)
1524 VariableInfo vi = VariableInfo;
1525 ILGenerator ig = ec.ig;
1532 ig.Emit (OpCodes.Ldloc_0);
1536 ig.Emit (OpCodes.Ldloc_1);
1540 ig.Emit (OpCodes.Ldloc_2);
1544 ig.Emit (OpCodes.Ldloc_3);
1549 ig.Emit (OpCodes.Ldloc_S, (byte) idx);
1551 ig.Emit (OpCodes.Ldloc, idx);
1556 public static void Store (ILGenerator ig, int idx)
1560 ig.Emit (OpCodes.Stloc_0);
1564 ig.Emit (OpCodes.Stloc_1);
1568 ig.Emit (OpCodes.Stloc_2);
1572 ig.Emit (OpCodes.Stloc_3);
1577 ig.Emit (OpCodes.Stloc_S, (byte) idx);
1579 ig.Emit (OpCodes.Stloc, idx);
1584 public void Store (EmitContext ec)
1586 ILGenerator ig = ec.ig;
1587 VariableInfo vi = VariableInfo;
1591 // Funny seems the above generates optimal code for us, but
1592 // seems to take too long to generate what we need.
1593 // ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
1598 public void AddressOf (EmitContext ec)
1600 VariableInfo vi = VariableInfo;
1607 ec.ig.Emit (OpCodes.Ldloca_S, (byte) idx);
1609 ec.ig.Emit (OpCodes.Ldloca, idx);
1613 public class ParameterReference : Expression, IStackStore, IMemoryLocation {
1614 public readonly Parameters Pars;
1615 public readonly String Name;
1616 public readonly int Idx;
1619 public ParameterReference (Parameters pars, int idx, string name)
1624 eclass = ExprClass.Variable;
1627 public override Expression DoResolve (EmitContext ec)
1629 Type [] types = Pars.GetParameterInfo (ec.TypeContainer);
1640 public override void Emit (EmitContext ec)
1643 ec.ig.Emit (OpCodes.Ldarg_S, (byte) arg_idx);
1645 ec.ig.Emit (OpCodes.Ldarg, arg_idx);
1648 public void Store (EmitContext ec)
1651 ec.ig.Emit (OpCodes.Starg_S, (byte) arg_idx);
1653 ec.ig.Emit (OpCodes.Starg, arg_idx);
1657 public void AddressOf (EmitContext ec)
1660 ec.ig.Emit (OpCodes.Ldarga_S, (byte) arg_idx);
1662 ec.ig.Emit (OpCodes.Ldarga, arg_idx);
1667 // Used for arguments to New(), Invocation()
1669 public class Argument {
1676 public readonly AType ArgType;
1677 public Expression expr;
1679 public Argument (Expression expr, AType type)
1682 this.ArgType = type;
1685 public Expression Expr {
1701 public Parameter.Modifier GetParameterModifier ()
1703 if (ArgType == AType.Ref)
1704 return Parameter.Modifier.REF;
1706 if (ArgType == AType.Out)
1707 return Parameter.Modifier.OUT;
1709 return Parameter.Modifier.NONE;
1712 public static string FullDesc (Argument a)
1714 StringBuilder sb = new StringBuilder ();
1716 if (a.ArgType == AType.Ref)
1719 if (a.ArgType == AType.Out)
1722 sb.Append (TypeManager.CSharpName (a.Expr.Type));
1724 return sb.ToString ();
1727 public bool Resolve (EmitContext ec)
1729 expr = expr.Resolve (ec);
1731 return expr != null;
1734 public void Emit (EmitContext ec)
1741 // Invocation of methods or delegates.
1743 public class Invocation : ExpressionStatement {
1744 public readonly ArrayList Arguments;
1745 public readonly Location Location;
1748 MethodBase method = null;
1750 static Hashtable method_parameter_cache;
1752 static Invocation ()
1754 method_parameter_cache = new Hashtable ();
1758 // arguments is an ArrayList, but we do not want to typecast,
1759 // as it might be null.
1761 // FIXME: only allow expr to be a method invocation or a
1762 // delegate invocation (7.5.5)
1764 public Invocation (Expression expr, ArrayList arguments, Location l)
1767 Arguments = arguments;
1771 public Expression Expr {
1778 // Returns the Parameters (a ParameterData interface) for the
1781 public static ParameterData GetParameterData (MethodBase mb)
1783 object pd = method_parameter_cache [mb];
1787 return (ParameterData) pd;
1790 ip = TypeContainer.LookupParametersByBuilder (mb);
1792 method_parameter_cache [mb] = ip;
1794 return (ParameterData) ip;
1796 ParameterInfo [] pi = mb.GetParameters ();
1797 ReflectionParameters rp = new ReflectionParameters (pi);
1798 method_parameter_cache [mb] = rp;
1800 return (ParameterData) rp;
1805 // Tells whether a user defined conversion from Type `from' to
1806 // Type `to' exists.
1808 // FIXME: we could implement a cache here.
1810 static bool ConversionExists (EmitContext ec, Type from, Type to, Location loc)
1812 // Locate user-defined implicit operators
1816 mg = MemberLookup (ec, to, "op_Implicit", false, loc);
1819 MethodGroupExpr me = (MethodGroupExpr) mg;
1821 for (int i = me.Methods.Length; i > 0;) {
1823 MethodBase mb = me.Methods [i];
1824 ParameterData pd = GetParameterData (mb);
1826 if (from == pd.ParameterType (0))
1831 mg = MemberLookup (ec, from, "op_Implicit", false, loc);
1834 MethodGroupExpr me = (MethodGroupExpr) mg;
1836 for (int i = me.Methods.Length; i > 0;) {
1838 MethodBase mb = me.Methods [i];
1839 MethodInfo mi = (MethodInfo) mb;
1841 if (mi.ReturnType == to)
1850 // Determines "better conversion" as specified in 7.4.2.3
1851 // Returns : 1 if a->p is better
1852 // 0 if a->q or neither is better
1854 static int BetterConversion (EmitContext ec, Argument a, Type p, Type q, bool use_standard,
1857 Type argument_type = a.Type;
1858 Expression argument_expr = a.Expr;
1860 if (argument_type == null)
1861 throw new Exception ("Expression of type " + a.Expr + " does not resolve its type");
1866 if (argument_type == p)
1869 if (argument_type == q)
1873 // Now probe whether an implicit constant expression conversion
1876 // An implicit constant expression conversion permits the following
1879 // * A constant-expression of type `int' can be converted to type
1880 // sbyte, byute, short, ushort, uint, ulong provided the value of
1881 // of the expression is withing the range of the destination type.
1883 // * A constant-expression of type long can be converted to type
1884 // ulong, provided the value of the constant expression is not negative
1886 // FIXME: Note that this assumes that constant folding has
1887 // taken place. We dont do constant folding yet.
1890 if (argument_expr is IntLiteral){
1891 IntLiteral ei = (IntLiteral) argument_expr;
1892 int value = ei.Value;
1894 if (p == TypeManager.sbyte_type){
1895 if (value >= SByte.MinValue && value <= SByte.MaxValue)
1897 } else if (p == TypeManager.byte_type){
1898 if (Byte.MinValue >= 0 && value <= Byte.MaxValue)
1900 } else if (p == TypeManager.short_type){
1901 if (value >= Int16.MinValue && value <= Int16.MaxValue)
1903 } else if (p == TypeManager.ushort_type){
1904 if (value >= UInt16.MinValue && value <= UInt16.MaxValue)
1906 } else if (p == TypeManager.uint32_type){
1908 // we can optimize this case: a positive int32
1909 // always fits on a uint32
1913 } else if (p == TypeManager.uint64_type){
1915 // we can optimize this case: a positive int32
1916 // always fits on a uint64
1921 } else if (argument_type == TypeManager.int64_type && argument_expr is LongLiteral){
1922 LongLiteral ll = (LongLiteral) argument_expr;
1924 if (p == TypeManager.uint64_type){
1935 tmp = ConvertImplicitStandard (ec, argument_expr, p, loc);
1937 tmp = ConvertImplicit (ec, argument_expr, p, loc);
1946 if (ConversionExists (ec, p, q, loc) == true &&
1947 ConversionExists (ec, q, p, loc) == false)
1950 if (p == TypeManager.sbyte_type)
1951 if (q == TypeManager.byte_type || q == TypeManager.ushort_type ||
1952 q == TypeManager.uint32_type || q == TypeManager.uint64_type)
1955 if (p == TypeManager.short_type)
1956 if (q == TypeManager.ushort_type || q == TypeManager.uint32_type ||
1957 q == TypeManager.uint64_type)
1960 if (p == TypeManager.int32_type)
1961 if (q == TypeManager.uint32_type || q == TypeManager.uint64_type)
1964 if (p == TypeManager.int64_type)
1965 if (q == TypeManager.uint64_type)
1972 // Determines "Better function" and returns an integer indicating :
1973 // 0 if candidate ain't better
1974 // 1 if candidate is better than the current best match
1976 static int BetterFunction (EmitContext ec, ArrayList args,
1977 MethodBase candidate, MethodBase best,
1978 bool use_standard, Location loc)
1980 ParameterData candidate_pd = GetParameterData (candidate);
1981 ParameterData best_pd;
1987 argument_count = args.Count;
1989 if (candidate_pd.Count == 0 && argument_count == 0)
1993 if (candidate_pd.Count == argument_count) {
1995 for (int j = argument_count; j > 0;) {
1998 Argument a = (Argument) args [j];
2000 x = BetterConversion (
2001 ec, a, candidate_pd.ParameterType (j), null,
2017 best_pd = GetParameterData (best);
2019 if (candidate_pd.Count == argument_count && best_pd.Count == argument_count) {
2020 int rating1 = 0, rating2 = 0;
2022 for (int j = argument_count; j > 0;) {
2026 Argument a = (Argument) args [j];
2028 x = BetterConversion (ec, a, candidate_pd.ParameterType (j),
2029 best_pd.ParameterType (j), use_standard, loc);
2030 y = BetterConversion (ec, a, best_pd.ParameterType (j),
2031 candidate_pd.ParameterType (j), use_standard,
2038 if (rating1 > rating2)
2047 public static string FullMethodDesc (MethodBase mb)
2049 StringBuilder sb = new StringBuilder (mb.Name);
2050 ParameterData pd = GetParameterData (mb);
2052 int count = pd.Count;
2055 for (int i = count; i > 0; ) {
2058 sb.Append (pd.ParameterDesc (count - i - 1));
2064 return sb.ToString ();
2067 public static MethodGroupExpr MakeUnionSet (Expression mg1, Expression mg2)
2069 MemberInfo [] miset;
2070 MethodGroupExpr union;
2072 if (mg1 != null && mg2 != null) {
2074 MethodGroupExpr left_set = null, right_set = null;
2075 int length1 = 0, length2 = 0;
2077 left_set = (MethodGroupExpr) mg1;
2078 length1 = left_set.Methods.Length;
2080 right_set = (MethodGroupExpr) mg2;
2081 length2 = right_set.Methods.Length;
2083 ArrayList common = new ArrayList ();
2085 for (int i = 0; i < left_set.Methods.Length; i++) {
2086 for (int j = 0; j < right_set.Methods.Length; j++) {
2087 if (left_set.Methods [i] == right_set.Methods [j])
2088 common.Add (left_set.Methods [i]);
2092 miset = new MemberInfo [length1 + length2 - common.Count];
2094 left_set.Methods.CopyTo (miset, 0);
2098 for (int j = 0; j < right_set.Methods.Length; j++)
2099 if (!common.Contains (right_set.Methods [j]))
2100 miset [length1 + k++] = right_set.Methods [j];
2102 union = new MethodGroupExpr (miset);
2106 } else if (mg1 == null && mg2 != null) {
2108 MethodGroupExpr me = (MethodGroupExpr) mg2;
2110 miset = new MemberInfo [me.Methods.Length];
2111 me.Methods.CopyTo (miset, 0);
2113 union = new MethodGroupExpr (miset);
2117 } else if (mg2 == null && mg1 != null) {
2119 MethodGroupExpr me = (MethodGroupExpr) mg1;
2121 miset = new MemberInfo [me.Methods.Length];
2122 me.Methods.CopyTo (miset, 0);
2124 union = new MethodGroupExpr (miset);
2133 // Determines is the candidate method, if a params method, is applicable
2134 // in its expanded form to the given set of arguments
2136 static bool IsParamsMethodApplicable (ArrayList arguments, MethodBase candidate)
2140 if (arguments == null)
2143 arg_count = arguments.Count;
2145 ParameterData pd = GetParameterData (candidate);
2147 int pd_count = pd.Count;
2149 if (pd.ParameterModifier (pd_count - 1) != Parameter.Modifier.PARAMS)
2152 if (pd_count - 1 > arg_count)
2155 // If we have come this far, the case which remains is when the number of parameters
2156 // is less than or equal to the argument count. So, we now check if the element type
2157 // of the params array is compatible with each argument type
2160 Type element_type = pd.ParameterType (pd_count - 1).GetElementType ();
2162 for (int i = pd_count - 1; i < arg_count - 1; i++) {
2163 Argument a = (Argument) arguments [i];
2164 if (!StandardConversionExists (a.Type, element_type))
2172 // Determines if the candidate method is applicable (section 14.4.2.1)
2173 // to the given set of arguments
2175 static bool IsApplicable (ArrayList arguments, MethodBase candidate)
2179 if (arguments == null)
2182 arg_count = arguments.Count;
2184 ParameterData pd = GetParameterData (candidate);
2186 int pd_count = pd.Count;
2188 if (arg_count != pd.Count)
2191 for (int i = arg_count; i > 0; ) {
2194 Argument a = (Argument) arguments [i];
2196 Parameter.Modifier a_mod = a.GetParameterModifier ();
2197 Parameter.Modifier p_mod = pd.ParameterModifier (i);
2199 if (a_mod == p_mod) {
2201 if (a_mod == Parameter.Modifier.NONE)
2202 if (!StandardConversionExists (a.Type, pd.ParameterType (i)))
2205 if (a_mod == Parameter.Modifier.REF ||
2206 a_mod == Parameter.Modifier.OUT)
2207 if (pd.ParameterType (i) != a.Type)
2219 // Find the Applicable Function Members (7.4.2.1)
2221 // me: Method Group expression with the members to select.
2222 // it might contain constructors or methods (or anything
2223 // that maps to a method).
2225 // Arguments: ArrayList containing resolved Argument objects.
2227 // loc: The location if we want an error to be reported, or a Null
2228 // location for "probing" purposes.
2230 // use_standard: controls whether OverloadResolve should use the
2231 // ConvertImplicit or ConvertImplicitStandard during overload resolution.
2233 // Returns: The MethodBase (either a ConstructorInfo or a MethodInfo)
2234 // that is the best match of me on Arguments.
2237 public static MethodBase OverloadResolve (EmitContext ec, MethodGroupExpr me,
2238 ArrayList Arguments, Location loc,
2241 ArrayList afm = new ArrayList ();
2242 int best_match_idx = -1;
2243 MethodBase method = null;
2246 for (int i = me.Methods.Length; i > 0; ){
2248 MethodBase candidate = me.Methods [i];
2251 // Check if candidate is applicable (section 14.4.2.1)
2252 if (!IsApplicable (Arguments, candidate))
2255 x = BetterFunction (ec, Arguments, candidate, method, use_standard, loc);
2261 method = me.Methods [best_match_idx];
2265 if (Arguments == null)
2268 argument_count = Arguments.Count;
2271 // Now we see if we can find params functions, applicable in their expanded form
2272 // since if they were applicable in their normal form, they would have been selected
2275 if (best_match_idx == -1) {
2277 for (int i = me.Methods.Length; i > 0; ) {
2279 MethodBase candidate = me.Methods [i];
2281 if (IsParamsMethodApplicable (Arguments, candidate)) {
2283 method = me.Methods [best_match_idx];
2290 // Now we see if we can at least find a method with the same number of arguments
2294 if (best_match_idx == -1) {
2296 for (int i = me.Methods.Length; i > 0;) {
2298 MethodBase mb = me.Methods [i];
2299 pd = GetParameterData (mb);
2301 if (pd.Count == argument_count) {
2303 method = me.Methods [best_match_idx];
2313 // And now convert implicitly, each argument to the required type
2315 pd = GetParameterData (method);
2316 int pd_count = pd.Count;
2318 for (int j = 0; j < argument_count; j++) {
2320 Argument a = (Argument) Arguments [j];
2321 Expression a_expr = a.Expr;
2322 Type parameter_type = pd.ParameterType (j);
2325 // Note that we need to compare against the element type
2326 // when we have a params method
2328 if (pd.ParameterModifier (pd_count - 1) == Parameter.Modifier.PARAMS) {
2329 if (j >= pd_count - 1)
2330 parameter_type = pd.ParameterType (pd_count - 1).GetElementType ();
2333 if (a.Type != parameter_type){
2337 conv = ConvertImplicitStandard (ec, a_expr, parameter_type,
2340 conv = ConvertImplicit (ec, a_expr, parameter_type,
2344 if (!Location.IsNull (loc)) {
2346 "The best overloaded match for method '" + FullMethodDesc (method)+
2347 "' has some invalid arguments");
2349 "Argument " + (j+1) +
2350 ": Cannot convert from '" + Argument.FullDesc (a)
2351 + "' to '" + pd.ParameterDesc (j) + "'");
2359 // Update the argument with the implicit conversion
2364 // FIXME : For the case of params methods, we need to actually instantiate
2365 // an array and initialize it with the argument values etc etc.
2369 if (a.GetParameterModifier () != pd.ParameterModifier (j) &&
2370 pd.ParameterModifier (j) != Parameter.Modifier.PARAMS) {
2371 if (!Location.IsNull (loc)) {
2373 "The best overloaded match for method '" + FullMethodDesc (method)+
2374 "' has some invalid arguments");
2376 "Argument " + (j+1) +
2377 ": Cannot convert from '" + Argument.FullDesc (a)
2378 + "' to '" + pd.ParameterDesc (j) + "'");
2389 public static MethodBase OverloadResolve (EmitContext ec, MethodGroupExpr me,
2390 ArrayList Arguments, Location loc)
2392 return OverloadResolve (ec, me, Arguments, loc, false);
2395 public override Expression DoResolve (EmitContext ec)
2398 // First, resolve the expression that is used to
2399 // trigger the invocation
2401 expr = expr.Resolve (ec);
2405 if (!(expr is MethodGroupExpr)) {
2406 Type expr_type = expr.Type;
2408 if (expr_type != null){
2409 bool IsDelegate = TypeManager.IsDelegateType (expr_type);
2411 return (new DelegateInvocation (
2412 this.expr, Arguments, Location)).Resolve (ec);
2416 if (!(expr is MethodGroupExpr)){
2417 report118 (Location, this.expr, "method group");
2422 // Next, evaluate all the expressions in the argument list
2424 if (Arguments != null){
2425 for (int i = Arguments.Count; i > 0;){
2427 Argument a = (Argument) Arguments [i];
2429 if (!a.Resolve (ec))
2434 method = OverloadResolve (ec, (MethodGroupExpr) this.expr, Arguments,
2437 if (method == null){
2438 Error (-6, Location,
2439 "Could not find any applicable function for this argument list");
2443 if (method is MethodInfo)
2444 type = ((MethodInfo)method).ReturnType;
2446 eclass = ExprClass.Value;
2450 public static void EmitArguments (EmitContext ec, ArrayList Arguments)
2454 if (Arguments != null)
2455 top = Arguments.Count;
2459 for (int i = 0; i < top; i++){
2460 Argument a = (Argument) Arguments [i];
2466 public static void EmitCall (EmitContext ec,
2467 bool is_static, Expression instance_expr,
2468 MethodBase method, ArrayList Arguments)
2470 ILGenerator ig = ec.ig;
2471 bool struct_call = false;
2475 // If this is ourselves, push "this"
2477 if (instance_expr == null){
2478 ig.Emit (OpCodes.Ldarg_0);
2481 // Push the instance expression
2483 if (instance_expr.Type.IsSubclassOf (TypeManager.value_type)){
2488 // If the expression implements IMemoryLocation, then
2489 // we can optimize and use AddressOf on the
2492 // If not we have to use some temporary storage for
2494 if (instance_expr is IMemoryLocation)
2495 ((IMemoryLocation) instance_expr).AddressOf (ec);
2497 Type t = instance_expr.Type;
2499 instance_expr.Emit (ec);
2500 LocalBuilder temp = ec.GetTemporaryStorage (t);
2501 ig.Emit (OpCodes.Stloc, temp);
2502 ig.Emit (OpCodes.Ldloca, temp);
2505 instance_expr.Emit (ec);
2509 if (Arguments != null)
2510 EmitArguments (ec, Arguments);
2512 if (is_static || struct_call){
2513 if (method is MethodInfo)
2514 ig.Emit (OpCodes.Call, (MethodInfo) method);
2516 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
2518 if (method is MethodInfo)
2519 ig.Emit (OpCodes.Callvirt, (MethodInfo) method);
2521 ig.Emit (OpCodes.Callvirt, (ConstructorInfo) method);
2525 public override void Emit (EmitContext ec)
2527 MethodGroupExpr mg = (MethodGroupExpr) this.expr;
2528 EmitCall (ec, method.IsStatic, mg.InstanceExpression, method, Arguments);
2531 public override void EmitStatement (EmitContext ec)
2536 // Pop the return value if there is one
2538 if (method is MethodInfo){
2539 if (((MethodInfo)method).ReturnType != TypeManager.void_type)
2540 ec.ig.Emit (OpCodes.Pop);
2545 public class New : ExpressionStatement {
2546 public readonly ArrayList Arguments;
2547 public readonly string RequestedType;
2550 MethodBase method = null;
2553 // If set, the new expression is for a value_target, and
2554 // we will not leave anything on the stack.
2556 Expression value_target;
2558 public New (string requested_type, ArrayList arguments, Location loc)
2560 RequestedType = requested_type;
2561 Arguments = arguments;
2565 public Expression ValueTypeVariable {
2567 return value_target;
2571 value_target = value;
2575 public override Expression DoResolve (EmitContext ec)
2577 type = ec.TypeContainer.LookupType (RequestedType, false);
2582 bool IsDelegate = TypeManager.IsDelegateType (type);
2585 return (new NewDelegate (type, Arguments, Location)).Resolve (ec);
2589 ml = MemberLookup (ec, type, ".ctor", false,
2590 MemberTypes.Constructor, AllBindingsFlags, Location);
2592 bool is_struct = false;
2593 is_struct = type.IsSubclassOf (TypeManager.value_type);
2595 if (! (ml is MethodGroupExpr)){
2597 report118 (Location, ml, "method group");
2603 if (Arguments != null){
2604 for (int i = Arguments.Count; i > 0;){
2606 Argument a = (Argument) Arguments [i];
2608 if (!a.Resolve (ec))
2613 method = Invocation.OverloadResolve (ec, (MethodGroupExpr) ml,
2614 Arguments, Location);
2617 if (method == null && !is_struct) {
2618 Error (-6, Location,
2619 "New invocation: Can not find a constructor for " +
2620 "this argument list");
2624 eclass = ExprClass.Value;
2629 // This DoEmit can be invoked in two contexts:
2630 // * As a mechanism that will leave a value on the stack (new object)
2631 // * As one that wont (init struct)
2633 // You can control whether a value is required on the stack by passing
2634 // need_value_on_stack. The code *might* leave a value on the stack
2635 // so it must be popped manually
2637 // Returns whether a value is left on the stack
2639 bool DoEmit (EmitContext ec, bool need_value_on_stack)
2641 if (method == null){
2642 IMemoryLocation ml = (IMemoryLocation) value_target;
2646 Invocation.EmitArguments (ec, Arguments);
2647 ec.ig.Emit (OpCodes.Newobj, (ConstructorInfo) method);
2652 // It must be a value type, sanity check
2654 if (value_target != null){
2655 ec.ig.Emit (OpCodes.Initobj, type);
2657 if (need_value_on_stack){
2658 value_target.Emit (ec);
2664 throw new Exception ("No method and no value type");
2667 public override void Emit (EmitContext ec)
2672 public override void EmitStatement (EmitContext ec)
2674 if (DoEmit (ec, false))
2675 ec.ig.Emit (OpCodes.Pop);
2680 // Represents an array creation expression.
2684 // There are two possible scenarios here: one is an array creation
2685 // expression that specifies the dimensions and optionally the
2686 // initialization data
2688 public class ArrayCreation : ExpressionStatement {
2690 string RequestedType;
2692 ArrayList Initializers;
2694 ArrayList Arguments;
2696 MethodBase method = null;
2697 Type array_element_type;
2698 bool IsOneDimensional = false;
2700 bool IsBuiltinType = false;
2702 public ArrayCreation (string requested_type, ArrayList exprs,
2703 string rank, ArrayList initializers, Location l)
2705 RequestedType = requested_type;
2707 Initializers = initializers;
2710 Arguments = new ArrayList ();
2712 foreach (Expression e in exprs)
2713 Arguments.Add (new Argument (e, Argument.AType.Expression));
2717 public ArrayCreation (string requested_type, string rank, ArrayList initializers, Location l)
2719 RequestedType = requested_type;
2721 Initializers = initializers;
2725 public static string FormArrayType (string base_type, int idx_count, string rank)
2727 StringBuilder sb = new StringBuilder (base_type);
2732 for (int i = 1; i < idx_count; i++)
2736 return sb.ToString ();
2739 public static string FormElementType (string base_type, int idx_count, string rank)
2741 StringBuilder sb = new StringBuilder (base_type);
2744 for (int i = 1; i < idx_count; i++)
2750 string val = sb.ToString ();
2752 return val.Substring (0, val.LastIndexOf ("["));
2756 public override Expression DoResolve (EmitContext ec)
2760 if (Arguments == null)
2763 arg_count = Arguments.Count;
2765 string array_type = FormArrayType (RequestedType, arg_count, Rank);
2767 string element_type = FormElementType (RequestedType, arg_count, Rank);
2769 type = ec.TypeContainer.LookupType (array_type, false);
2771 array_element_type = ec.TypeContainer.LookupType (element_type, false);
2776 if (arg_count == 1) {
2777 IsOneDimensional = true;
2778 eclass = ExprClass.Value;
2782 IsBuiltinType = TypeManager.IsBuiltinType (type);
2784 if (IsBuiltinType) {
2788 ml = MemberLookup (ec, type, ".ctor", false, MemberTypes.Constructor,
2789 AllBindingsFlags, Location);
2791 if (!(ml is MethodGroupExpr)){
2792 report118 (Location, ml, "method group");
2797 Report.Error (-6, Location, "New invocation: Can not find a constructor for " +
2798 "this argument list");
2802 if (Arguments != null) {
2803 for (int i = arg_count; i > 0;){
2805 Argument a = (Argument) Arguments [i];
2807 if (!a.Resolve (ec))
2812 method = Invocation.OverloadResolve (ec, (MethodGroupExpr) ml, Arguments, Location);
2814 if (method == null) {
2815 Report.Error (-6, Location, "New invocation: Can not find a constructor for " +
2816 "this argument list");
2820 eclass = ExprClass.Value;
2825 ModuleBuilder mb = ec.TypeContainer.RootContext.ModuleBuilder;
2827 ArrayList args = new ArrayList ();
2828 if (Arguments != null){
2829 for (int i = arg_count; i > 0;){
2831 Argument a = (Argument) Arguments [i];
2833 if (!a.Resolve (ec))
2840 Type [] arg_types = null;
2843 arg_types = new Type [args.Count];
2845 args.CopyTo (arg_types, 0);
2847 method = mb.GetArrayMethod (type, ".ctor", CallingConventions.HasThis, null,
2850 if (method == null) {
2851 Report.Error (-6, Location, "New invocation: Can not find a constructor for " +
2852 "this argument list");
2856 eclass = ExprClass.Value;
2862 public override void Emit (EmitContext ec)
2864 if (IsOneDimensional) {
2865 Invocation.EmitArguments (ec, Arguments);
2866 ec.ig.Emit (OpCodes.Newarr, array_element_type);
2869 Invocation.EmitArguments (ec, Arguments);
2872 ec.ig.Emit (OpCodes.Newobj, (ConstructorInfo) method);
2874 ec.ig.Emit (OpCodes.Newobj, (MethodInfo) method);
2879 public override void EmitStatement (EmitContext ec)
2882 ec.ig.Emit (OpCodes.Pop);
2888 // Represents the `this' construct
2890 public class This : Expression, IStackStore, IMemoryLocation {
2893 public This (Location loc)
2898 public override Expression DoResolve (EmitContext ec)
2900 eclass = ExprClass.Variable;
2901 type = ec.TypeContainer.TypeBuilder;
2904 Report.Error (26, loc,
2905 "Keyword this not valid in static code");
2912 public Expression DoResolveLValue (EmitContext ec)
2916 if (ec.TypeContainer is Class){
2917 Report.Error (1604, loc, "Cannot assign to `this'");
2924 public override void Emit (EmitContext ec)
2926 ec.ig.Emit (OpCodes.Ldarg_0);
2929 public void Store (EmitContext ec)
2931 ec.ig.Emit (OpCodes.Starg, 0);
2934 public void AddressOf (EmitContext ec)
2936 ec.ig.Emit (OpCodes.Ldarga_S, (byte) 0);
2941 // Implements the typeof operator
2943 public class TypeOf : Expression {
2944 public readonly string QueriedType;
2947 public TypeOf (string queried_type)
2949 QueriedType = queried_type;
2952 public override Expression DoResolve (EmitContext ec)
2954 typearg = ec.TypeContainer.LookupType (QueriedType, false);
2956 if (typearg == null)
2959 type = TypeManager.type_type;
2960 eclass = ExprClass.Type;
2964 public override void Emit (EmitContext ec)
2966 ec.ig.Emit (OpCodes.Ldtoken, typearg);
2967 ec.ig.Emit (OpCodes.Call, TypeManager.system_type_get_type_from_handle);
2971 public class SizeOf : Expression {
2972 public readonly string QueriedType;
2974 public SizeOf (string queried_type)
2976 this.QueriedType = queried_type;
2979 public override Expression DoResolve (EmitContext ec)
2981 // FIXME: Implement;
2982 throw new Exception ("Unimplemented");
2986 public override void Emit (EmitContext ec)
2988 throw new Exception ("Implement me");
2992 public class MemberAccess : Expression {
2993 public readonly string Identifier;
2995 Expression member_lookup;
2998 public MemberAccess (Expression expr, string id, Location l)
3005 public Expression Expr {
3011 void error176 (Location loc, string name)
3013 Report.Error (176, loc, "Static member `" +
3014 name + "' cannot be accessed " +
3015 "with an instance reference, qualify with a " +
3016 "type name instead");
3019 public override Expression DoResolve (EmitContext ec)
3022 // We are the sole users of ResolveWithSimpleName (ie, the only
3023 // ones that can cope with it
3025 expr = expr.ResolveWithSimpleName (ec);
3030 if (expr is SimpleName){
3031 SimpleName child_expr = (SimpleName) expr;
3033 expr = new SimpleName (child_expr.Name + "." + Identifier, loc);
3035 return expr.Resolve (ec);
3038 member_lookup = MemberLookup (ec, expr.Type, Identifier, false, loc);
3040 if (member_lookup == null)
3046 if (member_lookup is MethodGroupExpr){
3047 MethodGroupExpr mg = (MethodGroupExpr) member_lookup;
3052 if (expr is TypeExpr){
3053 if (!mg.RemoveInstanceMethods ()){
3054 SimpleName.Error120 (loc, mg.Methods [0].Name);
3058 return member_lookup;
3062 // Instance.MethodGroup
3064 if (!mg.RemoveStaticMethods ()){
3065 error176 (loc, mg.Methods [0].Name);
3069 mg.InstanceExpression = expr;
3071 return member_lookup;
3074 if (member_lookup is FieldExpr){
3075 FieldExpr fe = (FieldExpr) member_lookup;
3077 if (expr is TypeExpr){
3078 if (!fe.FieldInfo.IsStatic){
3079 error176 (loc, fe.FieldInfo.Name);
3082 return member_lookup;
3084 if (fe.FieldInfo.IsStatic){
3085 error176 (loc, fe.FieldInfo.Name);
3088 fe.InstanceExpression = expr;
3094 if (member_lookup is PropertyExpr){
3095 PropertyExpr pe = (PropertyExpr) member_lookup;
3097 if (expr is TypeExpr){
3099 SimpleName.Error120 (loc, pe.PropertyInfo.Name);
3105 error176 (loc, pe.PropertyInfo.Name);
3108 pe.InstanceExpression = expr;
3114 Console.WriteLine ("Support for [" + member_lookup + "] is not present yet");
3115 Environment.Exit (0);
3119 public override void Emit (EmitContext ec)
3121 throw new Exception ("Should not happen I think");
3126 public class CheckedExpr : Expression {
3128 public Expression Expr;
3130 public CheckedExpr (Expression e)
3135 public override Expression DoResolve (EmitContext ec)
3137 Expr = Expr.Resolve (ec);
3142 eclass = Expr.ExprClass;
3147 public override void Emit (EmitContext ec)
3149 bool last_check = ec.CheckState;
3151 ec.CheckState = true;
3153 ec.CheckState = last_check;
3158 public class UnCheckedExpr : Expression {
3160 public Expression Expr;
3162 public UnCheckedExpr (Expression e)
3167 public override Expression DoResolve (EmitContext ec)
3169 Expr = Expr.Resolve (ec);
3174 eclass = Expr.ExprClass;
3179 public override void Emit (EmitContext ec)
3181 bool last_check = ec.CheckState;
3183 ec.CheckState = false;
3185 ec.CheckState = last_check;
3190 public class ElementAccess : Expression {
3192 public ArrayList Arguments;
3193 public Expression Expr;
3194 public Location loc;
3196 public ElementAccess (Expression e, ArrayList e_list, Location l)
3200 Arguments = new ArrayList ();
3201 foreach (Expression tmp in e_list)
3202 Arguments.Add (new Argument (tmp, Argument.AType.Expression));
3207 bool CommonResolve (EmitContext ec)
3209 Expr = Expr.Resolve (ec);
3214 if (Arguments == null)
3217 for (int i = Arguments.Count; i > 0;){
3219 Argument a = (Argument) Arguments [i];
3221 if (!a.Resolve (ec))
3228 public override Expression DoResolve (EmitContext ec)
3230 if (!CommonResolve (ec))
3234 // We perform some simple tests, and then to "split" the emit and store
3235 // code we create an instance of a different class, and return that.
3237 // I am experimenting with this pattern.
3239 if (Expr.Type == TypeManager.array_type)
3240 return (new ArrayAccess (this)).Resolve (ec);
3242 return (new IndexerAccess (this)).Resolve (ec);
3245 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
3247 if (!CommonResolve (ec))
3250 if (Expr.Type == TypeManager.array_type)
3251 return (new ArrayAccess (this)).ResolveLValue (ec, right_side);
3253 return (new IndexerAccess (this)).ResolveLValue (ec, right_side);
3256 public override void Emit (EmitContext ec)
3258 throw new Exception ("Should never be reached");
3262 public class ArrayAccess : Expression, IStackStore {
3264 // Points to our "data" repository
3268 public ArrayAccess (ElementAccess ea_data)
3271 eclass = ExprClass.Variable;
3274 // FIXME: Figure out the type here
3278 Expression CommonResolve (EmitContext ec)
3283 public override Expression DoResolve (EmitContext ec)
3285 if (ea.Expr.ExprClass != ExprClass.Variable) {
3286 report118 (ea.loc, ea.Expr, "variable");
3290 throw new Exception ("Implement me");
3293 public void Store (EmitContext ec)
3295 throw new Exception ("Implement me !");
3298 public override void Emit (EmitContext ec)
3300 throw new Exception ("Implement me !");
3305 public ArrayList getters, setters;
3306 static Hashtable map;
3310 map = new Hashtable ();
3313 Indexers (MemberInfo [] mi)
3315 foreach (PropertyInfo property in mi){
3316 MethodInfo get, set;
3318 get = property.GetGetMethod (true);
3320 if (getters == null)
3321 getters = new ArrayList ();
3326 set = property.GetSetMethod (true);
3328 if (setters == null)
3329 setters = new ArrayList ();
3335 static public Indexers GetIndexersForType (Type t, TypeManager tm, Location loc)
3337 Indexers ix = (Indexers) map [t];
3338 string p_name = TypeManager.IndexerPropertyName (t);
3343 MemberInfo [] mi = tm.FindMembers (
3344 t, MemberTypes.Property,
3345 BindingFlags.Public | BindingFlags.Instance,
3346 Type.FilterName, p_name);
3348 if (mi == null || mi.Length == 0){
3349 Report.Error (21, loc,
3350 "Type `" + TypeManager.CSharpName (t) + "' does not have " +
3351 "any indexers defined");
3355 ix = new Indexers (mi);
3362 public class IndexerAccess : Expression, IAssignMethod {
3364 // Points to our "data" repository
3367 MethodInfo get, set;
3369 ArrayList set_arguments;
3371 public IndexerAccess (ElementAccess ea_data)
3374 eclass = ExprClass.Value;
3377 public bool VerifyAssignable (Expression source)
3379 throw new Exception ("Implement me!");
3382 public override Expression DoResolve (EmitContext ec)
3384 Type indexer_type = ea.Expr.Type;
3387 // Step 1: Query for all `Item' *properties*. Notice
3388 // that the actual methods are pointed from here.
3390 // This is a group of properties, piles of them.
3393 ilist = Indexers.GetIndexersForType (
3394 indexer_type, ec.TypeContainer.RootContext.TypeManager, ea.loc);
3396 if (ilist != null && ilist.getters != null && ilist.getters.Count > 0)
3397 get = (MethodInfo) Invocation.OverloadResolve (
3398 ec, new MethodGroupExpr (ilist.getters), ea.Arguments, ea.loc);
3401 Report.Error (154, ea.loc,
3402 "indexer can not be used in this context, because " +
3403 "it lacks a `get' accessor");
3407 type = get.ReturnType;
3408 eclass = ExprClass.Value;
3412 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
3414 Type indexer_type = ea.Expr.Type;
3415 Type right_type = right_side.Type;
3418 ilist = Indexers.GetIndexersForType (
3419 indexer_type, ec.TypeContainer.RootContext.TypeManager, ea.loc);
3421 if (ilist != null && ilist.setters != null && ilist.setters.Count > 0){
3422 set_arguments = (ArrayList) ea.Arguments.Clone ();
3423 set_arguments.Add (new Argument (right_side, Argument.AType.Expression));
3425 set = (MethodInfo) Invocation.OverloadResolve (
3426 ec, new MethodGroupExpr (ilist.setters), set_arguments, ea.loc);
3430 Report.Error (200, ea.loc,
3431 "indexer X.this [" + TypeManager.CSharpName (right_type) +
3432 "] lacks a `set' accessor");
3436 type = TypeManager.void_type;
3437 eclass = ExprClass.IndexerAccess;
3441 public override void Emit (EmitContext ec)
3443 Invocation.EmitCall (ec, false, ea.Expr, get, ea.Arguments);
3447 // source is ignored, because we already have a copy of it from the
3448 // LValue resolution and we have already constructed a pre-cached
3449 // version of the arguments (ea.set_arguments);
3451 public void EmitAssign (EmitContext ec, Expression source)
3453 Invocation.EmitCall (ec, false, ea.Expr, set, set_arguments);
3457 public class BaseAccess : Expression {
3459 public enum BaseAccessType {
3464 public readonly BaseAccessType BAType;
3465 public readonly string Member;
3466 public readonly ArrayList Arguments;
3468 public BaseAccess (BaseAccessType t, string member, ArrayList args)
3476 public override Expression DoResolve (EmitContext ec)
3478 // FIXME: Implement;
3479 throw new Exception ("Unimplemented");
3483 public override void Emit (EmitContext ec)
3485 throw new Exception ("Unimplemented");
3490 // This class exists solely to pass the Type around and to be a dummy
3491 // that can be passed to the conversion functions (this is used by
3492 // foreach implementation to typecast the object return value from
3493 // get_Current into the proper type. All code has been generated and
3494 // we only care about the side effect conversions to be performed
3497 public class EmptyExpression : Expression {
3498 public EmptyExpression ()
3500 type = TypeManager.object_type;
3501 eclass = ExprClass.Value;
3504 public override Expression DoResolve (EmitContext ec)
3509 public override void Emit (EmitContext ec)
3511 // nothing, as we only exist to not do anything.
3515 public class UserCast : Expression {
3519 public UserCast (MethodInfo method, Expression source)
3521 this.method = method;
3522 this.source = source;
3523 type = method.ReturnType;
3524 eclass = ExprClass.Value;
3527 public override Expression DoResolve (EmitContext ec)
3530 // We are born fully resolved
3535 public override void Emit (EmitContext ec)
3537 ILGenerator ig = ec.ig;
3541 if (method is MethodInfo)
3542 ig.Emit (OpCodes.Call, (MethodInfo) method);
3544 ig.Emit (OpCodes.Call, (ConstructorInfo) method);