2 // expression.cs: Expression representation for the IL tree.
5 // Miguel de Icaza (miguel@ximian.com)
7 // (C) 2001 Ximian, Inc.
11 // Maybe we should make Resolve be an instance method that just calls
12 // the virtual DoResolve function and checks conditions like the eclass
13 // and type being set if a non-null value is returned. For robustness
18 using System.Collections;
19 using System.Diagnostics;
21 using System.Reflection;
22 using System.Reflection.Emit;
26 // The ExprClass class contains the is used to pass the
27 // classification of an expression (value, variable, namespace,
28 // type, method group, property access, event access, indexer access,
31 public enum ExprClass {
35 Variable, // Every Variable should implement LValue
46 // Base class for expressions
48 public abstract class Expression {
49 protected ExprClass eclass;
62 public ExprClass ExprClass {
73 // Performs semantic analysis on the Expression
77 // The Resolve method is invoked to perform the semantic analysis
80 // The return value is an expression (it can be the
81 // same expression in some cases) or a new
82 // expression that better represents this node.
84 // For example, optimizations of Unary (LiteralInt)
85 // would return a new LiteralInt with a negated
88 // If there is an error during semantic analysis,
89 // then an error should
90 // be reported (using TypeContainer.RootContext.Report) and a null
91 // value should be returned.
93 // There are two side effects expected from calling
94 // Resolve(): the the field variable "eclass" should
95 // be set to any value of the enumeration
96 // `ExprClass' and the type variable should be set
97 // to a valid type (this is the type of the
101 public abstract Expression Resolve (TypeContainer tc);
104 // Emits the code for the expression
109 // The Emit method is invoked to generate the code
110 // for the expression.
113 public abstract void Emit (EmitContext ec);
116 // Protected constructor. Only derivate types should
117 // be able to be created
120 protected Expression ()
122 eclass = ExprClass.Invalid;
127 // Returns a fully formed expression after a MemberLookup
129 static Expression ExprClassFromMemberInfo (MemberInfo mi)
131 if (mi is EventInfo){
132 return new EventExpr ((EventInfo) mi);
133 } else if (mi is FieldInfo){
134 return new FieldExpr ((FieldInfo) mi);
135 } else if (mi is PropertyInfo){
136 return new PropertyExpr ((PropertyInfo) mi);
137 } else if (mi is Type)
138 return new TypeExpr ((Type) mi);
144 // FIXME: Probably implement a cache for (t,name,current_access_set)?
146 // FIXME: We need to cope with access permissions here, or this wont
149 // This code could use some optimizations, but we need to do some
150 // measurements. For example, we could use a delegate to `flag' when
151 // something can not any longer be a method-group (because it is something
155 // If the return value is an Array, then it is an array of
158 // If the return value is an MemberInfo, it is anything, but a Method
162 // FIXME: When calling MemberLookup inside an `Invocation', we should pass
163 // the arguments here and have MemberLookup return only the methods that
164 // match the argument count/type, unlike we are doing now (we delay this
167 // This is so we can catch correctly attempts to invoke instance methods
168 // from a static body (scan for error 120 in ResolveSimpleName).
170 public static Expression MemberLookup (RootContext rc, Type t, string name,
171 bool same_type, MemberTypes mt, BindingFlags bf)
174 bf |= BindingFlags.NonPublic;
176 MemberInfo [] mi = rc.TypeManager.FindMembers (t, mt, bf, Type.FilterName, name);
181 if (mi.Length == 1 && !(mi [0] is MethodBase))
182 return Expression.ExprClassFromMemberInfo (mi [0]);
184 for (int i = 0; i < mi.Length; i++)
185 if (!(mi [i] is MethodBase)){
186 rc.Report.Error (-5, "Do not know how to reproduce this case: " +
187 "Methods and non-Method with the same name, report this please");
189 for (i = 0; i < mi.Length; i++){
190 Type tt = mi [i].GetType ();
192 Console.WriteLine (i + ": " + mi [i]);
193 while (tt != TypeManager.object_type){
194 Console.WriteLine (tt);
200 return new MethodGroupExpr (mi);
203 public const MemberTypes AllMemberTypes =
204 MemberTypes.Constructor |
208 MemberTypes.NestedType |
209 MemberTypes.Property;
211 public const BindingFlags AllBindingsFlags =
212 BindingFlags.Public |
213 BindingFlags.Static |
214 BindingFlags.Instance;
216 public static Expression MemberLookup (RootContext rc, Type t, string name,
219 return MemberLookup (rc, t, name, same_type, AllMemberTypes, AllBindingsFlags);
223 // Resolves the E in `E.I' side for a member_access
225 // This is suboptimal and should be merged with ResolveMemberAccess
227 static Expression ResolvePrimary (TypeContainer tc, string name)
229 int dot_pos = name.LastIndexOf (".");
231 if (tc.RootContext.IsNamespace (name))
232 return new NamespaceExpr (name);
236 Type t = tc.LookupType (name, false);
239 return new TypeExpr (t);
245 static public Expression ResolveMemberAccess (TypeContainer tc, string name)
248 int dot_pos = name.LastIndexOf (".");
249 string left = name.Substring (0, dot_pos);
250 string right = name.Substring (dot_pos + 1);
252 left_e = ResolvePrimary (tc, left);
256 switch (left_e.ExprClass){
258 return MemberLookup (tc.RootContext,
260 left_e.Type == tc.TypeBuilder);
262 case ExprClass.Namespace:
263 case ExprClass.PropertyAccess:
264 case ExprClass.IndexerAccess:
265 case ExprClass.Variable:
266 case ExprClass.Value:
267 case ExprClass.Nothing:
268 case ExprClass.EventAccess:
269 case ExprClass.MethodGroup:
270 case ExprClass.Invalid:
271 tc.RootContext.Report.Error (-1000,
272 "Internal compiler error, should have " +
273 "got these handled before");
280 static public Expression ImplicitReferenceConversion (Expression expr, Type target_type)
282 Type expr_type = expr.Type;
284 if (target_type == TypeManager.object_type) {
285 if (expr_type.IsClass)
286 return new EmptyCast (expr, target_type);
287 if (expr_type.IsValueType)
288 return new BoxedCast (expr, target_type);
289 } else if (expr_type.IsSubclassOf (target_type))
290 return new EmptyCast (expr, target_type);
292 // FIXME: missing implicit reference conversions:
294 // from any class-type S to any interface-type T.
295 // from any interface type S to interface-type T.
296 // from an array-type S to an array-type of type T
297 // from an array-type to System.Array
298 // from any delegate type to System.Delegate
299 // from any array-type or delegate type into System.ICloneable.
300 // from the null type to any reference-type.
308 // Handles expressions like this: decimal d; d = 1;
309 // and changes them into: decimal d; d = new System.Decimal (1);
311 static Expression InternalTypeConstructor (TypeContainer tc, Expression expr, Type target)
313 ArrayList args = new ArrayList ();
315 args.Add (new Argument (expr, Argument.AType.Expression));
317 Expression ne = new New (target.FullName, args,
318 new Location ("FIXME", 1, 1));
320 return ne.Resolve (tc);
324 // Converts implicitly the resolved expression `expr' into the
325 // `target_type'. It returns a new expression that can be used
326 // in a context that expects a `target_type'.
328 static public Expression ConvertImplicit (TypeContainer tc, Expression expr, Type target_type)
330 Type expr_type = expr.Type;
332 if (expr_type == target_type)
336 // Step 1: Perform implicit conversions as found on expr.Type
340 imp = new UserImplicitCast (expr, target_type);
342 imp = imp.Resolve (tc);
348 // Step 2: Built-in conversions.
350 if (expr_type == TypeManager.sbyte_type){
352 // From sbyte to short, int, long, float, double.
354 if (target_type == TypeManager.int32_type)
355 return new OpcodeCast (expr, target_type, OpCodes.Conv_I4);
356 if (target_type == TypeManager.int64_type)
357 return new OpcodeCast (expr, target_type, OpCodes.Conv_U8);
358 if (target_type == TypeManager.double_type)
359 return new OpcodeCast (expr, target_type, OpCodes.Conv_R8);
360 if (target_type == TypeManager.float_type)
361 return new OpcodeCast (expr, target_type, OpCodes.Conv_R4);
362 if (target_type == TypeManager.short_type)
363 return new OpcodeCast (expr, target_type, OpCodes.Conv_I2);
364 if (target_type == TypeManager.decimal_type)
365 return InternalTypeConstructor (tc, expr, target_type);
366 } else if (expr_type == TypeManager.byte_type){
368 // From byte to short, ushort, int, uint, long, ulong, float, double
370 if ((target_type == TypeManager.short_type) ||
371 (target_type == TypeManager.ushort_type) ||
372 (target_type == TypeManager.int32_type) ||
373 (target_type == TypeManager.uint32_type))
374 return new EmptyCast (expr, target_type);
376 if (target_type == TypeManager.uint64_type)
377 return new OpcodeCast (expr, target_type, OpCodes.Conv_U8);
378 if (target_type == TypeManager.int64_type)
379 return new OpcodeCast (expr, target_type, OpCodes.Conv_I8);
381 if (target_type == TypeManager.float_type)
382 return new OpcodeCast (expr, target_type, OpCodes.Conv_R4);
383 if (target_type == TypeManager.double_type)
384 return new OpcodeCast (expr, target_type, OpCodes.Conv_R8);
385 if (target_type == TypeManager.decimal_type)
386 return InternalTypeConstructor (tc, expr, target_type);
387 } else if (expr_type == TypeManager.short_type){
389 // From short to int, long, float, double
391 if (target_type == TypeManager.int32_type)
392 return new EmptyCast (expr, target_type);
393 if (target_type == TypeManager.int64_type)
394 return new OpcodeCast (expr, target_type, OpCodes.Conv_I8);
395 if (target_type == TypeManager.double_type)
396 return new OpcodeCast (expr, target_type, OpCodes.Conv_R8);
397 if (target_type == TypeManager.float_type)
398 return new OpcodeCast (expr, target_type, OpCodes.Conv_R4);
399 if (target_type == TypeManager.decimal_type)
400 return InternalTypeConstructor (tc, expr, target_type);
401 } else if (expr_type == TypeManager.ushort_type){
403 // From ushort to int, uint, long, ulong, float, double
405 if ((target_type == TypeManager.uint32_type) ||
406 (target_type == TypeManager.uint64_type))
407 return new EmptyCast (expr, target_type);
409 if (target_type == TypeManager.int32_type)
410 return new OpcodeCast (expr, target_type, OpCodes.Conv_I4);
411 if (target_type == TypeManager.int64_type)
412 return new OpcodeCast (expr, target_type, OpCodes.Conv_I8);
413 if (target_type == TypeManager.double_type)
414 return new OpcodeCast (expr, target_type, OpCodes.Conv_R8);
415 if (target_type == TypeManager.float_type)
416 return new OpcodeCast (expr, target_type, OpCodes.Conv_R4);
417 if (target_type == TypeManager.decimal_type)
418 return InternalTypeConstructor (tc, expr, target_type);
419 } else if (expr_type == TypeManager.int32_type){
421 // From int to long, float, double
423 if (target_type == TypeManager.int64_type)
424 return new OpcodeCast (expr, target_type, OpCodes.Conv_I8);
425 if (target_type == TypeManager.double_type)
426 return new OpcodeCast (expr, target_type, OpCodes.Conv_R8);
427 if (target_type == TypeManager.float_type)
428 return new OpcodeCast (expr, target_type, OpCodes.Conv_R4);
429 if (target_type == TypeManager.decimal_type)
430 return InternalTypeConstructor (tc, expr, target_type);
431 } else if (expr_type == TypeManager.uint32_type){
433 // From uint to long, ulong, float, double
435 if (target_type == TypeManager.int64_type)
436 return new OpcodeCast (expr, target_type, OpCodes.Conv_I8);
437 if (target_type == TypeManager.uint64_type)
438 return new OpcodeCast (expr, target_type, OpCodes.Conv_U8);
439 if (target_type == TypeManager.double_type)
440 return new OpcodeCast (expr, target_type, OpCodes.Conv_R_Un,
442 if (target_type == TypeManager.float_type)
443 return new OpcodeCast (expr, target_type, OpCodes.Conv_R_Un,
445 if (target_type == TypeManager.decimal_type)
446 return InternalTypeConstructor (tc, expr, target_type);
447 } else if ((expr_type == TypeManager.uint64_type) ||
448 (expr_type == TypeManager.int64_type)){
450 // From long to float, double
452 if (target_type == TypeManager.double_type)
453 return new OpcodeCast (expr, target_type, OpCodes.Conv_R_Un,
455 if (target_type == TypeManager.float_type)
456 return new OpcodeCast (expr, target_type, OpCodes.Conv_R_Un,
458 if (target_type == TypeManager.decimal_type)
459 return InternalTypeConstructor (tc, expr, target_type);
460 } else if (expr_type == TypeManager.char_type){
462 // From char to ushort, int, uint, long, ulong, float, double
464 if ((target_type == TypeManager.ushort_type) ||
465 (target_type == TypeManager.int32_type) ||
466 (target_type == TypeManager.uint32_type))
467 return new EmptyCast (expr, target_type);
468 if (target_type == TypeManager.uint64_type)
469 return new OpcodeCast (expr, target_type, OpCodes.Conv_U8);
470 if (target_type == TypeManager.int64_type)
471 return new OpcodeCast (expr, target_type, OpCodes.Conv_I8);
472 if (target_type == TypeManager.float_type)
473 return new OpcodeCast (expr, target_type, OpCodes.Conv_R4);
474 if (target_type == TypeManager.double_type)
475 return new OpcodeCast (expr, target_type, OpCodes.Conv_R8);
476 if (target_type == TypeManager.decimal_type)
477 return InternalTypeConstructor (tc, expr, target_type);
479 return ImplicitReferenceConversion (expr, target_type);
484 // Could not find an implicit cast.
490 // Attemptes to implicityly convert `target' into `type', using
491 // ConvertImplicit. If there is no implicit conversion, then
492 // an error is signaled
494 static public Expression ConvertImplicitRequired (TypeContainer tc, Expression target,
495 Type type, Location l)
499 e = ConvertImplicit (tc, target, type);
501 string msg = "Can not convert implicitly from `"+
502 TypeManager.CSharpName (target.Type) + "' to `" +
503 TypeManager.CSharpName (type) + "'";
505 tc.RootContext.Report.Error (29, l, msg);
511 // Performs an explicit conversion of the expression `expr' whose
512 // type is expr.Type to `target_type'.
514 static public Expression ConvertExplicit (Expression expr, Type target_type)
519 void report (TypeContainer tc, int error, string s)
521 tc.RootContext.Report.Error (error, s);
524 static string ExprClassName (ExprClass c)
527 case ExprClass.Invalid:
529 case ExprClass.Value:
531 case ExprClass.Variable:
533 case ExprClass.Namespace:
537 case ExprClass.MethodGroup:
538 return "method group";
539 case ExprClass.PropertyAccess:
540 return "property access";
541 case ExprClass.EventAccess:
542 return "event access";
543 case ExprClass.IndexerAccess:
544 return "indexer access";
545 case ExprClass.Nothing:
548 throw new Exception ("Should not happen");
552 // Reports that we were expecting `expr' to be of class `expected'
554 protected void report118 (TypeContainer tc, Expression expr, string expected)
556 report (tc, 118, "Expression denotes a '" + ExprClassName (expr.ExprClass) +
557 "' where an " + expected + " was expected");
562 // This is just a base class for expressions that can
563 // appear on statements (invocations, object creation,
564 // assignments, post/pre increment and decrement). The idea
565 // being that they would support an extra Emition interface that
566 // does not leave a result on the stack.
569 public abstract class ExpressionStatement : Expression {
572 // Requests the expression to be emitted in a `statement'
573 // context. This means that no new value is left on the
574 // stack after invoking this method (constrasted with
575 // Emit that will always leave a value on the stack).
577 public abstract void EmitStatement (EmitContext ec);
581 // This kind of cast is used to encapsulate the child
582 // whose type is child.Type into an expression that is
583 // reported to return "return_type". This is used to encapsulate
584 // expressions which have compatible types, but need to be dealt
585 // at higher levels with.
587 // For example, a "byte" expression could be encapsulated in one
588 // of these as an "unsigned int". The type for the expression
589 // would be "unsigned int".
593 public class EmptyCast : Expression {
594 protected Expression child;
596 public EmptyCast (Expression child, Type return_type)
598 ExprClass = child.ExprClass;
603 public override Expression Resolve (TypeContainer tc)
605 // This should never be invoked, we are born in fully
606 // initialized state.
611 public override void Emit (EmitContext ec)
618 // This kind of cast is used to encapsulate Value Types in objects.
620 // The effect of it is to box the value type emitted by the previous
623 public class BoxedCast : EmptyCast {
625 public BoxedCast (Expression expr, Type target_type)
626 : base (expr, target_type)
630 public override Expression Resolve (TypeContainer tc)
632 // This should never be invoked, we are born in fully
633 // initialized state.
638 public override void Emit (EmitContext ec)
641 ec.ig.Emit (OpCodes.Box, child.Type);
646 // This kind of cast is used to encapsulate a child expression
647 // that can be trivially converted to a target type using one or
648 // two opcodes. The opcodes are passed as arguments.
650 public class OpcodeCast : EmptyCast {
654 public OpcodeCast (Expression child, Type return_type, OpCode op)
655 : base (child, return_type)
659 second_valid = false;
662 public OpcodeCast (Expression child, Type return_type, OpCode op, OpCode op2)
663 : base (child, return_type)
671 public override Expression Resolve (TypeContainer tc)
673 // This should never be invoked, we are born in fully
674 // initialized state.
679 public override void Emit (EmitContext ec)
690 public class Unary : ExpressionStatement {
691 public enum Operator {
692 Add, Subtract, Negate, BitComplement,
693 Indirection, AddressOf, PreIncrement,
694 PreDecrement, PostIncrement, PostDecrement
703 public Unary (Operator op, Expression expr, Location loc)
710 public Expression Expr {
720 public Operator Oper {
731 // Returns a stringified representation of the Operator
738 case Operator.Subtract:
740 case Operator.Negate:
742 case Operator.BitComplement:
744 case Operator.AddressOf:
746 case Operator.Indirection:
748 case Operator.PreIncrement : case Operator.PostIncrement :
750 case Operator.PreDecrement : case Operator.PostDecrement :
754 return oper.ToString ();
757 Expression ForceConversion (TypeContainer tc, Expression expr, Type target_type)
759 if (expr.Type == target_type)
762 return ConvertImplicit (tc, expr, target_type);
765 void report23 (Report r, Type t)
767 r.Error (23, "Operator " + OperName () + " cannot be applied to operand of type `" +
768 TypeManager.CSharpName (t) + "'");
772 // Returns whether an object of type `t' can be incremented
773 // or decremented with add/sub (ie, basically whether we can
774 // use pre-post incr-decr operations on it, but it is not a
775 // System.Decimal, which we test elsewhere)
777 static bool IsIncrementableNumber (Type t)
779 return (t == TypeManager.sbyte_type) ||
780 (t == TypeManager.byte_type) ||
781 (t == TypeManager.short_type) ||
782 (t == TypeManager.ushort_type) ||
783 (t == TypeManager.int32_type) ||
784 (t == TypeManager.uint32_type) ||
785 (t == TypeManager.int64_type) ||
786 (t == TypeManager.uint64_type) ||
787 (t == TypeManager.char_type) ||
788 (t.IsSubclassOf (TypeManager.enum_type)) ||
789 (t == TypeManager.float_type) ||
790 (t == TypeManager.double_type);
793 Expression ResolveOperator (TypeContainer tc)
795 Type expr_type = expr.Type;
798 // Step 1: Perform Operator Overload location
803 if (oper == Operator.PostIncrement || oper == Operator.PreIncrement)
804 op_name = "op_Increment";
805 else if (oper == Operator.PostDecrement || oper == Operator.PreDecrement)
806 op_name = "op_Decrement";
808 op_name = "op_" + oper;
810 mg = MemberLookup (tc.RootContext, expr_type, op_name, false);
813 Arguments = new ArrayList ();
814 Arguments.Add (new Argument (expr, Argument.AType.Expression));
816 method = Invocation.OverloadResolve (tc, (MethodGroupExpr) mg, Arguments, location);
817 if (method != null) {
818 MethodInfo mi = (MethodInfo) method;
820 type = mi.ReturnType;
826 // Step 2: Default operations on CLI native types.
829 // Only perform numeric promotions on:
832 if (expr_type == null)
835 if (oper == Operator.Negate){
836 if (expr_type != TypeManager.bool_type) {
837 report23 (tc.RootContext.Report, expr.Type);
841 type = TypeManager.bool_type;
845 if (oper == Operator.BitComplement) {
846 if (!((expr_type == TypeManager.int32_type) ||
847 (expr_type == TypeManager.uint32_type) ||
848 (expr_type == TypeManager.int64_type) ||
849 (expr_type == TypeManager.uint64_type) ||
850 (expr_type.IsSubclassOf (TypeManager.enum_type)))){
851 report23 (tc.RootContext.Report, expr.Type);
858 if (oper == Operator.Add) {
860 // A plus in front of something is just a no-op, so return the child.
866 // Deals with -literals
867 // int operator- (int x)
868 // long operator- (long x)
869 // float operator- (float f)
870 // double operator- (double d)
871 // decimal operator- (decimal d)
873 if (oper == Operator.Subtract){
875 // Fold a "- Constant" into a negative constant
881 // Is this a constant?
883 if (expr is IntLiteral)
884 e = new IntLiteral (-((IntLiteral) expr).Value);
885 else if (expr is LongLiteral)
886 e = new LongLiteral (-((LongLiteral) expr).Value);
887 else if (expr is FloatLiteral)
888 e = new FloatLiteral (-((FloatLiteral) expr).Value);
889 else if (expr is DoubleLiteral)
890 e = new DoubleLiteral (-((DoubleLiteral) expr).Value);
891 else if (expr is DecimalLiteral)
892 e = new DecimalLiteral (-((DecimalLiteral) expr).Value);
900 // Not a constant we can optimize, perform numeric
901 // promotions to int, long, double.
904 // The following is inneficient, because we call
905 // ConvertImplicit too many times.
907 // It is also not clear if we should convert to Float
908 // or Double initially.
910 if (expr_type == TypeManager.uint32_type){
912 // FIXME: handle exception to this rule that
913 // permits the int value -2147483648 (-2^31) to
914 // bt written as a decimal interger literal
916 type = TypeManager.int64_type;
917 expr = ConvertImplicit (tc, expr, type);
921 if (expr_type == TypeManager.uint64_type){
923 // FIXME: Handle exception of `long value'
924 // -92233720368547758087 (-2^63) to be written as
925 // decimal integer literal.
927 report23 (tc.RootContext.Report, expr_type);
931 e = ConvertImplicit (tc, expr, TypeManager.int32_type);
938 e = ConvertImplicit (tc, expr, TypeManager.int64_type);
945 e = ConvertImplicit (tc, expr, TypeManager.double_type);
952 report23 (tc.RootContext.Report, expr_type);
957 // The operand of the prefix/postfix increment decrement operators
958 // should be an expression that is classified as a variable,
959 // a property access or an indexer access
961 if (oper == Operator.PreDecrement || oper == Operator.PreIncrement ||
962 oper == Operator.PostDecrement || oper == Operator.PostIncrement){
963 if (expr.ExprClass == ExprClass.Variable){
964 if (IsIncrementableNumber (expr_type) ||
965 expr_type == TypeManager.decimal_type){
969 } else if (expr.ExprClass == ExprClass.IndexerAccess){
971 // FIXME: Verify that we have both get and set methods
973 throw new Exception ("Implement me");
974 } else if (expr.ExprClass == ExprClass.PropertyAccess){
976 // FIXME: Verify that we have both get and set methods
978 throw new Exception ("Implement me");
980 report118 (tc, expr, "variable, indexer or property access");
984 tc.RootContext.Report.Error (187, "No such operator '" + OperName () +
985 "' defined for type '" +
986 TypeManager.CSharpName (expr_type) + "'");
991 public override Expression Resolve (TypeContainer tc)
993 expr = expr.Resolve (tc);
998 return ResolveOperator (tc);
1001 public override void Emit (EmitContext ec)
1003 ILGenerator ig = ec.ig;
1004 Type expr_type = expr.Type;
1006 if (method != null) {
1008 // Note that operators are static anyway
1010 if (Arguments != null)
1011 Invocation.EmitArguments (ec, method, Arguments);
1014 // Post increment/decrement operations need a copy at this
1017 if (oper == Operator.PostDecrement || oper == Operator.PostIncrement)
1018 ig.Emit (OpCodes.Dup);
1021 ig.Emit (OpCodes.Call, (MethodInfo) method);
1024 // Pre Increment and Decrement operators
1026 if (oper == Operator.PreIncrement || oper == Operator.PreDecrement){
1027 ig.Emit (OpCodes.Dup);
1031 // Increment and Decrement should store the result
1033 if (oper == Operator.PreDecrement || oper == Operator.PreIncrement ||
1034 oper == Operator.PostDecrement || oper == Operator.PostIncrement){
1035 ((LValue) expr).Store (ig);
1042 throw new Exception ("This should be caught by Resolve");
1044 case Operator.Subtract:
1046 ig.Emit (OpCodes.Neg);
1049 case Operator.Negate:
1051 ig.Emit (OpCodes.Ldc_I4_0);
1052 ig.Emit (OpCodes.Ceq);
1055 case Operator.BitComplement:
1057 ig.Emit (OpCodes.Not);
1060 case Operator.AddressOf:
1061 throw new Exception ("Not implemented yet");
1063 case Operator.Indirection:
1064 throw new Exception ("Not implemented yet");
1066 case Operator.PreIncrement:
1067 case Operator.PreDecrement:
1068 if (expr.ExprClass == ExprClass.Variable){
1070 // Resolve already verified that it is an "incrementable"
1073 ig.Emit (OpCodes.Ldc_I4_1);
1075 if (oper == Operator.PreDecrement)
1076 ig.Emit (OpCodes.Sub);
1078 ig.Emit (OpCodes.Add);
1079 ig.Emit (OpCodes.Dup);
1080 ((LValue) expr).Store (ig);
1082 throw new Exception ("Handle Indexers and Properties here");
1086 case Operator.PostIncrement:
1087 case Operator.PostDecrement:
1088 if (expr.ExprClass == ExprClass.Variable){
1090 // Resolve already verified that it is an "incrementable"
1093 ig.Emit (OpCodes.Dup);
1094 ig.Emit (OpCodes.Ldc_I4_1);
1096 if (oper == Operator.PostDecrement)
1097 ig.Emit (OpCodes.Sub);
1099 ig.Emit (OpCodes.Add);
1100 ((LValue) expr).Store (ig);
1102 throw new Exception ("Handle Indexers and Properties here");
1107 throw new Exception ("This should not happen: Operator = "
1108 + oper.ToString ());
1113 public override void EmitStatement (EmitContext ec)
1116 // FIXME: we should rewrite this code to generate
1117 // better code for ++ and -- as we know we wont need
1118 // the values on the stack
1121 ec.ig.Emit (OpCodes.Pop);
1125 public class Probe : Expression {
1130 public enum Operator {
1134 public Probe (Operator oper, Expression expr, string probe_type)
1137 this.probe_type = probe_type;
1141 public Operator Oper {
1147 public Expression Expr {
1153 public string ProbeType {
1159 public override Expression Resolve (TypeContainer tc)
1161 // FIXME: Implement;
1162 throw new Exception ("Unimplemented");
1166 public override void Emit (EmitContext ec)
1171 public class Cast : Expression {
1175 public Cast (string cast_type, Expression expr)
1177 this.target_type = cast_type;
1181 public string TargetType {
1187 public Expression Expr {
1196 public override Expression Resolve (TypeContainer tc)
1198 type = tc.LookupType (target_type, false);
1199 eclass = ExprClass.Value;
1205 // FIXME: Unimplemented
1207 throw new Exception ("FINISH ME");
1210 public override void Emit (EmitContext ec)
1215 public class Binary : Expression {
1216 public enum Operator {
1217 Multiply, Division, Modulus,
1218 Addition, Subtraction,
1219 LeftShift, RightShift,
1220 LessThan, GreaterThan, LessThanOrEqual, GreaterThanOrEqual,
1221 Equality, Inequality,
1230 Expression left, right;
1232 ArrayList Arguments;
1236 public Binary (Operator oper, Expression left, Expression right, Location loc)
1241 this.location = loc;
1244 public Operator Oper {
1253 public Expression Left {
1262 public Expression Right {
1273 // Returns a stringified representation of the Operator
1278 case Operator.Multiply:
1280 case Operator.Division:
1282 case Operator.Modulus:
1284 case Operator.Addition:
1286 case Operator.Subtraction:
1288 case Operator.LeftShift:
1290 case Operator.RightShift:
1292 case Operator.LessThan:
1294 case Operator.GreaterThan:
1296 case Operator.LessThanOrEqual:
1298 case Operator.GreaterThanOrEqual:
1300 case Operator.Equality:
1302 case Operator.Inequality:
1304 case Operator.BitwiseAnd:
1306 case Operator.BitwiseOr:
1308 case Operator.ExclusiveOr:
1310 case Operator.LogicalOr:
1312 case Operator.LogicalAnd:
1316 return oper.ToString ();
1319 Expression ForceConversion (TypeContainer tc, Expression expr, Type target_type)
1321 if (expr.Type == target_type)
1324 return ConvertImplicit (tc, expr, target_type);
1328 // Note that handling the case l == Decimal || r == Decimal
1329 // is taken care of by the Step 1 Operator Overload resolution.
1331 void DoNumericPromotions (TypeContainer tc, Type l, Type r)
1333 if (l == TypeManager.double_type || r == TypeManager.double_type){
1335 // If either operand is of type double, the other operand is
1336 // conveted to type double.
1338 if (r != TypeManager.double_type)
1339 right = ConvertImplicit (tc, right, TypeManager.double_type);
1340 if (l != TypeManager.double_type)
1341 left = ConvertImplicit (tc, left, TypeManager.double_type);
1343 type = TypeManager.double_type;
1344 } else if (l == TypeManager.float_type || r == TypeManager.float_type){
1346 // if either operand is of type float, th eother operand is
1347 // converd to type float.
1349 if (r != TypeManager.double_type)
1350 right = ConvertImplicit (tc, right, TypeManager.float_type);
1351 if (l != TypeManager.double_type)
1352 left = ConvertImplicit (tc, left, TypeManager.float_type);
1353 type = TypeManager.float_type;
1354 } else if (l == TypeManager.uint64_type || r == TypeManager.uint64_type){
1356 // If either operand is of type ulong, the other operand is
1357 // converted to type ulong. or an error ocurrs if the other
1358 // operand is of type sbyte, short, int or long
1362 if (l == TypeManager.uint64_type)
1364 else if (r == TypeManager.uint64_type)
1367 if ((other == TypeManager.sbyte_type) ||
1368 (other == TypeManager.short_type) ||
1369 (other == TypeManager.int32_type) ||
1370 (other == TypeManager.int64_type)){
1371 string oper = OperName ();
1373 tc.RootContext.Report.Error (34, "Operator `" + OperName ()
1374 + "' is ambiguous on operands of type `"
1375 + TypeManager.CSharpName (l) + "' "
1376 + "and `" + TypeManager.CSharpName (r)
1379 type = TypeManager.uint64_type;
1380 } else if (l == TypeManager.int64_type || r == TypeManager.int64_type){
1382 // If either operand is of type long, the other operand is converted
1385 if (l != TypeManager.int64_type)
1386 left = ConvertImplicit (tc, left, TypeManager.int64_type);
1387 if (r != TypeManager.int64_type)
1388 right = ConvertImplicit (tc, right, TypeManager.int64_type);
1390 type = TypeManager.int64_type;
1391 } else if (l == TypeManager.uint32_type || r == TypeManager.uint32_type){
1393 // If either operand is of type uint, and the other
1394 // operand is of type sbyte, short or int, othe operands are
1395 // converted to type long.
1399 if (l == TypeManager.uint32_type)
1401 else if (r == TypeManager.uint32_type)
1404 if ((other == TypeManager.sbyte_type) ||
1405 (other == TypeManager.short_type) ||
1406 (other == TypeManager.int32_type)){
1407 left = ForceConversion (tc, left, TypeManager.int64_type);
1408 right = ForceConversion (tc, right, TypeManager.int64_type);
1409 type = TypeManager.int64_type;
1412 // if either operand is of type uint, the other
1413 // operand is converd to type uint
1415 left = ForceConversion (tc, left, TypeManager.uint32_type);
1416 right = ForceConversion (tc, left, TypeManager.uint32_type);
1417 type = TypeManager.uint32_type;
1419 } else if (l == TypeManager.decimal_type || r == TypeManager.decimal_type){
1420 if (l != TypeManager.decimal_type)
1421 left = ConvertImplicit (tc, left, TypeManager.decimal_type);
1422 if (r != TypeManager.decimal_type)
1423 right = ConvertImplicit (tc, right, TypeManager.decimal_type);
1425 type = TypeManager.decimal_type;
1427 left = ForceConversion (tc, left, TypeManager.int32_type);
1428 right = ForceConversion (tc, right, TypeManager.int32_type);
1429 type = TypeManager.int32_type;
1433 void error19 (TypeContainer tc)
1435 tc.RootContext.Report.Error (
1437 "Operator " + OperName () + " cannot be applied to operands of type `" +
1438 TypeManager.CSharpName (left.Type) + "' and `" +
1439 TypeManager.CSharpName (right.Type) + "'");
1443 Expression CheckShiftArguments (TypeContainer tc)
1447 Type r = right.Type;
1449 e = ForceConversion (tc, right, TypeManager.int32_type);
1456 if (((e = ConvertImplicit (tc, left, TypeManager.int32_type)) != null) ||
1457 ((e = ConvertImplicit (tc, left, TypeManager.uint32_type)) != null) ||
1458 ((e = ConvertImplicit (tc, left, TypeManager.int64_type)) != null) ||
1459 ((e = ConvertImplicit (tc, left, TypeManager.uint64_type)) != null)){
1468 Expression ResolveOperator (TypeContainer tc)
1471 Type r = right.Type;
1474 // Step 1: Perform Operator Overload location
1476 Expression left_expr, right_expr;
1478 string op = "op_" + oper;
1480 left_expr = MemberLookup (tc.RootContext, l, op, false);
1482 right_expr = MemberLookup (tc.RootContext, r, op, false);
1484 Console.WriteLine ("Looking up: " + op);
1486 if (left_expr != null || right_expr != null) {
1488 // Now we need to form the union of these two sets and
1489 // then call OverloadResolve on that.
1491 MethodGroupExpr left_set = null, right_set = null;
1492 int length1 = 0, length2 = 0;
1494 if (left_expr != null) {
1495 left_set = (MethodGroupExpr) left_expr;
1496 length1 = left_set.Methods.Length;
1499 if (right_expr != null) {
1500 right_set = (MethodGroupExpr) right_expr;
1501 length2 = right_set.Methods.Length;
1504 MemberInfo [] miset = new MemberInfo [length1 + length2];
1505 if (left_set != null)
1506 left_set.Methods.CopyTo (miset, 0);
1507 if (right_set != null)
1508 right_set.Methods.CopyTo (miset, length1);
1510 MethodGroupExpr union = new MethodGroupExpr (miset);
1512 Arguments = new ArrayList ();
1513 Arguments.Add (new Argument (left, Argument.AType.Expression));
1514 Arguments.Add (new Argument (right, Argument.AType.Expression));
1517 method = Invocation.OverloadResolve (tc, union, Arguments, location);
1518 if (method != null) {
1519 MethodInfo mi = (MethodInfo) method;
1521 type = mi.ReturnType;
1527 // Step 2: Default operations on CLI native types.
1530 // Only perform numeric promotions on:
1531 // +, -, *, /, %, &, |, ^, ==, !=, <, >, <=, >=
1533 if (oper == Operator.LeftShift || oper == Operator.RightShift){
1534 return CheckShiftArguments (tc);
1535 } else if (oper == Operator.LogicalOr || oper == Operator.LogicalAnd){
1537 if (l != TypeManager.bool_type || r != TypeManager.bool_type)
1540 DoNumericPromotions (tc, l, r);
1542 if (left == null || right == null)
1545 if (oper == Operator.BitwiseAnd ||
1546 oper == Operator.BitwiseOr ||
1547 oper == Operator.ExclusiveOr){
1548 if (!((l == TypeManager.int32_type) ||
1549 (l == TypeManager.uint32_type) ||
1550 (l == TypeManager.int64_type) ||
1551 (l == TypeManager.uint64_type))){
1557 if (oper == Operator.Equality ||
1558 oper == Operator.Inequality ||
1559 oper == Operator.LessThanOrEqual ||
1560 oper == Operator.LessThan ||
1561 oper == Operator.GreaterThanOrEqual ||
1562 oper == Operator.GreaterThan){
1563 type = TypeManager.bool_type;
1569 public override Expression Resolve (TypeContainer tc)
1571 left = left.Resolve (tc);
1572 right = right.Resolve (tc);
1574 if (left == null || right == null)
1577 return ResolveOperator (tc);
1580 public bool IsBranchable ()
1582 if (oper == Operator.Equality ||
1583 oper == Operator.Inequality ||
1584 oper == Operator.LessThan ||
1585 oper == Operator.GreaterThan ||
1586 oper == Operator.LessThanOrEqual ||
1587 oper == Operator.GreaterThanOrEqual){
1594 // This entry point is used by routines that might want
1595 // to emit a brfalse/brtrue after an expression, and instead
1596 // they could use a more compact notation.
1598 // Typically the code would generate l.emit/r.emit, followed
1599 // by the comparission and then a brtrue/brfalse. The comparissions
1600 // are sometimes inneficient (there are not as complete as the branches
1601 // look for the hacks in Emit using double ceqs).
1603 // So for those cases we provide EmitBranchable that can emit the
1604 // branch with the test
1606 public void EmitBranchable (EmitContext ec, int target)
1609 bool close_target = false;
1615 case Operator.Equality:
1617 opcode = OpCodes.Beq_S;
1619 opcode = OpCodes.Beq;
1622 case Operator.Inequality:
1624 opcode = OpCodes.Bne_Un_S;
1626 opcode = OpCodes.Bne_Un;
1629 case Operator.LessThan:
1631 opcode = OpCodes.Blt_S;
1633 opcode = OpCodes.Blt;
1636 case Operator.GreaterThan:
1638 opcode = OpCodes.Bgt_S;
1640 opcode = OpCodes.Bgt;
1643 case Operator.LessThanOrEqual:
1645 opcode = OpCodes.Ble_S;
1647 opcode = OpCodes.Ble;
1650 case Operator.GreaterThanOrEqual:
1652 opcode = OpCodes.Bge_S;
1654 opcode = OpCodes.Ble;
1658 throw new Exception ("EmitBranchable called on non-EmitBranchable operator: "
1659 + oper.ToString ());
1662 ec.ig.Emit (opcode, target);
1665 public override void Emit (EmitContext ec)
1667 ILGenerator ig = ec.ig;
1669 Type r = right.Type;
1672 if (method != null) {
1674 // Note that operators are static anyway
1676 if (Arguments != null)
1677 Invocation.EmitArguments (ec, method, Arguments);
1679 if (method is MethodInfo)
1680 ig.Emit (OpCodes.Call, (MethodInfo) method);
1682 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
1691 case Operator.Multiply:
1693 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
1694 opcode = OpCodes.Mul_Ovf;
1695 else if (l==TypeManager.uint32_type || l==TypeManager.uint64_type)
1696 opcode = OpCodes.Mul_Ovf_Un;
1698 opcode = OpCodes.Mul;
1700 opcode = OpCodes.Mul;
1704 case Operator.Division:
1705 if (l == TypeManager.uint32_type || l == TypeManager.uint64_type)
1706 opcode = OpCodes.Div_Un;
1708 opcode = OpCodes.Div;
1711 case Operator.Modulus:
1712 if (l == TypeManager.uint32_type || l == TypeManager.uint64_type)
1713 opcode = OpCodes.Rem_Un;
1715 opcode = OpCodes.Rem;
1718 case Operator.Addition:
1720 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
1721 opcode = OpCodes.Add_Ovf;
1722 else if (l==TypeManager.uint32_type || l==TypeManager.uint64_type)
1723 opcode = OpCodes.Add_Ovf_Un;
1725 opcode = OpCodes.Mul;
1727 opcode = OpCodes.Add;
1730 case Operator.Subtraction:
1732 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
1733 opcode = OpCodes.Sub_Ovf;
1734 else if (l==TypeManager.uint32_type || l==TypeManager.uint64_type)
1735 opcode = OpCodes.Sub_Ovf_Un;
1737 opcode = OpCodes.Sub;
1739 opcode = OpCodes.Sub;
1742 case Operator.RightShift:
1743 opcode = OpCodes.Shr;
1746 case Operator.LeftShift:
1747 opcode = OpCodes.Shl;
1750 case Operator.Equality:
1751 opcode = OpCodes.Ceq;
1754 case Operator.Inequality:
1755 ec.ig.Emit (OpCodes.Ceq);
1756 ec.ig.Emit (OpCodes.Ldc_I4_0);
1758 opcode = OpCodes.Ceq;
1761 case Operator.LessThan:
1762 opcode = OpCodes.Clt;
1765 case Operator.GreaterThan:
1766 opcode = OpCodes.Cgt;
1769 case Operator.LessThanOrEqual:
1770 ec.ig.Emit (OpCodes.Cgt);
1771 ec.ig.Emit (OpCodes.Ldc_I4_0);
1773 opcode = OpCodes.Ceq;
1776 case Operator.GreaterThanOrEqual:
1777 ec.ig.Emit (OpCodes.Clt);
1778 ec.ig.Emit (OpCodes.Ldc_I4_1);
1780 opcode = OpCodes.Sub;
1783 case Operator.LogicalOr:
1784 case Operator.BitwiseOr:
1785 opcode = OpCodes.Or;
1788 case Operator.LogicalAnd:
1789 case Operator.BitwiseAnd:
1790 opcode = OpCodes.And;
1793 case Operator.ExclusiveOr:
1794 opcode = OpCodes.Xor;
1798 throw new Exception ("This should not happen: Operator = "
1799 + oper.ToString ());
1806 public class Conditional : Expression {
1807 Expression expr, trueExpr, falseExpr;
1809 public Conditional (Expression expr, Expression trueExpr, Expression falseExpr)
1812 this.trueExpr = trueExpr;
1813 this.falseExpr = falseExpr;
1816 public Expression Expr {
1822 public Expression TrueExpr {
1828 public Expression FalseExpr {
1834 public override Expression Resolve (TypeContainer tc)
1836 // FIXME: Implement;
1837 throw new Exception ("Unimplemented");
1841 public override void Emit (EmitContext ec)
1846 public class SimpleName : Expression {
1847 public readonly string Name;
1848 public readonly Location Location;
1850 public SimpleName (string name, Location l)
1857 // Checks whether we are trying to access an instance
1858 // property, method or field from a static body.
1860 Expression MemberStaticCheck (Report r, Expression e)
1862 if (e is FieldExpr){
1863 FieldInfo fi = ((FieldExpr) e).FieldInfo;
1867 "An object reference is required " +
1868 "for the non-static field `"+Name+"'");
1871 } else if (e is MethodGroupExpr){
1872 // FIXME: Pending reorganization of MemberLookup
1873 // Basically at this point we should have the
1874 // best match already selected for us, and
1875 // we should only have to check a *single*
1876 // Method for its static on/off bit.
1878 } else if (e is PropertyExpr){
1879 if (!((PropertyExpr) e).IsStatic){
1881 "An object reference is required " +
1882 "for the non-static property access `"+
1892 // 7.5.2: Simple Names.
1894 // Local Variables and Parameters are handled at
1895 // parse time, so they never occur as SimpleNames.
1897 Expression ResolveSimpleName (TypeContainer tc)
1900 Report r = tc.RootContext.Report;
1902 e = MemberLookup (tc.RootContext, tc.TypeBuilder, Name, true);
1906 else if (e is FieldExpr){
1907 FieldExpr fe = (FieldExpr) e;
1909 if (!fe.FieldInfo.IsStatic)
1910 fe.Instance = new This ();
1913 if ((tc.ModFlags & Modifiers.STATIC) != 0)
1914 return MemberStaticCheck (r, e);
1920 // Do step 3 of the Simple Name resolution.
1922 // FIXME: implement me.
1924 r.Error (103, Location, "The name `" + Name + "' does not exist in the class `" +
1931 // SimpleName needs to handle a multitude of cases:
1933 // simple_names and qualified_identifiers are placed on
1934 // the tree equally.
1936 public override Expression Resolve (TypeContainer tc)
1938 if (Name.IndexOf (".") != -1)
1939 return ResolveMemberAccess (tc, Name);
1941 return ResolveSimpleName (tc);
1944 public override void Emit (EmitContext ec)
1946 throw new Exception ("SimpleNames should be gone from the tree");
1951 // A simple interface that should be implemeneted by LValues
1953 public interface LValue {
1954 void Store (ILGenerator ig);
1957 public class LocalVariableReference : Expression, LValue {
1958 public readonly string Name;
1959 public readonly Block Block;
1961 public LocalVariableReference (Block block, string name)
1965 eclass = ExprClass.Variable;
1968 public VariableInfo VariableInfo {
1970 return Block.GetVariableInfo (Name);
1974 public override Expression Resolve (TypeContainer tc)
1976 VariableInfo vi = Block.GetVariableInfo (Name);
1978 type = vi.VariableType;
1982 public override void Emit (EmitContext ec)
1984 VariableInfo vi = VariableInfo;
1985 ILGenerator ig = ec.ig;
1990 ig.Emit (OpCodes.Ldloc_0);
1994 ig.Emit (OpCodes.Ldloc_1);
1998 ig.Emit (OpCodes.Ldloc_2);
2002 ig.Emit (OpCodes.Ldloc_3);
2007 ig.Emit (OpCodes.Ldloc_S, idx);
2009 ig.Emit (OpCodes.Ldloc, idx);
2014 public void Store (ILGenerator ig)
2016 VariableInfo vi = VariableInfo;
2021 ig.Emit (OpCodes.Stloc_0);
2025 ig.Emit (OpCodes.Stloc_1);
2029 ig.Emit (OpCodes.Stloc_2);
2033 ig.Emit (OpCodes.Stloc_3);
2038 ig.Emit (OpCodes.Stloc_S, idx);
2040 ig.Emit (OpCodes.Stloc, idx);
2046 public class ParameterReference : Expression, LValue {
2047 public readonly Parameters Pars;
2048 public readonly String Name;
2049 public readonly int Idx;
2051 public ParameterReference (Parameters pars, int idx, string name)
2056 eclass = ExprClass.Variable;
2059 public override Expression Resolve (TypeContainer tc)
2061 Type [] types = Pars.GetParameterInfo (tc);
2068 public override void Emit (EmitContext ec)
2071 ec.ig.Emit (OpCodes.Ldarg_S, Idx);
2073 ec.ig.Emit (OpCodes.Ldarg, Idx);
2076 public void Store (ILGenerator ig)
2079 ig.Emit (OpCodes.Starg_S, Idx);
2081 ig.Emit (OpCodes.Starg, Idx);
2087 // Used for arguments to New(), Invocation()
2089 public class Argument {
2096 public readonly AType Type;
2099 public Argument (Expression expr, AType type)
2105 public Expression Expr {
2115 public bool Resolve (TypeContainer tc)
2117 expr = expr.Resolve (tc);
2119 return expr != null;
2122 public void Emit (EmitContext ec)
2129 // Invocation of methods or delegates.
2131 public class Invocation : ExpressionStatement {
2132 public readonly ArrayList Arguments;
2133 public readonly Location Location;
2136 MethodBase method = null;
2138 static Hashtable method_parameter_cache;
2140 static Invocation ()
2142 method_parameter_cache = new Hashtable ();
2146 // arguments is an ArrayList, but we do not want to typecast,
2147 // as it might be null.
2149 // FIXME: only allow expr to be a method invocation or a
2150 // delegate invocation (7.5.5)
2152 public Invocation (Expression expr, ArrayList arguments, Location l)
2155 Arguments = arguments;
2159 public Expression Expr {
2166 /// Computes whether Argument `a' and the Type t of the ParameterInfo `pi' are
2167 /// compatible, and if so, how good is the match (in terms of
2168 /// "better conversions" (7.4.2.3).
2170 /// 0 is the best possible match.
2171 /// -1 represents a type mismatch.
2172 /// -2 represents a ref/out mismatch.
2174 static int Badness (Argument a, Type t)
2176 Expression argument_expr = a.Expr;
2177 Type argument_type = argument_expr.Type;
2179 if (argument_type == null){
2180 throw new Exception ("Expression of type " + a.Expr + " does not resolve its type");
2183 if (t == argument_type)
2187 // Now probe whether an implicit constant expression conversion
2190 // An implicit constant expression conversion permits the following
2193 // * A constant-expression of type `int' can be converted to type
2194 // sbyte, byute, short, ushort, uint, ulong provided the value of
2195 // of the expression is withing the range of the destination type.
2197 // * A constant-expression of type long can be converted to type
2198 // ulong, provided the value of the constant expression is not negative
2200 // FIXME: Note that this assumes that constant folding has
2201 // taken place. We dont do constant folding yet.
2204 if (argument_type == TypeManager.int32_type && argument_expr is IntLiteral){
2205 IntLiteral ei = (IntLiteral) argument_expr;
2206 int value = ei.Value;
2208 if (t == TypeManager.sbyte_type){
2209 if (value >= SByte.MinValue && value <= SByte.MaxValue)
2211 } else if (t == TypeManager.byte_type){
2212 if (Byte.MinValue >= 0 && value <= Byte.MaxValue)
2214 } else if (t == TypeManager.short_type){
2215 if (value >= Int16.MinValue && value <= Int16.MaxValue)
2217 } else if (t == TypeManager.ushort_type){
2218 if (value >= UInt16.MinValue && value <= UInt16.MaxValue)
2220 } else if (t == TypeManager.uint32_type){
2222 // we can optimize this case: a positive int32
2223 // always fits on a uint32
2227 } else if (t == TypeManager.uint64_type){
2229 // we can optimize this case: a positive int32
2230 // always fits on a uint64
2235 } else if (argument_type == TypeManager.int64_type && argument_expr is LongLiteral){
2236 LongLiteral ll = (LongLiteral) argument_expr;
2238 if (t == TypeManager.uint64_type){
2244 // FIXME: Implement user-defined implicit conversions here.
2245 // FIXME: Implement better conversion here.
2251 // Returns the Parameters (a ParameterData interface) for the
2254 static ParameterData GetParameterData (MethodBase mb)
2256 object pd = method_parameter_cache [mb];
2259 return (ParameterData) pd;
2261 if (mb is MethodBuilder || mb is ConstructorBuilder){
2262 MethodCore mc = TypeContainer.LookupMethodByBuilder (mb);
2264 InternalParameters ip = mc.ParameterInfo;
2265 method_parameter_cache [mb] = ip;
2267 return (ParameterData) ip;
2269 ParameterInfo [] pi = mb.GetParameters ();
2270 ReflectionParameters rp = new ReflectionParameters (pi);
2271 method_parameter_cache [mb] = rp;
2273 return (ParameterData) rp;
2277 static bool ConversionExists (TypeContainer tc, Type from, Type to)
2279 // Locate user-defined implicit operators
2283 mg = MemberLookup (tc.RootContext, to, "op_Implicit", false);
2286 MethodGroupExpr me = (MethodGroupExpr) mg;
2288 for (int i = me.Methods.Length; i > 0;) {
2290 MethodBase mb = me.Methods [i];
2291 ParameterData pd = GetParameterData (mb);
2293 if (from == pd.ParameterType (0))
2298 mg = MemberLookup (tc.RootContext, from, "op_Implicit", false);
2301 MethodGroupExpr me = (MethodGroupExpr) mg;
2303 for (int i = me.Methods.Length; i > 0;) {
2305 MethodBase mb = me.Methods [i];
2306 MethodInfo mi = (MethodInfo) mb;
2308 if (mi.ReturnType == to)
2317 // Determines "better conversion" as specified in 7.4.2.3
2318 // Returns : 1 if a->p is better
2319 // 0 if a->q or neither is better
2321 static int BetterConversion (TypeContainer tc, Argument a, Type p, Type q)
2324 Type argument_type = a.Expr.Type;
2325 Expression argument_expr = a.Expr;
2327 if (argument_type == null)
2328 throw new Exception ("Expression of type " + a.Expr + " does not resolve its type");
2334 if (argument_type == p)
2337 if (argument_type == q)
2341 // Now probe whether an implicit constant expression conversion
2344 // An implicit constant expression conversion permits the following
2347 // * A constant-expression of type `int' can be converted to type
2348 // sbyte, byute, short, ushort, uint, ulong provided the value of
2349 // of the expression is withing the range of the destination type.
2351 // * A constant-expression of type long can be converted to type
2352 // ulong, provided the value of the constant expression is not negative
2354 // FIXME: Note that this assumes that constant folding has
2355 // taken place. We dont do constant folding yet.
2358 if (argument_type == TypeManager.int32_type && argument_expr is IntLiteral){
2359 IntLiteral ei = (IntLiteral) argument_expr;
2360 int value = ei.Value;
2362 if (p == TypeManager.sbyte_type){
2363 if (value >= SByte.MinValue && value <= SByte.MaxValue)
2365 } else if (p == TypeManager.byte_type){
2366 if (Byte.MinValue >= 0 && value <= Byte.MaxValue)
2368 } else if (p == TypeManager.short_type){
2369 if (value >= Int16.MinValue && value <= Int16.MaxValue)
2371 } else if (p == TypeManager.ushort_type){
2372 if (value >= UInt16.MinValue && value <= UInt16.MaxValue)
2374 } else if (p == TypeManager.uint32_type){
2376 // we can optimize this case: a positive int32
2377 // always fits on a uint32
2381 } else if (p == TypeManager.uint64_type){
2383 // we can optimize this case: a positive int32
2384 // always fits on a uint64
2389 } else if (argument_type == TypeManager.int64_type && argument_expr is LongLiteral){
2390 LongLiteral ll = (LongLiteral) argument_expr;
2392 if (p == TypeManager.uint64_type){
2398 // User-defined Implicit conversions come here
2401 if (ConversionExists (tc, p, q) == true &&
2402 ConversionExists (tc, q, p) == false)
2405 if (p == TypeManager.sbyte_type)
2406 if (q == TypeManager.byte_type || q == TypeManager.ushort_type ||
2407 q == TypeManager.uint32_type || q == TypeManager.uint64_type)
2410 if (p == TypeManager.short_type)
2411 if (q == TypeManager.ushort_type || q == TypeManager.uint32_type ||
2412 q == TypeManager.uint64_type)
2415 if (p == TypeManager.int32_type)
2416 if (q == TypeManager.uint32_type || q == TypeManager.uint64_type)
2419 if (p == TypeManager.int64_type)
2420 if (q == TypeManager.uint64_type)
2427 // Determines "Better function" and returns an integer indicating :
2428 // 0 if candidate ain't better
2429 // 1 if candidate is better than the current best match
2431 static int BetterFunction (TypeContainer tc, ArrayList args, MethodBase candidate, MethodBase best)
2433 ParameterData candidate_pd = GetParameterData (candidate);
2434 ParameterData best_pd;
2440 argument_count = args.Count;
2442 if (candidate_pd.Count == 0 && argument_count == 0)
2446 if (candidate_pd.Count == argument_count) {
2448 for (int j = argument_count; j > 0;) {
2451 Argument a = (Argument) args [j];
2453 x = BetterConversion (tc, a, candidate_pd.ParameterType (j), null);
2470 best_pd = GetParameterData (best);
2472 if (candidate_pd.Count == argument_count && best_pd.Count == argument_count) {
2473 int rating1 = 0, rating2 = 0;
2475 for (int j = argument_count; j > 0;) {
2479 Argument a = (Argument) args [j];
2481 x = BetterConversion (tc, a, candidate_pd.ParameterType (j),
2482 best_pd.ParameterType (j));
2483 y = BetterConversion (tc, a, best_pd.ParameterType (j),
2484 candidate_pd.ParameterType (j));
2490 if (rating1 > rating2)
2499 public static string FullMethodDesc (MethodBase mb)
2501 StringBuilder sb = new StringBuilder (mb.Name);
2502 ParameterData pd = GetParameterData (mb);
2505 for (int i = pd.Count; i > 0;) {
2507 sb.Append (TypeManager.CSharpName (pd.ParameterType (i)));
2513 return sb.ToString ();
2517 // Find the Applicable Function Members (7.4.2.1)
2519 // me: Method Group expression with the members to select.
2520 // it might contain constructors or methods (or anything
2521 // that maps to a method).
2523 // Arguments: ArrayList containing resolved Argument objects.
2525 // Returns: The MethodBase (either a ConstructorInfo or a MethodInfo)
2526 // that is the best match of me on Arguments.
2529 public static MethodBase OverloadResolve (TypeContainer tc, MethodGroupExpr me,
2530 ArrayList Arguments, Location loc)
2532 ArrayList afm = new ArrayList ();
2533 int best_match_idx = -1;
2534 MethodBase method = null;
2537 for (int i = me.Methods.Length; i > 0; ){
2539 MethodBase candidate = me.Methods [i];
2542 x = BetterFunction (tc, Arguments, candidate, method);
2548 method = me.Methods [best_match_idx];
2552 if (best_match_idx != -1)
2555 // Now we see if we can at least find a method with the same number of arguments
2556 // and then try doing implicit conversion on the arguments
2558 if (Arguments == null)
2561 argument_count = Arguments.Count;
2563 ParameterData pd = null;
2565 for (int i = me.Methods.Length; i > 0;) {
2567 MethodBase mb = me.Methods [i];
2568 pd = GetParameterData (mb);
2570 if (pd.Count == argument_count) {
2572 method = me.Methods [best_match_idx];
2578 if (best_match_idx == -1)
2581 // And now convert implicitly, each argument to the required type
2583 pd = GetParameterData (method);
2585 for (int j = argument_count; j > 0;) {
2587 Argument a = (Argument) Arguments [j];
2588 Expression a_expr = a.Expr;
2590 Expression conv = ConvertImplicit (tc, a_expr, pd.ParameterType (j));
2593 tc.RootContext.Report.Error (1502, loc,
2594 "The best overloaded match for method '" + FullMethodDesc (method) +
2595 "' has some invalid arguments");
2596 tc.RootContext.Report.Error (1503, loc,
2597 "Argument " + (j+1) +
2598 " : Cannot convert from '" + TypeManager.CSharpName (a_expr.Type)
2599 + "' to '" + TypeManager.CSharpName (pd.ParameterType (j)) + "'");
2604 // Update the argument with the implicit conversion
2614 public override Expression Resolve (TypeContainer tc)
2617 // First, resolve the expression that is used to
2618 // trigger the invocation
2620 this.expr = expr.Resolve (tc);
2621 if (this.expr == null)
2624 if (!(this.expr is MethodGroupExpr)){
2625 report118 (tc, this.expr, "method group");
2630 // Next, evaluate all the expressions in the argument list
2632 if (Arguments != null){
2633 for (int i = Arguments.Count; i > 0;){
2635 Argument a = (Argument) Arguments [i];
2637 if (!a.Resolve (tc))
2642 method = OverloadResolve (tc, (MethodGroupExpr) this.expr, Arguments, Location);
2644 if (method == null){
2645 tc.RootContext.Report.Error (-6, Location,
2646 "Could not find any applicable function for this argument list");
2650 if (method is MethodInfo)
2651 type = ((MethodInfo)method).ReturnType;
2656 public static void EmitArguments (EmitContext ec, MethodBase method, ArrayList Arguments)
2660 if (Arguments != null)
2661 top = Arguments.Count;
2665 for (int i = 0; i < top; i++){
2666 Argument a = (Argument) Arguments [i];
2668 Console.WriteLine ("Perform the actual type widening of arguments here for things like: void fn (sbyte s); ... fn (1)");
2674 public override void Emit (EmitContext ec)
2676 bool is_static = method.IsStatic;
2679 MethodGroupExpr mg = (MethodGroupExpr) this.expr;
2681 if (mg.InstanceExpression == null){
2682 throw new Exception ("Internal compiler error. Should check in the method groups for static/instance");
2685 mg.InstanceExpression.Emit (ec);
2688 if (Arguments != null)
2689 EmitArguments (ec, method, Arguments);
2692 if (method is MethodInfo)
2693 ec.ig.Emit (OpCodes.Call, (MethodInfo) method);
2695 ec.ig.Emit (OpCodes.Call, (ConstructorInfo) method);
2697 if (method is MethodInfo)
2698 ec.ig.Emit (OpCodes.Callvirt, (MethodInfo) method);
2700 ec.ig.Emit (OpCodes.Callvirt, (ConstructorInfo) method);
2704 public override void EmitStatement (EmitContext ec)
2709 // Pop the return value if there is one
2711 if (method is MethodInfo){
2712 if (((MethodInfo)method).ReturnType != TypeManager.void_type)
2713 ec.ig.Emit (OpCodes.Pop);
2718 public class New : ExpressionStatement {
2725 public readonly NType NewType;
2726 public readonly ArrayList Arguments;
2727 public readonly string RequestedType;
2728 // These are for the case when we have an array
2729 public readonly string Rank;
2730 public readonly ArrayList Indices;
2731 public readonly ArrayList Initializers;
2734 MethodBase method = null;
2736 public New (string requested_type, ArrayList arguments, Location loc)
2738 RequestedType = requested_type;
2739 Arguments = arguments;
2740 NewType = NType.Object;
2744 public New (string requested_type, ArrayList exprs, string rank, ArrayList initializers, Location loc)
2746 RequestedType = requested_type;
2749 Initializers = initializers;
2750 NewType = NType.Array;
2754 public override Expression Resolve (TypeContainer tc)
2756 type = tc.LookupType (RequestedType, false);
2763 ml = MemberLookup (tc.RootContext, type, ".ctor", false,
2764 MemberTypes.Constructor, AllBindingsFlags);
2766 if (! (ml is MethodGroupExpr)){
2768 // FIXME: Find proper error
2770 report118 (tc, ml, "method group");
2774 if (Arguments != null){
2775 for (int i = Arguments.Count; i > 0;){
2777 Argument a = (Argument) Arguments [i];
2779 if (!a.Resolve (tc))
2784 method = Invocation.OverloadResolve (tc, (MethodGroupExpr) ml, Arguments, Location);
2786 if (method == null) {
2787 tc.RootContext.Report.Error (-6, Location,
2788 "New invocation: Can not find a constructor for this argument list");
2795 public override void Emit (EmitContext ec)
2797 Invocation.EmitArguments (ec, method, Arguments);
2798 ec.ig.Emit (OpCodes.Newobj, (ConstructorInfo) method);
2801 public override void EmitStatement (EmitContext ec)
2804 ec.ig.Emit (OpCodes.Pop);
2809 // Represents the `this' construct
2811 public class This : Expression, LValue {
2812 public override Expression Resolve (TypeContainer tc)
2814 eclass = ExprClass.Variable;
2815 type = tc.TypeBuilder;
2818 // FIXME: Verify that this is only used in instance contexts.
2823 public override void Emit (EmitContext ec)
2825 ec.ig.Emit (OpCodes.Ldarg_0);
2828 public void Store (ILGenerator ig)
2831 // Assignment to the "this" variable
2833 ig.Emit (OpCodes.Starg, 0);
2837 public class TypeOf : Expression {
2838 public readonly string QueriedType;
2840 public TypeOf (string queried_type)
2842 QueriedType = queried_type;
2845 public override Expression Resolve (TypeContainer tc)
2847 type = tc.LookupType (QueriedType, false);
2852 eclass = ExprClass.Type;
2856 public override void Emit (EmitContext ec)
2858 throw new Exception ("Implement me");
2859 // FIXME: Implement.
2863 public class SizeOf : Expression {
2864 public readonly string QueriedType;
2866 public SizeOf (string queried_type)
2868 this.QueriedType = queried_type;
2871 public override Expression Resolve (TypeContainer tc)
2873 // FIXME: Implement;
2874 throw new Exception ("Unimplemented");
2878 public override void Emit (EmitContext ec)
2880 throw new Exception ("Implement me");
2884 public class MemberAccess : Expression {
2885 public readonly string Identifier;
2887 Expression member_lookup;
2889 public MemberAccess (Expression expr, string id)
2895 public Expression Expr {
2901 public override Expression Resolve (TypeContainer tc)
2903 Expression new_expression = expr.Resolve (tc);
2905 if (new_expression == null)
2908 member_lookup = MemberLookup (tc.RootContext, expr.Type, Identifier, false);
2910 if (member_lookup is MethodGroupExpr){
2911 MethodGroupExpr mg = (MethodGroupExpr) member_lookup;
2914 // Bind the instance expression to it
2916 // FIXME: This is a horrible way of detecting if it is
2917 // an instance expression. Figure out how to fix this.
2920 if (expr is LocalVariableReference ||
2921 expr is ParameterReference ||
2923 mg.InstanceExpression = expr;
2925 return member_lookup;
2926 } else if (member_lookup is FieldExpr){
2927 FieldExpr fe = (FieldExpr) member_lookup;
2931 return member_lookup;
2934 // FIXME: This should generate the proper node
2935 // ie, for a Property Access, it should like call it
2938 return member_lookup;
2941 public override void Emit (EmitContext ec)
2943 throw new Exception ("Implement me");
2949 // Nodes of type Namespace are created during the semantic
2950 // analysis to resolve member_access/qualified_identifier/simple_name
2953 // They are born `resolved'.
2955 public class NamespaceExpr : Expression {
2956 public readonly string Name;
2958 public NamespaceExpr (string name)
2961 eclass = ExprClass.Namespace;
2964 public override Expression Resolve (TypeContainer tc)
2969 public override void Emit (EmitContext ec)
2971 throw new Exception ("Namespace expressions should never be emitted");
2976 // Fully resolved expression that evaluates to a type
2978 public class TypeExpr : Expression {
2979 public TypeExpr (Type t)
2982 eclass = ExprClass.Type;
2985 override public Expression Resolve (TypeContainer tc)
2990 override public void Emit (EmitContext ec)
2992 throw new Exception ("Implement me");
2997 // MethodGroup Expression.
2999 // This is a fully resolved expression that evaluates to a type
3001 public class MethodGroupExpr : Expression {
3002 public readonly MethodBase [] Methods;
3003 Expression instance_expression = null;
3005 public MethodGroupExpr (MemberInfo [] mi)
3007 Methods = new MethodBase [mi.Length];
3008 mi.CopyTo (Methods, 0);
3009 eclass = ExprClass.MethodGroup;
3013 // `A method group may have associated an instance expression'
3015 public Expression InstanceExpression {
3017 return instance_expression;
3021 instance_expression = value;
3025 override public Expression Resolve (TypeContainer tc)
3030 override public void Emit (EmitContext ec)
3032 throw new Exception ("This should never be reached");
3036 public class BuiltinTypeAccess : Expression {
3037 public readonly string AccessBase;
3038 public readonly string Method;
3040 public BuiltinTypeAccess (string type, string method)
3042 System.Console.WriteLine ("DUDE! This type should be fully resolved!");
3047 public override Expression Resolve (TypeContainer tc)
3049 // FIXME: Implement;
3050 throw new Exception ("Unimplemented");
3054 public override void Emit (EmitContext ec)
3056 throw new Exception ("Unimplemented");
3061 // Fully resolved expression that evaluates to a Field
3063 public class FieldExpr : Expression, LValue {
3064 public readonly FieldInfo FieldInfo;
3065 public Expression Instance;
3067 public FieldExpr (FieldInfo fi)
3070 eclass = ExprClass.Variable;
3071 type = fi.FieldType;
3074 override public Expression Resolve (TypeContainer tc)
3076 if (!FieldInfo.IsStatic){
3077 if (Instance == null){
3078 throw new Exception ("non-static FieldExpr without instance var\n" +
3079 "You have to assign the Instance variable\n" +
3080 "Of the FieldExpr to set this\n");
3083 Instance = Instance.Resolve (tc);
3084 if (Instance == null)
3091 override public void Emit (EmitContext ec)
3093 ILGenerator ig = ec.ig;
3095 if (FieldInfo.IsStatic)
3096 ig.Emit (OpCodes.Ldsfld, FieldInfo);
3100 ig.Emit (OpCodes.Ldfld, FieldInfo);
3104 public void Store (ILGenerator ig)
3106 if (FieldInfo.IsStatic)
3107 ig.Emit (OpCodes.Stsfld, FieldInfo);
3109 ig.Emit (OpCodes.Stfld, FieldInfo);
3114 // Fully resolved expression that evaluates to a Property
3116 public class PropertyExpr : Expression {
3117 public readonly PropertyInfo PropertyInfo;
3118 public readonly bool IsStatic;
3120 public PropertyExpr (PropertyInfo pi)
3123 eclass = ExprClass.PropertyAccess;
3126 MethodBase [] acc = pi.GetAccessors ();
3128 for (int i = 0; i < acc.Length; i++)
3129 if (acc [i].IsStatic)
3132 type = pi.PropertyType;
3135 override public Expression Resolve (TypeContainer tc)
3137 // We are born in resolved state.
3141 override public void Emit (EmitContext ec)
3143 // FIXME: Implement;
3144 throw new Exception ("Unimplemented");
3149 // Fully resolved expression that evaluates to a Property
3151 public class EventExpr : Expression {
3152 public readonly EventInfo EventInfo;
3154 public EventExpr (EventInfo ei)
3157 eclass = ExprClass.EventAccess;
3160 override public Expression Resolve (TypeContainer tc)
3162 // We are born in resolved state.
3166 override public void Emit (EmitContext ec)
3168 throw new Exception ("Implement me");
3169 // FIXME: Implement.
3173 public class CheckedExpr : Expression {
3175 public Expression Expr;
3177 public CheckedExpr (Expression e)
3182 public override Expression Resolve (TypeContainer tc)
3184 Expr = Expr.Resolve (tc);
3189 eclass = Expr.ExprClass;
3194 public override void Emit (EmitContext ec)
3196 bool last_check = ec.CheckState;
3198 ec.CheckState = true;
3200 ec.CheckState = last_check;
3205 public class UnCheckedExpr : Expression {
3207 public Expression Expr;
3209 public UnCheckedExpr (Expression e)
3214 public override Expression Resolve (TypeContainer tc)
3216 Expr = Expr.Resolve (tc);
3221 eclass = Expr.ExprClass;
3226 public override void Emit (EmitContext ec)
3228 bool last_check = ec.CheckState;
3230 ec.CheckState = false;
3232 ec.CheckState = last_check;
3237 public class ElementAccess : Expression {
3239 public readonly ArrayList Arguments;
3240 public readonly Expression Expr;
3242 public ElementAccess (Expression e, ArrayList e_list)
3248 public override Expression Resolve (TypeContainer tc)
3250 // FIXME: Implement;
3251 throw new Exception ("Unimplemented");
3255 public override void Emit (EmitContext ec)
3257 // FIXME : Implement !
3258 throw new Exception ("Unimplemented");
3263 public class BaseAccess : Expression {
3265 public enum BaseAccessType {
3270 public readonly BaseAccessType BAType;
3271 public readonly string Member;
3272 public readonly ArrayList Arguments;
3274 public BaseAccess (BaseAccessType t, string member, ArrayList args)
3282 public override Expression Resolve (TypeContainer tc)
3284 // FIXME: Implement;
3285 throw new Exception ("Unimplemented");
3289 public override void Emit (EmitContext ec)
3291 throw new Exception ("Unimplemented");
3295 public class UserImplicitCast : Expression {
3300 ArrayList arguments;
3302 public UserImplicitCast (Expression source, Type target)
3304 this.source = source;
3305 this.target = target;
3308 public override Expression Resolve (TypeContainer tc)
3310 source = source.Resolve (tc);
3317 mg = MemberLookup (tc.RootContext, source.Type, "op_Implicit", false);
3321 MethodGroupExpr me = (MethodGroupExpr) mg;
3323 arguments = new ArrayList ();
3324 arguments.Add (new Argument (source, Argument.AType.Expression));
3326 method = Invocation.OverloadResolve (tc, me, arguments, new Location ("", 0,0));
3327 if (method != null) {
3328 MethodInfo mi = (MethodInfo) method;
3330 type = mi.ReturnType;
3343 public override void Emit (EmitContext ec)
3345 ILGenerator ig = ec.ig;
3347 if (method != null) {
3349 // Note that operators are static anyway
3351 if (arguments != null)
3352 Invocation.EmitArguments (ec, method, arguments);
3354 if (method is MethodInfo)
3355 ig.Emit (OpCodes.Call, (MethodInfo) method);
3357 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
3362 throw new Exception ("Implement me");