2 // expression.cs: Expression representation for the IL tree.
5 // Miguel de Icaza (miguel@ximian.com)
7 // (C) 2001 Ximian, Inc.
12 namespace Mono.CSharp {
14 using System.Collections;
15 using System.Diagnostics;
16 using System.Reflection;
17 using System.Reflection.Emit;
21 /// This is just a helper class, it is generated by Unary, UnaryMutator
22 /// when an overloaded method has been found. It just emits the code for a
25 public class StaticCallExpr : ExpressionStatement {
29 StaticCallExpr (MethodInfo m, ArrayList a)
35 eclass = ExprClass.Value;
38 public override Expression DoResolve (EmitContext ec)
41 // We are born fully resolved
46 public override void Emit (EmitContext ec)
49 Invocation.EmitArguments (ec, mi, args);
51 ec.ig.Emit (OpCodes.Call, mi);
55 static public Expression MakeSimpleCall (EmitContext ec, MethodGroupExpr mg,
56 Expression e, Location loc)
61 args = new ArrayList (1);
62 args.Add (new Argument (e, Argument.AType.Expression));
63 method = Invocation.OverloadResolve (ec, (MethodGroupExpr) mg, args, loc);
68 return new StaticCallExpr ((MethodInfo) method, args);
71 public override void EmitStatement (EmitContext ec)
74 if (type != TypeManager.void_type)
75 ec.ig.Emit (OpCodes.Pop);
80 /// Unary expressions.
84 /// Unary implements unary expressions. It derives from
85 /// ExpressionStatement becuase the pre/post increment/decrement
86 /// operators can be used in a statement context.
88 public class Unary : Expression {
89 public enum Operator : byte {
90 UnaryPlus, UnaryNegation, LogicalNot, OnesComplement,
91 Indirection, AddressOf, TOP
98 public Unary (Operator op, Expression expr, Location loc)
105 public Expression Expr {
115 public Operator Oper {
126 /// Returns a stringified representation of the Operator
131 case Operator.UnaryPlus:
133 case Operator.UnaryNegation:
135 case Operator.LogicalNot:
137 case Operator.OnesComplement:
139 case Operator.AddressOf:
141 case Operator.Indirection:
145 return oper.ToString ();
148 static string [] oper_names;
152 oper_names = new string [(int)Operator.TOP];
154 oper_names [(int) Operator.UnaryPlus] = "op_UnaryPlus";
155 oper_names [(int) Operator.UnaryNegation] = "op_UnaryNegation";
156 oper_names [(int) Operator.LogicalNot] = "op_LogicalNot";
157 oper_names [(int) Operator.OnesComplement] = "op_OnesComplement";
158 oper_names [(int) Operator.Indirection] = "op_Indirection";
159 oper_names [(int) Operator.AddressOf] = "op_AddressOf";
162 void error23 (Type t)
165 23, loc, "Operator " + OperName () +
166 " cannot be applied to operand of type `" +
167 TypeManager.CSharpName (t) + "'");
171 /// The result has been already resolved:
173 /// FIXME: a minus constant -128 sbyte cant be turned into a
176 static Expression TryReduceNegative (Expression expr)
180 if (expr is IntConstant)
181 e = new IntConstant (-((IntConstant) expr).Value);
182 else if (expr is UIntConstant)
183 e = new LongConstant (-((UIntConstant) expr).Value);
184 else if (expr is LongConstant)
185 e = new LongConstant (-((LongConstant) expr).Value);
186 else if (expr is FloatConstant)
187 e = new FloatConstant (-((FloatConstant) expr).Value);
188 else if (expr is DoubleConstant)
189 e = new DoubleConstant (-((DoubleConstant) expr).Value);
190 else if (expr is DecimalConstant)
191 e = new DecimalConstant (-((DecimalConstant) expr).Value);
192 else if (expr is ShortConstant)
193 e = new IntConstant (-((ShortConstant) expr).Value);
194 else if (expr is UShortConstant)
195 e = new IntConstant (-((UShortConstant) expr).Value);
200 Expression Reduce (EmitContext ec, Expression e)
202 Type expr_type = e.Type;
205 case Operator.UnaryPlus:
208 case Operator.UnaryNegation:
209 return TryReduceNegative (e);
211 case Operator.LogicalNot:
212 if (expr_type != TypeManager.bool_type) {
217 BoolConstant b = (BoolConstant) e;
218 return new BoolConstant (!(b.Value));
220 case Operator.OnesComplement:
221 if (!((expr_type == TypeManager.int32_type) ||
222 (expr_type == TypeManager.uint32_type) ||
223 (expr_type == TypeManager.int64_type) ||
224 (expr_type == TypeManager.uint64_type) ||
225 (expr_type.IsSubclassOf (TypeManager.enum_type)))){
230 if (e is EnumConstant){
231 EnumConstant enum_constant = (EnumConstant) e;
233 Expression reduced = Reduce (ec, enum_constant.Child);
235 return new EnumConstant ((Constant) reduced, enum_constant.Type);
238 if (expr_type == TypeManager.int32_type)
239 return new IntConstant (~ ((IntConstant) e).Value);
240 if (expr_type == TypeManager.uint32_type)
241 return new UIntConstant (~ ((UIntConstant) e).Value);
242 if (expr_type == TypeManager.int64_type)
243 return new LongConstant (~ ((LongConstant) e).Value);
244 if (expr_type == TypeManager.uint64_type)
245 return new ULongConstant (~ ((ULongConstant) e).Value);
247 throw new Exception (
248 "FIXME: Implement constant OnesComplement of:" +
251 throw new Exception ("Can not constant fold");
254 Expression ResolveOperator (EmitContext ec)
256 Type expr_type = expr.Type;
259 // Step 1: Perform Operator Overload location
264 op_name = oper_names [(int) oper];
266 mg = MemberLookup (ec, expr_type, op_name, false, loc);
268 if (mg == null && expr_type.BaseType != null)
269 mg = MemberLookup (ec, expr_type.BaseType, op_name, false, loc);
272 Expression e = StaticCallExpr.MakeSimpleCall (
273 ec, (MethodGroupExpr) mg, expr, loc);
283 // Only perform numeric promotions on:
286 if (expr_type == null)
290 // Step 2: Default operations on CLI native types.
292 if (expr is Constant)
293 return Reduce (ec, expr);
295 if (oper == Operator.LogicalNot){
296 if (expr_type != TypeManager.bool_type) {
301 type = TypeManager.bool_type;
305 if (oper == Operator.OnesComplement) {
306 if (!((expr_type == TypeManager.int32_type) ||
307 (expr_type == TypeManager.uint32_type) ||
308 (expr_type == TypeManager.int64_type) ||
309 (expr_type == TypeManager.uint64_type) ||
310 (expr_type.IsSubclassOf (TypeManager.enum_type)))){
318 if (oper == Operator.UnaryPlus) {
320 // A plus in front of something is just a no-op, so return the child.
326 // Deals with -literals
327 // int operator- (int x)
328 // long operator- (long x)
329 // float operator- (float f)
330 // double operator- (double d)
331 // decimal operator- (decimal d)
333 if (oper == Operator.UnaryNegation){
335 // Fold a "- Constant" into a negative constant
341 // Not a constant we can optimize, perform numeric
342 // promotions to int, long, double.
345 // The following is inneficient, because we call
346 // ConvertImplicit too many times.
348 // It is also not clear if we should convert to Float
349 // or Double initially.
351 if (expr_type == TypeManager.uint32_type){
353 // FIXME: handle exception to this rule that
354 // permits the int value -2147483648 (-2^31) to
355 // bt wrote as a decimal interger literal
357 type = TypeManager.int64_type;
358 expr = ConvertImplicit (ec, expr, type, loc);
362 if (expr_type == TypeManager.uint64_type){
364 // FIXME: Handle exception of `long value'
365 // -92233720368547758087 (-2^63) to be wrote as
366 // decimal integer literal.
372 e = ConvertImplicit (ec, expr, TypeManager.int32_type, loc);
379 e = ConvertImplicit (ec, expr, TypeManager.int64_type, loc);
386 e = ConvertImplicit (ec, expr, TypeManager.double_type, loc);
397 if (oper == Operator.AddressOf){
398 if (expr.eclass != ExprClass.Variable){
399 Error (211, loc, "Cannot take the address of non-variables");
402 type = Type.GetType (expr.Type.ToString () + "*");
407 Error (187, loc, "No such operator '" + OperName () + "' defined for type '" +
408 TypeManager.CSharpName (expr_type) + "'");
412 public override Expression DoResolve (EmitContext ec)
414 expr = expr.Resolve (ec);
419 eclass = ExprClass.Value;
420 return ResolveOperator (ec);
423 public override void Emit (EmitContext ec)
425 ILGenerator ig = ec.ig;
426 Type expr_type = expr.Type;
429 case Operator.UnaryPlus:
430 throw new Exception ("This should be caught by Resolve");
432 case Operator.UnaryNegation:
434 ig.Emit (OpCodes.Neg);
437 case Operator.LogicalNot:
439 ig.Emit (OpCodes.Ldc_I4_0);
440 ig.Emit (OpCodes.Ceq);
443 case Operator.OnesComplement:
445 ig.Emit (OpCodes.Not);
448 case Operator.AddressOf:
449 ((IMemoryLocation)expr).AddressOf (ec);
452 case Operator.Indirection:
453 throw new Exception ("Not implemented yet");
456 throw new Exception ("This should not happen: Operator = "
462 /// This will emit the child expression for `ec' avoiding the logical
463 /// not. The parent will take care of changing brfalse/brtrue
465 public void EmitLogicalNot (EmitContext ec)
467 if (oper != Operator.LogicalNot)
468 throw new Exception ("EmitLogicalNot can only be called with !expr");
476 /// Unary Mutator expressions (pre and post ++ and --)
480 /// UnaryMutator implements ++ and -- expressions. It derives from
481 /// ExpressionStatement becuase the pre/post increment/decrement
482 /// operators can be used in a statement context.
484 /// FIXME: Idea, we could split this up in two classes, one simpler
485 /// for the common case, and one with the extra fields for more complex
486 /// classes (indexers require temporary access; overloaded require method)
488 /// Maybe we should have classes PreIncrement, PostIncrement, PreDecrement,
489 /// PostDecrement, that way we could save the `Mode' byte as well.
491 public class UnaryMutator : ExpressionStatement {
492 public enum Mode : byte {
493 PreIncrement, PreDecrement, PostIncrement, PostDecrement
499 LocalTemporary temp_storage;
502 // This is expensive for the simplest case.
506 public UnaryMutator (Mode m, Expression e, Location l)
515 return (mode == Mode.PreIncrement || mode == Mode.PostIncrement) ?
519 void error23 (Type t)
522 23, loc, "Operator " + OperName () +
523 " cannot be applied to operand of type `" +
524 TypeManager.CSharpName (t) + "'");
528 /// Returns whether an object of type `t' can be incremented
529 /// or decremented with add/sub (ie, basically whether we can
530 /// use pre-post incr-decr operations on it, but it is not a
531 /// System.Decimal, which we require operator overloading to catch)
533 static bool IsIncrementableNumber (Type t)
535 return (t == TypeManager.sbyte_type) ||
536 (t == TypeManager.byte_type) ||
537 (t == TypeManager.short_type) ||
538 (t == TypeManager.ushort_type) ||
539 (t == TypeManager.int32_type) ||
540 (t == TypeManager.uint32_type) ||
541 (t == TypeManager.int64_type) ||
542 (t == TypeManager.uint64_type) ||
543 (t == TypeManager.char_type) ||
544 (t.IsSubclassOf (TypeManager.enum_type)) ||
545 (t == TypeManager.float_type) ||
546 (t == TypeManager.double_type);
549 Expression ResolveOperator (EmitContext ec)
551 Type expr_type = expr.Type;
554 // Step 1: Perform Operator Overload location
559 if (mode == Mode.PreIncrement || mode == Mode.PostIncrement)
560 op_name = "op_Increment";
562 op_name = "op_Decrement";
564 mg = MemberLookup (ec, expr_type, op_name, false, loc);
566 if (mg == null && expr_type.BaseType != null)
567 mg = MemberLookup (ec, expr_type.BaseType, op_name, false, loc);
570 method = StaticCallExpr.MakeSimpleCall (
571 ec, (MethodGroupExpr) mg, expr, loc);
578 // The operand of the prefix/postfix increment decrement operators
579 // should be an expression that is classified as a variable,
580 // a property access or an indexer access
583 if (expr.eclass == ExprClass.Variable){
584 if (IsIncrementableNumber (expr_type) ||
585 expr_type == TypeManager.decimal_type){
588 } else if (expr.eclass == ExprClass.IndexerAccess){
589 IndexerAccess ia = (IndexerAccess) expr;
591 temp_storage = new LocalTemporary (ec, expr.Type);
593 expr = ia.ResolveLValue (ec, temp_storage);
598 } else if (expr.eclass == ExprClass.PropertyAccess){
599 PropertyExpr pe = (PropertyExpr) expr;
601 if (pe.VerifyAssignable ())
606 report118 (loc, expr, "variable, indexer or property access");
610 Error (187, loc, "No such operator '" + OperName () + "' defined for type '" +
611 TypeManager.CSharpName (expr_type) + "'");
615 public override Expression DoResolve (EmitContext ec)
617 expr = expr.Resolve (ec);
622 eclass = ExprClass.Value;
623 return ResolveOperator (ec);
628 // FIXME: We need some way of avoiding the use of temp_storage
629 // for some types of storage (parameters, local variables,
630 // static fields) and single-dimension array access.
632 void EmitCode (EmitContext ec, bool is_expr)
634 ILGenerator ig = ec.ig;
635 IAssignMethod ia = (IAssignMethod) expr;
637 if (temp_storage == null)
638 temp_storage = new LocalTemporary (ec, expr.Type);
641 case Mode.PreIncrement:
642 case Mode.PreDecrement:
646 ig.Emit (OpCodes.Ldc_I4_1);
648 if (mode == Mode.PreDecrement)
649 ig.Emit (OpCodes.Sub);
651 ig.Emit (OpCodes.Add);
655 temp_storage.Store (ec);
656 ia.EmitAssign (ec, temp_storage);
658 temp_storage.Emit (ec);
661 case Mode.PostIncrement:
662 case Mode.PostDecrement:
670 ig.Emit (OpCodes.Dup);
672 ig.Emit (OpCodes.Ldc_I4_1);
674 if (mode == Mode.PostDecrement)
675 ig.Emit (OpCodes.Sub);
677 ig.Emit (OpCodes.Add);
682 temp_storage.Store (ec);
683 ia.EmitAssign (ec, temp_storage);
688 public override void Emit (EmitContext ec)
694 public override void EmitStatement (EmitContext ec)
696 EmitCode (ec, false);
702 /// Base class for the `Is' and `As' classes.
706 /// FIXME: Split this in two, and we get to save the `Operator' Oper
709 public abstract class Probe : Expression {
710 public readonly string ProbeType;
711 protected Expression expr;
712 protected Type probe_type;
715 public Probe (Expression expr, string probe_type, Location l)
717 ProbeType = probe_type;
722 public Expression Expr {
728 public override Expression DoResolve (EmitContext ec)
730 probe_type = RootContext.LookupType (ec.TypeContainer, ProbeType, false, loc);
732 if (probe_type == null)
735 expr = expr.Resolve (ec);
742 /// Implementation of the `is' operator.
744 public class Is : Probe {
745 public Is (Expression expr, string probe_type, Location l)
746 : base (expr, probe_type, l)
750 public override void Emit (EmitContext ec)
752 ILGenerator ig = ec.ig;
756 ig.Emit (OpCodes.Isinst, probe_type);
757 ig.Emit (OpCodes.Ldnull);
758 ig.Emit (OpCodes.Cgt_Un);
761 public override Expression DoResolve (EmitContext ec)
763 Expression e = base.DoResolve (ec);
768 type = TypeManager.bool_type;
769 eclass = ExprClass.Value;
776 /// Implementation of the `as' operator.
778 public class As : Probe {
779 public As (Expression expr, string probe_type, Location l)
780 : base (expr, probe_type, l)
784 public override void Emit (EmitContext ec)
786 ILGenerator ig = ec.ig;
789 ig.Emit (OpCodes.Isinst, probe_type);
792 public override Expression DoResolve (EmitContext ec)
794 Expression e = base.DoResolve (ec);
800 eclass = ExprClass.Value;
807 /// This represents a typecast in the source language.
809 /// FIXME: Cast expressions have an unusual set of parsing
810 /// rules, we need to figure those out.
812 public class Cast : Expression {
813 Expression target_type;
817 public Cast (Expression cast_type, Expression expr, Location loc)
819 this.target_type = cast_type;
824 public Expression TargetType {
830 public Expression Expr {
840 /// Attempts to do a compile-time folding of a constant cast.
842 Expression TryReduce (EmitContext ec, Type target_type)
844 if (expr is ByteConstant){
845 byte v = ((ByteConstant) expr).Value;
847 if (target_type == TypeManager.sbyte_type)
848 return new SByteConstant ((sbyte) v);
849 if (target_type == TypeManager.short_type)
850 return new ShortConstant ((short) v);
851 if (target_type == TypeManager.ushort_type)
852 return new UShortConstant ((ushort) v);
853 if (target_type == TypeManager.int32_type)
854 return new IntConstant ((int) v);
855 if (target_type == TypeManager.uint32_type)
856 return new UIntConstant ((uint) v);
857 if (target_type == TypeManager.int64_type)
858 return new LongConstant ((long) v);
859 if (target_type == TypeManager.uint64_type)
860 return new ULongConstant ((ulong) v);
861 if (target_type == TypeManager.float_type)
862 return new FloatConstant ((float) v);
863 if (target_type == TypeManager.double_type)
864 return new DoubleConstant ((double) v);
866 if (expr is SByteConstant){
867 sbyte v = ((SByteConstant) expr).Value;
869 if (target_type == TypeManager.byte_type)
870 return new ByteConstant ((byte) v);
871 if (target_type == TypeManager.short_type)
872 return new ShortConstant ((short) v);
873 if (target_type == TypeManager.ushort_type)
874 return new UShortConstant ((ushort) v);
875 if (target_type == TypeManager.int32_type)
876 return new IntConstant ((int) v);
877 if (target_type == TypeManager.uint32_type)
878 return new UIntConstant ((uint) v);
879 if (target_type == TypeManager.int64_type)
880 return new LongConstant ((long) v);
881 if (target_type == TypeManager.uint64_type)
882 return new ULongConstant ((ulong) v);
883 if (target_type == TypeManager.float_type)
884 return new FloatConstant ((float) v);
885 if (target_type == TypeManager.double_type)
886 return new DoubleConstant ((double) v);
888 if (expr is ShortConstant){
889 short v = ((ShortConstant) expr).Value;
891 if (target_type == TypeManager.byte_type)
892 return new ByteConstant ((byte) v);
893 if (target_type == TypeManager.sbyte_type)
894 return new SByteConstant ((sbyte) v);
895 if (target_type == TypeManager.ushort_type)
896 return new UShortConstant ((ushort) v);
897 if (target_type == TypeManager.int32_type)
898 return new IntConstant ((int) v);
899 if (target_type == TypeManager.uint32_type)
900 return new UIntConstant ((uint) v);
901 if (target_type == TypeManager.int64_type)
902 return new LongConstant ((long) v);
903 if (target_type == TypeManager.uint64_type)
904 return new ULongConstant ((ulong) v);
905 if (target_type == TypeManager.float_type)
906 return new FloatConstant ((float) v);
907 if (target_type == TypeManager.double_type)
908 return new DoubleConstant ((double) v);
910 if (expr is UShortConstant){
911 ushort v = ((UShortConstant) expr).Value;
913 if (target_type == TypeManager.byte_type)
914 return new ByteConstant ((byte) v);
915 if (target_type == TypeManager.sbyte_type)
916 return new SByteConstant ((sbyte) v);
917 if (target_type == TypeManager.short_type)
918 return new ShortConstant ((short) v);
919 if (target_type == TypeManager.int32_type)
920 return new IntConstant ((int) v);
921 if (target_type == TypeManager.uint32_type)
922 return new UIntConstant ((uint) v);
923 if (target_type == TypeManager.int64_type)
924 return new LongConstant ((long) v);
925 if (target_type == TypeManager.uint64_type)
926 return new ULongConstant ((ulong) v);
927 if (target_type == TypeManager.float_type)
928 return new FloatConstant ((float) v);
929 if (target_type == TypeManager.double_type)
930 return new DoubleConstant ((double) v);
932 if (expr is IntConstant){
933 int v = ((IntConstant) expr).Value;
935 if (target_type == TypeManager.byte_type)
936 return new ByteConstant ((byte) v);
937 if (target_type == TypeManager.sbyte_type)
938 return new SByteConstant ((sbyte) v);
939 if (target_type == TypeManager.short_type)
940 return new ShortConstant ((short) v);
941 if (target_type == TypeManager.ushort_type)
942 return new UShortConstant ((ushort) v);
943 if (target_type == TypeManager.uint32_type)
944 return new UIntConstant ((uint) v);
945 if (target_type == TypeManager.int64_type)
946 return new LongConstant ((long) v);
947 if (target_type == TypeManager.uint64_type)
948 return new ULongConstant ((ulong) v);
949 if (target_type == TypeManager.float_type)
950 return new FloatConstant ((float) v);
951 if (target_type == TypeManager.double_type)
952 return new DoubleConstant ((double) v);
954 if (expr is UIntConstant){
955 uint v = ((UIntConstant) expr).Value;
957 if (target_type == TypeManager.byte_type)
958 return new ByteConstant ((byte) v);
959 if (target_type == TypeManager.sbyte_type)
960 return new SByteConstant ((sbyte) v);
961 if (target_type == TypeManager.short_type)
962 return new ShortConstant ((short) v);
963 if (target_type == TypeManager.ushort_type)
964 return new UShortConstant ((ushort) v);
965 if (target_type == TypeManager.int32_type)
966 return new IntConstant ((int) v);
967 if (target_type == TypeManager.int64_type)
968 return new LongConstant ((long) v);
969 if (target_type == TypeManager.uint64_type)
970 return new ULongConstant ((ulong) v);
971 if (target_type == TypeManager.float_type)
972 return new FloatConstant ((float) v);
973 if (target_type == TypeManager.double_type)
974 return new DoubleConstant ((double) v);
976 if (expr is LongConstant){
977 long v = ((LongConstant) expr).Value;
979 if (target_type == TypeManager.byte_type)
980 return new ByteConstant ((byte) v);
981 if (target_type == TypeManager.sbyte_type)
982 return new SByteConstant ((sbyte) v);
983 if (target_type == TypeManager.short_type)
984 return new ShortConstant ((short) v);
985 if (target_type == TypeManager.ushort_type)
986 return new UShortConstant ((ushort) v);
987 if (target_type == TypeManager.int32_type)
988 return new IntConstant ((int) v);
989 if (target_type == TypeManager.uint32_type)
990 return new UIntConstant ((uint) v);
991 if (target_type == TypeManager.uint64_type)
992 return new ULongConstant ((ulong) v);
993 if (target_type == TypeManager.float_type)
994 return new FloatConstant ((float) v);
995 if (target_type == TypeManager.double_type)
996 return new DoubleConstant ((double) v);
998 if (expr is ULongConstant){
999 ulong v = ((ULongConstant) expr).Value;
1001 if (target_type == TypeManager.byte_type)
1002 return new ByteConstant ((byte) v);
1003 if (target_type == TypeManager.sbyte_type)
1004 return new SByteConstant ((sbyte) v);
1005 if (target_type == TypeManager.short_type)
1006 return new ShortConstant ((short) v);
1007 if (target_type == TypeManager.ushort_type)
1008 return new UShortConstant ((ushort) v);
1009 if (target_type == TypeManager.int32_type)
1010 return new IntConstant ((int) v);
1011 if (target_type == TypeManager.uint32_type)
1012 return new UIntConstant ((uint) v);
1013 if (target_type == TypeManager.int64_type)
1014 return new LongConstant ((long) v);
1015 if (target_type == TypeManager.float_type)
1016 return new FloatConstant ((float) v);
1017 if (target_type == TypeManager.double_type)
1018 return new DoubleConstant ((double) v);
1020 if (expr is FloatConstant){
1021 float v = ((FloatConstant) expr).Value;
1023 if (target_type == TypeManager.byte_type)
1024 return new ByteConstant ((byte) v);
1025 if (target_type == TypeManager.sbyte_type)
1026 return new SByteConstant ((sbyte) v);
1027 if (target_type == TypeManager.short_type)
1028 return new ShortConstant ((short) v);
1029 if (target_type == TypeManager.ushort_type)
1030 return new UShortConstant ((ushort) v);
1031 if (target_type == TypeManager.int32_type)
1032 return new IntConstant ((int) v);
1033 if (target_type == TypeManager.uint32_type)
1034 return new UIntConstant ((uint) v);
1035 if (target_type == TypeManager.int64_type)
1036 return new LongConstant ((long) v);
1037 if (target_type == TypeManager.uint64_type)
1038 return new ULongConstant ((ulong) v);
1039 if (target_type == TypeManager.double_type)
1040 return new DoubleConstant ((double) v);
1042 if (expr is DoubleConstant){
1043 double v = ((DoubleConstant) expr).Value;
1045 if (target_type == TypeManager.byte_type)
1046 return new ByteConstant ((byte) v);
1047 if (target_type == TypeManager.sbyte_type)
1048 return new SByteConstant ((sbyte) v);
1049 if (target_type == TypeManager.short_type)
1050 return new ShortConstant ((short) v);
1051 if (target_type == TypeManager.ushort_type)
1052 return new UShortConstant ((ushort) v);
1053 if (target_type == TypeManager.int32_type)
1054 return new IntConstant ((int) v);
1055 if (target_type == TypeManager.uint32_type)
1056 return new UIntConstant ((uint) v);
1057 if (target_type == TypeManager.int64_type)
1058 return new LongConstant ((long) v);
1059 if (target_type == TypeManager.uint64_type)
1060 return new ULongConstant ((ulong) v);
1061 if (target_type == TypeManager.float_type)
1062 return new FloatConstant ((float) v);
1068 public override Expression DoResolve (EmitContext ec)
1070 expr = expr.Resolve (ec);
1074 target_type = target_type.Resolve (ec);
1075 if (target_type == null)
1078 if (target_type.eclass != ExprClass.Type){
1079 report118 (loc, target_type, "class");
1083 type = target_type.Type;
1084 eclass = ExprClass.Value;
1089 if (expr is Constant){
1090 Expression e = TryReduce (ec, type);
1096 expr = ConvertExplicit (ec, expr, type, loc);
1100 public override void Emit (EmitContext ec)
1103 // This one will never happen
1105 throw new Exception ("Should not happen");
1110 /// Binary operators
1112 public class Binary : Expression {
1113 public enum Operator : byte {
1114 Multiply, Division, Modulus,
1115 Addition, Subtraction,
1116 LeftShift, RightShift,
1117 LessThan, GreaterThan, LessThanOrEqual, GreaterThanOrEqual,
1118 Equality, Inequality,
1127 Expression left, right;
1129 ArrayList Arguments;
1133 public Binary (Operator oper, Expression left, Expression right, Location loc)
1141 public Operator Oper {
1150 public Expression Left {
1159 public Expression Right {
1170 /// Returns a stringified representation of the Operator
1175 case Operator.Multiply:
1177 case Operator.Division:
1179 case Operator.Modulus:
1181 case Operator.Addition:
1183 case Operator.Subtraction:
1185 case Operator.LeftShift:
1187 case Operator.RightShift:
1189 case Operator.LessThan:
1191 case Operator.GreaterThan:
1193 case Operator.LessThanOrEqual:
1195 case Operator.GreaterThanOrEqual:
1197 case Operator.Equality:
1199 case Operator.Inequality:
1201 case Operator.BitwiseAnd:
1203 case Operator.BitwiseOr:
1205 case Operator.ExclusiveOr:
1207 case Operator.LogicalOr:
1209 case Operator.LogicalAnd:
1213 return oper.ToString ();
1216 Expression ForceConversion (EmitContext ec, Expression expr, Type target_type)
1218 if (expr.Type == target_type)
1221 return ConvertImplicit (ec, expr, target_type, new Location (-1));
1225 // Note that handling the case l == Decimal || r == Decimal
1226 // is taken care of by the Step 1 Operator Overload resolution.
1228 bool DoNumericPromotions (EmitContext ec, Type l, Type r)
1230 if (l == TypeManager.double_type || r == TypeManager.double_type){
1232 // If either operand is of type double, the other operand is
1233 // conveted to type double.
1235 if (r != TypeManager.double_type)
1236 right = ConvertImplicit (ec, right, TypeManager.double_type, loc);
1237 if (l != TypeManager.double_type)
1238 left = ConvertImplicit (ec, left, TypeManager.double_type, loc);
1240 type = TypeManager.double_type;
1241 } else if (l == TypeManager.float_type || r == TypeManager.float_type){
1243 // if either operand is of type float, th eother operand is
1244 // converd to type float.
1246 if (r != TypeManager.double_type)
1247 right = ConvertImplicit (ec, right, TypeManager.float_type, loc);
1248 if (l != TypeManager.double_type)
1249 left = ConvertImplicit (ec, left, TypeManager.float_type, loc);
1250 type = TypeManager.float_type;
1251 } else if (l == TypeManager.uint64_type || r == TypeManager.uint64_type){
1255 // If either operand is of type ulong, the other operand is
1256 // converted to type ulong. or an error ocurrs if the other
1257 // operand is of type sbyte, short, int or long
1260 if (l == TypeManager.uint64_type){
1261 if (r != TypeManager.uint64_type){
1262 if (right is IntConstant){
1263 e = TryImplicitIntConversion(l, (IntConstant) right);
1266 } else if (right is LongConstant){
1267 long ll = ((LongConstant) right).Value;
1270 right = new ULongConstant ((ulong) ll);
1275 if (left is IntConstant){
1276 e = TryImplicitIntConversion (r, (IntConstant) left);
1279 } else if (left is LongConstant){
1280 long ll = ((LongConstant) left).Value;
1283 left = new ULongConstant ((ulong) ll);
1288 if ((other == TypeManager.sbyte_type) ||
1289 (other == TypeManager.short_type) ||
1290 (other == TypeManager.int32_type) ||
1291 (other == TypeManager.int64_type)){
1292 string oper = OperName ();
1294 Error (34, loc, "Operator `" + OperName ()
1295 + "' is ambiguous on operands of type `"
1296 + TypeManager.CSharpName (l) + "' "
1297 + "and `" + TypeManager.CSharpName (r)
1300 type = TypeManager.uint64_type;
1301 } else if (l == TypeManager.int64_type || r == TypeManager.int64_type){
1303 // If either operand is of type long, the other operand is converted
1306 if (l != TypeManager.int64_type)
1307 left = ConvertImplicit (ec, left, TypeManager.int64_type, loc);
1308 if (r != TypeManager.int64_type)
1309 right = ConvertImplicit (ec, right, TypeManager.int64_type, loc);
1311 type = TypeManager.int64_type;
1312 } else if (l == TypeManager.uint32_type || r == TypeManager.uint32_type){
1314 // If either operand is of type uint, and the other
1315 // operand is of type sbyte, short or int, othe operands are
1316 // converted to type long.
1320 if (l == TypeManager.uint32_type)
1322 else if (r == TypeManager.uint32_type)
1325 if ((other == TypeManager.sbyte_type) ||
1326 (other == TypeManager.short_type) ||
1327 (other == TypeManager.int32_type)){
1328 left = ForceConversion (ec, left, TypeManager.int64_type);
1329 right = ForceConversion (ec, right, TypeManager.int64_type);
1330 type = TypeManager.int64_type;
1333 // if either operand is of type uint, the other
1334 // operand is converd to type uint
1336 left = ForceConversion (ec, left, TypeManager.uint32_type);
1337 right = ForceConversion (ec, right, TypeManager.uint32_type);
1338 type = TypeManager.uint32_type;
1340 } else if (l == TypeManager.decimal_type || r == TypeManager.decimal_type){
1341 if (l != TypeManager.decimal_type)
1342 left = ConvertImplicit (ec, left, TypeManager.decimal_type, loc);
1343 if (r != TypeManager.decimal_type)
1344 right = ConvertImplicit (ec, right, TypeManager.decimal_type, loc);
1346 type = TypeManager.decimal_type;
1348 Expression l_tmp, r_tmp;
1350 l_tmp = ForceConversion (ec, left, TypeManager.int32_type);
1354 r_tmp = ForceConversion (ec, right, TypeManager.int32_type);
1361 type = TypeManager.int32_type;
1370 "Operator " + OperName () + " cannot be applied to operands of type `" +
1371 TypeManager.CSharpName (left.Type) + "' and `" +
1372 TypeManager.CSharpName (right.Type) + "'");
1376 Expression CheckShiftArguments (EmitContext ec)
1380 Type r = right.Type;
1382 e = ForceConversion (ec, right, TypeManager.int32_type);
1389 if (((e = ConvertImplicit (ec, left, TypeManager.int32_type, loc)) != null) ||
1390 ((e = ConvertImplicit (ec, left, TypeManager.uint32_type, loc)) != null) ||
1391 ((e = ConvertImplicit (ec, left, TypeManager.int64_type, loc)) != null) ||
1392 ((e = ConvertImplicit (ec, left, TypeManager.uint64_type, loc)) != null)){
1402 Expression ResolveOperator (EmitContext ec)
1405 Type r = right.Type;
1408 // Step 1: Perform Operator Overload location
1410 Expression left_expr, right_expr;
1412 string op = "op_" + oper;
1414 left_expr = MemberLookup (ec, l, op, false, loc);
1415 if (left_expr == null && l.BaseType != null)
1416 left_expr = MemberLookup (ec, l.BaseType, op, false, loc);
1418 right_expr = MemberLookup (ec, r, op, false, loc);
1419 if (right_expr == null && r.BaseType != null)
1420 right_expr = MemberLookup (ec, r.BaseType, op, false, loc);
1422 MethodGroupExpr union = Invocation.MakeUnionSet (left_expr, right_expr);
1424 if (union != null) {
1425 Arguments = new ArrayList ();
1426 Arguments.Add (new Argument (left, Argument.AType.Expression));
1427 Arguments.Add (new Argument (right, Argument.AType.Expression));
1429 method = Invocation.OverloadResolve (ec, union, Arguments, loc);
1430 if (method != null) {
1431 MethodInfo mi = (MethodInfo) method;
1432 type = mi.ReturnType;
1441 // Step 2: Default operations on CLI native types.
1444 // Only perform numeric promotions on:
1445 // +, -, *, /, %, &, |, ^, ==, !=, <, >, <=, >=
1447 if (oper == Operator.Addition){
1449 // If any of the arguments is a string, cast to string
1451 if (l == TypeManager.string_type){
1452 if (r == TypeManager.string_type){
1453 if (left is Constant && right is Constant){
1454 StringConstant ls = (StringConstant) left;
1455 StringConstant rs = (StringConstant) right;
1457 return new StringConstant (
1458 ls.Value + rs.Value);
1462 method = TypeManager.string_concat_string_string;
1465 method = TypeManager.string_concat_object_object;
1466 right = ConvertImplicit (ec, right,
1467 TypeManager.object_type, loc);
1469 type = TypeManager.string_type;
1471 Arguments = new ArrayList ();
1472 Arguments.Add (new Argument (left, Argument.AType.Expression));
1473 Arguments.Add (new Argument (right, Argument.AType.Expression));
1477 } else if (r == TypeManager.string_type){
1479 method = TypeManager.string_concat_object_object;
1480 Arguments = new ArrayList ();
1481 Arguments.Add (new Argument (left, Argument.AType.Expression));
1482 Arguments.Add (new Argument (right, Argument.AType.Expression));
1484 left = ConvertImplicit (ec, left, TypeManager.object_type, loc);
1485 type = TypeManager.string_type;
1490 if (l.IsSubclassOf (TypeManager.delegate_type) &&
1491 r.IsSubclassOf (TypeManager.delegate_type)) {
1493 Arguments = new ArrayList ();
1494 Arguments.Add (new Argument (left, Argument.AType.Expression));
1495 Arguments.Add (new Argument (right, Argument.AType.Expression));
1497 method = TypeManager.delegate_combine_delegate_delegate;
1506 // Enumeration operators
1508 bool lie = TypeManager.IsEnumType (l);
1509 bool rie = TypeManager.IsEnumType (r);
1514 temp = ConvertImplicit (ec, right, l, loc);
1518 temp = ConvertImplicit (ec, left, r, loc);
1525 if (oper == Operator.Equality || oper == Operator.Inequality ||
1526 oper == Operator.LessThanOrEqual || oper == Operator.LessThan ||
1527 oper == Operator.GreaterThanOrEqual || oper == Operator.GreaterThan){
1528 type = TypeManager.bool_type;
1532 if (oper == Operator.BitwiseAnd ||
1533 oper == Operator.BitwiseOr ||
1534 oper == Operator.ExclusiveOr){
1540 if (oper == Operator.LeftShift || oper == Operator.RightShift)
1541 return CheckShiftArguments (ec);
1543 if (oper == Operator.LogicalOr || oper == Operator.LogicalAnd){
1544 if (l != TypeManager.bool_type || r != TypeManager.bool_type){
1549 type = TypeManager.bool_type;
1553 if (oper == Operator.Equality || oper == Operator.Inequality){
1554 if (l == TypeManager.bool_type || r == TypeManager.bool_type){
1555 if (r != TypeManager.bool_type || l != TypeManager.bool_type){
1560 type = TypeManager.bool_type;
1565 // operator != (object a, object b)
1566 // operator == (object a, object b)
1568 // For this to be used, both arguments have to be reference-types.
1569 // Read the rationale on the spec (14.9.6)
1571 // Also, if at compile time we know that the classes do not inherit
1572 // one from the other, then we catch the error there.
1574 if (!(l.IsValueType || r.IsValueType)){
1575 type = TypeManager.bool_type;
1580 if (l.IsSubclassOf (r) || r.IsSubclassOf (l))
1586 // We are dealing with numbers
1589 if (!DoNumericPromotions (ec, l, r)){
1594 if (left == null || right == null)
1598 // reload our cached types if required
1603 if (oper == Operator.BitwiseAnd ||
1604 oper == Operator.BitwiseOr ||
1605 oper == Operator.ExclusiveOr){
1607 if (!((l == TypeManager.int32_type) ||
1608 (l == TypeManager.uint32_type) ||
1609 (l == TypeManager.int64_type) ||
1610 (l == TypeManager.uint64_type)))
1618 if (oper == Operator.Equality ||
1619 oper == Operator.Inequality ||
1620 oper == Operator.LessThanOrEqual ||
1621 oper == Operator.LessThan ||
1622 oper == Operator.GreaterThanOrEqual ||
1623 oper == Operator.GreaterThan){
1624 type = TypeManager.bool_type;
1631 /// Constant expression reducer for binary operations
1633 public Expression ConstantFold (EmitContext ec)
1635 object l = ((Constant) left).GetValue ();
1636 object r = ((Constant) right).GetValue ();
1638 if (l is string && r is string)
1639 return new StringConstant ((string) l + (string) r);
1641 Type result_type = null;
1644 // Enumerator folding
1646 if (left.Type == right.Type && left is EnumConstant)
1647 result_type = left.Type;
1650 case Operator.BitwiseOr:
1651 if ((l is int) && (r is int)){
1653 int res = (int)l | (int)r;
1655 v = new IntConstant (res);
1656 if (result_type == null)
1659 return new EnumConstant (v, result_type);
1663 case Operator.BitwiseAnd:
1664 if ((l is int) && (r is int)){
1666 int res = (int)l & (int)r;
1668 v = new IntConstant (res);
1669 if (result_type == null)
1672 return new EnumConstant (v, result_type);
1680 public override Expression DoResolve (EmitContext ec)
1682 left = left.Resolve (ec);
1683 right = right.Resolve (ec);
1685 if (left == null || right == null)
1688 if (left.Type == null)
1689 throw new Exception (
1690 "Resolve returned non null, but did not set the type! (" +
1691 left + ") at Line: " + loc.Row);
1692 if (right.Type == null)
1693 throw new Exception (
1694 "Resolve returned non null, but did not set the type! (" +
1695 right + ") at Line: "+ loc.Row);
1697 eclass = ExprClass.Value;
1699 if (left is Constant && right is Constant){
1701 // This is temporary until we do the full folding
1703 Expression e = ConstantFold (ec);
1708 return ResolveOperator (ec);
1711 public bool IsBranchable ()
1713 if (oper == Operator.Equality ||
1714 oper == Operator.Inequality ||
1715 oper == Operator.LessThan ||
1716 oper == Operator.GreaterThan ||
1717 oper == Operator.LessThanOrEqual ||
1718 oper == Operator.GreaterThanOrEqual){
1725 /// This entry point is used by routines that might want
1726 /// to emit a brfalse/brtrue after an expression, and instead
1727 /// they could use a more compact notation.
1729 /// Typically the code would generate l.emit/r.emit, followed
1730 /// by the comparission and then a brtrue/brfalse. The comparissions
1731 /// are sometimes inneficient (there are not as complete as the branches
1732 /// look for the hacks in Emit using double ceqs).
1734 /// So for those cases we provide EmitBranchable that can emit the
1735 /// branch with the test
1737 public void EmitBranchable (EmitContext ec, int target)
1740 bool close_target = false;
1741 ILGenerator ig = ec.ig;
1744 // short-circuit operators
1746 if (oper == Operator.LogicalAnd){
1748 ig.Emit (OpCodes.Brfalse, target);
1750 ig.Emit (OpCodes.Brfalse, target);
1751 } else if (oper == Operator.LogicalOr){
1753 ig.Emit (OpCodes.Brtrue, target);
1755 ig.Emit (OpCodes.Brfalse, target);
1762 case Operator.Equality:
1764 opcode = OpCodes.Beq_S;
1766 opcode = OpCodes.Beq;
1769 case Operator.Inequality:
1771 opcode = OpCodes.Bne_Un_S;
1773 opcode = OpCodes.Bne_Un;
1776 case Operator.LessThan:
1778 opcode = OpCodes.Blt_S;
1780 opcode = OpCodes.Blt;
1783 case Operator.GreaterThan:
1785 opcode = OpCodes.Bgt_S;
1787 opcode = OpCodes.Bgt;
1790 case Operator.LessThanOrEqual:
1792 opcode = OpCodes.Ble_S;
1794 opcode = OpCodes.Ble;
1797 case Operator.GreaterThanOrEqual:
1799 opcode = OpCodes.Bge_S;
1801 opcode = OpCodes.Ble;
1805 throw new Exception ("EmitBranchable called on non-EmitBranchable operator: "
1806 + oper.ToString ());
1809 ig.Emit (opcode, target);
1812 public override void Emit (EmitContext ec)
1814 ILGenerator ig = ec.ig;
1816 Type r = right.Type;
1819 if (method != null) {
1821 // Note that operators are static anyway
1823 if (Arguments != null)
1824 Invocation.EmitArguments (ec, method, Arguments);
1826 if (method is MethodInfo)
1827 ig.Emit (OpCodes.Call, (MethodInfo) method);
1829 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
1835 // Handle short-circuit operators differently
1838 if (oper == Operator.LogicalAnd){
1839 Label load_zero = ig.DefineLabel ();
1840 Label end = ig.DefineLabel ();
1843 ig.Emit (OpCodes.Brfalse, load_zero);
1845 ig.Emit (OpCodes.Br, end);
1846 ig.MarkLabel (load_zero);
1847 ig.Emit (OpCodes.Ldc_I4_0);
1850 } else if (oper == Operator.LogicalOr){
1851 Label load_one = ig.DefineLabel ();
1852 Label end = ig.DefineLabel ();
1855 ig.Emit (OpCodes.Brtrue, load_one);
1857 ig.Emit (OpCodes.Br, end);
1858 ig.MarkLabel (load_one);
1859 ig.Emit (OpCodes.Ldc_I4_1);
1868 case Operator.Multiply:
1870 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
1871 opcode = OpCodes.Mul_Ovf;
1872 else if (l==TypeManager.uint32_type || l==TypeManager.uint64_type)
1873 opcode = OpCodes.Mul_Ovf_Un;
1875 opcode = OpCodes.Mul;
1877 opcode = OpCodes.Mul;
1881 case Operator.Division:
1882 if (l == TypeManager.uint32_type || l == TypeManager.uint64_type)
1883 opcode = OpCodes.Div_Un;
1885 opcode = OpCodes.Div;
1888 case Operator.Modulus:
1889 if (l == TypeManager.uint32_type || l == TypeManager.uint64_type)
1890 opcode = OpCodes.Rem_Un;
1892 opcode = OpCodes.Rem;
1895 case Operator.Addition:
1897 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
1898 opcode = OpCodes.Add_Ovf;
1899 else if (l==TypeManager.uint32_type || l==TypeManager.uint64_type)
1900 opcode = OpCodes.Add_Ovf_Un;
1902 opcode = OpCodes.Mul;
1904 opcode = OpCodes.Add;
1907 case Operator.Subtraction:
1909 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
1910 opcode = OpCodes.Sub_Ovf;
1911 else if (l==TypeManager.uint32_type || l==TypeManager.uint64_type)
1912 opcode = OpCodes.Sub_Ovf_Un;
1914 opcode = OpCodes.Sub;
1916 opcode = OpCodes.Sub;
1919 case Operator.RightShift:
1920 opcode = OpCodes.Shr;
1923 case Operator.LeftShift:
1924 opcode = OpCodes.Shl;
1927 case Operator.Equality:
1928 opcode = OpCodes.Ceq;
1931 case Operator.Inequality:
1932 ec.ig.Emit (OpCodes.Ceq);
1933 ec.ig.Emit (OpCodes.Ldc_I4_0);
1935 opcode = OpCodes.Ceq;
1938 case Operator.LessThan:
1939 opcode = OpCodes.Clt;
1942 case Operator.GreaterThan:
1943 opcode = OpCodes.Cgt;
1946 case Operator.LessThanOrEqual:
1947 ec.ig.Emit (OpCodes.Cgt);
1948 ec.ig.Emit (OpCodes.Ldc_I4_0);
1950 opcode = OpCodes.Ceq;
1953 case Operator.GreaterThanOrEqual:
1954 ec.ig.Emit (OpCodes.Clt);
1955 ec.ig.Emit (OpCodes.Ldc_I4_1);
1957 opcode = OpCodes.Sub;
1960 case Operator.BitwiseOr:
1961 opcode = OpCodes.Or;
1964 case Operator.BitwiseAnd:
1965 opcode = OpCodes.And;
1968 case Operator.ExclusiveOr:
1969 opcode = OpCodes.Xor;
1973 throw new Exception ("This should not happen: Operator = "
1974 + oper.ToString ());
1982 /// Implements the ternary conditiona operator (?:)
1984 public class Conditional : Expression {
1985 Expression expr, trueExpr, falseExpr;
1988 public Conditional (Expression expr, Expression trueExpr, Expression falseExpr, Location l)
1991 this.trueExpr = trueExpr;
1992 this.falseExpr = falseExpr;
1996 public Expression Expr {
2002 public Expression TrueExpr {
2008 public Expression FalseExpr {
2014 public override Expression DoResolve (EmitContext ec)
2016 expr = expr.Resolve (ec);
2018 if (expr.Type != TypeManager.bool_type)
2019 expr = Expression.ConvertImplicitRequired (
2020 ec, expr, TypeManager.bool_type, loc);
2022 trueExpr = trueExpr.Resolve (ec);
2023 falseExpr = falseExpr.Resolve (ec);
2025 if (expr == null || trueExpr == null || falseExpr == null)
2028 if (trueExpr.Type == falseExpr.Type)
2029 type = trueExpr.Type;
2034 // First, if an implicit conversion exists from trueExpr
2035 // to falseExpr, then the result type is of type falseExpr.Type
2037 conv = ConvertImplicit (ec, trueExpr, falseExpr.Type, loc);
2039 type = falseExpr.Type;
2041 } else if ((conv = ConvertImplicit(ec, falseExpr,trueExpr.Type,loc))!= null){
2042 type = trueExpr.Type;
2045 Error (173, loc, "The type of the conditional expression can " +
2046 "not be computed because there is no implicit conversion" +
2047 " from `" + TypeManager.CSharpName (trueExpr.Type) + "'" +
2048 " and `" + TypeManager.CSharpName (falseExpr.Type) + "'");
2053 if (expr is BoolConstant){
2054 BoolConstant bc = (BoolConstant) expr;
2062 eclass = ExprClass.Value;
2066 public override void Emit (EmitContext ec)
2068 ILGenerator ig = ec.ig;
2069 Label false_target = ig.DefineLabel ();
2070 Label end_target = ig.DefineLabel ();
2073 ig.Emit (OpCodes.Brfalse, false_target);
2075 ig.Emit (OpCodes.Br, end_target);
2076 ig.MarkLabel (false_target);
2077 falseExpr.Emit (ec);
2078 ig.MarkLabel (end_target);
2086 public class LocalVariableReference : Expression, IAssignMethod, IMemoryLocation {
2087 public readonly string Name;
2088 public readonly Block Block;
2090 VariableInfo variable_info;
2092 public LocalVariableReference (Block block, string name, Location l)
2097 eclass = ExprClass.Variable;
2100 public VariableInfo VariableInfo {
2102 if (variable_info == null)
2103 variable_info = Block.GetVariableInfo (Name);
2104 return variable_info;
2108 public override Expression DoResolve (EmitContext ec)
2110 VariableInfo vi = VariableInfo;
2112 if (Block.IsConstant (Name)) {
2113 Expression e = Block.GetConstantExpression (Name);
2119 if (!(e is Constant)) {
2120 Report.Error (150, loc, "A constant value is expected");
2128 type = vi.VariableType;
2132 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
2134 Expression e = DoResolve (ec);
2139 VariableInfo vi = VariableInfo;
2145 "cannot assign to `" + Name + "' because it is readonly");
2153 public override void Emit (EmitContext ec)
2155 VariableInfo vi = VariableInfo;
2156 ILGenerator ig = ec.ig;
2163 ig.Emit (OpCodes.Ldloc_0);
2167 ig.Emit (OpCodes.Ldloc_1);
2171 ig.Emit (OpCodes.Ldloc_2);
2175 ig.Emit (OpCodes.Ldloc_3);
2180 ig.Emit (OpCodes.Ldloc_S, (byte) idx);
2182 ig.Emit (OpCodes.Ldloc, idx);
2187 public static void Store (ILGenerator ig, int idx)
2191 ig.Emit (OpCodes.Stloc_0);
2195 ig.Emit (OpCodes.Stloc_1);
2199 ig.Emit (OpCodes.Stloc_2);
2203 ig.Emit (OpCodes.Stloc_3);
2208 ig.Emit (OpCodes.Stloc_S, (byte) idx);
2210 ig.Emit (OpCodes.Stloc, idx);
2215 public void EmitAssign (EmitContext ec, Expression source)
2217 ILGenerator ig = ec.ig;
2218 VariableInfo vi = VariableInfo;
2224 // Funny seems the code below generates optimal code for us, but
2225 // seems to take too long to generate what we need.
2226 // ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
2231 public void AddressOf (EmitContext ec)
2233 VariableInfo vi = VariableInfo;
2240 ec.ig.Emit (OpCodes.Ldloca_S, (byte) idx);
2242 ec.ig.Emit (OpCodes.Ldloca, idx);
2247 /// This represents a reference to a parameter in the intermediate
2250 public class ParameterReference : Expression, IAssignMethod, IMemoryLocation {
2256 public ParameterReference (Parameters pars, int idx, string name)
2261 eclass = ExprClass.Variable;
2265 // Notice that for ref/out parameters, the type exposed is not the
2266 // same type exposed externally.
2269 // externally we expose "int&"
2270 // here we expose "int".
2272 // We record this in "is_ref". This means that the type system can treat
2273 // the type as it is expected, but when we generate the code, we generate
2274 // the alternate kind of code.
2276 public override Expression DoResolve (EmitContext ec)
2278 type = pars.GetParameterInfo (ec.TypeContainer, idx, out is_ref);
2279 eclass = ExprClass.Variable;
2284 public override void Emit (EmitContext ec)
2286 ILGenerator ig = ec.ig;
2293 ig.Emit (OpCodes.Ldarg_S, (byte) arg_idx);
2295 ig.Emit (OpCodes.Ldarg, arg_idx);
2301 // If we are a reference, we loaded on the stack a pointer
2302 // Now lets load the real value
2305 if (type == TypeManager.int32_type)
2306 ig.Emit (OpCodes.Ldind_I4);
2307 else if (type == TypeManager.uint32_type)
2308 ig.Emit (OpCodes.Ldind_U4);
2309 else if (type == TypeManager.int64_type || type == TypeManager.uint64_type)
2310 ig.Emit (OpCodes.Ldind_I8);
2311 else if (type == TypeManager.char_type)
2312 ig.Emit (OpCodes.Ldind_U2);
2313 else if (type == TypeManager.short_type)
2314 ig.Emit (OpCodes.Ldind_I2);
2315 else if (type == TypeManager.ushort_type)
2316 ig.Emit (OpCodes.Ldind_U2);
2317 else if (type == TypeManager.float_type)
2318 ig.Emit (OpCodes.Ldind_R4);
2319 else if (type == TypeManager.double_type)
2320 ig.Emit (OpCodes.Ldind_R8);
2321 else if (type == TypeManager.byte_type)
2322 ig.Emit (OpCodes.Ldind_U1);
2323 else if (type == TypeManager.sbyte_type)
2324 ig.Emit (OpCodes.Ldind_I1);
2325 else if (type == TypeManager.intptr_type)
2326 ig.Emit (OpCodes.Ldind_I);
2328 ig.Emit (OpCodes.Ldind_Ref);
2331 public void EmitAssign (EmitContext ec, Expression source)
2333 ILGenerator ig = ec.ig;
2342 ig.Emit (OpCodes.Ldarg_S, (byte) arg_idx);
2344 ig.Emit (OpCodes.Ldarg, arg_idx);
2350 if (type == TypeManager.int32_type || type == TypeManager.uint32_type)
2351 ig.Emit (OpCodes.Stind_I4);
2352 else if (type == TypeManager.int64_type || type == TypeManager.uint64_type)
2353 ig.Emit (OpCodes.Stind_I8);
2354 else if (type == TypeManager.char_type || type == TypeManager.short_type ||
2355 type == TypeManager.ushort_type)
2356 ig.Emit (OpCodes.Stind_I2);
2357 else if (type == TypeManager.float_type)
2358 ig.Emit (OpCodes.Stind_R4);
2359 else if (type == TypeManager.double_type)
2360 ig.Emit (OpCodes.Stind_R8);
2361 else if (type == TypeManager.byte_type || type == TypeManager.sbyte_type)
2362 ig.Emit (OpCodes.Stind_I1);
2363 else if (type == TypeManager.intptr_type)
2364 ig.Emit (OpCodes.Stind_I);
2366 ig.Emit (OpCodes.Stind_Ref);
2369 ig.Emit (OpCodes.Starg_S, (byte) arg_idx);
2371 ig.Emit (OpCodes.Starg, arg_idx);
2376 public void AddressOf (EmitContext ec)
2384 ec.ig.Emit (OpCodes.Ldarga_S, (byte) arg_idx);
2386 ec.ig.Emit (OpCodes.Ldarga, arg_idx);
2391 /// Used for arguments to New(), Invocation()
2393 public class Argument {
2394 public enum AType : byte {
2400 public readonly AType ArgType;
2401 public Expression expr;
2403 public Argument (Expression expr, AType type)
2406 this.ArgType = type;
2409 public Expression Expr {
2425 public Parameter.Modifier GetParameterModifier ()
2427 if (ArgType == AType.Ref)
2428 return Parameter.Modifier.REF;
2430 if (ArgType == AType.Out)
2431 return Parameter.Modifier.OUT;
2433 return Parameter.Modifier.NONE;
2436 public static string FullDesc (Argument a)
2438 return (a.ArgType == AType.Ref ? "ref " :
2439 (a.ArgType == AType.Out ? "out " : "")) +
2440 TypeManager.CSharpName (a.Expr.Type);
2443 public bool Resolve (EmitContext ec, Location loc)
2445 expr = expr.Resolve (ec);
2447 if (ArgType == AType.Expression)
2448 return expr != null;
2450 if (expr.eclass != ExprClass.Variable){
2451 Report.Error (206, loc,
2452 "A property or indexer can not be passed as an out or ref " +
2457 return expr != null;
2460 public void Emit (EmitContext ec)
2462 if (ArgType == AType.Ref || ArgType == AType.Out)
2463 ((IMemoryLocation)expr).AddressOf (ec);
2470 /// Invocation of methods or delegates.
2472 public class Invocation : ExpressionStatement {
2473 public readonly ArrayList Arguments;
2477 MethodBase method = null;
2479 static Hashtable method_parameter_cache;
2481 static Invocation ()
2483 method_parameter_cache = new PtrHashtable ();
2487 // arguments is an ArrayList, but we do not want to typecast,
2488 // as it might be null.
2490 // FIXME: only allow expr to be a method invocation or a
2491 // delegate invocation (7.5.5)
2493 public Invocation (Expression expr, ArrayList arguments, Location l)
2496 Arguments = arguments;
2500 public Expression Expr {
2507 /// Returns the Parameters (a ParameterData interface) for the
2510 public static ParameterData GetParameterData (MethodBase mb)
2512 object pd = method_parameter_cache [mb];
2516 return (ParameterData) pd;
2519 ip = TypeManager.LookupParametersByBuilder (mb);
2521 method_parameter_cache [mb] = ip;
2523 return (ParameterData) ip;
2525 ParameterInfo [] pi = mb.GetParameters ();
2526 ReflectionParameters rp = new ReflectionParameters (pi);
2527 method_parameter_cache [mb] = rp;
2529 return (ParameterData) rp;
2534 /// Tells whether a user defined conversion from Type `from' to
2535 /// Type `to' exists.
2537 /// FIXME: we could implement a cache here.
2539 static bool ConversionExists (EmitContext ec, Type from, Type to, Location loc)
2541 // Locate user-defined implicit operators
2545 mg = MemberLookup (ec, to, "op_Implicit", false, loc);
2548 MethodGroupExpr me = (MethodGroupExpr) mg;
2550 for (int i = me.Methods.Length; i > 0;) {
2552 MethodBase mb = me.Methods [i];
2553 ParameterData pd = GetParameterData (mb);
2555 if (from == pd.ParameterType (0))
2560 mg = MemberLookup (ec, from, "op_Implicit", false, loc);
2563 MethodGroupExpr me = (MethodGroupExpr) mg;
2565 for (int i = me.Methods.Length; i > 0;) {
2567 MethodBase mb = me.Methods [i];
2568 MethodInfo mi = (MethodInfo) mb;
2570 if (mi.ReturnType == to)
2579 /// Determines "better conversion" as specified in 7.4.2.3
2580 /// Returns : 1 if a->p is better
2581 /// 0 if a->q or neither is better
2583 static int BetterConversion (EmitContext ec, Argument a, Type p, Type q, bool use_standard,
2586 Type argument_type = a.Type;
2587 Expression argument_expr = a.Expr;
2589 if (argument_type == null)
2590 throw new Exception ("Expression of type " + a.Expr + " does not resolve its type");
2595 if (argument_type == p)
2598 if (argument_type == q)
2602 // Now probe whether an implicit constant expression conversion
2605 // An implicit constant expression conversion permits the following
2608 // * A constant-expression of type `int' can be converted to type
2609 // sbyte, byute, short, ushort, uint, ulong provided the value of
2610 // of the expression is withing the range of the destination type.
2612 // * A constant-expression of type long can be converted to type
2613 // ulong, provided the value of the constant expression is not negative
2615 // FIXME: Note that this assumes that constant folding has
2616 // taken place. We dont do constant folding yet.
2619 if (argument_expr is IntConstant){
2620 IntConstant ei = (IntConstant) argument_expr;
2621 int value = ei.Value;
2623 if (p == TypeManager.sbyte_type){
2624 if (value >= SByte.MinValue && value <= SByte.MaxValue)
2626 } else if (p == TypeManager.byte_type){
2627 if (Byte.MinValue >= 0 && value <= Byte.MaxValue)
2629 } else if (p == TypeManager.short_type){
2630 if (value >= Int16.MinValue && value <= Int16.MaxValue)
2632 } else if (p == TypeManager.ushort_type){
2633 if (value >= UInt16.MinValue && value <= UInt16.MaxValue)
2635 } else if (p == TypeManager.uint32_type){
2637 // we can optimize this case: a positive int32
2638 // always fits on a uint32
2642 } else if (p == TypeManager.uint64_type){
2644 // we can optimize this case: a positive int32
2645 // always fits on a uint64
2650 } else if (argument_type == TypeManager.int64_type && argument_expr is LongConstant){
2651 LongConstant lc = (LongConstant) argument_expr;
2653 if (p == TypeManager.uint64_type){
2664 tmp = ConvertImplicitStandard (ec, argument_expr, p, loc);
2666 tmp = ConvertImplicit (ec, argument_expr, p, loc);
2675 if (ConversionExists (ec, p, q, loc) == true &&
2676 ConversionExists (ec, q, p, loc) == false)
2679 if (p == TypeManager.sbyte_type)
2680 if (q == TypeManager.byte_type || q == TypeManager.ushort_type ||
2681 q == TypeManager.uint32_type || q == TypeManager.uint64_type)
2684 if (p == TypeManager.short_type)
2685 if (q == TypeManager.ushort_type || q == TypeManager.uint32_type ||
2686 q == TypeManager.uint64_type)
2689 if (p == TypeManager.int32_type)
2690 if (q == TypeManager.uint32_type || q == TypeManager.uint64_type)
2693 if (p == TypeManager.int64_type)
2694 if (q == TypeManager.uint64_type)
2701 /// Determines "Better function"
2704 /// and returns an integer indicating :
2705 /// 0 if candidate ain't better
2706 /// 1 if candidate is better than the current best match
2708 static int BetterFunction (EmitContext ec, ArrayList args,
2709 MethodBase candidate, MethodBase best,
2710 bool use_standard, Location loc)
2712 ParameterData candidate_pd = GetParameterData (candidate);
2713 ParameterData best_pd;
2719 argument_count = args.Count;
2721 if (candidate_pd.Count == 0 && argument_count == 0)
2725 if (candidate_pd.Count == argument_count) {
2727 for (int j = argument_count; j > 0;) {
2730 Argument a = (Argument) args [j];
2732 x = BetterConversion (
2733 ec, a, candidate_pd.ParameterType (j), null,
2749 best_pd = GetParameterData (best);
2751 if (candidate_pd.Count == argument_count && best_pd.Count == argument_count) {
2752 int rating1 = 0, rating2 = 0;
2754 for (int j = argument_count; j > 0;) {
2758 Argument a = (Argument) args [j];
2760 x = BetterConversion (ec, a, candidate_pd.ParameterType (j),
2761 best_pd.ParameterType (j), use_standard, loc);
2762 y = BetterConversion (ec, a, best_pd.ParameterType (j),
2763 candidate_pd.ParameterType (j), use_standard,
2770 if (rating1 > rating2)
2779 public static string FullMethodDesc (MethodBase mb)
2781 StringBuilder sb = new StringBuilder (mb.Name);
2782 ParameterData pd = GetParameterData (mb);
2784 int count = pd.Count;
2787 for (int i = count; i > 0; ) {
2790 sb.Append (pd.ParameterDesc (count - i - 1));
2796 return sb.ToString ();
2799 public static MethodGroupExpr MakeUnionSet (Expression mg1, Expression mg2)
2801 MemberInfo [] miset;
2802 MethodGroupExpr union;
2804 if (mg1 != null && mg2 != null) {
2806 MethodGroupExpr left_set = null, right_set = null;
2807 int length1 = 0, length2 = 0;
2809 left_set = (MethodGroupExpr) mg1;
2810 length1 = left_set.Methods.Length;
2812 right_set = (MethodGroupExpr) mg2;
2813 length2 = right_set.Methods.Length;
2815 ArrayList common = new ArrayList ();
2817 for (int i = 0; i < left_set.Methods.Length; i++) {
2818 for (int j = 0; j < right_set.Methods.Length; j++) {
2819 if (left_set.Methods [i] == right_set.Methods [j])
2820 common.Add (left_set.Methods [i]);
2824 miset = new MemberInfo [length1 + length2 - common.Count];
2826 left_set.Methods.CopyTo (miset, 0);
2830 for (int j = 0; j < right_set.Methods.Length; j++)
2831 if (!common.Contains (right_set.Methods [j]))
2832 miset [length1 + k++] = right_set.Methods [j];
2834 union = new MethodGroupExpr (miset);
2838 } else if (mg1 == null && mg2 != null) {
2840 MethodGroupExpr me = (MethodGroupExpr) mg2;
2842 miset = new MemberInfo [me.Methods.Length];
2843 me.Methods.CopyTo (miset, 0);
2845 union = new MethodGroupExpr (miset);
2849 } else if (mg2 == null && mg1 != null) {
2851 MethodGroupExpr me = (MethodGroupExpr) mg1;
2853 miset = new MemberInfo [me.Methods.Length];
2854 me.Methods.CopyTo (miset, 0);
2856 union = new MethodGroupExpr (miset);
2865 /// Determines is the candidate method, if a params method, is applicable
2866 /// in its expanded form to the given set of arguments
2868 static bool IsParamsMethodApplicable (ArrayList arguments, MethodBase candidate)
2872 if (arguments == null)
2875 arg_count = arguments.Count;
2877 ParameterData pd = GetParameterData (candidate);
2879 int pd_count = pd.Count;
2884 if (pd.ParameterModifier (pd_count - 1) != Parameter.Modifier.PARAMS)
2887 if (pd_count - 1 > arg_count)
2890 // If we have come this far, the case which remains is when the number of parameters
2891 // is less than or equal to the argument count. So, we now check if the element type
2892 // of the params array is compatible with each argument type
2895 Type element_type = pd.ParameterType (pd_count - 1).GetElementType ();
2897 for (int i = pd_count - 1; i < arg_count - 1; i++) {
2898 Argument a = (Argument) arguments [i];
2899 if (!StandardConversionExists (a.Type, element_type))
2907 /// Determines if the candidate method is applicable (section 14.4.2.1)
2908 /// to the given set of arguments
2910 static bool IsApplicable (ArrayList arguments, MethodBase candidate)
2914 if (arguments == null)
2917 arg_count = arguments.Count;
2919 ParameterData pd = GetParameterData (candidate);
2921 int pd_count = pd.Count;
2923 if (arg_count != pd.Count)
2926 for (int i = arg_count; i > 0; ) {
2929 Argument a = (Argument) arguments [i];
2931 Parameter.Modifier a_mod = a.GetParameterModifier ();
2932 Parameter.Modifier p_mod = pd.ParameterModifier (i);
2934 if (a_mod == p_mod) {
2936 if (a_mod == Parameter.Modifier.NONE)
2937 if (!StandardConversionExists (a.Type, pd.ParameterType (i)))
2940 if (a_mod == Parameter.Modifier.REF ||
2941 a_mod == Parameter.Modifier.OUT)
2942 if (pd.ParameterType (i) != a.Type)
2954 /// Find the Applicable Function Members (7.4.2.1)
2956 /// me: Method Group expression with the members to select.
2957 /// it might contain constructors or methods (or anything
2958 /// that maps to a method).
2960 /// Arguments: ArrayList containing resolved Argument objects.
2962 /// loc: The location if we want an error to be reported, or a Null
2963 /// location for "probing" purposes.
2965 /// use_standard: controls whether OverloadResolve should use the
2966 /// ConvertImplicit or ConvertImplicitStandard during overload resolution.
2968 /// Returns: The MethodBase (either a ConstructorInfo or a MethodInfo)
2969 /// that is the best match of me on Arguments.
2972 public static MethodBase OverloadResolve (EmitContext ec, MethodGroupExpr me,
2973 ArrayList Arguments, Location loc,
2976 ArrayList afm = new ArrayList ();
2977 int best_match_idx = -1;
2978 MethodBase method = null;
2980 ArrayList candidates = new ArrayList ();
2982 for (int i = me.Methods.Length; i > 0; ){
2984 MethodBase candidate = me.Methods [i];
2987 // Check if candidate is applicable (section 14.4.2.1)
2988 if (!IsApplicable (Arguments, candidate))
2991 candidates.Add (candidate);
2992 x = BetterFunction (ec, Arguments, candidate, method, use_standard, loc);
2998 method = me.Methods [best_match_idx];
3002 if (Arguments == null)
3005 argument_count = Arguments.Count;
3008 // Now we see if we can find params functions, applicable in their expanded form
3009 // since if they were applicable in their normal form, they would have been selected
3012 if (best_match_idx == -1) {
3014 for (int i = me.Methods.Length; i > 0; ) {
3016 MethodBase candidate = me.Methods [i];
3018 if (IsParamsMethodApplicable (Arguments, candidate)) {
3020 method = me.Methods [best_match_idx];
3027 // Now we see if we can at least find a method with the same number of arguments
3030 int method_count = 0;
3032 if (best_match_idx == -1) {
3034 for (int i = me.Methods.Length; i > 0;) {
3036 MethodBase mb = me.Methods [i];
3037 pd = GetParameterData (mb);
3039 if (pd.Count == argument_count) {
3041 method = me.Methods [best_match_idx];
3052 // Now check that there are no ambiguities i.e the selected method
3053 // should be better than all the others
3056 for (int i = candidates.Count; i > 0; ) {
3058 MethodBase candidate = (MethodBase) candidates [i];
3061 if (candidate == method)
3064 x = BetterFunction (ec, Arguments, method, candidate, use_standard, loc);
3069 "Ambiguous call when selecting function due to implicit casts");
3075 // And now convert implicitly, each argument to the required type
3077 pd = GetParameterData (method);
3078 int pd_count = pd.Count;
3080 for (int j = 0; j < argument_count; j++) {
3081 Argument a = (Argument) Arguments [j];
3082 Expression a_expr = a.Expr;
3083 Type parameter_type = pd.ParameterType (j);
3086 // Note that we need to compare against the element type
3087 // when we have a params method
3089 if (pd.ParameterModifier (pd_count - 1) == Parameter.Modifier.PARAMS) {
3090 if (j >= pd_count - 1)
3091 parameter_type = pd.ParameterType (pd_count - 1).GetElementType ();
3094 if (a.Type != parameter_type){
3098 conv = ConvertImplicitStandard (
3099 ec, a_expr, parameter_type, Location.Null);
3101 conv = ConvertImplicit (
3102 ec, a_expr, parameter_type, Location.Null);
3105 if (!Location.IsNull (loc)) {
3107 "The best overloaded match for method '" +
3108 FullMethodDesc (method) +
3109 "' has some invalid arguments");
3111 "Argument " + (j+1) +
3112 ": Cannot convert from '" + Argument.FullDesc (a)
3113 + "' to '" + pd.ParameterDesc (j) + "'");
3121 // Update the argument with the implicit conversion
3126 // FIXME : For the case of params methods, we need to actually instantiate
3127 // an array and initialize it with the argument values etc etc.
3131 if (a.GetParameterModifier () != pd.ParameterModifier (j) &&
3132 pd.ParameterModifier (j) != Parameter.Modifier.PARAMS) {
3133 if (!Location.IsNull (loc)) {
3135 "The best overloaded match for method '" + FullMethodDesc (method)+
3136 "' has some invalid arguments");
3138 "Argument " + (j+1) +
3139 ": Cannot convert from '" + Argument.FullDesc (a)
3140 + "' to '" + pd.ParameterDesc (j) + "'");
3151 public static MethodBase OverloadResolve (EmitContext ec, MethodGroupExpr me,
3152 ArrayList Arguments, Location loc)
3154 return OverloadResolve (ec, me, Arguments, loc, false);
3157 public override Expression DoResolve (EmitContext ec)
3160 // First, resolve the expression that is used to
3161 // trigger the invocation
3163 expr = expr.Resolve (ec);
3167 if (!(expr is MethodGroupExpr)) {
3168 Type expr_type = expr.Type;
3170 if (expr_type != null){
3171 bool IsDelegate = TypeManager.IsDelegateType (expr_type);
3173 return (new DelegateInvocation (
3174 this.expr, Arguments, loc)).Resolve (ec);
3178 if (!(expr is MethodGroupExpr)){
3179 report118 (loc, this.expr, "method group");
3184 // Next, evaluate all the expressions in the argument list
3186 if (Arguments != null){
3187 for (int i = Arguments.Count; i > 0;){
3189 Argument a = (Argument) Arguments [i];
3191 if (!a.Resolve (ec, loc))
3196 method = OverloadResolve (ec, (MethodGroupExpr) this.expr, Arguments, loc);
3198 if (method == null){
3200 "Could not find any applicable function for this argument list");
3204 if (method is MethodInfo)
3205 type = ((MethodInfo)method).ReturnType;
3207 eclass = ExprClass.Value;
3212 // Emits the list of arguments as an array
3214 static void EmitParams (EmitContext ec, int idx, ArrayList arguments)
3216 ILGenerator ig = ec.ig;
3217 int count = arguments.Count - idx;
3218 Argument a = (Argument) arguments [idx];
3219 Type t = a.expr.Type;
3220 string array_type = t.FullName + "[]";
3223 array = ig.DeclareLocal (Type.GetType (array_type));
3224 IntConstant.EmitInt (ig, count);
3225 ig.Emit (OpCodes.Newarr, t);
3226 ig.Emit (OpCodes.Stloc, array);
3228 int top = arguments.Count;
3229 for (int j = idx; j < top; j++){
3230 a = (Argument) arguments [j];
3232 ig.Emit (OpCodes.Ldloc, array);
3233 IntConstant.EmitInt (ig, j - idx);
3236 ArrayAccess.EmitStoreOpcode (ig, t);
3238 ig.Emit (OpCodes.Ldloc, array);
3242 /// Emits a list of resolved Arguments that are in the arguments
3245 /// The MethodBase argument might be null if the
3246 /// emission of the arguments is known not to contain
3247 /// a `params' field (for example in constructors or other routines
3248 /// that keep their arguments in this structure
3250 public static void EmitArguments (EmitContext ec, MethodBase mb, ArrayList arguments)
3252 ParameterData pd = null;
3255 if (arguments != null)
3256 top = arguments.Count;
3261 pd = GetParameterData (mb);
3263 for (int i = 0; i < top; i++){
3264 Argument a = (Argument) arguments [i];
3267 if (pd.ParameterModifier (i) == Parameter.Modifier.PARAMS){
3268 EmitParams (ec, i, arguments);
3277 public static void EmitCall (EmitContext ec,
3278 bool is_static, Expression instance_expr,
3279 MethodBase method, ArrayList Arguments)
3281 ILGenerator ig = ec.ig;
3282 bool struct_call = false;
3286 // If this is ourselves, push "this"
3288 if (instance_expr == null){
3289 ig.Emit (OpCodes.Ldarg_0);
3292 // Push the instance expression
3294 if (instance_expr.Type.IsSubclassOf (TypeManager.value_type)){
3299 // If the expression implements IMemoryLocation, then
3300 // we can optimize and use AddressOf on the
3303 // If not we have to use some temporary storage for
3305 if (instance_expr is IMemoryLocation)
3306 ((IMemoryLocation) instance_expr).AddressOf (ec);
3308 Type t = instance_expr.Type;
3310 instance_expr.Emit (ec);
3311 LocalBuilder temp = ig.DeclareLocal (t);
3312 ig.Emit (OpCodes.Stloc, temp);
3313 ig.Emit (OpCodes.Ldloca, temp);
3316 instance_expr.Emit (ec);
3320 if (Arguments != null)
3321 EmitArguments (ec, method, Arguments);
3323 if (is_static || struct_call){
3324 if (method is MethodInfo)
3325 ig.Emit (OpCodes.Call, (MethodInfo) method);
3327 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
3329 if (method is MethodInfo)
3330 ig.Emit (OpCodes.Callvirt, (MethodInfo) method);
3332 ig.Emit (OpCodes.Callvirt, (ConstructorInfo) method);
3336 public override void Emit (EmitContext ec)
3338 MethodGroupExpr mg = (MethodGroupExpr) this.expr;
3339 EmitCall (ec, method.IsStatic, mg.InstanceExpression, method, Arguments);
3342 public override void EmitStatement (EmitContext ec)
3347 // Pop the return value if there is one
3349 if (method is MethodInfo){
3350 if (((MethodInfo)method).ReturnType != TypeManager.void_type)
3351 ec.ig.Emit (OpCodes.Pop);
3357 /// Implements the new expression
3359 public class New : ExpressionStatement {
3360 public readonly ArrayList Arguments;
3361 public readonly string RequestedType;
3364 MethodBase method = null;
3367 // If set, the new expression is for a value_target, and
3368 // we will not leave anything on the stack.
3370 Expression value_target;
3372 public New (string requested_type, ArrayList arguments, Location l)
3374 RequestedType = requested_type;
3375 Arguments = arguments;
3379 public Expression ValueTypeVariable {
3381 return value_target;
3385 value_target = value;
3389 public override Expression DoResolve (EmitContext ec)
3391 type = RootContext.LookupType (ec.TypeContainer, RequestedType, false, loc);
3396 bool IsDelegate = TypeManager.IsDelegateType (type);
3399 return (new NewDelegate (type, Arguments, loc)).Resolve (ec);
3401 bool is_struct = false;
3402 is_struct = type.IsSubclassOf (TypeManager.value_type);
3403 eclass = ExprClass.Value;
3406 // SRE returns a match for .ctor () on structs (the object constructor),
3407 // so we have to manually ignore it.
3409 if (is_struct && Arguments == null)
3413 ml = MemberLookup (ec, type, ".ctor", false,
3414 MemberTypes.Constructor, AllBindingFlags, loc);
3416 if (! (ml is MethodGroupExpr)){
3418 report118 (loc, ml, "method group");
3424 if (Arguments != null){
3425 for (int i = Arguments.Count; i > 0;){
3427 Argument a = (Argument) Arguments [i];
3429 if (!a.Resolve (ec, loc))
3434 method = Invocation.OverloadResolve (ec, (MethodGroupExpr) ml,
3438 if (method == null && !is_struct) {
3440 "New invocation: Can not find a constructor for " +
3441 "this argument list");
3448 // This DoEmit can be invoked in two contexts:
3449 // * As a mechanism that will leave a value on the stack (new object)
3450 // * As one that wont (init struct)
3452 // You can control whether a value is required on the stack by passing
3453 // need_value_on_stack. The code *might* leave a value on the stack
3454 // so it must be popped manually
3456 // If we are dealing with a ValueType, we have a few
3457 // situations to deal with:
3459 // * The target is a ValueType, and we have been provided
3460 // the instance (this is easy, we are being assigned).
3462 // * The target of New is being passed as an argument,
3463 // to a boxing operation or a function that takes a
3466 // In this case, we need to create a temporary variable
3467 // that is the argument of New.
3469 // Returns whether a value is left on the stack
3471 bool DoEmit (EmitContext ec, bool need_value_on_stack)
3473 if (method == null){
3476 if (value_target == null)
3477 value_target = new LocalTemporary (ec, type);
3479 ml = (IMemoryLocation) value_target;
3482 Invocation.EmitArguments (ec, method, Arguments);
3483 ec.ig.Emit (OpCodes.Newobj, (ConstructorInfo) method);
3488 // It must be a value type, sanity check
3490 if (value_target != null){
3491 ec.ig.Emit (OpCodes.Initobj, type);
3493 if (need_value_on_stack){
3494 value_target.Emit (ec);
3500 throw new Exception ("No method and no value type");
3503 public override void Emit (EmitContext ec)
3508 public override void EmitStatement (EmitContext ec)
3510 if (DoEmit (ec, false))
3511 ec.ig.Emit (OpCodes.Pop);
3516 /// Represents an array creation expression.
3520 /// There are two possible scenarios here: one is an array creation
3521 /// expression that specifies the dimensions and optionally the
3522 /// initialization data and the other which does not need dimensions
3523 /// specified but where initialization data is mandatory.
3525 public class ArrayCreation : ExpressionStatement {
3526 string RequestedType;
3528 ArrayList Initializers;
3530 ArrayList Arguments;
3532 MethodBase method = null;
3533 Type array_element_type;
3534 bool IsOneDimensional = false;
3535 bool IsBuiltinType = false;
3536 bool ExpectInitializers = false;
3539 Type underlying_type;
3541 ArrayList ArrayData;
3545 public ArrayCreation (string requested_type, ArrayList exprs,
3546 string rank, ArrayList initializers, Location l)
3548 RequestedType = requested_type;
3550 Initializers = initializers;
3553 Arguments = new ArrayList ();
3555 foreach (Expression e in exprs)
3556 Arguments.Add (new Argument (e, Argument.AType.Expression));
3560 public ArrayCreation (string requested_type, string rank, ArrayList initializers, Location l)
3562 RequestedType = requested_type;
3563 Initializers = initializers;
3566 Rank = rank.Substring (0, rank.LastIndexOf ("["));
3568 string tmp = rank.Substring (rank.LastIndexOf ("["));
3570 dimensions = tmp.Length - 1;
3571 ExpectInitializers = true;
3574 public static string FormArrayType (string base_type, int idx_count, string rank)
3576 StringBuilder sb = new StringBuilder (base_type);
3581 for (int i = 1; i < idx_count; i++)
3585 return sb.ToString ();
3588 public static string FormElementType (string base_type, int idx_count, string rank)
3590 StringBuilder sb = new StringBuilder (base_type);
3593 for (int i = 1; i < idx_count; i++)
3599 string val = sb.ToString ();
3601 return val.Substring (0, val.LastIndexOf ("["));
3606 Report.Error (178, loc, "Incorrectly structured array initializer");
3609 public bool CheckIndices (EmitContext ec, ArrayList probe, int idx, bool specified_dims)
3611 if (specified_dims) {
3612 Argument a = (Argument) Arguments [idx];
3614 if (!a.Resolve (ec, loc))
3617 if (!(a.Expr is Constant)) {
3618 Report.Error (150, loc, "A constant value is expected");
3622 int value = (int) ((Constant) a.Expr).GetValue ();
3624 if (value != probe.Count) {
3629 Bounds [idx] = value;
3632 foreach (object o in probe) {
3633 if (o is ArrayList) {
3634 bool ret = CheckIndices (ec, (ArrayList) o, idx + 1, specified_dims);
3638 Expression tmp = (Expression) o;
3639 tmp = tmp.Resolve (ec);
3643 // Handle initialization from vars, fields etc.
3645 Expression conv = ConvertImplicitRequired (
3646 ec, tmp, underlying_type, loc);
3651 if (conv is StringConstant)
3652 ArrayData.Add (conv);
3653 else if (conv is Constant)
3654 ArrayData.Add (((Constant) conv).GetValue ());
3656 ArrayData.Add (conv);
3663 public void UpdateIndices (EmitContext ec)
3666 for (ArrayList probe = Initializers; probe != null;) {
3668 if (probe [0] is ArrayList) {
3669 Expression e = new IntConstant (probe.Count);
3670 Arguments.Add (new Argument (e, Argument.AType.Expression));
3672 Bounds [i++] = probe.Count;
3674 probe = (ArrayList) probe [0];
3677 Expression e = new IntConstant (probe.Count);
3678 Arguments.Add (new Argument (e, Argument.AType.Expression));
3680 Bounds [i++] = probe.Count;
3687 public bool ValidateInitializers (EmitContext ec)
3689 if (Initializers == null) {
3690 if (ExpectInitializers)
3696 underlying_type = RootContext.LookupType (
3697 ec.TypeContainer, RequestedType, false, loc);
3700 // We use this to store all the date values in the order in which we
3701 // will need to store them in the byte blob later
3703 ArrayData = new ArrayList ();
3704 Bounds = new Hashtable ();
3708 if (Arguments != null) {
3709 ret = CheckIndices (ec, Initializers, 0, true);
3713 Arguments = new ArrayList ();
3715 ret = CheckIndices (ec, Initializers, 0, false);
3722 if (Arguments.Count != dimensions) {
3731 public override Expression DoResolve (EmitContext ec)
3735 if (!ValidateInitializers (ec))
3738 if (Arguments == null)
3741 arg_count = Arguments.Count;
3742 for (int i = arg_count; i > 0;){
3744 Argument a = (Argument) Arguments [i];
3746 if (!a.Resolve (ec, loc))
3751 string array_type = FormArrayType (RequestedType, arg_count, Rank);
3752 string element_type = FormElementType (RequestedType, arg_count, Rank);
3754 type = RootContext.LookupType (ec.TypeContainer, array_type, false, loc);
3756 array_element_type = RootContext.LookupType (
3757 ec.TypeContainer, element_type, false, loc);
3762 if (arg_count == 1) {
3763 IsOneDimensional = true;
3764 eclass = ExprClass.Value;
3768 IsBuiltinType = TypeManager.IsBuiltinType (type);
3770 if (IsBuiltinType) {
3774 ml = MemberLookup (ec, type, ".ctor", false, MemberTypes.Constructor,
3775 AllBindingFlags, loc);
3777 if (!(ml is MethodGroupExpr)){
3778 report118 (loc, ml, "method group");
3783 Report.Error (-6, loc, "New invocation: Can not find a constructor for " +
3784 "this argument list");
3788 method = Invocation.OverloadResolve (ec, (MethodGroupExpr) ml, Arguments, loc);
3790 if (method == null) {
3791 Report.Error (-6, loc, "New invocation: Can not find a constructor for " +
3792 "this argument list");
3796 eclass = ExprClass.Value;
3800 ModuleBuilder mb = RootContext.ModuleBuilder;
3802 ArrayList args = new ArrayList ();
3803 if (Arguments != null){
3804 for (int i = arg_count; i > 0;){
3806 Argument a = (Argument) Arguments [i];
3812 Type [] arg_types = null;
3815 arg_types = new Type [args.Count];
3817 args.CopyTo (arg_types, 0);
3819 method = mb.GetArrayMethod (type, ".ctor", CallingConventions.HasThis, null,
3822 if (method == null) {
3823 Report.Error (-6, loc, "New invocation: Can not find a constructor for " +
3824 "this argument list");
3828 eclass = ExprClass.Value;
3834 public static byte [] MakeByteBlob (ArrayList ArrayData, Type underlying_type, Location loc)
3839 int count = ArrayData.Count;
3841 if (underlying_type == TypeManager.int32_type ||
3842 underlying_type == TypeManager.uint32_type ||
3843 underlying_type == TypeManager.float_type)
3845 else if (underlying_type == TypeManager.int64_type ||
3846 underlying_type == TypeManager.uint64_type ||
3847 underlying_type == TypeManager.double_type)
3849 else if (underlying_type == TypeManager.byte_type ||
3850 underlying_type == TypeManager.sbyte_type ||
3851 underlying_type == TypeManager.bool_type)
3853 else if (underlying_type == TypeManager.short_type ||
3854 underlying_type == TypeManager.char_type ||
3855 underlying_type == TypeManager.ushort_type)
3858 Report.Error (-100, loc, "Unhandled type in MakeByteBlob!!");
3862 data = new byte [count * factor];
3865 for (int i = 0; i < count; ++i) {
3866 object v = ArrayData [i];
3868 if (v is EnumConstant)
3869 v = ((EnumConstant) v).Child;
3871 if (underlying_type == TypeManager.int64_type ||
3872 underlying_type == TypeManager.uint64_type){
3874 if (!(v is Expression))
3877 for (int j = 0; j < factor; ++j) {
3878 data [idx + j] = (byte) (val & 0xFF);
3881 } else if (underlying_type == TypeManager.float_type) {
3887 if (!(v is Expression))
3890 byte *ptr = (byte *) &val;
3892 for (int j = 0; j < factor; ++j)
3893 data [idx + j] = (byte) ptr [j];
3896 } else if (underlying_type == TypeManager.double_type) {
3902 if (!(v is Expression))
3905 byte *ptr = (byte *) &val;
3907 for (int j = 0; j < factor; ++j)
3908 data [idx + j] = (byte) ptr [j];
3911 } else if (underlying_type == TypeManager.char_type){
3914 if (!(v is Expression))
3915 v = (int) ((char) v);
3917 data [idx] = (byte) (val & 0xff);
3918 data [idx+1] = (byte) (val >> 8);
3920 } else if (underlying_type == TypeManager.int32_type) {
3923 if (!(v is Expression))
3926 data [idx] = (byte) (val & 0xff);
3927 data [idx+1] = (byte) ((val >> 8) & 0xff);
3928 data [idx+2] = (byte) ((val >> 16) & 0xff);
3929 data [idx+3] = (byte) (val >> 24);
3931 throw new Exception ("Unrecognized type in MakeByteBlob");
3940 // Emits the initializers for the array
3942 void EmitStaticInitializers (EmitContext ec, bool is_expression)
3945 // First, the static data
3948 ILGenerator ig = ec.ig;
3950 byte [] data = MakeByteBlob (ArrayData, underlying_type, loc);
3953 fb = RootContext.MakeStaticData (data);
3956 ig.Emit (OpCodes.Dup);
3957 ig.Emit (OpCodes.Ldtoken, fb);
3958 ig.Emit (OpCodes.Call,
3959 TypeManager.void_initializearray_array_fieldhandle);
3964 // Emits pieces of the array that can not be computed at compile
3965 // time (variables and string locations).
3967 // This always expect the top value on the stack to be the array
3969 void EmitDynamicInitializers (EmitContext ec, bool is_expression)
3971 ILGenerator ig = ec.ig;
3972 int dims = Bounds.Count;
3973 int [] current_pos = new int [dims];
3974 int top = ArrayData.Count;
3975 LocalBuilder temp = ig.DeclareLocal (type);
3977 ig.Emit (OpCodes.Stloc, temp);
3979 MethodInfo set = null;
3983 ModuleBuilder mb = null;
3984 mb = RootContext.ModuleBuilder;
3985 args = new Type [dims + 1];
3988 for (j = 0; j < dims; j++)
3989 args [j] = TypeManager.int32_type;
3991 args [j] = array_element_type;
3993 set = mb.GetArrayMethod (
3995 CallingConventions.HasThis | CallingConventions.Standard,
3996 TypeManager.void_type, args);
3999 for (int i = 0; i < top; i++){
4001 Expression e = null;
4003 if (ArrayData [i] is Expression)
4004 e = (Expression) ArrayData [i];
4008 // Basically we do this for string literals and
4009 // other non-literal expressions
4011 if (e is StringConstant || !(e is Constant)) {
4013 ig.Emit (OpCodes.Ldloc, temp);
4015 for (int idx = dims; idx > 0; ) {
4017 IntConstant.EmitInt (ig, current_pos [idx]);
4023 ArrayAccess.EmitStoreOpcode (ig, array_element_type);
4025 ig.Emit (OpCodes.Call, set);
4033 for (int j = 0; j < dims; j++){
4035 if (current_pos [j] < (int) Bounds [j])
4037 current_pos [j] = 0;
4042 ig.Emit (OpCodes.Ldloc, temp);
4045 void DoEmit (EmitContext ec, bool is_statement)
4047 ILGenerator ig = ec.ig;
4049 if (IsOneDimensional) {
4050 Invocation.EmitArguments (ec, null, Arguments);
4051 ig.Emit (OpCodes.Newarr, array_element_type);
4054 Invocation.EmitArguments (ec, null, Arguments);
4057 ig.Emit (OpCodes.Newobj, (ConstructorInfo) method);
4059 ig.Emit (OpCodes.Newobj, (MethodInfo) method);
4062 if (Initializers != null){
4064 // FIXME: Set this variable correctly.
4066 bool dynamic_initializers = true;
4068 if (underlying_type != TypeManager.string_type &&
4069 underlying_type != TypeManager.object_type)
4070 EmitStaticInitializers (ec, dynamic_initializers || !is_statement);
4072 if (dynamic_initializers)
4073 EmitDynamicInitializers (ec, !is_statement);
4077 public override void Emit (EmitContext ec)
4082 public override void EmitStatement (EmitContext ec)
4090 /// Represents the `this' construct
4092 public class This : Expression, IAssignMethod, IMemoryLocation {
4095 public This (Location loc)
4100 public override Expression DoResolve (EmitContext ec)
4102 eclass = ExprClass.Variable;
4103 type = ec.TypeContainer.TypeBuilder;
4106 Report.Error (26, loc,
4107 "Keyword this not valid in static code");
4114 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
4118 if (ec.TypeContainer is Class){
4119 Report.Error (1604, loc, "Cannot assign to `this'");
4126 public override void Emit (EmitContext ec)
4128 ec.ig.Emit (OpCodes.Ldarg_0);
4131 public void EmitAssign (EmitContext ec, Expression source)
4134 ec.ig.Emit (OpCodes.Starg, 0);
4137 public void AddressOf (EmitContext ec)
4139 ec.ig.Emit (OpCodes.Ldarg_0);
4142 // FIGURE OUT WHY LDARG_S does not work
4144 // consider: struct X { int val; int P { set { val = value; }}}
4146 // Yes, this looks very bad. Look at `NOTAS' for
4148 // ec.ig.Emit (OpCodes.Ldarga_S, (byte) 0);
4153 /// Implements the typeof operator
4155 public class TypeOf : Expression {
4156 public readonly string QueriedType;
4160 public TypeOf (string queried_type, Location l)
4162 QueriedType = queried_type;
4166 public override Expression DoResolve (EmitContext ec)
4168 typearg = RootContext.LookupType (
4169 ec.TypeContainer, QueriedType, false, loc);
4171 if (typearg == null)
4174 type = TypeManager.type_type;
4175 eclass = ExprClass.Type;
4179 public override void Emit (EmitContext ec)
4181 ec.ig.Emit (OpCodes.Ldtoken, typearg);
4182 ec.ig.Emit (OpCodes.Call, TypeManager.system_type_get_type_from_handle);
4187 /// Implements the sizeof expression
4189 public class SizeOf : Expression {
4190 public readonly string QueriedType;
4192 public SizeOf (string queried_type)
4194 this.QueriedType = queried_type;
4197 public override Expression DoResolve (EmitContext ec)
4199 // FIXME: Implement;
4200 throw new Exception ("Unimplemented");
4204 public override void Emit (EmitContext ec)
4206 throw new Exception ("Implement me");
4211 /// Implements the member access expression
4213 public class MemberAccess : Expression {
4214 public readonly string Identifier;
4216 Expression member_lookup;
4219 public MemberAccess (Expression expr, string id, Location l)
4226 public Expression Expr {
4232 static void error176 (Location loc, string name)
4234 Report.Error (176, loc, "Static member `" +
4235 name + "' cannot be accessed " +
4236 "with an instance reference, qualify with a " +
4237 "type name instead");
4241 public static Expression ResolveMemberAccess (EmitContext ec, Expression member_lookup,
4242 Expression left, Location loc)
4247 if (member_lookup is MethodGroupExpr){
4248 MethodGroupExpr mg = (MethodGroupExpr) member_lookup;
4250 #if SHOW_METHOD_GROUPS
4251 Console.WriteLine ("Method Groups:");
4252 foreach (MethodInfo mi in mg.Methods){
4253 Console.WriteLine (" " + mi.DeclaringType + "/" + mi.Name +
4261 if (left is TypeExpr){
4262 if (!mg.RemoveInstanceMethods ()){
4263 SimpleName.Error120 (loc, mg.Methods [0].Name);
4267 return member_lookup;
4271 // Instance.MethodGroup
4273 if (!mg.RemoveStaticMethods ()){
4274 error176 (loc, mg.Methods [0].Name);
4278 mg.InstanceExpression = left;
4280 return member_lookup;
4283 if (member_lookup is FieldExpr){
4284 FieldExpr fe = (FieldExpr) member_lookup;
4285 FieldInfo fi = fe.FieldInfo;
4287 if (fi is FieldBuilder) {
4288 Const c = TypeManager.LookupConstant ((FieldBuilder) fi);
4291 object o = c.LookupConstantValue (ec);
4292 return Constantify (o, fi.FieldType);
4297 Type t = fi.FieldType;
4298 Type decl_type = fi.DeclaringType;
4301 if (fi is FieldBuilder)
4302 o = TypeManager.GetValue ((FieldBuilder) fi);
4304 o = fi.GetValue (fi);
4306 if (decl_type.IsSubclassOf (TypeManager.enum_type)) {
4307 Expression enum_member = MemberLookup (ec, decl_type, "value__",
4310 Enum en = TypeManager.LookupEnum (decl_type);
4314 c = Constantify (o, en.UnderlyingType);
4316 c = Constantify (o, enum_member.Type);
4318 return new EnumConstant (c, decl_type);
4321 Expression exp = Constantify (o, t);
4323 if (!(left is TypeExpr)) {
4324 error176 (loc, fe.FieldInfo.Name);
4331 if (left is TypeExpr){
4332 if (!fe.FieldInfo.IsStatic){
4333 error176 (loc, fe.FieldInfo.Name);
4336 return member_lookup;
4338 if (fe.FieldInfo.IsStatic){
4339 error176 (loc, fe.FieldInfo.Name);
4342 fe.InstanceExpression = left;
4348 if (member_lookup is PropertyExpr){
4349 PropertyExpr pe = (PropertyExpr) member_lookup;
4351 if (left is TypeExpr){
4353 SimpleName.Error120 (loc, pe.PropertyInfo.Name);
4359 error176 (loc, pe.PropertyInfo.Name);
4362 pe.InstanceExpression = left;
4368 if (member_lookup is EventExpr) {
4370 EventExpr ee = (EventExpr) member_lookup;
4373 // If the event is local to this class, we transform ourselves into
4377 Expression ml = MemberLookup (ec, ec.TypeContainer.TypeBuilder, ee.EventInfo.Name,
4378 true, MemberTypes.Event, AllBindingFlags, loc);
4381 MemberInfo mi = ec.TypeContainer.GetFieldFromEvent ((EventExpr) ml);
4383 ml = ExprClassFromMemberInfo (ec, mi, loc);
4386 Report.Error (-200, loc, "Internal error!!");
4390 return ResolveMemberAccess (ec, ml, left, loc);
4393 if (left is TypeExpr) {
4395 SimpleName.Error120 (loc, ee.EventInfo.Name);
4403 error176 (loc, ee.EventInfo.Name);
4407 ee.InstanceExpression = left;
4413 if (member_lookup is TypeExpr){
4414 member_lookup.Resolve (ec);
4415 return member_lookup;
4418 Console.WriteLine ("Left is: " + left);
4419 Report.Error (-100, loc, "Support for [" + member_lookup + "] is not present yet");
4420 Environment.Exit (0);
4424 public override Expression DoResolve (EmitContext ec)
4427 // We are the sole users of ResolveWithSimpleName (ie, the only
4428 // ones that can cope with it
4430 expr = expr.ResolveWithSimpleName (ec);
4435 if (expr is SimpleName){
4436 SimpleName child_expr = (SimpleName) expr;
4438 expr = new SimpleName (child_expr.Name + "." + Identifier, loc);
4440 return expr.ResolveWithSimpleName (ec);
4444 // Handle enums here when they are in transit.
4445 // Note that we cannot afford to hit MemberLookup in this case because
4446 // it will fail to find any members at all
4449 Type expr_type = expr.Type;
4450 if (expr_type.IsSubclassOf (TypeManager.enum_type)) {
4452 Enum en = TypeManager.LookupEnum (expr_type);
4455 object value = en.LookupEnumValue (ec, Identifier, loc);
4460 Constant c = Constantify (value, en.UnderlyingType);
4461 return new EnumConstant (c, expr_type);
4465 member_lookup = MemberLookup (ec, expr.Type, Identifier, false, loc);
4467 if (member_lookup == null)
4470 return ResolveMemberAccess (ec, member_lookup, expr, loc);
4476 // This code is more conformant to the spec (it follows it step by step),
4477 // but it has not been tested yet, and there is nothing here that is not
4478 // caught by the above code. But it might be a better foundation to improve
4481 public ResolveTypeMemberAccess (EmitContext ec, Expression member_lookup,
4482 Expression left, Location loc)
4484 if (member_lookup is TypeExpr){
4485 member_lookup.Resolve (ec);
4486 return member_lookup;
4489 if (member_lookup is MethodGroupExpr){
4490 if (!mg.RemoveStaticMethods ()){
4491 SimpleName.Error120 (loc, mg.Methods [0].Name);
4495 return member_lookup;
4498 if (member_lookup is PropertyExpr){
4499 PropertyExpr pe = (PropertyExpr) member_lookup;
4502 SimpleName.Error120 (loc, pe.PropertyInfo.Name);
4508 if (member_lookup is FieldExpr){
4509 FieldExpr fe = (FieldExpr) member_lookup;
4510 FieldInfo fi = fe.FieldInfo;
4512 if (fi is FieldBuilder) {
4513 Const c = TypeManager.LookupConstant ((FieldBuilder) fi);
4516 object o = c.LookupConstantValue (ec);
4517 return Constantify (o, fi.FieldType);
4522 Type t = fi.FieldType;
4523 Type decl_type = fi.DeclaringType;
4526 if (fi is FieldBuilder)
4527 o = TypeManager.GetValue ((FieldBuilder) fi);
4529 o = fi.GetValue (fi);
4531 if (decl_type.IsSubclassOf (TypeManager.enum_type)) {
4532 Expression enum_member = MemberLookup (
4533 ec, decl_type, "value__",
4536 Enum en = TypeManager.LookupEnum (decl_type);
4540 c = Constantify (o, en.UnderlyingType);
4542 c = Constantify (o, enum_member.Type);
4544 return new EnumConstant (c, decl_type);
4547 Expression exp = Constantify (o, t);
4552 if (!fe.FieldInfo.IsStatic){
4553 error176 (loc, fe.FieldInfo.Name);
4556 return member_lookup;
4559 if (member_lookup is EventExpr){
4561 EventExpr ee = (EventExpr) member_lookup;
4564 // If the event is local to this class, we transform ourselves into
4568 Expression ml = MemberLookup (
4569 ec, ec.TypeContainer.TypeBuilder, ee.EventInfo.Name,
4570 true, MemberTypes.Event, AllBindingFlags, loc);
4573 MemberInfo mi = ec.TypeContainer.GetFieldFromEvent ((EventExpr) ml);
4575 ml = ExprClassFromMemberInfo (ec, mi, loc);
4578 Report.Error (-200, loc, "Internal error!!");
4582 return ResolveMemberAccess (ec, ml, left, loc);
4586 SimpleName.Error120 (loc, ee.EventInfo.Name);
4593 Console.WriteLine ("Left is: " + left);
4594 Report.Error (-100, loc, "Support for [" + member_lookup + "] is not present yet");
4595 Environment.Exit (0);
4600 public ResolveInstanceMemberAccess (EmitContext ec, Expression member_lookup,
4601 Expression left, Location loc)
4603 if (member_lookup is MethodGroupExpr){
4605 // Instance.MethodGroup
4607 if (!mg.RemoveStaticMethods ()){
4608 error176 (loc, mg.Methods [0].Name);
4612 mg.InstanceExpression = left;
4614 return member_lookup;
4617 if (member_lookup is PropertyExpr){
4618 PropertyExpr pe = (PropertyExpr) member_lookup;
4621 error176 (loc, pe.PropertyInfo.Name);
4624 pe.InstanceExpression = left;
4629 Type left_type = left.type;
4631 if (left_type.IsValueType){
4637 public override Expression DoResolve (EmitContext ec)
4640 // We are the sole users of ResolveWithSimpleName (ie, the only
4641 // ones that can cope with it
4643 expr = expr.ResolveWithSimpleName (ec);
4648 if (expr is SimpleName){
4649 SimpleName child_expr = (SimpleName) expr;
4651 expr = new SimpleName (child_expr.Name + "." + Identifier, loc);
4653 return expr.ResolveWithSimpleName (ec);
4657 // Handle enums here when they are in transit.
4658 // Note that we cannot afford to hit MemberLookup in this case because
4659 // it will fail to find any members at all (Why?)
4662 Type expr_type = expr.Type;
4663 if (expr_type.IsSubclassOf (TypeManager.enum_type)) {
4665 Enum en = TypeManager.LookupEnum (expr_type);
4668 object value = en.LookupEnumValue (ec, Identifier, loc);
4673 Constant c = Constantify (value, en.UnderlyingType);
4674 return new EnumConstant (c, expr_type);
4678 member_lookup = MemberLookup (ec, expr.Type, Identifier, false, loc);
4680 if (member_lookup == null)
4683 if (expr is TypeExpr)
4684 return ResolveTypeMemberAccess (ec, member_lookup, expr, loc);
4686 return ResolveInstanceMemberAccess (ec, member_lookup, expr, loc);
4689 public override void Emit (EmitContext ec)
4691 throw new Exception ("Should not happen I think");
4696 /// Implements checked expressions
4698 public class CheckedExpr : Expression {
4700 public Expression Expr;
4702 public CheckedExpr (Expression e)
4707 public override Expression DoResolve (EmitContext ec)
4709 Expr = Expr.Resolve (ec);
4714 eclass = Expr.eclass;
4719 public override void Emit (EmitContext ec)
4721 bool last_check = ec.CheckState;
4723 ec.CheckState = true;
4725 ec.CheckState = last_check;
4731 /// Implements the unchecked expression
4733 public class UnCheckedExpr : Expression {
4735 public Expression Expr;
4737 public UnCheckedExpr (Expression e)
4742 public override Expression DoResolve (EmitContext ec)
4744 Expr = Expr.Resolve (ec);
4749 eclass = Expr.eclass;
4754 public override void Emit (EmitContext ec)
4756 bool last_check = ec.CheckState;
4758 ec.CheckState = false;
4760 ec.CheckState = last_check;
4766 /// An Element Access expression.
4768 /// During semantic analysis these are transformed into
4769 /// IndexerAccess or ArrayAccess
4771 public class ElementAccess : Expression {
4772 public ArrayList Arguments;
4773 public Expression Expr;
4774 public Location loc;
4776 public ElementAccess (Expression e, ArrayList e_list, Location l)
4785 Arguments = new ArrayList ();
4786 foreach (Expression tmp in e_list)
4787 Arguments.Add (new Argument (tmp, Argument.AType.Expression));
4791 bool CommonResolve (EmitContext ec)
4793 Expr = Expr.Resolve (ec);
4798 if (Arguments == null)
4801 for (int i = Arguments.Count; i > 0;){
4803 Argument a = (Argument) Arguments [i];
4805 if (!a.Resolve (ec, loc))
4812 public override Expression DoResolve (EmitContext ec)
4814 if (!CommonResolve (ec))
4818 // We perform some simple tests, and then to "split" the emit and store
4819 // code we create an instance of a different class, and return that.
4821 // I am experimenting with this pattern.
4823 if (Expr.Type.IsSubclassOf (TypeManager.array_type))
4824 return (new ArrayAccess (this)).Resolve (ec);
4826 return (new IndexerAccess (this)).Resolve (ec);
4829 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
4831 if (!CommonResolve (ec))
4834 if (Expr.Type.IsSubclassOf (TypeManager.array_type))
4835 return (new ArrayAccess (this)).ResolveLValue (ec, right_side);
4837 return (new IndexerAccess (this)).ResolveLValue (ec, right_side);
4840 public override void Emit (EmitContext ec)
4842 throw new Exception ("Should never be reached");
4847 /// Implements array access
4849 public class ArrayAccess : Expression, IAssignMethod, IMemoryLocation {
4851 // Points to our "data" repository
4855 public ArrayAccess (ElementAccess ea_data)
4858 eclass = ExprClass.Variable;
4861 public override Expression DoResolve (EmitContext ec)
4863 if (ea.Expr.eclass != ExprClass.Variable) {
4864 report118 (ea.loc, ea.Expr, "variable");
4868 Type t = ea.Expr.Type;
4870 if (t.GetArrayRank () != ea.Arguments.Count){
4871 Report.Error (22, ea.loc,
4872 "Incorrect number of indexes for array " +
4873 " expected: " + t.GetArrayRank () + " got: " +
4874 ea.Arguments.Count);
4877 type = t.GetElementType ();
4878 eclass = ExprClass.Variable;
4884 /// Emits the right opcode to load an object of Type `t'
4885 /// from an array of T
4887 static public void EmitLoadOpcode (ILGenerator ig, Type type)
4889 if (type == TypeManager.byte_type)
4890 ig.Emit (OpCodes.Ldelem_I1);
4891 else if (type == TypeManager.sbyte_type)
4892 ig.Emit (OpCodes.Ldelem_U1);
4893 else if (type == TypeManager.short_type)
4894 ig.Emit (OpCodes.Ldelem_I2);
4895 else if (type == TypeManager.ushort_type)
4896 ig.Emit (OpCodes.Ldelem_U2);
4897 else if (type == TypeManager.int32_type)
4898 ig.Emit (OpCodes.Ldelem_I4);
4899 else if (type == TypeManager.uint32_type)
4900 ig.Emit (OpCodes.Ldelem_U4);
4901 else if (type == TypeManager.uint64_type)
4902 ig.Emit (OpCodes.Ldelem_I8);
4903 else if (type == TypeManager.int64_type)
4904 ig.Emit (OpCodes.Ldelem_I8);
4905 else if (type == TypeManager.float_type)
4906 ig.Emit (OpCodes.Ldelem_R4);
4907 else if (type == TypeManager.double_type)
4908 ig.Emit (OpCodes.Ldelem_R8);
4909 else if (type == TypeManager.intptr_type)
4910 ig.Emit (OpCodes.Ldelem_I);
4911 else if (type.IsValueType)
4912 ig.Emit (OpCodes.Ldelema, type);
4914 ig.Emit (OpCodes.Ldelem_Ref);
4918 /// Emits the right opcode to store an object of Type `t'
4919 /// from an array of T.
4921 static public void EmitStoreOpcode (ILGenerator ig, Type t)
4923 if (t == TypeManager.byte_type || t == TypeManager.sbyte_type)
4924 ig.Emit (OpCodes.Stelem_I1);
4925 else if (t == TypeManager.short_type || t == TypeManager.ushort_type)
4926 ig.Emit (OpCodes.Stelem_I2);
4927 else if (t == TypeManager.int32_type || t == TypeManager.uint32_type)
4928 ig.Emit (OpCodes.Stelem_I4);
4929 else if (t == TypeManager.int64_type || t == TypeManager.uint64_type)
4930 ig.Emit (OpCodes.Stelem_I8);
4931 else if (t == TypeManager.float_type)
4932 ig.Emit (OpCodes.Stelem_R4);
4933 else if (t == TypeManager.double_type)
4934 ig.Emit (OpCodes.Stelem_R8);
4935 else if (t == TypeManager.intptr_type)
4936 ig.Emit (OpCodes.Stelem_I);
4938 ig.Emit (OpCodes.Stelem_Ref);
4941 MethodInfo FetchGetMethod ()
4943 ModuleBuilder mb = RootContext.ModuleBuilder;
4944 Type [] args = new Type [ea.Arguments.Count];
4949 foreach (Argument a in ea.Arguments)
4950 args [i++] = a.Type;
4952 get = mb.GetArrayMethod (
4953 ea.Expr.Type, "Get",
4954 CallingConventions.HasThis |
4955 CallingConventions.Standard,
4961 MethodInfo FetchAddressMethod ()
4963 ModuleBuilder mb = RootContext.ModuleBuilder;
4964 Type [] args = new Type [ea.Arguments.Count];
4966 string ptr_type_name;
4970 ptr_type_name = type.FullName + "&";
4971 ret_type = Type.GetType (ptr_type_name);
4974 // It is a type defined by the source code we are compiling
4976 if (ret_type == null){
4977 ret_type = mb.GetType (ptr_type_name);
4980 foreach (Argument a in ea.Arguments)
4981 args [i++] = a.Type;
4983 address = mb.GetArrayMethod (
4984 ea.Expr.Type, "Address",
4985 CallingConventions.HasThis |
4986 CallingConventions.Standard,
4992 public override void Emit (EmitContext ec)
4994 int rank = ea.Expr.Type.GetArrayRank ();
4995 ILGenerator ig = ec.ig;
4999 foreach (Argument a in ea.Arguments)
5003 EmitLoadOpcode (ig, type);
5007 method = FetchGetMethod ();
5008 ig.Emit (OpCodes.Call, method);
5012 public void EmitAssign (EmitContext ec, Expression source)
5014 int rank = ea.Expr.Type.GetArrayRank ();
5015 ILGenerator ig = ec.ig;
5019 foreach (Argument a in ea.Arguments)
5024 Type t = source.Type;
5027 EmitStoreOpcode (ig, t);
5029 ModuleBuilder mb = RootContext.ModuleBuilder;
5030 Type [] args = new Type [ea.Arguments.Count + 1];
5035 foreach (Argument a in ea.Arguments)
5036 args [i++] = a.Type;
5040 set = mb.GetArrayMethod (
5041 ea.Expr.Type, "Set",
5042 CallingConventions.HasThis |
5043 CallingConventions.Standard,
5044 TypeManager.void_type, args);
5046 ig.Emit (OpCodes.Call, set);
5050 public void AddressOf (EmitContext ec)
5052 int rank = ea.Expr.Type.GetArrayRank ();
5053 ILGenerator ig = ec.ig;
5057 foreach (Argument a in ea.Arguments)
5061 ig.Emit (OpCodes.Ldelema, type);
5063 MethodInfo address = FetchAddressMethod ();
5064 ig.Emit (OpCodes.Call, address);
5071 public ArrayList getters, setters;
5072 static Hashtable map;
5076 map = new Hashtable ();
5079 Indexers (MemberInfo [] mi)
5081 foreach (PropertyInfo property in mi){
5082 MethodInfo get, set;
5084 get = property.GetGetMethod (true);
5086 if (getters == null)
5087 getters = new ArrayList ();
5092 set = property.GetSetMethod (true);
5094 if (setters == null)
5095 setters = new ArrayList ();
5101 static public Indexers GetIndexersForType (Type t, TypeManager tm, Location loc)
5103 Indexers ix = (Indexers) map [t];
5104 string p_name = TypeManager.IndexerPropertyName (t);
5109 MemberInfo [] mi = tm.FindMembers (
5110 t, MemberTypes.Property,
5111 BindingFlags.Public | BindingFlags.Instance,
5112 Type.FilterName, p_name);
5114 if (mi == null || mi.Length == 0){
5115 Report.Error (21, loc,
5116 "Type `" + TypeManager.CSharpName (t) + "' does not have " +
5117 "any indexers defined");
5121 ix = new Indexers (mi);
5129 /// Expressions that represent an indexer call.
5131 public class IndexerAccess : Expression, IAssignMethod {
5133 // Points to our "data" repository
5136 MethodInfo get, set;
5138 ArrayList set_arguments;
5140 public IndexerAccess (ElementAccess ea_data)
5143 eclass = ExprClass.Value;
5146 public override Expression DoResolve (EmitContext ec)
5148 Type indexer_type = ea.Expr.Type;
5151 // Step 1: Query for all `Item' *properties*. Notice
5152 // that the actual methods are pointed from here.
5154 // This is a group of properties, piles of them.
5157 ilist = Indexers.GetIndexersForType (
5158 indexer_type, RootContext.TypeManager, ea.loc);
5162 // Step 2: find the proper match
5164 if (ilist != null && ilist.getters != null && ilist.getters.Count > 0)
5165 get = (MethodInfo) Invocation.OverloadResolve (
5166 ec, new MethodGroupExpr (ilist.getters), ea.Arguments, ea.loc);
5169 Report.Error (154, ea.loc,
5170 "indexer can not be used in this context, because " +
5171 "it lacks a `get' accessor");
5175 type = get.ReturnType;
5176 eclass = ExprClass.IndexerAccess;
5180 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
5182 Type indexer_type = ea.Expr.Type;
5183 Type right_type = right_side.Type;
5186 ilist = Indexers.GetIndexersForType (
5187 indexer_type, RootContext.TypeManager, ea.loc);
5189 if (ilist != null && ilist.setters != null && ilist.setters.Count > 0){
5190 set_arguments = (ArrayList) ea.Arguments.Clone ();
5191 set_arguments.Add (new Argument (right_side, Argument.AType.Expression));
5193 set = (MethodInfo) Invocation.OverloadResolve (
5194 ec, new MethodGroupExpr (ilist.setters), set_arguments, ea.loc);
5198 Report.Error (200, ea.loc,
5199 "indexer X.this [" + TypeManager.CSharpName (right_type) +
5200 "] lacks a `set' accessor");
5204 type = TypeManager.void_type;
5205 eclass = ExprClass.IndexerAccess;
5209 public override void Emit (EmitContext ec)
5211 Invocation.EmitCall (ec, false, ea.Expr, get, ea.Arguments);
5215 // source is ignored, because we already have a copy of it from the
5216 // LValue resolution and we have already constructed a pre-cached
5217 // version of the arguments (ea.set_arguments);
5219 public void EmitAssign (EmitContext ec, Expression source)
5221 Invocation.EmitCall (ec, false, ea.Expr, set, set_arguments);
5226 /// The base operator for method names
5228 public class BaseAccess : Expression {
5232 public BaseAccess (string member, Location l)
5234 this.member = member;
5238 public override Expression DoResolve (EmitContext ec)
5240 Expression member_lookup;
5241 Type current_type = ec.TypeContainer.TypeBuilder;
5242 Type base_type = current_type.BaseType;
5244 member_lookup = MemberLookup (ec, base_type, member, false, loc);
5245 if (member_lookup == null)
5251 left = new TypeExpr (base_type);
5253 left = new This (loc).Resolve (ec);
5255 return MemberAccess.ResolveMemberAccess (ec, member_lookup, left, loc);
5258 public override void Emit (EmitContext ec)
5260 throw new Exception ("Should never be called");
5265 /// The base indexer operator
5267 public class BaseIndexerAccess : Expression {
5268 ArrayList Arguments;
5270 public BaseIndexerAccess (ArrayList args)
5275 public override Expression DoResolve (EmitContext ec)
5277 // FIXME: Implement;
5278 throw new Exception ("Unimplemented");
5282 public override void Emit (EmitContext ec)
5284 throw new Exception ("Unimplemented");
5289 /// This class exists solely to pass the Type around and to be a dummy
5290 /// that can be passed to the conversion functions (this is used by
5291 /// foreach implementation to typecast the object return value from
5292 /// get_Current into the proper type. All code has been generated and
5293 /// we only care about the side effect conversions to be performed
5295 public class EmptyExpression : Expression {
5296 public EmptyExpression ()
5298 type = TypeManager.object_type;
5299 eclass = ExprClass.Value;
5302 public EmptyExpression (Type t)
5305 eclass = ExprClass.Value;
5308 public override Expression DoResolve (EmitContext ec)
5313 public override void Emit (EmitContext ec)
5315 // nothing, as we only exist to not do anything.
5319 // This is just because we might want to reuse this bad boy
5320 // instead of creating gazillions of EmptyExpressions.
5321 // (CanConvertImplicit uses it)
5323 public void SetType (Type t)
5329 public class UserCast : Expression {
5333 public UserCast (MethodInfo method, Expression source)
5335 this.method = method;
5336 this.source = source;
5337 type = method.ReturnType;
5338 eclass = ExprClass.Value;
5341 public override Expression DoResolve (EmitContext ec)
5344 // We are born fully resolved
5349 public override void Emit (EmitContext ec)
5351 ILGenerator ig = ec.ig;
5355 if (method is MethodInfo)
5356 ig.Emit (OpCodes.Call, (MethodInfo) method);
5358 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
5365 // This class is used to "construct" the type during a typecast
5366 // operation. Since the Type.GetType class in .NET can parse
5367 // the type specification, we just use this to construct the type
5368 // one bit at a time.
5370 public class ComposedCast : Expression {
5375 public ComposedCast (Expression left, string dim, Location l)
5382 public override Expression DoResolve (EmitContext ec)
5384 left = left.Resolve (ec);
5388 if (left.eclass != ExprClass.Type){
5389 report118 (loc, left, "type");
5393 type = RootContext.LookupType (
5394 ec.TypeContainer, left.Type.FullName + dim, false, loc);
5398 eclass = ExprClass.Type;
5402 public override void Emit (EmitContext ec)
5404 throw new Exception ("This should never be called");