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 /// Base class for the `Is' and `As' classes.
676 /// FIXME: Split this in two, and we get to save the `Operator' Oper
679 public abstract class Probe : Expression {
680 public readonly string ProbeType;
681 protected Expression expr;
682 protected Type probe_type;
684 public Probe (Expression expr, string probe_type)
686 ProbeType = probe_type;
690 public Expression Expr {
696 public override Expression DoResolve (EmitContext ec)
698 probe_type = ec.TypeContainer.LookupType (ProbeType, false);
700 if (probe_type == null)
703 expr = expr.Resolve (ec);
710 /// Implementation of the `is' operator.
712 public class Is : Probe {
713 public Is (Expression expr, string probe_type)
714 : base (expr, probe_type)
718 public override void Emit (EmitContext ec)
720 ILGenerator ig = ec.ig;
724 ig.Emit (OpCodes.Isinst, probe_type);
725 ig.Emit (OpCodes.Ldnull);
726 ig.Emit (OpCodes.Cgt_Un);
729 public override Expression DoResolve (EmitContext ec)
731 Expression e = base.DoResolve (ec);
736 type = TypeManager.bool_type;
737 eclass = ExprClass.Value;
744 /// Implementation of the `as' operator.
746 public class As : Probe {
747 public As (Expression expr, string probe_type)
748 : base (expr, probe_type)
752 public override void Emit (EmitContext ec)
754 ILGenerator ig = ec.ig;
757 ig.Emit (OpCodes.Isinst, probe_type);
760 public override Expression DoResolve (EmitContext ec)
762 Expression e = base.DoResolve (ec);
768 eclass = ExprClass.Value;
775 /// This represents a typecast in the source language.
777 /// FIXME: Cast expressions have an unusual set of parsing
778 /// rules, we need to figure those out.
780 public class Cast : Expression {
781 Expression target_type;
785 public Cast (Expression cast_type, Expression expr, Location loc)
787 this.target_type = cast_type;
792 public Expression TargetType {
798 public Expression Expr {
807 public override Expression DoResolve (EmitContext ec)
809 expr = expr.Resolve (ec);
813 target_type = target_type.Resolve (ec);
814 if (target_type == null)
817 if (target_type.ExprClass != ExprClass.Type){
818 report118 (loc, target_type, "class");
822 type = target_type.Type;
823 eclass = ExprClass.Value;
828 expr = ConvertExplicit (ec, expr, type, loc);
832 public override void Emit (EmitContext ec)
835 // This one will never happen
837 throw new Exception ("Should not happen");
844 public class Binary : Expression {
845 public enum Operator : byte {
846 Multiply, Division, Modulus,
847 Addition, Subtraction,
848 LeftShift, RightShift,
849 LessThan, GreaterThan, LessThanOrEqual, GreaterThanOrEqual,
850 Equality, Inequality,
859 Expression left, right;
865 public Binary (Operator oper, Expression left, Expression right, Location loc)
873 public Operator Oper {
882 public Expression Left {
891 public Expression Right {
902 /// Returns a stringified representation of the Operator
907 case Operator.Multiply:
909 case Operator.Division:
911 case Operator.Modulus:
913 case Operator.Addition:
915 case Operator.Subtraction:
917 case Operator.LeftShift:
919 case Operator.RightShift:
921 case Operator.LessThan:
923 case Operator.GreaterThan:
925 case Operator.LessThanOrEqual:
927 case Operator.GreaterThanOrEqual:
929 case Operator.Equality:
931 case Operator.Inequality:
933 case Operator.BitwiseAnd:
935 case Operator.BitwiseOr:
937 case Operator.ExclusiveOr:
939 case Operator.LogicalOr:
941 case Operator.LogicalAnd:
945 return oper.ToString ();
948 Expression ForceConversion (EmitContext ec, Expression expr, Type target_type)
950 if (expr.Type == target_type)
953 return ConvertImplicit (ec, expr, target_type, new Location (-1));
957 // Note that handling the case l == Decimal || r == Decimal
958 // is taken care of by the Step 1 Operator Overload resolution.
960 bool DoNumericPromotions (EmitContext ec, Type l, Type r)
962 if (l == TypeManager.double_type || r == TypeManager.double_type){
964 // If either operand is of type double, the other operand is
965 // conveted to type double.
967 if (r != TypeManager.double_type)
968 right = ConvertImplicit (ec, right, TypeManager.double_type, loc);
969 if (l != TypeManager.double_type)
970 left = ConvertImplicit (ec, left, TypeManager.double_type, loc);
972 type = TypeManager.double_type;
973 } else if (l == TypeManager.float_type || r == TypeManager.float_type){
975 // if either operand is of type float, th eother operand is
976 // converd to type float.
978 if (r != TypeManager.double_type)
979 right = ConvertImplicit (ec, right, TypeManager.float_type, loc);
980 if (l != TypeManager.double_type)
981 left = ConvertImplicit (ec, left, TypeManager.float_type, loc);
982 type = TypeManager.float_type;
983 } else if (l == TypeManager.uint64_type || r == TypeManager.uint64_type){
987 // If either operand is of type ulong, the other operand is
988 // converted to type ulong. or an error ocurrs if the other
989 // operand is of type sbyte, short, int or long
992 if (l == TypeManager.uint64_type){
993 if (r != TypeManager.uint64_type && right is IntLiteral){
994 e = TryImplicitIntConversion (l, (IntLiteral) right);
1000 if (left is IntLiteral){
1001 e = TryImplicitIntConversion (r, (IntLiteral) left);
1008 if ((other == TypeManager.sbyte_type) ||
1009 (other == TypeManager.short_type) ||
1010 (other == TypeManager.int32_type) ||
1011 (other == TypeManager.int64_type)){
1012 string oper = OperName ();
1014 Error (34, loc, "Operator `" + OperName ()
1015 + "' is ambiguous on operands of type `"
1016 + TypeManager.CSharpName (l) + "' "
1017 + "and `" + TypeManager.CSharpName (r)
1020 type = TypeManager.uint64_type;
1021 } else if (l == TypeManager.int64_type || r == TypeManager.int64_type){
1023 // If either operand is of type long, the other operand is converted
1026 if (l != TypeManager.int64_type)
1027 left = ConvertImplicit (ec, left, TypeManager.int64_type, loc);
1028 if (r != TypeManager.int64_type)
1029 right = ConvertImplicit (ec, right, TypeManager.int64_type, loc);
1031 type = TypeManager.int64_type;
1032 } else if (l == TypeManager.uint32_type || r == TypeManager.uint32_type){
1034 // If either operand is of type uint, and the other
1035 // operand is of type sbyte, short or int, othe operands are
1036 // converted to type long.
1040 if (l == TypeManager.uint32_type)
1042 else if (r == TypeManager.uint32_type)
1045 if ((other == TypeManager.sbyte_type) ||
1046 (other == TypeManager.short_type) ||
1047 (other == TypeManager.int32_type)){
1048 left = ForceConversion (ec, left, TypeManager.int64_type);
1049 right = ForceConversion (ec, right, TypeManager.int64_type);
1050 type = TypeManager.int64_type;
1053 // if either operand is of type uint, the other
1054 // operand is converd to type uint
1056 left = ForceConversion (ec, left, TypeManager.uint32_type);
1057 right = ForceConversion (ec, right, TypeManager.uint32_type);
1058 type = TypeManager.uint32_type;
1060 } else if (l == TypeManager.decimal_type || r == TypeManager.decimal_type){
1061 if (l != TypeManager.decimal_type)
1062 left = ConvertImplicit (ec, left, TypeManager.decimal_type, loc);
1063 if (r != TypeManager.decimal_type)
1064 right = ConvertImplicit (ec, right, TypeManager.decimal_type, loc);
1066 type = TypeManager.decimal_type;
1068 Expression l_tmp, r_tmp;
1070 l_tmp = ForceConversion (ec, left, TypeManager.int32_type);
1074 r_tmp = ForceConversion (ec, right, TypeManager.int32_type);
1081 type = TypeManager.int32_type;
1090 "Operator " + OperName () + " cannot be applied to operands of type `" +
1091 TypeManager.CSharpName (left.Type) + "' and `" +
1092 TypeManager.CSharpName (right.Type) + "'");
1096 Expression CheckShiftArguments (EmitContext ec)
1100 Type r = right.Type;
1102 e = ForceConversion (ec, right, TypeManager.int32_type);
1109 if (((e = ConvertImplicit (ec, left, TypeManager.int32_type, loc)) != null) ||
1110 ((e = ConvertImplicit (ec, left, TypeManager.uint32_type, loc)) != null) ||
1111 ((e = ConvertImplicit (ec, left, TypeManager.int64_type, loc)) != null) ||
1112 ((e = ConvertImplicit (ec, left, TypeManager.uint64_type, loc)) != null)){
1122 Expression ResolveOperator (EmitContext ec)
1125 Type r = right.Type;
1128 // Step 1: Perform Operator Overload location
1130 Expression left_expr, right_expr;
1132 string op = "op_" + oper;
1134 left_expr = MemberLookup (ec, l, op, false, loc);
1135 if (left_expr == null && l.BaseType != null)
1136 left_expr = MemberLookup (ec, l.BaseType, op, false, loc);
1138 right_expr = MemberLookup (ec, r, op, false, loc);
1139 if (right_expr == null && r.BaseType != null)
1140 right_expr = MemberLookup (ec, r.BaseType, op, false, loc);
1142 MethodGroupExpr union = Invocation.MakeUnionSet (left_expr, right_expr);
1144 if (union != null) {
1145 Arguments = new ArrayList ();
1146 Arguments.Add (new Argument (left, Argument.AType.Expression));
1147 Arguments.Add (new Argument (right, Argument.AType.Expression));
1149 method = Invocation.OverloadResolve (ec, union, Arguments, loc);
1150 if (method != null) {
1151 MethodInfo mi = (MethodInfo) method;
1152 type = mi.ReturnType;
1161 // Step 2: Default operations on CLI native types.
1164 // Only perform numeric promotions on:
1165 // +, -, *, /, %, &, |, ^, ==, !=, <, >, <=, >=
1167 if (oper == Operator.Addition){
1169 // If any of the arguments is a string, cast to string
1171 if (l == TypeManager.string_type){
1172 if (r == TypeManager.string_type){
1173 if (left is Literal && right is Literal){
1174 StringLiteral ls = (StringLiteral) left;
1175 StringLiteral rs = (StringLiteral) right;
1177 return new StringLiteral (ls.Value + rs.Value);
1181 method = TypeManager.string_concat_string_string;
1184 method = TypeManager.string_concat_object_object;
1185 right = ConvertImplicit (ec, right,
1186 TypeManager.object_type, loc);
1188 type = TypeManager.string_type;
1190 Arguments = new ArrayList ();
1191 Arguments.Add (new Argument (left, Argument.AType.Expression));
1192 Arguments.Add (new Argument (right, Argument.AType.Expression));
1196 } else if (r == TypeManager.string_type){
1198 method = TypeManager.string_concat_object_object;
1199 Arguments = new ArrayList ();
1200 Arguments.Add (new Argument (left, Argument.AType.Expression));
1201 Arguments.Add (new Argument (right, Argument.AType.Expression));
1203 left = ConvertImplicit (ec, left, TypeManager.object_type, loc);
1204 type = TypeManager.string_type;
1210 // FIXME: is Delegate operator + (D x, D y) handled?
1214 if (oper == Operator.LeftShift || oper == Operator.RightShift)
1215 return CheckShiftArguments (ec);
1217 if (oper == Operator.LogicalOr || oper == Operator.LogicalAnd){
1218 if (l != TypeManager.bool_type || r != TypeManager.bool_type){
1223 type = TypeManager.bool_type;
1227 if (oper == Operator.Equality || oper == Operator.Inequality){
1228 if (l == TypeManager.bool_type || r == TypeManager.bool_type){
1229 if (r != TypeManager.bool_type || l != TypeManager.bool_type){
1234 type = TypeManager.bool_type;
1241 // We are dealing with numbers
1244 if (!DoNumericPromotions (ec, l, r)){
1247 // operator != (object a, object b)
1248 // operator == (object a, object b)
1251 if (oper == Operator.Equality || oper == Operator.Inequality){
1253 li = ConvertImplicit (ec, left, TypeManager.object_type, loc);
1255 ri = ConvertImplicit (ec, right, TypeManager.object_type,
1261 type = TypeManager.bool_type;
1271 if (left == null || right == null)
1275 // reload our cached types if required
1280 if (oper == Operator.BitwiseAnd ||
1281 oper == Operator.BitwiseOr ||
1282 oper == Operator.ExclusiveOr){
1284 if (l.IsSubclassOf (TypeManager.enum_type) ||
1285 !((l == TypeManager.int32_type) ||
1286 (l == TypeManager.uint32_type) ||
1287 (l == TypeManager.int64_type) ||
1288 (l == TypeManager.uint64_type)))
1296 if (oper == Operator.Equality ||
1297 oper == Operator.Inequality ||
1298 oper == Operator.LessThanOrEqual ||
1299 oper == Operator.LessThan ||
1300 oper == Operator.GreaterThanOrEqual ||
1301 oper == Operator.GreaterThan){
1302 type = TypeManager.bool_type;
1308 public override Expression DoResolve (EmitContext ec)
1310 left = left.Resolve (ec);
1311 right = right.Resolve (ec);
1313 if (left == null || right == null)
1316 if (left.Type == null)
1317 throw new Exception (
1318 "Resolve returned non null, but did not set the type! (" +
1319 left + ") at Line: " + loc.Row);
1320 if (right.Type == null)
1321 throw new Exception (
1322 "Resolve returned non null, but did not set the type! (" +
1323 right + ") at Line: "+ loc.Row);
1325 eclass = ExprClass.Value;
1327 return ResolveOperator (ec);
1330 public bool IsBranchable ()
1332 if (oper == Operator.Equality ||
1333 oper == Operator.Inequality ||
1334 oper == Operator.LessThan ||
1335 oper == Operator.GreaterThan ||
1336 oper == Operator.LessThanOrEqual ||
1337 oper == Operator.GreaterThanOrEqual){
1344 /// This entry point is used by routines that might want
1345 /// to emit a brfalse/brtrue after an expression, and instead
1346 /// they could use a more compact notation.
1348 /// Typically the code would generate l.emit/r.emit, followed
1349 /// by the comparission and then a brtrue/brfalse. The comparissions
1350 /// are sometimes inneficient (there are not as complete as the branches
1351 /// look for the hacks in Emit using double ceqs).
1353 /// So for those cases we provide EmitBranchable that can emit the
1354 /// branch with the test
1356 public void EmitBranchable (EmitContext ec, int target)
1359 bool close_target = false;
1360 ILGenerator ig = ec.ig;
1363 // short-circuit operators
1365 if (oper == Operator.LogicalAnd){
1367 ig.Emit (OpCodes.Brfalse, target);
1369 ig.Emit (OpCodes.Brfalse, target);
1370 } else if (oper == Operator.LogicalOr){
1372 ig.Emit (OpCodes.Brtrue, target);
1374 ig.Emit (OpCodes.Brfalse, target);
1381 case Operator.Equality:
1383 opcode = OpCodes.Beq_S;
1385 opcode = OpCodes.Beq;
1388 case Operator.Inequality:
1390 opcode = OpCodes.Bne_Un_S;
1392 opcode = OpCodes.Bne_Un;
1395 case Operator.LessThan:
1397 opcode = OpCodes.Blt_S;
1399 opcode = OpCodes.Blt;
1402 case Operator.GreaterThan:
1404 opcode = OpCodes.Bgt_S;
1406 opcode = OpCodes.Bgt;
1409 case Operator.LessThanOrEqual:
1411 opcode = OpCodes.Ble_S;
1413 opcode = OpCodes.Ble;
1416 case Operator.GreaterThanOrEqual:
1418 opcode = OpCodes.Bge_S;
1420 opcode = OpCodes.Ble;
1424 throw new Exception ("EmitBranchable called on non-EmitBranchable operator: "
1425 + oper.ToString ());
1428 ig.Emit (opcode, target);
1431 public override void Emit (EmitContext ec)
1433 ILGenerator ig = ec.ig;
1435 Type r = right.Type;
1438 if (method != null) {
1440 // Note that operators are static anyway
1442 if (Arguments != null)
1443 Invocation.EmitArguments (ec, method, Arguments);
1445 if (method is MethodInfo)
1446 ig.Emit (OpCodes.Call, (MethodInfo) method);
1448 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
1454 // Handle short-circuit operators differently
1457 if (oper == Operator.LogicalAnd){
1458 Label load_zero = ig.DefineLabel ();
1459 Label end = ig.DefineLabel ();
1462 ig.Emit (OpCodes.Brfalse, load_zero);
1464 ig.Emit (OpCodes.Br, end);
1465 ig.MarkLabel (load_zero);
1466 ig.Emit (OpCodes.Ldc_I4_0);
1469 } else if (oper == Operator.LogicalOr){
1470 Label load_one = ig.DefineLabel ();
1471 Label end = ig.DefineLabel ();
1474 ig.Emit (OpCodes.Brtrue, load_one);
1476 ig.Emit (OpCodes.Br, end);
1477 ig.MarkLabel (load_one);
1478 ig.Emit (OpCodes.Ldc_I4_1);
1487 case Operator.Multiply:
1489 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
1490 opcode = OpCodes.Mul_Ovf;
1491 else if (l==TypeManager.uint32_type || l==TypeManager.uint64_type)
1492 opcode = OpCodes.Mul_Ovf_Un;
1494 opcode = OpCodes.Mul;
1496 opcode = OpCodes.Mul;
1500 case Operator.Division:
1501 if (l == TypeManager.uint32_type || l == TypeManager.uint64_type)
1502 opcode = OpCodes.Div_Un;
1504 opcode = OpCodes.Div;
1507 case Operator.Modulus:
1508 if (l == TypeManager.uint32_type || l == TypeManager.uint64_type)
1509 opcode = OpCodes.Rem_Un;
1511 opcode = OpCodes.Rem;
1514 case Operator.Addition:
1516 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
1517 opcode = OpCodes.Add_Ovf;
1518 else if (l==TypeManager.uint32_type || l==TypeManager.uint64_type)
1519 opcode = OpCodes.Add_Ovf_Un;
1521 opcode = OpCodes.Mul;
1523 opcode = OpCodes.Add;
1526 case Operator.Subtraction:
1528 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
1529 opcode = OpCodes.Sub_Ovf;
1530 else if (l==TypeManager.uint32_type || l==TypeManager.uint64_type)
1531 opcode = OpCodes.Sub_Ovf_Un;
1533 opcode = OpCodes.Sub;
1535 opcode = OpCodes.Sub;
1538 case Operator.RightShift:
1539 opcode = OpCodes.Shr;
1542 case Operator.LeftShift:
1543 opcode = OpCodes.Shl;
1546 case Operator.Equality:
1547 opcode = OpCodes.Ceq;
1550 case Operator.Inequality:
1551 ec.ig.Emit (OpCodes.Ceq);
1552 ec.ig.Emit (OpCodes.Ldc_I4_0);
1554 opcode = OpCodes.Ceq;
1557 case Operator.LessThan:
1558 opcode = OpCodes.Clt;
1561 case Operator.GreaterThan:
1562 opcode = OpCodes.Cgt;
1565 case Operator.LessThanOrEqual:
1566 ec.ig.Emit (OpCodes.Cgt);
1567 ec.ig.Emit (OpCodes.Ldc_I4_0);
1569 opcode = OpCodes.Ceq;
1572 case Operator.GreaterThanOrEqual:
1573 ec.ig.Emit (OpCodes.Clt);
1574 ec.ig.Emit (OpCodes.Ldc_I4_1);
1576 opcode = OpCodes.Sub;
1579 case Operator.BitwiseOr:
1580 opcode = OpCodes.Or;
1583 case Operator.BitwiseAnd:
1584 opcode = OpCodes.And;
1587 case Operator.ExclusiveOr:
1588 opcode = OpCodes.Xor;
1592 throw new Exception ("This should not happen: Operator = "
1593 + oper.ToString ());
1600 /// Constant expression reducer for binary operations
1602 public override Expression Reduce (EmitContext ec)
1605 left = left.Reduce (ec);
1606 right = right.Reduce (ec);
1608 if (!(left is Literal && right is Literal))
1611 if (method == TypeManager.string_concat_string_string){
1612 StringLiteral ls = (StringLiteral) left;
1613 StringLiteral rs = (StringLiteral) right;
1615 return new StringLiteral (ls.Value + rs.Value);
1625 /// Implements the ternary conditiona operator (?:)
1627 public class Conditional : Expression {
1628 Expression expr, trueExpr, falseExpr;
1631 public Conditional (Expression expr, Expression trueExpr, Expression falseExpr, Location l)
1634 this.trueExpr = trueExpr;
1635 this.falseExpr = falseExpr;
1639 public Expression Expr {
1645 public Expression TrueExpr {
1651 public Expression FalseExpr {
1657 public override Expression DoResolve (EmitContext ec)
1659 expr = expr.Resolve (ec);
1661 if (expr.Type != TypeManager.bool_type)
1662 expr = Expression.ConvertImplicitRequired (
1663 ec, expr, TypeManager.bool_type, loc);
1665 trueExpr = trueExpr.Resolve (ec);
1666 falseExpr = falseExpr.Resolve (ec);
1668 if (expr == null || trueExpr == null || falseExpr == null)
1671 if (trueExpr.Type == falseExpr.Type)
1672 type = trueExpr.Type;
1677 // First, if an implicit conversion exists from trueExpr
1678 // to falseExpr, then the result type is of type falseExpr.Type
1680 conv = ConvertImplicit (ec, trueExpr, falseExpr.Type, loc);
1682 type = falseExpr.Type;
1684 } else if ((conv = ConvertImplicit(ec, falseExpr,trueExpr.Type,loc))!= null){
1685 type = trueExpr.Type;
1688 Error (173, loc, "The type of the conditional expression can " +
1689 "not be computed because there is no implicit conversion" +
1690 " from `" + TypeManager.CSharpName (trueExpr.Type) + "'" +
1691 " and `" + TypeManager.CSharpName (falseExpr.Type) + "'");
1696 if (expr is BoolLiteral){
1697 BoolLiteral bl = (BoolLiteral) expr;
1705 eclass = ExprClass.Value;
1709 public override void Emit (EmitContext ec)
1711 ILGenerator ig = ec.ig;
1712 Label false_target = ig.DefineLabel ();
1713 Label end_target = ig.DefineLabel ();
1716 ig.Emit (OpCodes.Brfalse, false_target);
1718 ig.Emit (OpCodes.Br, end_target);
1719 ig.MarkLabel (false_target);
1720 falseExpr.Emit (ec);
1721 ig.MarkLabel (end_target);
1724 public override Expression Reduce (EmitContext ec)
1726 expr = expr.Reduce (ec);
1727 trueExpr = trueExpr.Reduce (ec);
1728 falseExpr = falseExpr.Reduce (ec);
1730 if (!(expr is Literal && trueExpr is Literal && falseExpr is Literal))
1733 BoolLiteral bl = (BoolLiteral) expr;
1745 public class LocalVariableReference : Expression, IAssignMethod, IMemoryLocation {
1746 public readonly string Name;
1747 public readonly Block Block;
1749 VariableInfo variable_info;
1751 public LocalVariableReference (Block block, string name, Location l)
1756 eclass = ExprClass.Variable;
1759 public VariableInfo VariableInfo {
1761 if (variable_info == null)
1762 variable_info = Block.GetVariableInfo (Name);
1763 return variable_info;
1767 public override Expression DoResolve (EmitContext ec)
1769 VariableInfo vi = VariableInfo;
1771 if (Block.IsConstant (Name)) {
1772 Expression e = Block.GetConstantExpression (Name);
1778 e = Expression.Reduce (ec, e);
1780 if (!(e is Literal)) {
1781 Report.Error (150, loc, "A constant value is expected");
1789 type = vi.VariableType;
1793 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
1795 Expression e = DoResolve (ec);
1800 VariableInfo vi = VariableInfo;
1806 "cannot assign to `" + Name + "' because it is readonly");
1814 public override void Emit (EmitContext ec)
1816 VariableInfo vi = VariableInfo;
1817 ILGenerator ig = ec.ig;
1824 ig.Emit (OpCodes.Ldloc_0);
1828 ig.Emit (OpCodes.Ldloc_1);
1832 ig.Emit (OpCodes.Ldloc_2);
1836 ig.Emit (OpCodes.Ldloc_3);
1841 ig.Emit (OpCodes.Ldloc_S, (byte) idx);
1843 ig.Emit (OpCodes.Ldloc, idx);
1848 public static void Store (ILGenerator ig, int idx)
1852 ig.Emit (OpCodes.Stloc_0);
1856 ig.Emit (OpCodes.Stloc_1);
1860 ig.Emit (OpCodes.Stloc_2);
1864 ig.Emit (OpCodes.Stloc_3);
1869 ig.Emit (OpCodes.Stloc_S, (byte) idx);
1871 ig.Emit (OpCodes.Stloc, idx);
1876 public void EmitAssign (EmitContext ec, Expression source)
1878 ILGenerator ig = ec.ig;
1879 VariableInfo vi = VariableInfo;
1885 // Funny seems the code below generates optimal code for us, but
1886 // seems to take too long to generate what we need.
1887 // ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
1892 public void AddressOf (EmitContext ec)
1894 VariableInfo vi = VariableInfo;
1901 ec.ig.Emit (OpCodes.Ldloca_S, (byte) idx);
1903 ec.ig.Emit (OpCodes.Ldloca, idx);
1908 /// This represents a reference to a parameter in the intermediate
1911 public class ParameterReference : Expression, IAssignMethod, IMemoryLocation {
1917 public ParameterReference (Parameters pars, int idx, string name)
1922 eclass = ExprClass.Variable;
1926 // Notice that for ref/out parameters, the type exposed is not the
1927 // same type exposed externally.
1930 // externally we expose "int&"
1931 // here we expose "int".
1933 // We record this in "is_ref". This means that the type system can treat
1934 // the type as it is expected, but when we generate the code, we generate
1935 // the alternate kind of code.
1937 public override Expression DoResolve (EmitContext ec)
1939 type = pars.GetParameterInfo (ec.TypeContainer, idx, out is_ref);
1940 eclass = ExprClass.Variable;
1945 public override void Emit (EmitContext ec)
1947 ILGenerator ig = ec.ig;
1954 ig.Emit (OpCodes.Ldarg_S, (byte) arg_idx);
1956 ig.Emit (OpCodes.Ldarg, arg_idx);
1962 // If we are a reference, we loaded on the stack a pointer
1963 // Now lets load the real value
1966 if (type == TypeManager.int32_type)
1967 ig.Emit (OpCodes.Ldind_I4);
1968 else if (type == TypeManager.uint32_type)
1969 ig.Emit (OpCodes.Ldind_U4);
1970 else if (type == TypeManager.int64_type || type == TypeManager.uint64_type)
1971 ig.Emit (OpCodes.Ldind_I8);
1972 else if (type == TypeManager.char_type)
1973 ig.Emit (OpCodes.Ldind_U2);
1974 else if (type == TypeManager.short_type)
1975 ig.Emit (OpCodes.Ldind_I2);
1976 else if (type == TypeManager.ushort_type)
1977 ig.Emit (OpCodes.Ldind_U2);
1978 else if (type == TypeManager.float_type)
1979 ig.Emit (OpCodes.Ldind_R4);
1980 else if (type == TypeManager.double_type)
1981 ig.Emit (OpCodes.Ldind_R8);
1982 else if (type == TypeManager.byte_type)
1983 ig.Emit (OpCodes.Ldind_U1);
1984 else if (type == TypeManager.sbyte_type)
1985 ig.Emit (OpCodes.Ldind_I1);
1986 else if (type == TypeManager.intptr_type)
1987 ig.Emit (OpCodes.Ldind_I);
1989 ig.Emit (OpCodes.Ldind_Ref);
1992 public void EmitAssign (EmitContext ec, Expression source)
1994 ILGenerator ig = ec.ig;
2003 ig.Emit (OpCodes.Ldarg_S, (byte) arg_idx);
2005 ig.Emit (OpCodes.Ldarg, arg_idx);
2011 if (type == TypeManager.int32_type || type == TypeManager.uint32_type)
2012 ig.Emit (OpCodes.Stind_I4);
2013 else if (type == TypeManager.int64_type || type == TypeManager.uint64_type)
2014 ig.Emit (OpCodes.Stind_I8);
2015 else if (type == TypeManager.char_type || type == TypeManager.short_type ||
2016 type == TypeManager.ushort_type)
2017 ig.Emit (OpCodes.Stind_I2);
2018 else if (type == TypeManager.float_type)
2019 ig.Emit (OpCodes.Stind_R4);
2020 else if (type == TypeManager.double_type)
2021 ig.Emit (OpCodes.Stind_R8);
2022 else if (type == TypeManager.byte_type || type == TypeManager.sbyte_type)
2023 ig.Emit (OpCodes.Stind_I1);
2024 else if (type == TypeManager.intptr_type)
2025 ig.Emit (OpCodes.Stind_I);
2027 ig.Emit (OpCodes.Stind_Ref);
2030 ig.Emit (OpCodes.Starg_S, (byte) arg_idx);
2032 ig.Emit (OpCodes.Starg, arg_idx);
2037 public void AddressOf (EmitContext ec)
2045 ec.ig.Emit (OpCodes.Ldarga_S, (byte) arg_idx);
2047 ec.ig.Emit (OpCodes.Ldarga, arg_idx);
2052 /// Used for arguments to New(), Invocation()
2054 public class Argument {
2055 public enum AType : byte {
2061 public readonly AType ArgType;
2062 public Expression expr;
2064 public Argument (Expression expr, AType type)
2067 this.ArgType = type;
2070 public Expression Expr {
2086 public Parameter.Modifier GetParameterModifier ()
2088 if (ArgType == AType.Ref)
2089 return Parameter.Modifier.REF;
2091 if (ArgType == AType.Out)
2092 return Parameter.Modifier.OUT;
2094 return Parameter.Modifier.NONE;
2097 public static string FullDesc (Argument a)
2099 return (a.ArgType == AType.Ref ? "ref " :
2100 (a.ArgType == AType.Out ? "out " : "")) +
2101 TypeManager.CSharpName (a.Expr.Type);
2104 public bool Resolve (EmitContext ec, Location loc)
2106 expr = expr.Resolve (ec);
2108 if (ArgType == AType.Expression)
2109 return expr != null;
2111 if (expr.ExprClass != ExprClass.Variable){
2112 Report.Error (206, loc,
2113 "A property or indexer can not be passed as an out or ref " +
2118 return expr != null;
2121 public void Emit (EmitContext ec)
2123 if (ArgType == AType.Ref || ArgType == AType.Out)
2124 ((IMemoryLocation)expr).AddressOf (ec);
2131 /// Invocation of methods or delegates.
2133 public class Invocation : ExpressionStatement {
2134 public readonly ArrayList Arguments;
2138 MethodBase method = null;
2140 static Hashtable method_parameter_cache;
2142 static Invocation ()
2144 method_parameter_cache = new Hashtable ();
2148 // arguments is an ArrayList, but we do not want to typecast,
2149 // as it might be null.
2151 // FIXME: only allow expr to be a method invocation or a
2152 // delegate invocation (7.5.5)
2154 public Invocation (Expression expr, ArrayList arguments, Location l)
2157 Arguments = arguments;
2161 public Expression Expr {
2168 /// Returns the Parameters (a ParameterData interface) for the
2171 public static ParameterData GetParameterData (MethodBase mb)
2173 object pd = method_parameter_cache [mb];
2177 return (ParameterData) pd;
2180 ip = TypeContainer.LookupParametersByBuilder (mb);
2182 method_parameter_cache [mb] = ip;
2184 return (ParameterData) ip;
2186 ParameterInfo [] pi = mb.GetParameters ();
2187 ReflectionParameters rp = new ReflectionParameters (pi);
2188 method_parameter_cache [mb] = rp;
2190 return (ParameterData) rp;
2195 /// Tells whether a user defined conversion from Type `from' to
2196 /// Type `to' exists.
2198 /// FIXME: we could implement a cache here.
2200 static bool ConversionExists (EmitContext ec, Type from, Type to, Location loc)
2202 // Locate user-defined implicit operators
2206 mg = MemberLookup (ec, to, "op_Implicit", false, loc);
2209 MethodGroupExpr me = (MethodGroupExpr) mg;
2211 for (int i = me.Methods.Length; i > 0;) {
2213 MethodBase mb = me.Methods [i];
2214 ParameterData pd = GetParameterData (mb);
2216 if (from == pd.ParameterType (0))
2221 mg = MemberLookup (ec, from, "op_Implicit", false, loc);
2224 MethodGroupExpr me = (MethodGroupExpr) mg;
2226 for (int i = me.Methods.Length; i > 0;) {
2228 MethodBase mb = me.Methods [i];
2229 MethodInfo mi = (MethodInfo) mb;
2231 if (mi.ReturnType == to)
2240 /// Determines "better conversion" as specified in 7.4.2.3
2241 /// Returns : 1 if a->p is better
2242 /// 0 if a->q or neither is better
2244 static int BetterConversion (EmitContext ec, Argument a, Type p, Type q, bool use_standard,
2247 Type argument_type = a.Type;
2248 Expression argument_expr = a.Expr;
2250 if (argument_type == null)
2251 throw new Exception ("Expression of type " + a.Expr + " does not resolve its type");
2256 if (argument_type == p)
2259 if (argument_type == q)
2263 // Now probe whether an implicit constant expression conversion
2266 // An implicit constant expression conversion permits the following
2269 // * A constant-expression of type `int' can be converted to type
2270 // sbyte, byute, short, ushort, uint, ulong provided the value of
2271 // of the expression is withing the range of the destination type.
2273 // * A constant-expression of type long can be converted to type
2274 // ulong, provided the value of the constant expression is not negative
2276 // FIXME: Note that this assumes that constant folding has
2277 // taken place. We dont do constant folding yet.
2280 if (argument_expr is IntLiteral){
2281 IntLiteral ei = (IntLiteral) argument_expr;
2282 int value = ei.Value;
2284 if (p == TypeManager.sbyte_type){
2285 if (value >= SByte.MinValue && value <= SByte.MaxValue)
2287 } else if (p == TypeManager.byte_type){
2288 if (Byte.MinValue >= 0 && value <= Byte.MaxValue)
2290 } else if (p == TypeManager.short_type){
2291 if (value >= Int16.MinValue && value <= Int16.MaxValue)
2293 } else if (p == TypeManager.ushort_type){
2294 if (value >= UInt16.MinValue && value <= UInt16.MaxValue)
2296 } else if (p == TypeManager.uint32_type){
2298 // we can optimize this case: a positive int32
2299 // always fits on a uint32
2303 } else if (p == TypeManager.uint64_type){
2305 // we can optimize this case: a positive int32
2306 // always fits on a uint64
2311 } else if (argument_type == TypeManager.int64_type && argument_expr is LongLiteral){
2312 LongLiteral ll = (LongLiteral) argument_expr;
2314 if (p == TypeManager.uint64_type){
2325 tmp = ConvertImplicitStandard (ec, argument_expr, p, loc);
2327 tmp = ConvertImplicit (ec, argument_expr, p, loc);
2336 if (ConversionExists (ec, p, q, loc) == true &&
2337 ConversionExists (ec, q, p, loc) == false)
2340 if (p == TypeManager.sbyte_type)
2341 if (q == TypeManager.byte_type || q == TypeManager.ushort_type ||
2342 q == TypeManager.uint32_type || q == TypeManager.uint64_type)
2345 if (p == TypeManager.short_type)
2346 if (q == TypeManager.ushort_type || q == TypeManager.uint32_type ||
2347 q == TypeManager.uint64_type)
2350 if (p == TypeManager.int32_type)
2351 if (q == TypeManager.uint32_type || q == TypeManager.uint64_type)
2354 if (p == TypeManager.int64_type)
2355 if (q == TypeManager.uint64_type)
2362 /// Determines "Better function"
2365 /// and returns an integer indicating :
2366 /// 0 if candidate ain't better
2367 /// 1 if candidate is better than the current best match
2369 static int BetterFunction (EmitContext ec, ArrayList args,
2370 MethodBase candidate, MethodBase best,
2371 bool use_standard, Location loc)
2373 ParameterData candidate_pd = GetParameterData (candidate);
2374 ParameterData best_pd;
2380 argument_count = args.Count;
2382 if (candidate_pd.Count == 0 && argument_count == 0)
2386 if (candidate_pd.Count == argument_count) {
2388 for (int j = argument_count; j > 0;) {
2391 Argument a = (Argument) args [j];
2393 x = BetterConversion (
2394 ec, a, candidate_pd.ParameterType (j), null,
2410 best_pd = GetParameterData (best);
2412 if (candidate_pd.Count == argument_count && best_pd.Count == argument_count) {
2413 int rating1 = 0, rating2 = 0;
2415 for (int j = argument_count; j > 0;) {
2419 Argument a = (Argument) args [j];
2421 x = BetterConversion (ec, a, candidate_pd.ParameterType (j),
2422 best_pd.ParameterType (j), use_standard, loc);
2423 y = BetterConversion (ec, a, best_pd.ParameterType (j),
2424 candidate_pd.ParameterType (j), use_standard,
2431 if (rating1 > rating2)
2440 public static string FullMethodDesc (MethodBase mb)
2442 StringBuilder sb = new StringBuilder (mb.Name);
2443 ParameterData pd = GetParameterData (mb);
2445 int count = pd.Count;
2448 for (int i = count; i > 0; ) {
2451 sb.Append (pd.ParameterDesc (count - i - 1));
2457 return sb.ToString ();
2460 public static MethodGroupExpr MakeUnionSet (Expression mg1, Expression mg2)
2462 MemberInfo [] miset;
2463 MethodGroupExpr union;
2465 if (mg1 != null && mg2 != null) {
2467 MethodGroupExpr left_set = null, right_set = null;
2468 int length1 = 0, length2 = 0;
2470 left_set = (MethodGroupExpr) mg1;
2471 length1 = left_set.Methods.Length;
2473 right_set = (MethodGroupExpr) mg2;
2474 length2 = right_set.Methods.Length;
2476 ArrayList common = new ArrayList ();
2478 for (int i = 0; i < left_set.Methods.Length; i++) {
2479 for (int j = 0; j < right_set.Methods.Length; j++) {
2480 if (left_set.Methods [i] == right_set.Methods [j])
2481 common.Add (left_set.Methods [i]);
2485 miset = new MemberInfo [length1 + length2 - common.Count];
2487 left_set.Methods.CopyTo (miset, 0);
2491 for (int j = 0; j < right_set.Methods.Length; j++)
2492 if (!common.Contains (right_set.Methods [j]))
2493 miset [length1 + k++] = right_set.Methods [j];
2495 union = new MethodGroupExpr (miset);
2499 } else if (mg1 == null && mg2 != null) {
2501 MethodGroupExpr me = (MethodGroupExpr) mg2;
2503 miset = new MemberInfo [me.Methods.Length];
2504 me.Methods.CopyTo (miset, 0);
2506 union = new MethodGroupExpr (miset);
2510 } else if (mg2 == null && mg1 != null) {
2512 MethodGroupExpr me = (MethodGroupExpr) mg1;
2514 miset = new MemberInfo [me.Methods.Length];
2515 me.Methods.CopyTo (miset, 0);
2517 union = new MethodGroupExpr (miset);
2526 /// Determines is the candidate method, if a params method, is applicable
2527 /// in its expanded form to the given set of arguments
2529 static bool IsParamsMethodApplicable (ArrayList arguments, MethodBase candidate)
2533 if (arguments == null)
2536 arg_count = arguments.Count;
2538 ParameterData pd = GetParameterData (candidate);
2540 int pd_count = pd.Count;
2542 if (pd.ParameterModifier (pd_count - 1) != Parameter.Modifier.PARAMS)
2545 if (pd_count - 1 > arg_count)
2548 // If we have come this far, the case which remains is when the number of parameters
2549 // is less than or equal to the argument count. So, we now check if the element type
2550 // of the params array is compatible with each argument type
2553 Type element_type = pd.ParameterType (pd_count - 1).GetElementType ();
2555 for (int i = pd_count - 1; i < arg_count - 1; i++) {
2556 Argument a = (Argument) arguments [i];
2557 if (!StandardConversionExists (a.Type, element_type))
2565 /// Determines if the candidate method is applicable (section 14.4.2.1)
2566 /// to the given set of arguments
2568 static bool IsApplicable (ArrayList arguments, MethodBase candidate)
2572 if (arguments == null)
2575 arg_count = arguments.Count;
2577 ParameterData pd = GetParameterData (candidate);
2579 int pd_count = pd.Count;
2581 if (arg_count != pd.Count)
2584 for (int i = arg_count; i > 0; ) {
2587 Argument a = (Argument) arguments [i];
2589 Parameter.Modifier a_mod = a.GetParameterModifier ();
2590 Parameter.Modifier p_mod = pd.ParameterModifier (i);
2592 if (a_mod == p_mod) {
2594 if (a_mod == Parameter.Modifier.NONE)
2595 if (!StandardConversionExists (a.Type, pd.ParameterType (i)))
2598 if (a_mod == Parameter.Modifier.REF ||
2599 a_mod == Parameter.Modifier.OUT)
2600 if (pd.ParameterType (i) != a.Type)
2612 /// Find the Applicable Function Members (7.4.2.1)
2614 /// me: Method Group expression with the members to select.
2615 /// it might contain constructors or methods (or anything
2616 /// that maps to a method).
2618 /// Arguments: ArrayList containing resolved Argument objects.
2620 /// loc: The location if we want an error to be reported, or a Null
2621 /// location for "probing" purposes.
2623 /// use_standard: controls whether OverloadResolve should use the
2624 /// ConvertImplicit or ConvertImplicitStandard during overload resolution.
2626 /// Returns: The MethodBase (either a ConstructorInfo or a MethodInfo)
2627 /// that is the best match of me on Arguments.
2630 public static MethodBase OverloadResolve (EmitContext ec, MethodGroupExpr me,
2631 ArrayList Arguments, Location loc,
2634 ArrayList afm = new ArrayList ();
2635 int best_match_idx = -1;
2636 MethodBase method = null;
2639 for (int i = me.Methods.Length; i > 0; ){
2641 MethodBase candidate = me.Methods [i];
2644 // Check if candidate is applicable (section 14.4.2.1)
2645 if (!IsApplicable (Arguments, candidate))
2648 x = BetterFunction (ec, Arguments, candidate, method, use_standard, loc);
2654 method = me.Methods [best_match_idx];
2658 if (Arguments == null)
2661 argument_count = Arguments.Count;
2664 // Now we see if we can find params functions, applicable in their expanded form
2665 // since if they were applicable in their normal form, they would have been selected
2668 if (best_match_idx == -1) {
2670 for (int i = me.Methods.Length; i > 0; ) {
2672 MethodBase candidate = me.Methods [i];
2674 if (IsParamsMethodApplicable (Arguments, candidate)) {
2676 method = me.Methods [best_match_idx];
2683 // Now we see if we can at least find a method with the same number of arguments
2687 if (best_match_idx == -1) {
2689 for (int i = me.Methods.Length; i > 0;) {
2691 MethodBase mb = me.Methods [i];
2692 pd = GetParameterData (mb);
2694 if (pd.Count == argument_count) {
2696 method = me.Methods [best_match_idx];
2706 // And now convert implicitly, each argument to the required type
2708 pd = GetParameterData (method);
2709 int pd_count = pd.Count;
2711 for (int j = 0; j < argument_count; j++) {
2712 Argument a = (Argument) Arguments [j];
2713 Expression a_expr = a.Expr;
2714 Type parameter_type = pd.ParameterType (j);
2717 // Note that we need to compare against the element type
2718 // when we have a params method
2720 if (pd.ParameterModifier (pd_count - 1) == Parameter.Modifier.PARAMS) {
2721 if (j >= pd_count - 1)
2722 parameter_type = pd.ParameterType (pd_count - 1).GetElementType ();
2725 if (a.Type != parameter_type){
2729 conv = ConvertImplicitStandard (
2730 ec, a_expr, parameter_type, Location.Null);
2732 conv = ConvertImplicit (
2733 ec, a_expr, parameter_type, Location.Null);
2735 Console.WriteLine ("From " + a.Type + " to " + parameter_type);
2737 if (!Location.IsNull (loc)) {
2739 "The best overloaded match for method '" +
2740 FullMethodDesc (method) +
2741 "' has some invalid arguments");
2743 "Argument " + (j+1) +
2744 ": Cannot convert from '" + Argument.FullDesc (a)
2745 + "' to '" + pd.ParameterDesc (j) + "'");
2753 // Update the argument with the implicit conversion
2758 // FIXME : For the case of params methods, we need to actually instantiate
2759 // an array and initialize it with the argument values etc etc.
2763 if (a.GetParameterModifier () != pd.ParameterModifier (j) &&
2764 pd.ParameterModifier (j) != Parameter.Modifier.PARAMS) {
2765 if (!Location.IsNull (loc)) {
2767 "The best overloaded match for method '" + FullMethodDesc (method)+
2768 "' has some invalid arguments");
2770 "Argument " + (j+1) +
2771 ": Cannot convert from '" + Argument.FullDesc (a)
2772 + "' to '" + pd.ParameterDesc (j) + "'");
2783 public static MethodBase OverloadResolve (EmitContext ec, MethodGroupExpr me,
2784 ArrayList Arguments, Location loc)
2786 return OverloadResolve (ec, me, Arguments, loc, false);
2789 public override Expression DoResolve (EmitContext ec)
2792 // First, resolve the expression that is used to
2793 // trigger the invocation
2795 expr = expr.Resolve (ec);
2799 if (!(expr is MethodGroupExpr)) {
2800 Type expr_type = expr.Type;
2802 if (expr_type != null){
2803 bool IsDelegate = TypeManager.IsDelegateType (expr_type);
2805 return (new DelegateInvocation (
2806 this.expr, Arguments, loc)).Resolve (ec);
2810 if (!(expr is MethodGroupExpr)){
2811 report118 (loc, this.expr, "method group");
2816 // Next, evaluate all the expressions in the argument list
2818 if (Arguments != null){
2819 for (int i = Arguments.Count; i > 0;){
2821 Argument a = (Argument) Arguments [i];
2823 if (!a.Resolve (ec, loc))
2828 method = OverloadResolve (ec, (MethodGroupExpr) this.expr, Arguments, loc);
2830 if (method == null){
2832 "Could not find any applicable function for this argument list");
2836 if (method is MethodInfo)
2837 type = ((MethodInfo)method).ReturnType;
2839 eclass = ExprClass.Value;
2844 // Emits the list of arguments as an array
2846 static void EmitParams (EmitContext ec, int idx, ArrayList arguments)
2848 ILGenerator ig = ec.ig;
2849 int count = arguments.Count - idx;
2850 Argument a = (Argument) arguments [idx];
2851 Type t = a.expr.Type;
2852 string array_type = t.FullName + "[]";
2855 array = ig.DeclareLocal (Type.GetType (array_type));
2856 IntLiteral.EmitInt (ig, count);
2857 ig.Emit (OpCodes.Newarr, t);
2858 ig.Emit (OpCodes.Stloc, array);
2860 int top = arguments.Count;
2861 for (int j = idx; j < top; j++){
2862 a = (Argument) arguments [j];
2864 ig.Emit (OpCodes.Ldloc, array);
2865 IntLiteral.EmitInt (ig, j - idx);
2868 ArrayAccess.EmitStoreOpcode (ig, t);
2870 ig.Emit (OpCodes.Ldloc, array);
2874 /// Emits a list of resolved Arguments that are in the arguments
2877 /// The MethodBase argument might be null if the
2878 /// emission of the arguments is known not to contain
2879 /// a `params' field (for example in constructors or other routines
2880 /// that keep their arguments in this structure
2882 public static void EmitArguments (EmitContext ec, MethodBase mb, ArrayList arguments)
2884 ParameterData pd = null;
2887 if (arguments != null)
2888 top = arguments.Count;
2893 pd = GetParameterData (mb);
2895 for (int i = 0; i < top; i++){
2896 Argument a = (Argument) arguments [i];
2899 if (pd.ParameterModifier (i) == Parameter.Modifier.PARAMS){
2900 EmitParams (ec, i, arguments);
2909 public static void EmitCall (EmitContext ec,
2910 bool is_static, Expression instance_expr,
2911 MethodBase method, ArrayList Arguments)
2913 ILGenerator ig = ec.ig;
2914 bool struct_call = false;
2918 // If this is ourselves, push "this"
2920 if (instance_expr == null){
2921 ig.Emit (OpCodes.Ldarg_0);
2924 // Push the instance expression
2926 if (instance_expr.Type.IsSubclassOf (TypeManager.value_type)){
2931 // If the expression implements IMemoryLocation, then
2932 // we can optimize and use AddressOf on the
2935 // If not we have to use some temporary storage for
2937 if (instance_expr is IMemoryLocation)
2938 ((IMemoryLocation) instance_expr).AddressOf (ec);
2940 Type t = instance_expr.Type;
2942 instance_expr.Emit (ec);
2943 LocalBuilder temp = ig.DeclareLocal (t);
2944 ig.Emit (OpCodes.Stloc, temp);
2945 ig.Emit (OpCodes.Ldloca, temp);
2948 instance_expr.Emit (ec);
2952 if (Arguments != null)
2953 EmitArguments (ec, method, Arguments);
2955 if (is_static || struct_call){
2956 if (method is MethodInfo)
2957 ig.Emit (OpCodes.Call, (MethodInfo) method);
2959 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
2961 if (method is MethodInfo)
2962 ig.Emit (OpCodes.Callvirt, (MethodInfo) method);
2964 ig.Emit (OpCodes.Callvirt, (ConstructorInfo) method);
2968 public override void Emit (EmitContext ec)
2970 MethodGroupExpr mg = (MethodGroupExpr) this.expr;
2971 EmitCall (ec, method.IsStatic, mg.InstanceExpression, method, Arguments);
2974 public override void EmitStatement (EmitContext ec)
2979 // Pop the return value if there is one
2981 if (method is MethodInfo){
2982 if (((MethodInfo)method).ReturnType != TypeManager.void_type)
2983 ec.ig.Emit (OpCodes.Pop);
2989 /// Implements the new expression
2991 public class New : ExpressionStatement {
2992 public readonly ArrayList Arguments;
2993 public readonly string RequestedType;
2996 MethodBase method = null;
2999 // If set, the new expression is for a value_target, and
3000 // we will not leave anything on the stack.
3002 Expression value_target;
3004 public New (string requested_type, ArrayList arguments, Location l)
3006 RequestedType = requested_type;
3007 Arguments = arguments;
3011 public Expression ValueTypeVariable {
3013 return value_target;
3017 value_target = value;
3021 public override Expression DoResolve (EmitContext ec)
3023 type = ec.TypeContainer.LookupType (RequestedType, false);
3028 bool IsDelegate = TypeManager.IsDelegateType (type);
3031 return (new NewDelegate (type, Arguments, loc)).Resolve (ec);
3035 ml = MemberLookup (ec, type, ".ctor", false,
3036 MemberTypes.Constructor, AllBindingsFlags, loc);
3038 bool is_struct = false;
3039 is_struct = type.IsSubclassOf (TypeManager.value_type);
3041 if (! (ml is MethodGroupExpr)){
3043 report118 (loc, ml, "method group");
3049 if (Arguments != null){
3050 for (int i = Arguments.Count; i > 0;){
3052 Argument a = (Argument) Arguments [i];
3054 if (!a.Resolve (ec, loc))
3059 method = Invocation.OverloadResolve (ec, (MethodGroupExpr) ml,
3063 if (method == null && !is_struct) {
3065 "New invocation: Can not find a constructor for " +
3066 "this argument list");
3070 eclass = ExprClass.Value;
3075 // This DoEmit can be invoked in two contexts:
3076 // * As a mechanism that will leave a value on the stack (new object)
3077 // * As one that wont (init struct)
3079 // You can control whether a value is required on the stack by passing
3080 // need_value_on_stack. The code *might* leave a value on the stack
3081 // so it must be popped manually
3083 // Returns whether a value is left on the stack
3085 bool DoEmit (EmitContext ec, bool need_value_on_stack)
3087 if (method == null){
3088 IMemoryLocation ml = (IMemoryLocation) value_target;
3092 Invocation.EmitArguments (ec, method, Arguments);
3093 ec.ig.Emit (OpCodes.Newobj, (ConstructorInfo) method);
3098 // It must be a value type, sanity check
3100 if (value_target != null){
3101 ec.ig.Emit (OpCodes.Initobj, type);
3103 if (need_value_on_stack){
3104 value_target.Emit (ec);
3110 throw new Exception ("No method and no value type");
3113 public override void Emit (EmitContext ec)
3118 public override void EmitStatement (EmitContext ec)
3120 if (DoEmit (ec, false))
3121 ec.ig.Emit (OpCodes.Pop);
3126 /// Represents an array creation expression.
3130 /// There are two possible scenarios here: one is an array creation
3131 /// expression that specifies the dimensions and optionally the
3132 /// initialization data and the other which does not need dimensions
3133 /// specified but where initialization data is mandatory.
3135 public class ArrayCreation : ExpressionStatement {
3136 string RequestedType;
3138 ArrayList Initializers;
3140 ArrayList Arguments;
3142 MethodBase method = null;
3143 Type array_element_type;
3144 bool IsOneDimensional = false;
3145 bool IsBuiltinType = false;
3146 bool ExpectInitializers = false;
3149 Type underlying_type;
3151 ArrayList ArrayData;
3155 public ArrayCreation (string requested_type, ArrayList exprs,
3156 string rank, ArrayList initializers, Location l)
3158 RequestedType = requested_type;
3160 Initializers = initializers;
3163 Arguments = new ArrayList ();
3165 foreach (Expression e in exprs)
3166 Arguments.Add (new Argument (e, Argument.AType.Expression));
3170 public ArrayCreation (string requested_type, string rank, ArrayList initializers, Location l)
3172 RequestedType = requested_type;
3173 Initializers = initializers;
3176 Rank = rank.Substring (0, rank.LastIndexOf ("["));
3178 string tmp = rank.Substring (rank.LastIndexOf ("["));
3180 dimensions = tmp.Length - 1;
3181 ExpectInitializers = true;
3184 public static string FormArrayType (string base_type, int idx_count, string rank)
3186 StringBuilder sb = new StringBuilder (base_type);
3191 for (int i = 1; i < idx_count; i++)
3195 return sb.ToString ();
3198 public static string FormElementType (string base_type, int idx_count, string rank)
3200 StringBuilder sb = new StringBuilder (base_type);
3203 for (int i = 1; i < idx_count; i++)
3209 string val = sb.ToString ();
3211 return val.Substring (0, val.LastIndexOf ("["));
3216 Report.Error (178, loc, "Incorrectly structured array initializer");
3219 public bool CheckIndices (EmitContext ec, ArrayList probe, int idx, bool specified_dims)
3221 if (specified_dims) {
3222 Argument a = (Argument) Arguments [idx];
3224 if (!a.Resolve (ec, loc))
3227 Expression e = Expression.Reduce (ec, a.Expr);
3229 if (!(e is Literal)) {
3230 Report.Error (150, loc, "A constant value is expected");
3234 int value = (int) ((Literal) e).GetValue ();
3236 if (value != probe.Count) {
3241 Bounds [idx] = value;
3244 foreach (object o in probe) {
3245 if (o is ArrayList) {
3246 bool ret = CheckIndices (ec, (ArrayList) o, idx + 1, specified_dims);
3250 Expression tmp = (Expression) o;
3251 tmp = tmp.Resolve (ec);
3255 tmp = Expression.Reduce (ec, tmp);
3257 // Handle initialization from vars, fields etc.
3259 Expression conv = ConvertImplicitRequired (ec, tmp, underlying_type, loc);
3264 if (tmp is StringLiteral)
3265 ArrayData.Add (tmp);
3266 else if (tmp is Literal)
3267 ArrayData.Add (((Literal) tmp).GetValue ());
3269 ArrayData.Add (tmp);
3276 public void UpdateIndices (EmitContext ec)
3279 for (ArrayList probe = Initializers; probe != null;) {
3281 if (probe [0] is ArrayList) {
3282 Expression e = new IntLiteral (probe.Count);
3283 Arguments.Add (new Argument (e, Argument.AType.Expression));
3285 Bounds [i++] = probe.Count;
3287 probe = (ArrayList) probe [0];
3290 Expression e = new IntLiteral (probe.Count);
3291 Arguments.Add (new Argument (e, Argument.AType.Expression));
3293 Bounds [i++] = probe.Count;
3300 public bool ValidateInitializers (EmitContext ec)
3302 if (Initializers == null) {
3303 if (ExpectInitializers)
3309 underlying_type = ec.TypeContainer.LookupType (RequestedType, false);
3312 // We use this to store all the date values in the order in which we
3313 // will need to store them in the byte blob later
3315 ArrayData = new ArrayList ();
3316 Bounds = new Hashtable ();
3320 if (Arguments != null) {
3321 ret = CheckIndices (ec, Initializers, 0, true);
3325 Arguments = new ArrayList ();
3327 ret = CheckIndices (ec, Initializers, 0, false);
3334 if (Arguments.Count != dimensions) {
3343 public override Expression DoResolve (EmitContext ec)
3347 if (!ValidateInitializers (ec))
3350 if (Arguments == null)
3353 arg_count = Arguments.Count;
3355 string array_type = FormArrayType (RequestedType, arg_count, Rank);
3356 string element_type = FormElementType (RequestedType, arg_count, Rank);
3358 type = ec.TypeContainer.LookupType (array_type, false);
3360 array_element_type = ec.TypeContainer.LookupType (element_type, false);
3365 if (arg_count == 1) {
3366 IsOneDimensional = true;
3367 eclass = ExprClass.Value;
3371 IsBuiltinType = TypeManager.IsBuiltinType (type);
3373 if (IsBuiltinType) {
3377 ml = MemberLookup (ec, type, ".ctor", false, MemberTypes.Constructor,
3378 AllBindingsFlags, loc);
3380 if (!(ml is MethodGroupExpr)){
3381 report118 (loc, ml, "method group");
3386 Report.Error (-6, loc, "New invocation: Can not find a constructor for " +
3387 "this argument list");
3391 if (Arguments != null) {
3392 for (int i = arg_count; i > 0;){
3394 Argument a = (Argument) Arguments [i];
3396 if (!a.Resolve (ec, loc))
3401 method = Invocation.OverloadResolve (ec, (MethodGroupExpr) ml, Arguments, loc);
3403 if (method == null) {
3404 Report.Error (-6, loc, "New invocation: Can not find a constructor for " +
3405 "this argument list");
3409 eclass = ExprClass.Value;
3413 ModuleBuilder mb = RootContext.ModuleBuilder;
3415 ArrayList args = new ArrayList ();
3416 if (Arguments != null){
3417 for (int i = arg_count; i > 0;){
3419 Argument a = (Argument) Arguments [i];
3421 if (!a.Resolve (ec, loc))
3428 Type [] arg_types = null;
3431 arg_types = new Type [args.Count];
3433 args.CopyTo (arg_types, 0);
3435 method = mb.GetArrayMethod (type, ".ctor", CallingConventions.HasThis, null,
3438 if (method == null) {
3439 Report.Error (-6, loc, "New invocation: Can not find a constructor for " +
3440 "this argument list");
3444 eclass = ExprClass.Value;
3450 public static byte [] MakeByteBlob (ArrayList ArrayData, Type underlying_type, Location loc)
3455 int count = ArrayData.Count;
3457 if (underlying_type == TypeManager.int32_type ||
3458 underlying_type == TypeManager.uint32_type ||
3459 underlying_type == TypeManager.float_type)
3461 else if (underlying_type == TypeManager.int64_type ||
3462 underlying_type == TypeManager.uint64_type ||
3463 underlying_type == TypeManager.double_type)
3465 else if (underlying_type == TypeManager.byte_type ||
3466 underlying_type == TypeManager.sbyte_type ||
3467 underlying_type == TypeManager.char_type ||
3468 underlying_type == TypeManager.bool_type)
3470 else if (underlying_type == TypeManager.short_type ||
3471 underlying_type == TypeManager.ushort_type)
3474 Report.Error (-100, loc, "Unhandled type in MakeByteBlob!!");
3478 data = new byte [count * factor];
3480 for (int i = 0; i < count; ++i) {
3482 if (underlying_type == TypeManager.int64_type ||
3483 underlying_type == TypeManager.uint64_type){
3486 if (!(ArrayData [i] is Expression))
3487 val = (long) ArrayData [i];
3489 for (int j = 0; j < factor; ++j) {
3490 data [(i * factor) + j] = (byte) (val & 0xFF);
3494 } else if (underlying_type == TypeManager.float_type) {
3496 // FIXME : How does one get the bits out ?
3498 } else if (underlying_type == TypeManager.double_type) {
3500 // FIXME : Same here. '&' and '>>' don't work !
3506 if (!(ArrayData [i] is Expression))
3507 val = (int) ArrayData [i];
3509 for (int j = 0; j < factor; ++j) {
3510 data [(i * factor) + j] = (byte) (val & 0xFF);
3520 // Emits the initializers for the array
3522 void EmitStaticInitializers (EmitContext ec, bool is_expression)
3525 // First, the static data
3528 ILGenerator ig = ec.ig;
3530 byte [] data = MakeByteBlob (ArrayData, underlying_type, loc);
3533 fb = ec.TypeContainer.RootContext.MakeStaticData (data);
3536 ig.Emit (OpCodes.Dup);
3537 ig.Emit (OpCodes.Ldtoken, fb);
3538 ig.Emit (OpCodes.Call,
3539 TypeManager.void_initializearray_array_fieldhandle);
3544 // Emits pieces of the array that can not be computed at compile
3545 // time (variables and string locations).
3547 // This always expect the top value on the stack to be the array
3549 void EmitDynamicInitializers (EmitContext ec, bool is_expression)
3551 ILGenerator ig = ec.ig;
3552 int dims = Bounds.Count;
3553 int [] current_pos = new int [dims];
3554 int top = ArrayData.Count;
3555 LocalBuilder temp = ig.DeclareLocal (type);
3557 ig.Emit (OpCodes.Stloc, temp);
3559 MethodInfo set = null;
3563 ModuleBuilder mb = null;
3564 mb = RootContext.ModuleBuilder;
3565 args = new Type [dims + 1];
3568 for (j = 0; j < dims; j++)
3569 args [j] = TypeManager.int32_type;
3571 args [j] = array_element_type;
3573 set = mb.GetArrayMethod (
3575 CallingConventions.HasThis | CallingConventions.Standard,
3576 TypeManager.void_type, args);
3579 for (int i = 0; i < top; i++){
3581 Expression e = null;
3583 if (ArrayData [i] is Expression)
3584 e = (Expression) ArrayData [i];
3589 // Basically we do this for string literals and
3590 // other non-literal expressions
3592 if (e is StringLiteral || !(e is Literal)) {
3594 ig.Emit (OpCodes.Ldloc, temp);
3596 for (int idx = dims; idx > 0; ) {
3598 IntLiteral.EmitInt (ig, current_pos [idx]);
3604 ArrayAccess.EmitStoreOpcode (ig, array_element_type);
3606 ig.Emit (OpCodes.Call, set);
3614 for (int j = 0; j < dims; j++){
3616 if (current_pos [j] < (int) Bounds [j])
3618 current_pos [j] = 0;
3623 ig.Emit (OpCodes.Ldloc, temp);
3626 void DoEmit (EmitContext ec, bool is_statement)
3628 ILGenerator ig = ec.ig;
3630 if (IsOneDimensional) {
3631 Invocation.EmitArguments (ec, null, Arguments);
3632 ig.Emit (OpCodes.Newarr, array_element_type);
3635 Invocation.EmitArguments (ec, null, Arguments);
3638 ig.Emit (OpCodes.Newobj, (ConstructorInfo) method);
3640 ig.Emit (OpCodes.Newobj, (MethodInfo) method);
3643 if (Initializers != null){
3645 // FIXME: Set this variable correctly.
3647 bool dynamic_initializers = true;
3649 if (underlying_type != TypeManager.string_type)
3650 EmitStaticInitializers (ec, dynamic_initializers || !is_statement);
3652 if (dynamic_initializers)
3653 EmitDynamicInitializers (ec, !is_statement);
3657 public override void Emit (EmitContext ec)
3662 public override void EmitStatement (EmitContext ec)
3670 /// Represents the `this' construct
3672 public class This : Expression, IAssignMethod, IMemoryLocation {
3675 public This (Location loc)
3680 public override Expression DoResolve (EmitContext ec)
3682 eclass = ExprClass.Variable;
3683 type = ec.TypeContainer.TypeBuilder;
3686 Report.Error (26, loc,
3687 "Keyword this not valid in static code");
3694 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
3698 if (ec.TypeContainer is Class){
3699 Report.Error (1604, loc, "Cannot assign to `this'");
3706 public override void Emit (EmitContext ec)
3708 ec.ig.Emit (OpCodes.Ldarg_0);
3711 public void EmitAssign (EmitContext ec, Expression source)
3714 ec.ig.Emit (OpCodes.Starg, 0);
3717 public void AddressOf (EmitContext ec)
3719 ec.ig.Emit (OpCodes.Ldarg_0);
3722 // FIGURE OUT WHY LDARG_S does not work
3724 // consider: struct X { int val; int P { set { val = value; }}}
3726 // Yes, this looks very bad. Look at `NOTAS' for
3728 // ec.ig.Emit (OpCodes.Ldarga_S, (byte) 0);
3733 /// Implements the typeof operator
3735 public class TypeOf : Expression {
3736 public readonly string QueriedType;
3739 public TypeOf (string queried_type)
3741 QueriedType = queried_type;
3744 public override Expression DoResolve (EmitContext ec)
3746 typearg = ec.TypeContainer.LookupType (QueriedType, false);
3748 if (typearg == null)
3751 type = TypeManager.type_type;
3752 eclass = ExprClass.Type;
3756 public override void Emit (EmitContext ec)
3758 ec.ig.Emit (OpCodes.Ldtoken, typearg);
3759 ec.ig.Emit (OpCodes.Call, TypeManager.system_type_get_type_from_handle);
3764 /// Implements the sizeof expression
3766 public class SizeOf : Expression {
3767 public readonly string QueriedType;
3769 public SizeOf (string queried_type)
3771 this.QueriedType = queried_type;
3774 public override Expression DoResolve (EmitContext ec)
3776 // FIXME: Implement;
3777 throw new Exception ("Unimplemented");
3781 public override void Emit (EmitContext ec)
3783 throw new Exception ("Implement me");
3788 /// Implements the member access expression
3790 public class MemberAccess : Expression {
3791 public readonly string Identifier;
3793 Expression member_lookup;
3796 public MemberAccess (Expression expr, string id, Location l)
3803 public Expression Expr {
3809 static void error176 (Location loc, string name)
3811 Report.Error (176, loc, "Static member `" +
3812 name + "' cannot be accessed " +
3813 "with an instance reference, qualify with a " +
3814 "type name instead");
3817 public static Expression ResolveMemberAccess (EmitContext ec, Expression member_lookup,
3818 Expression left, Location loc)
3823 if (member_lookup is MethodGroupExpr){
3824 MethodGroupExpr mg = (MethodGroupExpr) member_lookup;
3829 if (left is TypeExpr){
3830 if (!mg.RemoveInstanceMethods ()){
3831 SimpleName.Error120 (loc, mg.Methods [0].Name);
3835 return member_lookup;
3839 // Instance.MethodGroup
3841 if (!mg.RemoveStaticMethods ()){
3842 error176 (loc, mg.Methods [0].Name);
3846 mg.InstanceExpression = left;
3848 return member_lookup;
3851 if (member_lookup is FieldExpr){
3852 FieldExpr fe = (FieldExpr) member_lookup;
3853 FieldInfo fi = fe.FieldInfo;
3855 if (fi is FieldBuilder) {
3856 Constant c = TypeManager.LookupConstant ((FieldBuilder) fi);
3859 object o = c.LookupConstantValue (ec);
3860 Expression l = Literalize (o, fi.FieldType);
3862 return ((Literal) l);
3867 Type t = fi.FieldType;
3868 Type decl_type = fi.DeclaringType;
3871 if (fi is FieldBuilder)
3872 o = TypeManager.GetValue ((FieldBuilder) fi);
3874 o = fi.GetValue (fi);
3876 if (decl_type.IsSubclassOf (TypeManager.enum_type)) {
3877 Expression enum_member = MemberLookup (ec, decl_type, "value__",
3880 Enum en = TypeManager.LookupEnum (decl_type);
3884 e = Literalize (o, en.UnderlyingType);
3886 e = Literalize (o, enum_member.Type);
3889 return new EnumLiteral (e, decl_type);
3892 Expression exp = Literalize (o, t);
3895 if (!(left is TypeExpr)) {
3896 error176 (loc, fe.FieldInfo.Name);
3903 if (left is TypeExpr){
3904 if (!fe.FieldInfo.IsStatic){
3905 error176 (loc, fe.FieldInfo.Name);
3908 return member_lookup;
3910 if (fe.FieldInfo.IsStatic){
3911 error176 (loc, fe.FieldInfo.Name);
3914 fe.InstanceExpression = left;
3920 if (member_lookup is PropertyExpr){
3921 PropertyExpr pe = (PropertyExpr) member_lookup;
3923 if (left is TypeExpr){
3925 SimpleName.Error120 (loc, pe.PropertyInfo.Name);
3931 error176 (loc, pe.PropertyInfo.Name);
3934 pe.InstanceExpression = left;
3940 Console.WriteLine ("Support for [" + member_lookup + "] is not present yet");
3941 Environment.Exit (0);
3945 public override Expression DoResolve (EmitContext ec)
3948 // We are the sole users of ResolveWithSimpleName (ie, the only
3949 // ones that can cope with it
3951 expr = expr.ResolveWithSimpleName (ec);
3956 if (expr is SimpleName){
3957 SimpleName child_expr = (SimpleName) expr;
3959 expr = new SimpleName (child_expr.Name + "." + Identifier, loc);
3961 return expr.ResolveWithSimpleName (ec);
3965 // Handle enums here when they are in transit.
3966 // Note that we cannot afford to hit MemberLookup in this case because
3967 // it will fail to find any members at all
3970 Type expr_type = expr.Type;
3971 if (expr_type.IsSubclassOf (TypeManager.enum_type)) {
3973 Enum en = TypeManager.LookupEnum (expr_type);
3976 object value = en.LookupEnumValue (ec, Identifier, loc);
3981 Expression l = Literalize (value, en.UnderlyingType);
3983 return new EnumLiteral (l, expr_type);
3987 member_lookup = MemberLookup (ec, expr.Type, Identifier, false, loc);
3989 if (member_lookup == null)
3992 return ResolveMemberAccess (ec, member_lookup, expr, loc);
3995 public override void Emit (EmitContext ec)
3997 throw new Exception ("Should not happen I think");
4002 /// Implements checked expressions
4004 public class CheckedExpr : Expression {
4006 public Expression Expr;
4008 public CheckedExpr (Expression e)
4013 public override Expression DoResolve (EmitContext ec)
4015 Expr = Expr.Resolve (ec);
4020 eclass = Expr.ExprClass;
4025 public override void Emit (EmitContext ec)
4027 bool last_check = ec.CheckState;
4029 ec.CheckState = true;
4031 ec.CheckState = last_check;
4037 /// Implements the unchecked expression
4039 public class UnCheckedExpr : Expression {
4041 public Expression Expr;
4043 public UnCheckedExpr (Expression e)
4048 public override Expression DoResolve (EmitContext ec)
4050 Expr = Expr.Resolve (ec);
4055 eclass = Expr.ExprClass;
4060 public override void Emit (EmitContext ec)
4062 bool last_check = ec.CheckState;
4064 ec.CheckState = false;
4066 ec.CheckState = last_check;
4072 /// An Element Access expression. During semantic
4073 /// analysis these are transformed into IndexerAccess or
4074 /// ArrayAccess expressions
4076 public class ElementAccess : Expression {
4077 public ArrayList Arguments;
4078 public Expression Expr;
4079 public Location loc;
4081 public ElementAccess (Expression e, ArrayList e_list, Location l)
4085 Arguments = new ArrayList ();
4086 foreach (Expression tmp in e_list)
4087 Arguments.Add (new Argument (tmp, Argument.AType.Expression));
4092 bool CommonResolve (EmitContext ec)
4094 Expr = Expr.Resolve (ec);
4099 if (Arguments == null)
4102 for (int i = Arguments.Count; i > 0;){
4104 Argument a = (Argument) Arguments [i];
4106 if (!a.Resolve (ec, loc))
4113 public override Expression DoResolve (EmitContext ec)
4115 if (!CommonResolve (ec))
4119 // We perform some simple tests, and then to "split" the emit and store
4120 // code we create an instance of a different class, and return that.
4122 // I am experimenting with this pattern.
4124 if (Expr.Type.IsSubclassOf (TypeManager.array_type))
4125 return (new ArrayAccess (this)).Resolve (ec);
4127 return (new IndexerAccess (this)).Resolve (ec);
4130 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
4132 if (!CommonResolve (ec))
4135 if (Expr.Type.IsSubclassOf (TypeManager.array_type))
4136 return (new ArrayAccess (this)).ResolveLValue (ec, right_side);
4138 return (new IndexerAccess (this)).ResolveLValue (ec, right_side);
4141 public override void Emit (EmitContext ec)
4143 throw new Exception ("Should never be reached");
4148 /// Implements array access
4150 public class ArrayAccess : Expression, IAssignMethod {
4152 // Points to our "data" repository
4156 public ArrayAccess (ElementAccess ea_data)
4159 eclass = ExprClass.Variable;
4162 public override Expression DoResolve (EmitContext ec)
4164 if (ea.Expr.ExprClass != ExprClass.Variable) {
4165 report118 (ea.loc, ea.Expr, "variable");
4169 Type t = ea.Expr.Type;
4171 if (t.GetArrayRank () != ea.Arguments.Count){
4172 Report.Error (22, ea.loc,
4173 "Incorrect number of indexes for array " +
4174 " expected: " + t.GetArrayRank () + " got: " +
4175 ea.Arguments.Count);
4178 type = t.GetElementType ();
4179 eclass = ExprClass.Variable;
4185 /// Emits the right opcode to load an object of Type `t'
4186 /// from an array of T
4188 static public void EmitLoadOpcode (ILGenerator ig, Type type)
4190 if (type == TypeManager.byte_type)
4191 ig.Emit (OpCodes.Ldelem_I1);
4192 else if (type == TypeManager.sbyte_type)
4193 ig.Emit (OpCodes.Ldelem_U1);
4194 else if (type == TypeManager.short_type)
4195 ig.Emit (OpCodes.Ldelem_I2);
4196 else if (type == TypeManager.ushort_type)
4197 ig.Emit (OpCodes.Ldelem_U2);
4198 else if (type == TypeManager.int32_type)
4199 ig.Emit (OpCodes.Ldelem_I4);
4200 else if (type == TypeManager.uint32_type)
4201 ig.Emit (OpCodes.Ldelem_U4);
4202 else if (type == TypeManager.uint64_type)
4203 ig.Emit (OpCodes.Ldelem_I8);
4204 else if (type == TypeManager.int64_type)
4205 ig.Emit (OpCodes.Ldelem_I8);
4206 else if (type == TypeManager.float_type)
4207 ig.Emit (OpCodes.Ldelem_R4);
4208 else if (type == TypeManager.double_type)
4209 ig.Emit (OpCodes.Ldelem_R8);
4210 else if (type == TypeManager.intptr_type)
4211 ig.Emit (OpCodes.Ldelem_I);
4213 ig.Emit (OpCodes.Ldelem_Ref);
4217 /// Emits the right opcode to store an object of Type `t'
4218 /// from an array of T.
4220 static public void EmitStoreOpcode (ILGenerator ig, Type t)
4222 if (t == TypeManager.byte_type || t == TypeManager.sbyte_type)
4223 ig.Emit (OpCodes.Stelem_I1);
4224 else if (t == TypeManager.short_type || t == TypeManager.ushort_type)
4225 ig.Emit (OpCodes.Stelem_I2);
4226 else if (t == TypeManager.int32_type || t == TypeManager.uint32_type)
4227 ig.Emit (OpCodes.Stelem_I4);
4228 else if (t == TypeManager.int64_type || t == TypeManager.uint64_type)
4229 ig.Emit (OpCodes.Stelem_I8);
4230 else if (t == TypeManager.float_type)
4231 ig.Emit (OpCodes.Stelem_R4);
4232 else if (t == TypeManager.double_type)
4233 ig.Emit (OpCodes.Stelem_R8);
4234 else if (t == TypeManager.intptr_type)
4235 ig.Emit (OpCodes.Stelem_I);
4237 ig.Emit (OpCodes.Stelem_Ref);
4240 public override void Emit (EmitContext ec)
4242 int rank = ea.Expr.Type.GetArrayRank ();
4243 ILGenerator ig = ec.ig;
4247 foreach (Argument a in ea.Arguments)
4251 EmitLoadOpcode (ig, type);
4253 ModuleBuilder mb = RootContext.ModuleBuilder;
4254 Type [] args = new Type [ea.Arguments.Count];
4259 foreach (Argument a in ea.Arguments)
4260 args [i++] = a.Type;
4262 get = mb.GetArrayMethod (
4263 ea.Expr.Type, "Get",
4264 CallingConventions.HasThis |
4265 CallingConventions.Standard,
4268 ig.Emit (OpCodes.Call, get);
4272 public void EmitAssign (EmitContext ec, Expression source)
4274 int rank = ea.Expr.Type.GetArrayRank ();
4275 ILGenerator ig = ec.ig;
4279 foreach (Argument a in ea.Arguments)
4284 Type t = source.Type;
4287 EmitStoreOpcode (ig, t);
4289 ModuleBuilder mb = RootContext.ModuleBuilder;
4290 Type [] args = new Type [ea.Arguments.Count + 1];
4295 foreach (Argument a in ea.Arguments)
4296 args [i++] = a.Type;
4300 set = mb.GetArrayMethod (
4301 ea.Expr.Type, "Set",
4302 CallingConventions.HasThis |
4303 CallingConventions.Standard,
4304 TypeManager.void_type, args);
4306 ig.Emit (OpCodes.Call, set);
4313 public ArrayList getters, setters;
4314 static Hashtable map;
4318 map = new Hashtable ();
4321 Indexers (MemberInfo [] mi)
4323 foreach (PropertyInfo property in mi){
4324 MethodInfo get, set;
4326 get = property.GetGetMethod (true);
4328 if (getters == null)
4329 getters = new ArrayList ();
4334 set = property.GetSetMethod (true);
4336 if (setters == null)
4337 setters = new ArrayList ();
4343 static public Indexers GetIndexersForType (Type t, TypeManager tm, Location loc)
4345 Indexers ix = (Indexers) map [t];
4346 string p_name = TypeManager.IndexerPropertyName (t);
4351 MemberInfo [] mi = tm.FindMembers (
4352 t, MemberTypes.Property,
4353 BindingFlags.Public | BindingFlags.Instance,
4354 Type.FilterName, p_name);
4356 if (mi == null || mi.Length == 0){
4357 Report.Error (21, loc,
4358 "Type `" + TypeManager.CSharpName (t) + "' does not have " +
4359 "any indexers defined");
4363 ix = new Indexers (mi);
4371 /// Expressions that represent an indexer call.
4373 public class IndexerAccess : Expression, IAssignMethod {
4375 // Points to our "data" repository
4378 MethodInfo get, set;
4380 ArrayList set_arguments;
4382 public IndexerAccess (ElementAccess ea_data)
4385 eclass = ExprClass.Value;
4388 public override Expression DoResolve (EmitContext ec)
4390 Type indexer_type = ea.Expr.Type;
4393 // Step 1: Query for all `Item' *properties*. Notice
4394 // that the actual methods are pointed from here.
4396 // This is a group of properties, piles of them.
4399 ilist = Indexers.GetIndexersForType (
4400 indexer_type, ec.TypeContainer.RootContext.TypeManager, ea.loc);
4404 // Step 2: find the proper match
4406 if (ilist != null && ilist.getters != null && ilist.getters.Count > 0)
4407 get = (MethodInfo) Invocation.OverloadResolve (
4408 ec, new MethodGroupExpr (ilist.getters), ea.Arguments, ea.loc);
4411 Report.Error (154, ea.loc,
4412 "indexer can not be used in this context, because " +
4413 "it lacks a `get' accessor");
4417 type = get.ReturnType;
4418 eclass = ExprClass.IndexerAccess;
4422 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
4424 Type indexer_type = ea.Expr.Type;
4425 Type right_type = right_side.Type;
4428 ilist = Indexers.GetIndexersForType (
4429 indexer_type, ec.TypeContainer.RootContext.TypeManager, ea.loc);
4431 if (ilist != null && ilist.setters != null && ilist.setters.Count > 0){
4432 set_arguments = (ArrayList) ea.Arguments.Clone ();
4433 set_arguments.Add (new Argument (right_side, Argument.AType.Expression));
4435 set = (MethodInfo) Invocation.OverloadResolve (
4436 ec, new MethodGroupExpr (ilist.setters), set_arguments, ea.loc);
4440 Report.Error (200, ea.loc,
4441 "indexer X.this [" + TypeManager.CSharpName (right_type) +
4442 "] lacks a `set' accessor");
4446 type = TypeManager.void_type;
4447 eclass = ExprClass.IndexerAccess;
4451 public override void Emit (EmitContext ec)
4453 Invocation.EmitCall (ec, false, ea.Expr, get, ea.Arguments);
4457 // source is ignored, because we already have a copy of it from the
4458 // LValue resolution and we have already constructed a pre-cached
4459 // version of the arguments (ea.set_arguments);
4461 public void EmitAssign (EmitContext ec, Expression source)
4463 Invocation.EmitCall (ec, false, ea.Expr, set, set_arguments);
4468 /// The base operator for method names
4470 public class BaseAccess : Expression {
4474 public BaseAccess (string member, Location l)
4476 this.member = member;
4480 public override Expression DoResolve (EmitContext ec)
4482 Expression member_lookup;
4483 Type current_type = ec.TypeContainer.TypeBuilder;
4484 Type base_type = current_type.BaseType;
4486 member_lookup = MemberLookup (ec, base_type, member, false, loc);
4487 if (member_lookup == null)
4493 left = new TypeExpr (base_type);
4495 left = new This (loc);
4497 return MemberAccess.ResolveMemberAccess (ec, member_lookup, left, loc);
4500 public override void Emit (EmitContext ec)
4502 throw new Exception ("Should never be called");
4507 /// The base indexer operator
4509 public class BaseIndexerAccess : Expression {
4510 ArrayList Arguments;
4512 public BaseIndexerAccess (ArrayList args)
4517 public override Expression DoResolve (EmitContext ec)
4519 // FIXME: Implement;
4520 throw new Exception ("Unimplemented");
4524 public override void Emit (EmitContext ec)
4526 throw new Exception ("Unimplemented");
4531 /// This class exists solely to pass the Type around and to be a dummy
4532 /// that can be passed to the conversion functions (this is used by
4533 /// foreach implementation to typecast the object return value from
4534 /// get_Current into the proper type. All code has been generated and
4535 /// we only care about the side effect conversions to be performed
4537 public class EmptyExpression : Expression {
4538 public EmptyExpression ()
4540 type = TypeManager.object_type;
4541 eclass = ExprClass.Value;
4544 public EmptyExpression (Type t)
4547 eclass = ExprClass.Value;
4550 public override Expression DoResolve (EmitContext ec)
4555 public override void Emit (EmitContext ec)
4557 // nothing, as we only exist to not do anything.
4561 // This is just because we might want to reuse this bad boy
4562 // instead of creating gazillions of EmptyExpressions.
4563 // (CanConvertImplicit uses it)
4565 public void SetType (Type t)
4571 public class UserCast : Expression {
4575 public UserCast (MethodInfo method, Expression source)
4577 this.method = method;
4578 this.source = source;
4579 type = method.ReturnType;
4580 eclass = ExprClass.Value;
4583 public override Expression DoResolve (EmitContext ec)
4586 // We are born fully resolved
4591 public override void Emit (EmitContext ec)
4593 ILGenerator ig = ec.ig;
4597 if (method is MethodInfo)
4598 ig.Emit (OpCodes.Call, (MethodInfo) method);
4600 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
4607 // This class is used to "construct" the type during a typecast
4608 // operation. Since the Type.GetType class in .NET can parse
4609 // the type specification, we just use this to construct the type
4610 // one bit at a time.
4612 public class ComposedCast : Expression {
4617 public ComposedCast (Expression left, string dim, Location l)
4624 public override Expression DoResolve (EmitContext ec)
4626 left = left.Resolve (ec);
4630 if (left.ExprClass != ExprClass.Type){
4631 report118 (loc, left, "type");
4635 type = ec.TypeContainer.LookupType (left.Type.FullName + dim, false);
4639 eclass = ExprClass.Type;
4643 public override void Emit (EmitContext ec)
4645 throw new Exception ("This should never be called");