2 // expression.cs: Expression representation for the IL tree.
5 // Miguel de Icaza (miguel@ximian.com)
7 // (C) 2001 Ximian, Inc.
12 namespace Mono.MonoBASIC {
14 using System.Collections;
15 using System.Reflection;
16 using System.Reflection.Emit;
20 /// This is just a helper class, it is generated by Unary, UnaryMutator
21 /// when an overloaded method has been found. It just emits the code for a
24 public class StaticCallExpr : ExpressionStatement {
28 StaticCallExpr (MethodInfo m, ArrayList a, Location l)
34 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, loc);
71 public override void EmitStatement (EmitContext ec)
74 if (TypeManager.TypeToCoreType (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
95 public Expression Expr;
97 public Unary (Operator op, Expression expr, Location loc)
105 /// Returns a stringified representation of the Operator
107 static public string OperName (Operator oper)
110 case Operator.UnaryPlus:
112 case Operator.UnaryNegation:
114 case Operator.LogicalNot:
116 case Operator.OnesComplement:
118 case Operator.AddressOf:
120 case Operator.Indirection:
124 return oper.ToString ();
127 static string [] oper_names;
131 oper_names = new string [(int)Operator.TOP];
133 oper_names [(int) Operator.UnaryPlus] = "op_UnaryPlus";
134 oper_names [(int) Operator.UnaryNegation] = "op_UnaryNegation";
135 oper_names [(int) Operator.LogicalNot] = "op_LogicalNot";
136 oper_names [(int) Operator.OnesComplement] = "op_OnesComplement";
137 oper_names [(int) Operator.Indirection] = "op_Indirection";
138 oper_names [(int) Operator.AddressOf] = "op_AddressOf";
141 void Error23 (Type t)
144 23, "Operator " + OperName (Oper) +
145 " cannot be applied to operand of type '" +
146 TypeManager.MonoBASIC_Name (t) + "'");
150 /// The result has been already resolved:
152 /// FIXME: a minus constant -128 sbyte cant be turned into a
155 static Expression TryReduceNegative (Constant expr)
159 if (expr is IntConstant)
160 e = new IntConstant (-((IntConstant) expr).Value);
161 else if (expr is UIntConstant){
162 uint value = ((UIntConstant) expr).Value;
164 if (value < 2147483649)
165 return new IntConstant (-(int)value);
167 e = new LongConstant (value);
169 else if (expr is LongConstant)
170 e = new LongConstant (-((LongConstant) expr).Value);
171 else if (expr is ULongConstant){
172 ulong value = ((ULongConstant) expr).Value;
174 if (value < 9223372036854775809)
175 return new LongConstant(-(long)value);
177 else if (expr is FloatConstant)
178 e = new FloatConstant (-((FloatConstant) expr).Value);
179 else if (expr is DoubleConstant)
180 e = new DoubleConstant (-((DoubleConstant) expr).Value);
181 else if (expr is DecimalConstant)
182 e = new DecimalConstant (-((DecimalConstant) expr).Value);
183 else if (expr is ShortConstant)
184 e = new IntConstant (-((ShortConstant) expr).Value);
185 else if (expr is UShortConstant)
186 e = new IntConstant (-((UShortConstant) expr).Value);
191 // This routine will attempt to simplify the unary expression when the
192 // argument is a constant. The result is returned in 'result' and the
193 // function returns true or false depending on whether a reduction
194 // was performed or not
196 bool Reduce (EmitContext ec, Constant e, out Expression result)
198 Type expr_type = e.Type;
201 case Operator.UnaryPlus:
205 case Operator.UnaryNegation:
206 result = TryReduceNegative (e);
209 case Operator.LogicalNot:
210 if (expr_type != TypeManager.bool_type) {
216 BoolConstant b = (BoolConstant) e;
217 result = 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)))){
231 if (e is EnumConstant){
232 EnumConstant enum_constant = (EnumConstant) e;
235 if (Reduce (ec, enum_constant.Child, out reduced)){
236 result = new EnumConstant ((Constant) reduced, enum_constant.Type);
244 if (expr_type == TypeManager.int32_type){
245 result = new IntConstant (~ ((IntConstant) e).Value);
246 } else if (expr_type == TypeManager.uint32_type){
247 result = new UIntConstant (~ ((UIntConstant) e).Value);
248 } else if (expr_type == TypeManager.int64_type){
249 result = new LongConstant (~ ((LongConstant) e).Value);
250 } else if (expr_type == TypeManager.uint64_type){
251 result = new ULongConstant (~ ((ULongConstant) e).Value);
259 case Operator.AddressOf:
263 case Operator.Indirection:
267 throw new Exception ("Can not constant fold: " + Oper.ToString());
270 Expression ResolveOperator (EmitContext ec)
272 Type expr_type = Expr.Type;
275 // Step 1: Perform Operator Overload location
280 op_name = oper_names [(int) Oper];
282 mg = MemberLookup (ec, expr_type, op_name, MemberTypes.Method, AllBindingFlags, loc);
285 Expression e = StaticCallExpr.MakeSimpleCall (
286 ec, (MethodGroupExpr) mg, Expr, loc);
296 // Only perform numeric promotions on:
299 if (expr_type == null)
303 // Step 2: Default operations on CLI native types.
306 // Attempt to use a constant folding operation.
307 if (Expr is Constant){
310 if (Reduce (ec, (Constant) Expr, out result))
315 case Operator.LogicalNot:
316 if (expr_type != TypeManager.bool_type) {
321 type = TypeManager.bool_type;
324 case Operator.OnesComplement:
325 if (!((expr_type == TypeManager.int32_type) ||
326 (expr_type == TypeManager.uint32_type) ||
327 (expr_type == TypeManager.int64_type) ||
328 (expr_type == TypeManager.uint64_type) ||
329 (expr_type.IsSubclassOf (TypeManager.enum_type)))){
332 e = ConvertImplicit (ec, Expr, TypeManager.int32_type, loc);
334 type = TypeManager.int32_type;
337 e = ConvertImplicit (ec, Expr, TypeManager.uint32_type, loc);
339 type = TypeManager.uint32_type;
342 e = ConvertImplicit (ec, Expr, TypeManager.int64_type, loc);
344 type = TypeManager.int64_type;
347 e = ConvertImplicit (ec, Expr, TypeManager.uint64_type, loc);
349 type = TypeManager.uint64_type;
358 case Operator.AddressOf:
359 if (Expr.eclass != ExprClass.Variable){
360 Error (211, "Cannot take the address of non-variables");
369 if (!TypeManager.VerifyUnManaged (Expr.Type, loc)){
373 string ptr_type_name = Expr.Type.FullName + "*";
374 type = TypeManager.LookupType (ptr_type_name);
378 case Operator.Indirection:
384 if (!expr_type.IsPointer){
387 "The * or -> operator can only be applied to pointers");
392 // We create an Indirection expression, because
393 // it can implement the IMemoryLocation.
395 return new Indirection (Expr, loc);
397 case Operator.UnaryPlus:
399 // A plus in front of something is just a no-op, so return the child.
403 case Operator.UnaryNegation:
405 // Deals with -literals
406 // int operator- (int x)
407 // long operator- (long x)
408 // float operator- (float f)
409 // double operator- (double d)
410 // decimal operator- (decimal d)
412 Expression expr = null;
415 // transform - - expr into expr
418 Unary unary = (Unary) Expr;
420 if (unary.Oper == Operator.UnaryNegation)
425 // perform numeric promotions to int,
429 // The following is inneficient, because we call
430 // ConvertImplicit too many times.
432 // It is also not clear if we should convert to Float
433 // or Double initially.
435 if (expr_type == TypeManager.uint32_type){
437 // FIXME: handle exception to this rule that
438 // permits the int value -2147483648 (-2^31) to
439 // bt wrote as a decimal interger literal
441 type = TypeManager.int64_type;
442 Expr = ConvertImplicit (ec, Expr, type, loc);
446 if (expr_type == TypeManager.uint64_type){
448 // FIXME: Handle exception of 'long value'
449 // -92233720368547758087 (-2^63) to be wrote as
450 // decimal integer literal.
456 if (expr_type == TypeManager.float_type){
461 expr = ConvertImplicit (ec, Expr, TypeManager.int32_type, loc);
468 expr = ConvertImplicit (ec, Expr, TypeManager.int64_type, loc);
475 expr = ConvertImplicit (ec, Expr, TypeManager.double_type, loc);
486 Error (187, "No such operator '" + OperName (Oper) + "' defined for type '" +
487 TypeManager.MonoBASIC_Name (expr_type) + "'");
491 public override Expression DoResolve (EmitContext ec)
493 if (Oper == Operator.AddressOf)
494 Expr = Expr.ResolveLValue (ec, new EmptyExpression ());
496 Expr = Expr.Resolve (ec);
501 eclass = ExprClass.Value;
502 return ResolveOperator (ec);
505 public override void Emit (EmitContext ec)
507 ILGenerator ig = ec.ig;
508 Type expr_type = Expr.Type;
511 case Operator.UnaryPlus:
512 throw new Exception ("This should be caught by Resolve");
514 case Operator.UnaryNegation:
516 ig.Emit (OpCodes.Neg);
519 case Operator.LogicalNot:
521 ig.Emit (OpCodes.Ldc_I4_0);
522 ig.Emit (OpCodes.Ceq);
525 case Operator.OnesComplement:
527 ig.Emit (OpCodes.Not);
530 case Operator.AddressOf:
531 ((IMemoryLocation)Expr).AddressOf (ec, AddressOp.LoadStore);
535 throw new Exception ("This should not happen: Operator = "
541 /// This will emit the child expression for 'ec' avoiding the logical
542 /// not. The parent will take care of changing brfalse/brtrue
544 public void EmitLogicalNot (EmitContext ec)
546 if (Oper != Operator.LogicalNot)
547 throw new Exception ("EmitLogicalNot can only be called with !expr");
552 public override string ToString ()
554 return "Unary (" + Oper + ", " + Expr + ")";
560 // Unary operators are turned into Indirection expressions
561 // after semantic analysis (this is so we can take the address
562 // of an indirection).
564 public class Indirection : Expression, IMemoryLocation, IAssignMethod {
566 LocalTemporary temporary;
569 public Indirection (Expression expr, Location l)
572 this.type = TypeManager.TypeToCoreType (expr.Type.GetElementType ());
573 eclass = ExprClass.Variable;
577 void LoadExprValue (EmitContext ec)
581 public override void Emit (EmitContext ec)
583 ILGenerator ig = ec.ig;
585 if (temporary != null){
591 ec.ig.Emit (OpCodes.Dup);
592 temporary.Store (ec);
593 have_temporary = true;
597 LoadFromPtr (ig, Type);
600 public void EmitAssign (EmitContext ec, Expression source)
602 if (temporary != null){
608 ec.ig.Emit (OpCodes.Dup);
609 temporary.Store (ec);
610 have_temporary = true;
615 StoreFromPtr (ec.ig, type);
618 public void AddressOf (EmitContext ec, AddressOp Mode)
620 if (temporary != null){
626 ec.ig.Emit (OpCodes.Dup);
627 temporary.Store (ec);
628 have_temporary = true;
633 public override Expression DoResolve (EmitContext ec)
636 // Born fully resolved
641 public new void CacheTemporaries (EmitContext ec)
643 temporary = new LocalTemporary (ec, type);
648 /// Unary Mutator expressions (pre and post ++ and --)
652 /// UnaryMutator implements ++ and -- expressions. It derives from
653 /// ExpressionStatement becuase the pre/post increment/decrement
654 /// operators can be used in a statement context.
656 /// FIXME: Idea, we could split this up in two classes, one simpler
657 /// for the common case, and one with the extra fields for more complex
658 /// classes (indexers require temporary access; overloaded require method)
660 /// Maybe we should have classes PreIncrement, PostIncrement, PreDecrement,
661 /// PostDecrement, that way we could save the 'Mode' byte as well.
663 public class UnaryMutator : ExpressionStatement {
664 public enum Mode : byte {
665 PreIncrement, PreDecrement, PostIncrement, PostDecrement
670 LocalTemporary temp_storage;
673 // This is expensive for the simplest case.
677 public UnaryMutator (Mode m, Expression e, Location l)
684 static string OperName (Mode mode)
686 return (mode == Mode.PreIncrement || mode == Mode.PostIncrement) ?
690 void Error23 (Type t)
693 23, "Operator " + OperName (mode) +
694 " cannot be applied to operand of type '" +
695 TypeManager.MonoBASIC_Name (t) + "'");
699 /// Returns whether an object of type 't' can be incremented
700 /// or decremented with add/sub (ie, basically whether we can
701 /// use pre-post incr-decr operations on it, but it is not a
702 /// System.Decimal, which we require operator overloading to catch)
704 static bool IsIncrementableNumber (Type t)
706 return (t == TypeManager.sbyte_type) ||
707 (t == TypeManager.byte_type) ||
708 (t == TypeManager.short_type) ||
709 (t == TypeManager.ushort_type) ||
710 (t == TypeManager.int32_type) ||
711 (t == TypeManager.uint32_type) ||
712 (t == TypeManager.int64_type) ||
713 (t == TypeManager.uint64_type) ||
714 (t == TypeManager.char_type) ||
715 (t.IsSubclassOf (TypeManager.enum_type)) ||
716 (t == TypeManager.float_type) ||
717 (t == TypeManager.double_type) ||
718 (t.IsPointer && t != TypeManager.void_ptr_type);
721 Expression ResolveOperator (EmitContext ec)
723 Type expr_type = expr.Type;
726 // Step 1: Perform Operator Overload location
731 if (mode == Mode.PreIncrement || mode == Mode.PostIncrement)
732 op_name = "op_Increment";
734 op_name = "op_Decrement";
736 mg = MemberLookup (ec, expr_type, op_name, MemberTypes.Method, AllBindingFlags, loc);
738 if (mg == null && expr_type.BaseType != null)
739 mg = MemberLookup (ec, expr_type.BaseType, op_name,
740 MemberTypes.Method, AllBindingFlags, loc);
743 method = StaticCallExpr.MakeSimpleCall (
744 ec, (MethodGroupExpr) mg, expr, loc);
751 // The operand of the prefix/postfix increment decrement operators
752 // should be an expression that is classified as a variable,
753 // a property access or an indexer access
756 if (expr.eclass == ExprClass.Variable){
757 if (IsIncrementableNumber (expr_type) ||
758 expr_type == TypeManager.decimal_type){
761 } else if (expr.eclass == ExprClass.IndexerAccess){
762 IndexerAccess ia = (IndexerAccess) expr;
764 temp_storage = new LocalTemporary (ec, expr.Type);
766 expr = ia.ResolveLValue (ec, temp_storage);
771 } else if (expr.eclass == ExprClass.PropertyAccess){
772 PropertyExpr pe = (PropertyExpr) expr;
774 if (pe.VerifyAssignable ())
779 expr.Error118 ("variable, indexer or property access");
783 Error (187, "No such operator '" + OperName (mode) + "' defined for type '" +
784 TypeManager.MonoBASIC_Name (expr_type) + "'");
788 public override Expression DoResolve (EmitContext ec)
790 expr = expr.Resolve (ec);
795 eclass = ExprClass.Value;
796 return ResolveOperator (ec);
799 static int PtrTypeSize (Type t)
801 return GetTypeSize (t.GetElementType ());
805 // Loads the proper "1" into the stack based on the type
807 static void LoadOne (ILGenerator ig, Type t)
809 if (t == TypeManager.uint64_type || t == TypeManager.int64_type)
810 ig.Emit (OpCodes.Ldc_I8, 1L);
811 else if (t == TypeManager.double_type)
812 ig.Emit (OpCodes.Ldc_R8, 1.0);
813 else if (t == TypeManager.float_type)
814 ig.Emit (OpCodes.Ldc_R4, 1.0F);
815 else if (t.IsPointer){
816 int n = PtrTypeSize (t);
819 ig.Emit (OpCodes.Sizeof, t);
821 IntConstant.EmitInt (ig, n);
823 ig.Emit (OpCodes.Ldc_I4_1);
828 // FIXME: We need some way of avoiding the use of temp_storage
829 // for some types of storage (parameters, local variables,
830 // static fields) and single-dimension array access.
832 void EmitCode (EmitContext ec, bool is_expr)
834 ILGenerator ig = ec.ig;
835 IAssignMethod ia = (IAssignMethod) expr;
836 Type expr_type = expr.Type;
838 if (temp_storage == null)
839 temp_storage = new LocalTemporary (ec, expr_type);
841 ia.CacheTemporaries (ec);
842 ig.Emit (OpCodes.Nop);
844 case Mode.PreIncrement:
845 case Mode.PreDecrement:
849 LoadOne (ig, expr_type);
852 // Select the opcode based on the check state (then the type)
853 // and the actual operation
856 if (expr_type == TypeManager.int32_type ||
857 expr_type == TypeManager.int64_type){
858 if (mode == Mode.PreDecrement)
859 ig.Emit (OpCodes.Sub_Ovf);
861 ig.Emit (OpCodes.Add_Ovf);
862 } else if (expr_type == TypeManager.uint32_type ||
863 expr_type == TypeManager.uint64_type){
864 if (mode == Mode.PreDecrement)
865 ig.Emit (OpCodes.Sub_Ovf_Un);
867 ig.Emit (OpCodes.Add_Ovf_Un);
869 if (mode == Mode.PreDecrement)
870 ig.Emit (OpCodes.Sub_Ovf);
872 ig.Emit (OpCodes.Add_Ovf);
875 if (mode == Mode.PreDecrement)
876 ig.Emit (OpCodes.Sub);
878 ig.Emit (OpCodes.Add);
883 temp_storage.Store (ec);
884 ia.EmitAssign (ec, temp_storage);
886 temp_storage.Emit (ec);
889 case Mode.PostIncrement:
890 case Mode.PostDecrement:
898 ig.Emit (OpCodes.Dup);
900 LoadOne (ig, expr_type);
903 if (expr_type == TypeManager.int32_type ||
904 expr_type == TypeManager.int64_type){
905 if (mode == Mode.PostDecrement)
906 ig.Emit (OpCodes.Sub_Ovf);
908 ig.Emit (OpCodes.Add_Ovf);
909 } else if (expr_type == TypeManager.uint32_type ||
910 expr_type == TypeManager.uint64_type){
911 if (mode == Mode.PostDecrement)
912 ig.Emit (OpCodes.Sub_Ovf_Un);
914 ig.Emit (OpCodes.Add_Ovf_Un);
916 if (mode == Mode.PostDecrement)
917 ig.Emit (OpCodes.Sub_Ovf);
919 ig.Emit (OpCodes.Add_Ovf);
922 if (mode == Mode.PostDecrement)
923 ig.Emit (OpCodes.Sub);
925 ig.Emit (OpCodes.Add);
931 temp_storage.Store (ec);
932 ia.EmitAssign (ec, temp_storage);
937 public override void Emit (EmitContext ec)
943 public override void EmitStatement (EmitContext ec)
945 EmitCode (ec, false);
951 /// Base class for the 'Is' and 'As' classes.
955 /// FIXME: Split this in two, and we get to save the 'Operator' Oper
958 public abstract class Probe : Expression {
959 public readonly Expression ProbeType;
960 protected Expression expr;
961 protected Type probe_type;
963 public Probe (Expression expr, Expression probe_type, Location l)
965 ProbeType = probe_type;
970 public Expression Expr {
976 public override Expression DoResolve (EmitContext ec)
978 probe_type = ec.DeclSpace.ResolveType (ProbeType, false, loc);
980 if (probe_type == null)
983 expr = expr.Resolve (ec);
990 /// Implementation of the 'is' operator.
992 public class Is : Probe {
993 public Is (Expression expr, Expression probe_type, Location l)
994 : base (expr, probe_type, l)
999 AlwaysTrue, AlwaysNull, AlwaysFalse, LeaveOnStack, Probe
1004 public override void Emit (EmitContext ec)
1006 ILGenerator ig = ec.ig;
1011 case Action.AlwaysFalse:
1012 ig.Emit (OpCodes.Pop);
1013 IntConstant.EmitInt (ig, 0);
1015 case Action.AlwaysTrue:
1016 ig.Emit (OpCodes.Pop);
1017 ig.Emit (OpCodes.Nop);
1018 IntConstant.EmitInt (ig, 1);
1020 case Action.LeaveOnStack:
1021 // the 'e != null' rule.
1024 ig.Emit (OpCodes.Isinst, probe_type);
1025 ig.Emit (OpCodes.Ldnull);
1026 ig.Emit (OpCodes.Cgt_Un);
1029 throw new Exception ("never reached");
1032 public override Expression DoResolve (EmitContext ec)
1034 Expression e = base.DoResolve (ec);
1036 if ((e == null) || (expr == null))
1039 Type etype = expr.Type;
1040 bool warning_always_matches = false;
1041 bool warning_never_matches = false;
1043 type = TypeManager.bool_type;
1044 eclass = ExprClass.Value;
1047 // First case, if at compile time, there is an implicit conversion
1048 // then e != null (objects) or true (value types)
1050 e = ConvertImplicitStandard (ec, expr, probe_type, loc);
1053 if (etype.IsValueType)
1054 action = Action.AlwaysTrue;
1056 action = Action.LeaveOnStack;
1058 warning_always_matches = true;
1059 } else if (ExplicitReferenceConversionExists (etype, probe_type)){
1061 // Second case: explicit reference convresion
1063 if (expr is NullLiteral)
1064 action = Action.AlwaysFalse;
1066 action = Action.Probe;
1068 action = Action.AlwaysFalse;
1069 warning_never_matches = true;
1072 if (RootContext.WarningLevel >= 1){
1073 if (warning_always_matches)
1076 "The expression is always of type '" +
1077 TypeManager.MonoBASIC_Name (probe_type) + "'");
1078 else if (warning_never_matches){
1079 if (!(probe_type.IsInterface || expr.Type.IsInterface))
1082 "The expression is never of type '" +
1083 TypeManager.MonoBASIC_Name (probe_type) + "'");
1092 /// Implementation of the 'as' operator.
1094 public class As : Probe {
1095 public As (Expression expr, Expression probe_type, Location l)
1096 : base (expr, probe_type, l)
1100 bool do_isinst = false;
1102 public override void Emit (EmitContext ec)
1104 ILGenerator ig = ec.ig;
1109 ig.Emit (OpCodes.Isinst, probe_type);
1112 static void Error_CannotConvertType (Type source, Type target, Location loc)
1115 39, loc, "as operator can not convert from '" +
1116 TypeManager.MonoBASIC_Name (source) + "' to '" +
1117 TypeManager.MonoBASIC_Name (target) + "'");
1120 public override Expression DoResolve (EmitContext ec)
1122 Expression e = base.DoResolve (ec);
1128 eclass = ExprClass.Value;
1129 Type etype = expr.Type;
1131 if (TypeManager.IsValueType (probe_type)){
1132 Report.Error (77, loc, "The as operator should be used with a reference type only (" +
1133 TypeManager.MonoBASIC_Name (probe_type) + " is a value type)");
1138 e = ConvertImplicit (ec, expr, probe_type, loc);
1145 if (ExplicitReferenceConversionExists (etype, probe_type)){
1150 Error_CannotConvertType (etype, probe_type, loc);
1156 /// This represents a typecast in the source language.
1158 /// FIXME: Cast expressions have an unusual set of parsing
1159 /// rules, we need to figure those out.
1161 public class Cast : Expression {
1162 Expression target_type;
1166 public Cast (Expression cast_type, Expression expr, Location loc)
1168 this.target_type = cast_type;
1171 runtime_cast = false;
1174 public Expression TargetType {
1180 public Expression Expr {
1189 public bool IsRuntimeCast
1192 return runtime_cast;
1195 runtime_cast = value;
1200 /// Attempts to do a compile-time folding of a constant cast.
1202 Expression TryReduce (EmitContext ec, Type target_type)
1204 if (expr is ByteConstant){
1205 byte v = ((ByteConstant) expr).Value;
1207 if (target_type == TypeManager.sbyte_type)
1208 return new SByteConstant ((sbyte) v);
1209 if (target_type == TypeManager.short_type)
1210 return new ShortConstant ((short) v);
1211 if (target_type == TypeManager.ushort_type)
1212 return new UShortConstant ((ushort) v);
1213 if (target_type == TypeManager.int32_type)
1214 return new IntConstant ((int) v);
1215 if (target_type == TypeManager.uint32_type)
1216 return new UIntConstant ((uint) v);
1217 if (target_type == TypeManager.int64_type)
1218 return new LongConstant ((long) v);
1219 if (target_type == TypeManager.uint64_type)
1220 return new ULongConstant ((ulong) v);
1221 if (target_type == TypeManager.float_type)
1222 return new FloatConstant ((float) v);
1223 if (target_type == TypeManager.double_type)
1224 return new DoubleConstant ((double) v);
1225 if (target_type == TypeManager.char_type)
1226 return new CharConstant ((char) v);
1227 if (target_type == TypeManager.decimal_type)
1228 return new DecimalConstant ((decimal) v);
1230 if (expr is SByteConstant){
1231 sbyte v = ((SByteConstant) expr).Value;
1233 if (target_type == TypeManager.byte_type)
1234 return new ByteConstant ((byte) v);
1235 if (target_type == TypeManager.short_type)
1236 return new ShortConstant ((short) v);
1237 if (target_type == TypeManager.ushort_type)
1238 return new UShortConstant ((ushort) v);
1239 if (target_type == TypeManager.int32_type)
1240 return new IntConstant ((int) v);
1241 if (target_type == TypeManager.uint32_type)
1242 return new UIntConstant ((uint) v);
1243 if (target_type == TypeManager.int64_type)
1244 return new LongConstant ((long) v);
1245 if (target_type == TypeManager.uint64_type)
1246 return new ULongConstant ((ulong) v);
1247 if (target_type == TypeManager.float_type)
1248 return new FloatConstant ((float) v);
1249 if (target_type == TypeManager.double_type)
1250 return new DoubleConstant ((double) v);
1251 if (target_type == TypeManager.char_type)
1252 return new CharConstant ((char) v);
1253 if (target_type == TypeManager.decimal_type)
1254 return new DecimalConstant ((decimal) v);
1256 if (expr is ShortConstant){
1257 short v = ((ShortConstant) expr).Value;
1259 if (target_type == TypeManager.byte_type)
1260 return new ByteConstant ((byte) v);
1261 if (target_type == TypeManager.sbyte_type)
1262 return new SByteConstant ((sbyte) v);
1263 if (target_type == TypeManager.ushort_type)
1264 return new UShortConstant ((ushort) v);
1265 if (target_type == TypeManager.int32_type)
1266 return new IntConstant ((int) v);
1267 if (target_type == TypeManager.uint32_type)
1268 return new UIntConstant ((uint) v);
1269 if (target_type == TypeManager.int64_type)
1270 return new LongConstant ((long) v);
1271 if (target_type == TypeManager.uint64_type)
1272 return new ULongConstant ((ulong) v);
1273 if (target_type == TypeManager.float_type)
1274 return new FloatConstant ((float) v);
1275 if (target_type == TypeManager.double_type)
1276 return new DoubleConstant ((double) v);
1277 if (target_type == TypeManager.char_type)
1278 return new CharConstant ((char) v);
1279 if (target_type == TypeManager.decimal_type)
1280 return new DecimalConstant ((decimal) v);
1282 if (expr is UShortConstant){
1283 ushort v = ((UShortConstant) expr).Value;
1285 if (target_type == TypeManager.byte_type)
1286 return new ByteConstant ((byte) v);
1287 if (target_type == TypeManager.sbyte_type)
1288 return new SByteConstant ((sbyte) v);
1289 if (target_type == TypeManager.short_type)
1290 return new ShortConstant ((short) v);
1291 if (target_type == TypeManager.int32_type)
1292 return new IntConstant ((int) v);
1293 if (target_type == TypeManager.uint32_type)
1294 return new UIntConstant ((uint) v);
1295 if (target_type == TypeManager.int64_type)
1296 return new LongConstant ((long) v);
1297 if (target_type == TypeManager.uint64_type)
1298 return new ULongConstant ((ulong) v);
1299 if (target_type == TypeManager.float_type)
1300 return new FloatConstant ((float) v);
1301 if (target_type == TypeManager.double_type)
1302 return new DoubleConstant ((double) v);
1303 if (target_type == TypeManager.char_type)
1304 return new CharConstant ((char) v);
1305 if (target_type == TypeManager.decimal_type)
1306 return new DecimalConstant ((decimal) v);
1308 if (expr is IntConstant){
1309 int v = ((IntConstant) expr).Value;
1311 if (target_type == TypeManager.byte_type)
1312 return new ByteConstant ((byte) v);
1313 if (target_type == TypeManager.sbyte_type)
1314 return new SByteConstant ((sbyte) v);
1315 if (target_type == TypeManager.short_type)
1316 return new ShortConstant ((short) v);
1317 if (target_type == TypeManager.ushort_type)
1318 return new UShortConstant ((ushort) v);
1319 if (target_type == TypeManager.uint32_type)
1320 return new UIntConstant ((uint) v);
1321 if (target_type == TypeManager.int64_type)
1322 return new LongConstant ((long) v);
1323 if (target_type == TypeManager.uint64_type)
1324 return new ULongConstant ((ulong) v);
1325 if (target_type == TypeManager.float_type)
1326 return new FloatConstant ((float) v);
1327 if (target_type == TypeManager.double_type)
1328 return new DoubleConstant ((double) v);
1329 if (target_type == TypeManager.char_type)
1330 return new CharConstant ((char) v);
1331 if (target_type == TypeManager.decimal_type)
1332 return new DecimalConstant ((decimal) v);
1334 if (expr is UIntConstant){
1335 uint v = ((UIntConstant) expr).Value;
1337 if (target_type == TypeManager.byte_type)
1338 return new ByteConstant ((byte) v);
1339 if (target_type == TypeManager.sbyte_type)
1340 return new SByteConstant ((sbyte) v);
1341 if (target_type == TypeManager.short_type)
1342 return new ShortConstant ((short) v);
1343 if (target_type == TypeManager.ushort_type)
1344 return new UShortConstant ((ushort) v);
1345 if (target_type == TypeManager.int32_type)
1346 return new IntConstant ((int) v);
1347 if (target_type == TypeManager.int64_type)
1348 return new LongConstant ((long) v);
1349 if (target_type == TypeManager.uint64_type)
1350 return new ULongConstant ((ulong) v);
1351 if (target_type == TypeManager.float_type)
1352 return new FloatConstant ((float) v);
1353 if (target_type == TypeManager.double_type)
1354 return new DoubleConstant ((double) v);
1355 if (target_type == TypeManager.char_type)
1356 return new CharConstant ((char) v);
1357 if (target_type == TypeManager.decimal_type)
1358 return new DecimalConstant ((decimal) v);
1360 if (expr is LongConstant){
1361 long v = ((LongConstant) expr).Value;
1363 if (target_type == TypeManager.byte_type)
1364 return new ByteConstant ((byte) v);
1365 if (target_type == TypeManager.sbyte_type)
1366 return new SByteConstant ((sbyte) v);
1367 if (target_type == TypeManager.short_type)
1368 return new ShortConstant ((short) v);
1369 if (target_type == TypeManager.ushort_type)
1370 return new UShortConstant ((ushort) v);
1371 if (target_type == TypeManager.int32_type)
1372 return new IntConstant ((int) v);
1373 if (target_type == TypeManager.uint32_type)
1374 return new UIntConstant ((uint) v);
1375 if (target_type == TypeManager.uint64_type)
1376 return new ULongConstant ((ulong) v);
1377 if (target_type == TypeManager.float_type)
1378 return new FloatConstant ((float) v);
1379 if (target_type == TypeManager.double_type)
1380 return new DoubleConstant ((double) v);
1381 if (target_type == TypeManager.char_type)
1382 return new CharConstant ((char) v);
1383 if (target_type == TypeManager.decimal_type)
1384 return new DecimalConstant ((decimal) v);
1386 if (expr is ULongConstant){
1387 ulong v = ((ULongConstant) expr).Value;
1389 if (target_type == TypeManager.byte_type)
1390 return new ByteConstant ((byte) v);
1391 if (target_type == TypeManager.sbyte_type)
1392 return new SByteConstant ((sbyte) v);
1393 if (target_type == TypeManager.short_type)
1394 return new ShortConstant ((short) v);
1395 if (target_type == TypeManager.ushort_type)
1396 return new UShortConstant ((ushort) v);
1397 if (target_type == TypeManager.int32_type)
1398 return new IntConstant ((int) v);
1399 if (target_type == TypeManager.uint32_type)
1400 return new UIntConstant ((uint) v);
1401 if (target_type == TypeManager.int64_type)
1402 return new LongConstant ((long) v);
1403 if (target_type == TypeManager.float_type)
1404 return new FloatConstant ((float) v);
1405 if (target_type == TypeManager.double_type)
1406 return new DoubleConstant ((double) v);
1407 if (target_type == TypeManager.char_type)
1408 return new CharConstant ((char) v);
1409 if (target_type == TypeManager.decimal_type)
1410 return new DecimalConstant ((decimal) v);
1412 if (expr is FloatConstant){
1413 float v = ((FloatConstant) expr).Value;
1415 if (target_type == TypeManager.byte_type)
1416 return new ByteConstant ((byte) v);
1417 if (target_type == TypeManager.sbyte_type)
1418 return new SByteConstant ((sbyte) v);
1419 if (target_type == TypeManager.short_type)
1420 return new ShortConstant ((short) v);
1421 if (target_type == TypeManager.ushort_type)
1422 return new UShortConstant ((ushort) v);
1423 if (target_type == TypeManager.int32_type)
1424 return new IntConstant ((int) v);
1425 if (target_type == TypeManager.uint32_type)
1426 return new UIntConstant ((uint) v);
1427 if (target_type == TypeManager.int64_type)
1428 return new LongConstant ((long) v);
1429 if (target_type == TypeManager.uint64_type)
1430 return new ULongConstant ((ulong) v);
1431 if (target_type == TypeManager.double_type)
1432 return new DoubleConstant ((double) v);
1433 if (target_type == TypeManager.char_type)
1434 return new CharConstant ((char) v);
1435 if (target_type == TypeManager.decimal_type)
1436 return new DecimalConstant ((decimal) v);
1438 if (expr is DoubleConstant){
1439 double v = ((DoubleConstant) expr).Value;
1441 if (target_type == TypeManager.byte_type)
1442 return new ByteConstant ((byte) v);
1443 if (target_type == TypeManager.sbyte_type)
1444 return new SByteConstant ((sbyte) v);
1445 if (target_type == TypeManager.short_type)
1446 return new ShortConstant ((short) v);
1447 if (target_type == TypeManager.ushort_type)
1448 return new UShortConstant ((ushort) v);
1449 if (target_type == TypeManager.int32_type)
1450 return new IntConstant ((int) v);
1451 if (target_type == TypeManager.uint32_type)
1452 return new UIntConstant ((uint) v);
1453 if (target_type == TypeManager.int64_type)
1454 return new LongConstant ((long) v);
1455 if (target_type == TypeManager.uint64_type)
1456 return new ULongConstant ((ulong) v);
1457 if (target_type == TypeManager.float_type)
1458 return new FloatConstant ((float) v);
1459 if (target_type == TypeManager.char_type)
1460 return new CharConstant ((char) v);
1461 if (target_type == TypeManager.decimal_type)
1462 return new DecimalConstant ((decimal) v);
1468 public override Expression DoResolve (EmitContext ec)
1470 expr = expr.Resolve (ec);
1474 int errors = Report.Errors;
1476 type = ec.DeclSpace.ResolveType (target_type, false, Location);
1481 eclass = ExprClass.Value;
1483 if (expr is Constant){
1484 Expression e = TryReduce (ec, type);
1490 expr = ConvertExplicit (ec, expr, type, runtime_cast, loc);
1494 public override void Emit (EmitContext ec)
1497 // This one will never happen
1499 throw new Exception ("Should not happen");
1504 /// Binary operators
1506 public class Binary : Expression {
1507 public enum Operator : byte {
1508 Multiply, Division, Modulus,
1509 Addition, Subtraction,
1510 LeftShift, RightShift,
1511 LessThan, GreaterThan, LessThanOrEqual, GreaterThanOrEqual,
1512 Equality, Inequality,
1522 Expression left, right;
1525 // After resolution, method might contain the operator overload
1528 protected MethodBase method;
1529 ArrayList Arguments;
1531 bool DelegateOperation;
1533 // This must be kept in sync with Operator!!!
1534 static string [] oper_names;
1538 oper_names = new string [(int) Operator.TOP];
1540 oper_names [(int) Operator.Multiply] = "op_Multiply";
1541 oper_names [(int) Operator.Division] = "op_Division";
1542 oper_names [(int) Operator.Modulus] = "op_Modulus";
1543 oper_names [(int) Operator.Addition] = "op_Addition";
1544 oper_names [(int) Operator.Subtraction] = "op_Subtraction";
1545 oper_names [(int) Operator.LeftShift] = "op_LeftShift";
1546 oper_names [(int) Operator.RightShift] = "op_RightShift";
1547 oper_names [(int) Operator.LessThan] = "op_LessThan";
1548 oper_names [(int) Operator.GreaterThan] = "op_GreaterThan";
1549 oper_names [(int) Operator.LessThanOrEqual] = "op_LessThanOrEqual";
1550 oper_names [(int) Operator.GreaterThanOrEqual] = "op_GreaterThanOrEqual";
1551 oper_names [(int) Operator.Equality] = "op_Equality";
1552 oper_names [(int) Operator.Inequality] = "op_Inequality";
1553 oper_names [(int) Operator.BitwiseAnd] = "op_BitwiseAnd";
1554 oper_names [(int) Operator.BitwiseOr] = "op_BitwiseOr";
1555 oper_names [(int) Operator.ExclusiveOr] = "op_ExclusiveOr";
1556 oper_names [(int) Operator.LogicalOr] = "op_LogicalOr";
1557 oper_names [(int) Operator.LogicalAnd] = "op_LogicalAnd";
1560 public Binary (Operator oper, Expression left, Expression right, Location loc)
1568 public Operator Oper {
1577 public Expression Left {
1586 public Expression Right {
1597 /// Returns a stringified representation of the Operator
1599 static string OperName (Operator oper)
1602 case Operator.Multiply:
1604 case Operator.Division:
1606 case Operator.Modulus:
1608 case Operator.Addition:
1610 case Operator.Subtraction:
1612 case Operator.LeftShift:
1614 case Operator.RightShift:
1616 case Operator.LessThan:
1618 case Operator.GreaterThan:
1620 case Operator.LessThanOrEqual:
1622 case Operator.GreaterThanOrEqual:
1624 case Operator.Equality:
1626 case Operator.Inequality:
1628 case Operator.BitwiseAnd:
1630 case Operator.BitwiseOr:
1632 case Operator.ExclusiveOr:
1634 case Operator.LogicalOr:
1636 case Operator.LogicalAnd:
1640 return oper.ToString ();
1643 public override string ToString ()
1645 return "operator " + OperName (oper) + "(" + left.ToString () + ", " +
1646 right.ToString () + ")";
1649 Expression ForceConversion (EmitContext ec, Expression expr, Type target_type)
1651 if (expr.Type == target_type)
1654 return ConvertImplicit (ec, expr, target_type, Location.Null);
1657 public static void Error_OperatorAmbiguous (Location loc, Operator oper, Type l, Type r)
1660 34, loc, "Operator '" + OperName (oper)
1661 + "' is ambiguous on operands of type '"
1662 + TypeManager.MonoBASIC_Name (l) + "' "
1663 + "and '" + TypeManager.MonoBASIC_Name (r)
1668 // Note that handling the case l == Decimal || r == Decimal
1669 // is taken care of by the Step 1 Operator Overload resolution.
1671 bool DoNumericPromotions (EmitContext ec, Type l, Type r)
1673 if (l == TypeManager.double_type || r == TypeManager.double_type){
1675 // If either operand is of type double, the other operand is
1676 // conveted to type double.
1678 if (r != TypeManager.double_type)
1679 right = ConvertImplicit (ec, right, TypeManager.double_type, loc);
1680 if (l != TypeManager.double_type)
1681 left = ConvertImplicit (ec, left, TypeManager.double_type, loc);
1683 type = TypeManager.double_type;
1684 } else if (l == TypeManager.float_type || r == TypeManager.float_type){
1686 // if either operand is of type float, the other operand is
1687 // converted to type float.
1689 if (r != TypeManager.double_type)
1690 right = ConvertImplicit (ec, right, TypeManager.float_type, loc);
1691 if (l != TypeManager.double_type)
1692 left = ConvertImplicit (ec, left, TypeManager.float_type, loc);
1693 type = TypeManager.float_type;
1694 } else if (l == TypeManager.uint64_type || r == TypeManager.uint64_type){
1698 // If either operand is of type ulong, the other operand is
1699 // converted to type ulong. or an error ocurrs if the other
1700 // operand is of type sbyte, short, int or long
1702 if (l == TypeManager.uint64_type){
1703 if (r != TypeManager.uint64_type){
1704 if (right is IntConstant){
1705 IntConstant ic = (IntConstant) right;
1707 e = TryImplicitIntConversion (l, ic);
1710 } else if (right is LongConstant){
1711 long ll = ((LongConstant) right).Value;
1714 right = new ULongConstant ((ulong) ll);
1716 e = ImplicitNumericConversion (ec, right, l, loc);
1723 if (left is IntConstant){
1724 e = TryImplicitIntConversion (r, (IntConstant) left);
1727 } else if (left is LongConstant){
1728 long ll = ((LongConstant) left).Value;
1731 left = new ULongConstant ((ulong) ll);
1733 e = ImplicitNumericConversion (ec, left, r, loc);
1740 if ((other == TypeManager.sbyte_type) ||
1741 (other == TypeManager.short_type) ||
1742 (other == TypeManager.int32_type) ||
1743 (other == TypeManager.int64_type))
1744 Error_OperatorAmbiguous (loc, oper, l, r);
1745 type = TypeManager.uint64_type;
1746 } else if (l == TypeManager.int64_type || r == TypeManager.int64_type){
1748 // If either operand is of type long, the other operand is converted
1751 if (l != TypeManager.int64_type)
1752 left = ConvertImplicit (ec, left, TypeManager.int64_type, loc);
1753 if (r != TypeManager.int64_type)
1754 right = ConvertImplicit (ec, right, TypeManager.int64_type, loc);
1756 type = TypeManager.int64_type;
1757 } else if (l == TypeManager.uint32_type || r == TypeManager.uint32_type){
1759 // If either operand is of type uint, and the other
1760 // operand is of type sbyte, short or int, othe operands are
1761 // converted to type long.
1765 if (l == TypeManager.uint32_type){
1766 if (right is IntConstant){
1767 IntConstant ic = (IntConstant) right;
1771 right = new UIntConstant ((uint) val);
1778 else if (r == TypeManager.uint32_type){
1779 if (left is IntConstant){
1780 IntConstant ic = (IntConstant) left;
1784 left = new UIntConstant ((uint) val);
1793 if ((other == TypeManager.sbyte_type) ||
1794 (other == TypeManager.short_type) ||
1795 (other == TypeManager.int32_type)){
1796 left = ForceConversion (ec, left, TypeManager.int64_type);
1797 right = ForceConversion (ec, right, TypeManager.int64_type);
1798 type = TypeManager.int64_type;
1801 // if either operand is of type uint, the other
1802 // operand is converd to type uint
1804 left = ForceConversion (ec, left, TypeManager.uint32_type);
1805 right = ForceConversion (ec, right, TypeManager.uint32_type);
1806 type = TypeManager.uint32_type;
1808 } else if (l == TypeManager.decimal_type || r == TypeManager.decimal_type){
1809 if (l != TypeManager.decimal_type)
1810 left = ConvertImplicit (ec, left, TypeManager.decimal_type, loc);
1812 if (r != TypeManager.decimal_type)
1813 right = ConvertImplicit (ec, right, TypeManager.decimal_type, loc);
1814 type = TypeManager.decimal_type;
1816 left = ForceConversion (ec, left, TypeManager.int32_type);
1817 right = ForceConversion (ec, right, TypeManager.int32_type);
1819 type = TypeManager.int32_type;
1822 return (left != null) && (right != null);
1825 static public void Error_OperatorCannotBeApplied (Location loc, string name, Type l, Type r)
1827 Report.Error (19, loc,
1828 "Operator " + name + " cannot be applied to operands of type '" +
1829 TypeManager.MonoBASIC_Name (l) + "' and '" +
1830 TypeManager.MonoBASIC_Name (r) + "'");
1833 void Error_OperatorCannotBeApplied ()
1835 Error_OperatorCannotBeApplied (loc, OperName (oper), left.Type, right.Type);
1838 static bool is_32_or_64 (Type t)
1840 return (t == TypeManager.int32_type || t == TypeManager.uint32_type ||
1841 t == TypeManager.int64_type || t == TypeManager.uint64_type);
1844 static bool is_unsigned (Type t)
1846 return (t == TypeManager.uint32_type || t == TypeManager.uint64_type ||
1847 t == TypeManager.short_type || t == TypeManager.byte_type);
1850 Expression CheckShiftArguments (EmitContext ec)
1854 Type r = right.Type;
1856 e = ForceConversion (ec, right, TypeManager.int32_type);
1858 Error_OperatorCannotBeApplied ();
1863 if (((e = ConvertImplicit (ec, left, TypeManager.int32_type, loc)) != null) ||
1864 ((e = ConvertImplicit (ec, left, TypeManager.uint32_type, loc)) != null) ||
1865 ((e = ConvertImplicit (ec, left, TypeManager.int64_type, loc)) != null) ||
1866 ((e = ConvertImplicit (ec, left, TypeManager.uint64_type, loc)) != null)){
1872 Error_OperatorCannotBeApplied ();
1876 Expression ResolveOperator (EmitContext ec)
1879 Type r = right.Type;
1881 bool overload_failed = false;
1884 // Step 1: Perform Operator Overload location
1886 Expression left_expr, right_expr;
1888 string op = oper_names [(int) oper];
1890 MethodGroupExpr union;
1891 left_expr = MemberLookup (ec, l, op, MemberTypes.Method, AllBindingFlags, loc);
1893 right_expr = MemberLookup (
1894 ec, r, op, MemberTypes.Method, AllBindingFlags, loc);
1895 union = Invocation.MakeUnionSet (left_expr, right_expr, loc);
1897 union = (MethodGroupExpr) left_expr;
1899 if (union != null) {
1900 Arguments = new ArrayList ();
1901 Arguments.Add (new Argument (left, Argument.AType.Expression));
1902 Arguments.Add (new Argument (right, Argument.AType.Expression));
1904 method = Invocation.OverloadResolve (ec, union, Arguments, Location.Null);
1905 if (method != null) {
1906 MethodInfo mi = (MethodInfo) method;
1908 type = mi.ReturnType;
1911 overload_failed = true;
1916 // Step 2: Default operations on CLI native types.
1920 // Step 0: String concatenation (because overloading will get this wrong)
1922 if (oper == Operator.Addition){
1924 // If any of the arguments is a string, cast to string
1927 if (l == TypeManager.string_type){
1929 if (r == TypeManager.void_type) {
1930 Error_OperatorCannotBeApplied ();
1934 if (r == TypeManager.string_type){
1935 if (left is Constant && right is Constant){
1936 StringConstant ls = (StringConstant) left;
1937 StringConstant rs = (StringConstant) right;
1939 return new StringConstant (
1940 ls.Value + rs.Value);
1944 method = TypeManager.string_concat_string_string;
1947 method = TypeManager.string_concat_object_object;
1948 right = ConvertImplicit (ec, right,
1949 TypeManager.object_type, loc);
1951 Error_OperatorCannotBeApplied (loc, OperName (oper), l, r);
1955 type = TypeManager.string_type;
1957 Arguments = new ArrayList ();
1958 Arguments.Add (new Argument (left, Argument.AType.Expression));
1959 Arguments.Add (new Argument (right, Argument.AType.Expression));
1963 } else if (r == TypeManager.string_type){
1966 if (l == TypeManager.void_type) {
1967 Error_OperatorCannotBeApplied ();
1971 method = TypeManager.string_concat_object_object;
1972 left = ConvertImplicit (ec, left, TypeManager.object_type, loc);
1974 Error_OperatorCannotBeApplied (loc, OperName (oper), l, r);
1977 Arguments = new ArrayList ();
1978 Arguments.Add (new Argument (left, Argument.AType.Expression));
1979 Arguments.Add (new Argument (right, Argument.AType.Expression));
1981 type = TypeManager.string_type;
1987 // Transform a + ( - b) into a - b
1989 if (right is Unary){
1990 Unary right_unary = (Unary) right;
1992 if (right_unary.Oper == Unary.Operator.UnaryNegation){
1993 oper = Operator.Subtraction;
1994 right = right_unary.Expr;
2000 if (oper == Operator.Equality || oper == Operator.Inequality){
2001 if (l == TypeManager.bool_type || r == TypeManager.bool_type){
2002 if (r != TypeManager.bool_type || l != TypeManager.bool_type){
2003 Error_OperatorCannotBeApplied ();
2007 type = TypeManager.bool_type;
2012 // operator != (object a, object b)
2013 // operator == (object a, object b)
2015 // For this to be used, both arguments have to be reference-types.
2016 // Read the rationale on the spec (14.9.6)
2018 // Also, if at compile time we know that the classes do not inherit
2019 // one from the other, then we catch the error there.
2021 if (!(l.IsValueType || r.IsValueType)){
2022 type = TypeManager.bool_type;
2027 if (l.IsSubclassOf (r) || r.IsSubclassOf (l))
2031 // Also, a standard conversion must exist from either one
2033 if (!(StandardConversionExists (left, r) ||
2034 StandardConversionExists (right, l))){
2035 Error_OperatorCannotBeApplied ();
2039 // We are going to have to convert to an object to compare
2041 if (l != TypeManager.object_type)
2042 left = new EmptyCast (left, TypeManager.object_type);
2043 if (r != TypeManager.object_type)
2044 right = new EmptyCast (right, TypeManager.object_type);
2047 // FIXME: CSC here catches errors cs254 and cs252
2053 // One of them is a valuetype, but the other one is not.
2055 if (!l.IsValueType || !r.IsValueType) {
2056 Error_OperatorCannotBeApplied ();
2061 // Only perform numeric promotions on:
2062 // +, -, *, /, %, &, |, ^, ==, !=, <, >, <=, >=
2064 if (oper == Operator.Addition || oper == Operator.Subtraction) {
2065 if (l.IsSubclassOf (TypeManager.delegate_type) &&
2066 r.IsSubclassOf (TypeManager.delegate_type)) {
2068 Arguments = new ArrayList ();
2069 Arguments.Add (new Argument (left, Argument.AType.Expression));
2070 Arguments.Add (new Argument (right, Argument.AType.Expression));
2072 if (oper == Operator.Addition)
2073 method = TypeManager.delegate_combine_delegate_delegate;
2075 method = TypeManager.delegate_remove_delegate_delegate;
2078 Error_OperatorCannotBeApplied ();
2082 DelegateOperation = true;
2088 // Pointer arithmetic:
2090 // T* operator + (T* x, int y);
2091 // T* operator + (T* x, uint y);
2092 // T* operator + (T* x, long y);
2093 // T* operator + (T* x, ulong y);
2095 // T* operator + (int y, T* x);
2096 // T* operator + (uint y, T *x);
2097 // T* operator + (long y, T *x);
2098 // T* operator + (ulong y, T *x);
2100 // T* operator - (T* x, int y);
2101 // T* operator - (T* x, uint y);
2102 // T* operator - (T* x, long y);
2103 // T* operator - (T* x, ulong y);
2105 // long operator - (T* x, T *y)
2108 if (r.IsPointer && oper == Operator.Subtraction){
2110 return new PointerArithmetic (
2111 false, left, right, TypeManager.int64_type,
2113 } else if (is_32_or_64 (r))
2114 return new PointerArithmetic (
2115 oper == Operator.Addition, left, right, l, loc);
2116 } else if (r.IsPointer && is_32_or_64 (l) && oper == Operator.Addition)
2117 return new PointerArithmetic (
2118 true, right, left, r, loc);
2122 // Enumeration operators
2124 bool lie = TypeManager.IsEnumType (l);
2125 bool rie = TypeManager.IsEnumType (r);
2129 // U operator - (E e, E f)
2130 if (lie && rie && oper == Operator.Subtraction){
2132 type = TypeManager.EnumToUnderlying (l);
2135 Error_OperatorCannotBeApplied ();
2140 // operator + (E e, U x)
2141 // operator - (E e, U x)
2143 if (oper == Operator.Addition || oper == Operator.Subtraction){
2144 Type enum_type = lie ? l : r;
2145 Type other_type = lie ? r : l;
2146 Type underlying_type = TypeManager.EnumToUnderlying (enum_type);
2149 if (underlying_type != other_type){
2150 Error_OperatorCannotBeApplied ();
2159 temp = ConvertImplicit (ec, right, l, loc);
2163 Error_OperatorCannotBeApplied ();
2167 temp = ConvertImplicit (ec, left, r, loc);
2172 Error_OperatorCannotBeApplied ();
2177 if (oper == Operator.Equality || oper == Operator.Inequality ||
2178 oper == Operator.LessThanOrEqual || oper == Operator.LessThan ||
2179 oper == Operator.GreaterThanOrEqual || oper == Operator.GreaterThan){
2180 type = TypeManager.bool_type;
2184 if (oper == Operator.BitwiseAnd ||
2185 oper == Operator.BitwiseOr ||
2186 oper == Operator.ExclusiveOr){
2190 Error_OperatorCannotBeApplied ();
2194 if (oper == Operator.LeftShift || oper == Operator.RightShift)
2195 return CheckShiftArguments (ec);
2197 if (oper == Operator.LogicalOr || oper == Operator.LogicalAnd){
2198 if (l != TypeManager.bool_type || r != TypeManager.bool_type){
2199 Error_OperatorCannotBeApplied ();
2203 type = TypeManager.bool_type;
2208 // operator & (bool x, bool y)
2209 // operator | (bool x, bool y)
2210 // operator ^ (bool x, bool y)
2212 if (l == TypeManager.bool_type && r == TypeManager.bool_type){
2213 if (oper == Operator.BitwiseAnd ||
2214 oper == Operator.BitwiseOr ||
2215 oper == Operator.ExclusiveOr){
2222 // Pointer comparison
2224 if (l.IsPointer && r.IsPointer){
2225 if (oper == Operator.Equality || oper == Operator.Inequality ||
2226 oper == Operator.LessThan || oper == Operator.LessThanOrEqual ||
2227 oper == Operator.GreaterThan || oper == Operator.GreaterThanOrEqual){
2228 type = TypeManager.bool_type;
2234 // We are dealing with numbers
2236 if (overload_failed){
2237 Error_OperatorCannotBeApplied ();
2242 // This will leave left or right set to null if there is an error
2244 DoNumericPromotions (ec, l, r);
2245 if (left == null || right == null){
2246 Error_OperatorCannotBeApplied (loc, OperName (oper), l, r);
2251 // reload our cached types if required
2256 if (oper == Operator.BitwiseAnd ||
2257 oper == Operator.BitwiseOr ||
2258 oper == Operator.ExclusiveOr){
2260 if (!((l == TypeManager.int32_type) ||
2261 (l == TypeManager.uint32_type) ||
2262 (l == TypeManager.int64_type) ||
2263 (l == TypeManager.uint64_type)))
2266 Error_OperatorCannotBeApplied ();
2271 if (oper == Operator.Equality ||
2272 oper == Operator.Inequality ||
2273 oper == Operator.LessThanOrEqual ||
2274 oper == Operator.LessThan ||
2275 oper == Operator.GreaterThanOrEqual ||
2276 oper == Operator.GreaterThan){
2277 type = TypeManager.bool_type;
2283 public override Expression DoResolve (EmitContext ec)
2285 left = left.Resolve (ec);
2286 right = right.Resolve (ec);
2288 if (left == null || right == null)
2291 if (left.Type == null)
2292 throw new Exception (
2293 "Resolve returned non null, but did not set the type! (" +
2294 left + ") at Line: " + loc.Row);
2295 if (right.Type == null)
2296 throw new Exception (
2297 "Resolve returned non null, but did not set the type! (" +
2298 right + ") at Line: "+ loc.Row);
2300 eclass = ExprClass.Value;
2302 if (left is Constant && right is Constant){
2303 Expression e = ConstantFold.BinaryFold (
2304 ec, oper, (Constant) left, (Constant) right, loc);
2309 return ResolveOperator (ec);
2313 /// EmitBranchable is called from Statement.EmitBoolExpression in the
2314 /// context of a conditional bool expression. This function will return
2315 /// false if it is was possible to use EmitBranchable, or true if it was.
2317 /// The expression's code is generated, and we will generate a branch to 'target'
2318 /// if the resulting expression value is equal to isTrue
2320 public bool EmitBranchable (EmitContext ec, Label target, bool onTrue)
2325 ILGenerator ig = ec.ig;
2328 // This is more complicated than it looks, but its just to avoid
2329 // duplicated tests: basically, we allow ==, !=, >, <, >= and <=
2330 // but on top of that we want for == and != to use a special path
2331 // if we are comparing against null
2333 if (oper == Operator.Equality || oper == Operator.Inequality){
2334 bool my_on_true = oper == Operator.Inequality ? onTrue : !onTrue;
2336 if (left is NullLiteral){
2339 ig.Emit (OpCodes.Brtrue, target);
2341 ig.Emit (OpCodes.Brfalse, target);
2343 } else if (right is NullLiteral){
2346 ig.Emit (OpCodes.Brtrue, target);
2348 ig.Emit (OpCodes.Brfalse, target);
2351 } else if (!(oper == Operator.LessThan ||
2352 oper == Operator.GreaterThan ||
2353 oper == Operator.LessThanOrEqual ||
2354 oper == Operator.GreaterThanOrEqual))
2362 bool isUnsigned = is_unsigned (left.Type);
2365 case Operator.Equality:
2367 ig.Emit (OpCodes.Beq, target);
2369 ig.Emit (OpCodes.Bne_Un, target);
2372 case Operator.Inequality:
2374 ig.Emit (OpCodes.Bne_Un, target);
2376 ig.Emit (OpCodes.Beq, target);
2379 case Operator.LessThan:
2382 ig.Emit (OpCodes.Blt_Un, target);
2384 ig.Emit (OpCodes.Blt, target);
2387 ig.Emit (OpCodes.Bge_Un, target);
2389 ig.Emit (OpCodes.Bge, target);
2392 case Operator.GreaterThan:
2395 ig.Emit (OpCodes.Bgt_Un, target);
2397 ig.Emit (OpCodes.Bgt, target);
2400 ig.Emit (OpCodes.Ble_Un, target);
2402 ig.Emit (OpCodes.Ble, target);
2405 case Operator.LessThanOrEqual:
2408 ig.Emit (OpCodes.Ble_Un, target);
2410 ig.Emit (OpCodes.Ble, target);
2413 ig.Emit (OpCodes.Bgt_Un, target);
2415 ig.Emit (OpCodes.Bgt, target);
2419 case Operator.GreaterThanOrEqual:
2422 ig.Emit (OpCodes.Bge_Un, target);
2424 ig.Emit (OpCodes.Bge, target);
2427 ig.Emit (OpCodes.Blt_Un, target);
2429 ig.Emit (OpCodes.Blt, target);
2439 public override void Emit (EmitContext ec)
2441 ILGenerator ig = ec.ig;
2443 Type r = right.Type;
2446 if (method != null) {
2448 // Note that operators are static anyway
2450 if (Arguments != null)
2451 Invocation.EmitArguments (ec, method, Arguments);
2453 if (method is MethodInfo)
2454 ig.Emit (OpCodes.Call, (MethodInfo) method);
2456 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
2458 if (DelegateOperation)
2459 ig.Emit (OpCodes.Castclass, type);
2465 // Handle short-circuit operators differently
2468 if (oper == Operator.LogicalAnd){
2469 Label load_zero = ig.DefineLabel ();
2470 Label end = ig.DefineLabel ();
2473 ig.Emit (OpCodes.Brfalse, load_zero);
2475 ig.Emit (OpCodes.Br, end);
2476 ig.MarkLabel (load_zero);
2477 ig.Emit (OpCodes.Ldc_I4_0);
2480 } else if (oper == Operator.LogicalOr){
2481 Label load_one = ig.DefineLabel ();
2482 Label end = ig.DefineLabel ();
2485 ig.Emit (OpCodes.Brtrue, load_one);
2487 ig.Emit (OpCodes.Br, end);
2488 ig.MarkLabel (load_one);
2489 ig.Emit (OpCodes.Ldc_I4_1);
2498 case Operator.Multiply:
2500 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
2501 opcode = OpCodes.Mul_Ovf;
2502 else if (l==TypeManager.uint32_type || l==TypeManager.uint64_type)
2503 opcode = OpCodes.Mul_Ovf_Un;
2505 opcode = OpCodes.Mul;
2507 opcode = OpCodes.Mul;
2511 case Operator.Division:
2512 if (l == TypeManager.uint32_type || l == TypeManager.uint64_type)
2513 opcode = OpCodes.Div_Un;
2515 opcode = OpCodes.Div;
2518 case Operator.Modulus:
2519 if (l == TypeManager.uint32_type || l == TypeManager.uint64_type)
2520 opcode = OpCodes.Rem_Un;
2522 opcode = OpCodes.Rem;
2525 case Operator.Addition:
2527 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
2528 opcode = OpCodes.Add_Ovf;
2529 else if (l==TypeManager.uint32_type || l==TypeManager.uint64_type)
2530 opcode = OpCodes.Add_Ovf_Un;
2532 opcode = OpCodes.Add;
2534 opcode = OpCodes.Add;
2537 case Operator.Subtraction:
2539 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
2540 opcode = OpCodes.Sub_Ovf;
2541 else if (l==TypeManager.uint32_type || l==TypeManager.uint64_type)
2542 opcode = OpCodes.Sub_Ovf_Un;
2544 opcode = OpCodes.Sub;
2546 opcode = OpCodes.Sub;
2549 case Operator.RightShift:
2550 if (l == TypeManager.uint32_type || l == TypeManager.uint64_type)
2551 opcode = OpCodes.Shr_Un;
2553 opcode = OpCodes.Shr;
2556 case Operator.LeftShift:
2557 opcode = OpCodes.Shl;
2560 case Operator.Equality:
2561 opcode = OpCodes.Ceq;
2564 case Operator.Inequality:
2565 ec.ig.Emit (OpCodes.Ceq);
2566 ec.ig.Emit (OpCodes.Ldc_I4_0);
2568 opcode = OpCodes.Ceq;
2571 case Operator.LessThan:
2572 opcode = OpCodes.Clt;
2575 case Operator.GreaterThan:
2576 opcode = OpCodes.Cgt;
2579 case Operator.LessThanOrEqual:
2580 ec.ig.Emit (OpCodes.Cgt);
2581 ec.ig.Emit (OpCodes.Ldc_I4_0);
2583 opcode = OpCodes.Ceq;
2586 case Operator.GreaterThanOrEqual:
2587 ec.ig.Emit (OpCodes.Clt);
2588 ec.ig.Emit (OpCodes.Ldc_I4_1);
2590 opcode = OpCodes.Sub;
2593 case Operator.BitwiseOr:
2594 opcode = OpCodes.Or;
2597 case Operator.BitwiseAnd:
2598 opcode = OpCodes.And;
2601 case Operator.ExclusiveOr:
2602 opcode = OpCodes.Xor;
2606 throw new Exception ("This should not happen: Operator = "
2607 + oper.ToString ());
2613 public bool IsBuiltinOperator {
2615 return method == null;
2620 public class PointerArithmetic : Expression {
2621 Expression left, right;
2625 // We assume that 'l' is always a pointer
2627 public PointerArithmetic (bool is_addition, Expression l, Expression r, Type t,
2631 eclass = ExprClass.Variable;
2635 is_add = is_addition;
2638 public override Expression DoResolve (EmitContext ec)
2641 // We are born fully resolved
2646 public override void Emit (EmitContext ec)
2648 Type op_type = left.Type;
2649 ILGenerator ig = ec.ig;
2650 int size = GetTypeSize (op_type.GetElementType ());
2652 if (right.Type.IsPointer){
2654 // handle (pointer - pointer)
2658 ig.Emit (OpCodes.Sub);
2662 ig.Emit (OpCodes.Sizeof, op_type);
2664 IntLiteral.EmitInt (ig, size);
2665 ig.Emit (OpCodes.Div);
2667 ig.Emit (OpCodes.Conv_I8);
2670 // handle + and - on (pointer op int)
2673 ig.Emit (OpCodes.Conv_I);
2677 ig.Emit (OpCodes.Sizeof, op_type);
2679 IntLiteral.EmitInt (ig, size);
2680 ig.Emit (OpCodes.Mul);
2683 ig.Emit (OpCodes.Add);
2685 ig.Emit (OpCodes.Sub);
2691 /// Implements the ternary conditional operator (?:)
2693 public class Conditional : Expression {
2694 Expression expr, trueExpr, falseExpr;
2696 public Conditional (Expression expr, Expression trueExpr, Expression falseExpr, Location l)
2699 this.trueExpr = trueExpr;
2700 this.falseExpr = falseExpr;
2704 public Expression Expr {
2710 public Expression TrueExpr {
2716 public Expression FalseExpr {
2722 public override Expression DoResolve (EmitContext ec)
2724 expr = expr.Resolve (ec);
2729 if (expr.Type != TypeManager.bool_type)
2730 expr = Expression.ConvertImplicitRequired (
2731 ec, expr, TypeManager.bool_type, loc);
2733 trueExpr = trueExpr.Resolve (ec);
2734 falseExpr = falseExpr.Resolve (ec);
2736 if (trueExpr == null || falseExpr == null)
2739 eclass = ExprClass.Value;
2740 if (trueExpr.Type == falseExpr.Type)
2741 type = trueExpr.Type;
2744 Type true_type = trueExpr.Type;
2745 Type false_type = falseExpr.Type;
2747 if (trueExpr is NullLiteral){
2750 } else if (falseExpr is NullLiteral){
2756 // First, if an implicit conversion exists from trueExpr
2757 // to falseExpr, then the result type is of type falseExpr.Type
2759 conv = ConvertImplicit (ec, trueExpr, false_type, loc);
2762 // Check if both can convert implicitl to each other's type
2764 if (ConvertImplicit (ec, falseExpr, true_type, loc) != null){
2766 "Can not compute type of conditional expression " +
2767 "as '" + TypeManager.MonoBASIC_Name (trueExpr.Type) +
2768 "' and '" + TypeManager.MonoBASIC_Name (falseExpr.Type) +
2769 "' convert implicitly to each other");
2774 } else if ((conv = ConvertImplicit(ec, falseExpr, true_type,loc))!= null){
2778 Error (173, "The type of the conditional expression can " +
2779 "not be computed because there is no implicit conversion" +
2780 " from '" + TypeManager.MonoBASIC_Name (trueExpr.Type) + "'" +
2781 " and '" + TypeManager.MonoBASIC_Name (falseExpr.Type) + "'");
2786 if (expr is BoolConstant){
2787 BoolConstant bc = (BoolConstant) expr;
2798 public override void Emit (EmitContext ec)
2800 ILGenerator ig = ec.ig;
2801 Label false_target = ig.DefineLabel ();
2802 Label end_target = ig.DefineLabel ();
2804 Statement.EmitBoolExpression (ec, expr, false_target, false);
2806 ig.Emit (OpCodes.Br, end_target);
2807 ig.MarkLabel (false_target);
2808 falseExpr.Emit (ec);
2809 ig.MarkLabel (end_target);
2817 public class LocalVariableReference : Expression, IAssignMethod, IMemoryLocation, IVariable {
2818 public readonly string Name;
2819 public readonly Block Block;
2820 VariableInfo variable_info;
2823 public LocalVariableReference (Block block, string name, Location l)
2828 eclass = ExprClass.Variable;
2831 // Setting 'is_readonly' to false will allow you to create a writable
2832 // reference to a read-only variable. This is used by foreach and using.
2833 public LocalVariableReference (Block block, string name, Location l,
2834 VariableInfo variable_info, bool is_readonly)
2835 : this (block, name, l)
2837 this.variable_info = variable_info;
2838 this.is_readonly = is_readonly;
2841 public VariableInfo VariableInfo {
2843 if (variable_info == null) {
2844 variable_info = Block.GetVariableInfo (Name);
2845 is_readonly = variable_info.ReadOnly;
2847 return variable_info;
2851 public bool IsAssigned (EmitContext ec, Location loc)
2853 return VariableInfo.IsAssigned (ec, loc);
2856 public bool IsFieldAssigned (EmitContext ec, string name, Location loc)
2858 return VariableInfo.IsFieldAssigned (ec, name, loc);
2861 public void SetAssigned (EmitContext ec)
2863 VariableInfo.SetAssigned (ec);
2866 public void SetFieldAssigned (EmitContext ec, string name)
2868 VariableInfo.SetFieldAssigned (ec, name);
2871 public bool IsReadOnly {
2873 if (variable_info == null) {
2874 variable_info = Block.GetVariableInfo (Name);
2875 is_readonly = variable_info.ReadOnly;
2881 public override Expression DoResolve (EmitContext ec)
2883 VariableInfo vi = VariableInfo;
2885 if (Block.IsConstant (Name)) {
2886 Expression e = Block.GetConstantExpression (Name);
2892 if (ec.DoFlowAnalysis && !IsAssigned (ec, loc))
2895 type = vi.VariableType;
2899 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
2901 VariableInfo vi = VariableInfo;
2903 if (ec.DoFlowAnalysis)
2904 ec.SetVariableAssigned (vi);
2906 Expression e = DoResolve (ec);
2912 Error (1604, "cannot assign to '" + Name + "' because it is readonly");
2919 public override void Emit (EmitContext ec)
2921 VariableInfo vi = VariableInfo;
2922 ILGenerator ig = ec.ig;
2924 ig.Emit (OpCodes.Ldloc, vi.LocalBuilder);
2928 public void EmitAssign (EmitContext ec, Expression source)
2930 ILGenerator ig = ec.ig;
2931 VariableInfo vi = VariableInfo;
2937 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
2940 public void AddressOf (EmitContext ec, AddressOp mode)
2942 VariableInfo vi = VariableInfo;
2944 ec.ig.Emit (OpCodes.Ldloca, vi.LocalBuilder);
2949 /// This represents a reference to a parameter in the intermediate
2952 public class ParameterReference : Expression, IAssignMethod, IMemoryLocation, IVariable {
2956 public Parameter.Modifier mod;
2957 public bool is_ref, is_out;
2959 public ParameterReference (Parameters pars, int idx, string name, Location loc)
2965 eclass = ExprClass.Variable;
2968 public bool IsAssigned (EmitContext ec, Location loc)
2970 if (!is_out || !ec.DoFlowAnalysis)
2973 if (!ec.CurrentBranching.IsParameterAssigned (idx)) {
2974 Report.Error (165, loc,
2975 "Use of unassigned local variable '" + name + "'");
2982 public bool IsFieldAssigned (EmitContext ec, string field_name, Location loc)
2984 if (!is_out || !ec.DoFlowAnalysis)
2987 if (ec.CurrentBranching.IsParameterAssigned (idx))
2990 if (!ec.CurrentBranching.IsParameterAssigned (idx, field_name)) {
2991 Report.Error (170, loc,
2992 "Use of possibly unassigned field '" + field_name + "'");
2999 public void SetAssigned (EmitContext ec)
3001 if (is_out && ec.DoFlowAnalysis)
3002 ec.CurrentBranching.SetParameterAssigned (idx);
3005 public void SetFieldAssigned (EmitContext ec, string field_name)
3007 if (is_out && ec.DoFlowAnalysis)
3008 ec.CurrentBranching.SetParameterAssigned (idx, field_name);
3012 // Notice that for ref/out parameters, the type exposed is not the
3013 // same type exposed externally.
3016 // externally we expose "int&"
3017 // here we expose "int".
3019 // We record this in "is_ref". This means that the type system can treat
3020 // the type as it is expected, but when we generate the code, we generate
3021 // the alternate kind of code.
3023 public override Expression DoResolve (EmitContext ec)
3025 type = pars.GetParameterInfo (ec.DeclSpace, idx, out mod);
3026 is_ref = (mod & Parameter.Modifier.ISBYREF) != 0;
3027 is_out = (mod & Parameter.Modifier.OUT) != 0;
3028 eclass = ExprClass.Variable;
3030 if (is_out && ec.DoFlowAnalysis && !IsAssigned (ec, loc))
3036 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
3038 type = pars.GetParameterInfo (ec.DeclSpace, idx, out mod);
3039 is_ref = (mod & Parameter.Modifier.ISBYREF) != 0;
3040 is_out = (mod & Parameter.Modifier.OUT) != 0;
3041 eclass = ExprClass.Variable;
3043 if (is_out && ec.DoFlowAnalysis)
3044 ec.SetParameterAssigned (idx);
3049 static void EmitLdArg (ILGenerator ig, int x)
3053 case 0: ig.Emit (OpCodes.Ldarg_0); break;
3054 case 1: ig.Emit (OpCodes.Ldarg_1); break;
3055 case 2: ig.Emit (OpCodes.Ldarg_2); break;
3056 case 3: ig.Emit (OpCodes.Ldarg_3); break;
3057 default: ig.Emit (OpCodes.Ldarg_S, (byte) x); break;
3060 ig.Emit (OpCodes.Ldarg, x);
3064 // This method is used by parameters that are references, that are
3065 // being passed as references: we only want to pass the pointer (that
3066 // is already stored in the parameter, not the address of the pointer,
3067 // and not the value of the variable).
3069 public void EmitLoad (EmitContext ec)
3071 ILGenerator ig = ec.ig;
3077 EmitLdArg (ig, arg_idx);
3080 public override void Emit (EmitContext ec)
3082 ILGenerator ig = ec.ig;
3088 EmitLdArg (ig, arg_idx);
3094 // If we are a reference, we loaded on the stack a pointer
3095 // Now lets load the real value
3097 LoadFromPtr (ig, type);
3100 public void EmitAssign (EmitContext ec, Expression source)
3102 ILGenerator ig = ec.ig;
3109 EmitLdArg (ig, arg_idx);
3114 StoreFromPtr (ig, type);
3117 ig.Emit (OpCodes.Starg_S, (byte) arg_idx);
3119 ig.Emit (OpCodes.Starg, arg_idx);
3123 public void AddressOf (EmitContext ec, AddressOp mode)
3132 ec.ig.Emit (OpCodes.Ldarg_S, (byte) arg_idx);
3134 ec.ig.Emit (OpCodes.Ldarg, arg_idx);
3137 ec.ig.Emit (OpCodes.Ldarga_S, (byte) arg_idx);
3139 ec.ig.Emit (OpCodes.Ldarga, arg_idx);
3146 /// Invocation of methods or delegates.
3148 public class Invocation : ExpressionStatement {
3149 public ArrayList Arguments;
3151 public Expression expr;
3152 MethodBase method = null;
3154 bool is_left_hand; // Needed for late bound calls
3155 static Hashtable method_parameter_cache;
3156 static MemberFilter CompareName;
3158 static Invocation ()
3160 method_parameter_cache = new PtrHashtable ();
3164 // arguments is an ArrayList, but we do not want to typecast,
3165 // as it might be null.
3167 // FIXME: only allow expr to be a method invocation or a
3168 // delegate invocation (7.5.5)
3170 public Invocation (Expression expr, ArrayList arguments, Location l)
3173 Arguments = arguments;
3175 CompareName = new MemberFilter (compare_name_filter);
3178 public Expression Expr {
3185 /// Returns the Parameters (a ParameterData interface) for the
3188 public static ParameterData GetParameterData (MethodBase mb)
3190 object pd = method_parameter_cache [mb];
3194 return (ParameterData) pd;
3197 ip = TypeManager.LookupParametersByBuilder (mb);
3199 method_parameter_cache [mb] = ip;
3201 return (ParameterData) ip;
3203 ParameterInfo [] pi = mb.GetParameters ();
3205 ReflectionParameters rp = new ReflectionParameters (pi);
3206 method_parameter_cache [mb] = rp;
3208 return (ParameterData) rp;
3212 enum Applicability { Same, Better, Worse };
3215 /// Determines "Better function"
3218 /// and returns an integer indicating :
3219 /// 0 if candidate ain't better
3220 /// 1 if candidate is better than the current best match
3222 static Applicability BetterFunction (EmitContext ec, ArrayList args,
3223 MethodBase candidate, MethodBase best,
3224 bool expanded_form, Location loc)
3226 ParameterData candidate_pd = GetParameterData (candidate);
3227 ParameterData best_pd;
3233 argument_count = args.Count;
3235 int cand_count = candidate_pd.Count;
3237 if (cand_count == 0 && argument_count == 0)
3238 return Applicability.Same;
3240 if (candidate_pd.ParameterModifier (cand_count - 1) != Parameter.Modifier.PARAMS)
3241 if (cand_count != argument_count)
3242 return Applicability.Worse;
3244 best_pd = GetParameterData (best);
3246 Applicability res = Applicability.Same;
3248 for (int j = 0; j < argument_count; ++j) {
3251 Argument a = (Argument) args [j];
3253 Type ct = candidate_pd.ParameterType (j);
3254 Type bt = best_pd.ParameterType (j);
3256 if (candidate_pd.ParameterModifier (j) == Parameter.Modifier.PARAMS)
3258 ct = ct.GetElementType ();
3260 if (best_pd.ParameterModifier (j) == Parameter.Modifier.PARAMS)
3262 bt = bt.GetElementType ();
3265 if (!WideningConversionExists (ct, bt))
3266 return Applicability.Worse;
3267 res = Applicability.Better;
3271 if (res == Applicability.Same)
3272 if (candidate_pd.Count < best_pd.Count)
3273 res = Applicability.Better;
3274 else if (candidate_pd.Count > best_pd.Count)
3275 res = Applicability.Worse;
3280 public static string FullMethodDesc (MethodBase mb)
3282 string ret_type = "";
3284 if (mb is MethodInfo)
3285 ret_type = TypeManager.MonoBASIC_Name (((MethodInfo) mb).ReturnType) + " ";
3287 StringBuilder sb = new StringBuilder (ret_type + mb.Name);
3288 ParameterData pd = GetParameterData (mb);
3290 int count = pd.Count;
3293 for (int i = count; i > 0; ) {
3296 sb.Append (pd.ParameterDesc (count - i - 1));
3302 return sb.ToString ();
3305 public static MethodGroupExpr MakeUnionSet (Expression mg1, Expression mg2, Location loc)
3307 MemberInfo [] miset;
3308 MethodGroupExpr union;
3313 return (MethodGroupExpr) mg2;
3316 return (MethodGroupExpr) mg1;
3319 MethodGroupExpr left_set = null, right_set = null;
3320 int length1 = 0, length2 = 0;
3322 left_set = (MethodGroupExpr) mg1;
3323 length1 = left_set.Methods.Length;
3325 right_set = (MethodGroupExpr) mg2;
3326 length2 = right_set.Methods.Length;
3328 ArrayList common = new ArrayList ();
3330 foreach (MethodBase l in left_set.Methods){
3331 foreach (MethodBase r in right_set.Methods){
3339 miset = new MemberInfo [length1 + length2 - common.Count];
3340 left_set.Methods.CopyTo (miset, 0);
3344 foreach (MemberInfo mi in right_set.Methods){
3345 if (!common.Contains (mi))
3349 union = new MethodGroupExpr (miset, loc);
3355 /// Determines is the candidate method, if a params method, is applicable
3356 /// in its expanded form to the given set of arguments
3358 static bool IsParamsMethodApplicable (EmitContext ec, ArrayList arguments, MethodBase candidate)
3362 if (arguments == null)
3365 arg_count = arguments.Count;
3367 ParameterData pd = GetParameterData (candidate);
3369 int pd_count = pd.Count;
3374 if (pd.ParameterModifier (pd_count - 1) != Parameter.Modifier.PARAMS)
3377 if (pd_count - 1 > arg_count)
3380 if (pd_count == 1 && arg_count == 0)
3384 // If we have come this far, the case which remains is when the number of parameters
3385 // is less than or equal to the argument count.
3387 for (int i = 0; i < pd_count - 1; ++i) {
3389 Argument a = (Argument) arguments [i];
3391 Parameter.Modifier a_mod = a.GetParameterModifier () &
3392 ~(Parameter.Modifier.OUT | Parameter.Modifier.REF);
3393 Parameter.Modifier p_mod = pd.ParameterModifier (i) &
3394 ~(Parameter.Modifier.OUT | Parameter.Modifier.REF);
3396 if (a_mod == p_mod) {
3398 if (a_mod == Parameter.Modifier.NONE)
3399 if (!ImplicitConversionExists (ec, a.Expr, pd.ParameterType (i)))
3402 if ((a_mod & Parameter.Modifier.ISBYREF) != 0) {
3403 Type pt = pd.ParameterType (i);
3406 pt = TypeManager.LookupType (pt.FullName + "&");
3416 Type element_type = pd.ParameterType (pd_count - 1).GetElementType ();
3418 for (int i = pd_count - 1; i < arg_count; i++) {
3419 Argument a = (Argument) arguments [i];
3421 if (!StandardConversionExists (a.Expr, element_type))
3429 protected enum ConversionType { None, Widening, Narrowing };
3431 static ConversionType CheckParameterAgainstArgument (EmitContext ec, ParameterData pd, int i, Argument a, Type ptype)
3433 Parameter.Modifier a_mod = a.GetParameterModifier () &
3434 ~(Parameter.Modifier.OUT | Parameter.Modifier.REF);
3435 Parameter.Modifier p_mod = pd.ParameterModifier (i) &
3436 ~(Parameter.Modifier.OUT | Parameter.Modifier.REF | Parameter.Modifier.OPTIONAL);
3438 if (a_mod == p_mod ||
3439 (a_mod == Parameter.Modifier.NONE && p_mod == Parameter.Modifier.PARAMS)) {
3440 if (a_mod == Parameter.Modifier.NONE) {
3441 if (! WideningConversionExists (a.Expr, ptype) ) {
3442 if (! NarrowingConversionExists (ec, a.Expr, ptype) )
3443 return ConversionType.None;
3445 return ConversionType.Narrowing;
3447 return ConversionType.Widening;
3450 if ((a_mod & Parameter.Modifier.ISBYREF) != 0) {
3451 Type pt = pd.ParameterType (i);
3454 pt = TypeManager.LookupType (pt.FullName + "&");
3457 return ConversionType.None;
3459 return ConversionType.Widening;
3461 return ConversionType.None;
3464 static bool HasArrayParameter (ParameterData pd)
3467 return c > 0 && (pd.ParameterModifier (c - 1) & Parameter.Modifier.PARAMS) != 0;
3470 static int CountStandardParams (ParameterData pd)
3472 int count = pd.Count;
3473 for (int i = 0; i < count; i++) {
3474 Parameter.Modifier pm = pd.ParameterModifier (i);
3475 if ((pm & (Parameter.Modifier.OPTIONAL | Parameter.Modifier.PARAMS)) != 0)
3482 /// Determines if the candidate method is applicable (section 14.4.2.1)
3483 /// to the given set of arguments
3485 static ConversionType IsApplicable (EmitContext ec, ArrayList arguments, MethodBase candidate, out bool expanded)
3487 int arg_count, po_count;
3492 if (arguments == null)
3495 arg_count = arguments.Count;
3497 ParameterData pd = GetParameterData (candidate);
3498 int ps_count = CountStandardParams (pd);
3499 int pd_count = pd.Count;
3501 // Validate argument count
3502 if (ps_count == pd_count) {
3503 if (arg_count != pd_count)
3504 return ConversionType.None;
3507 if (arg_count < ps_count)
3508 return ConversionType.None;
3509 if (!HasArrayParameter (pd) && arg_count > pd_count)
3510 return ConversionType.None;
3512 ConversionType result = ConversionType.Widening;
3513 ArrayList newarglist = new ArrayList();
3514 if (arg_count > 0) {
3515 result = ConversionType.None;
3516 int array_param_index = -1;
3517 for (int i = 0; i < arg_count; ++i) {
3518 Argument a = (Argument) arguments [i];
3519 param_type = pd.ParameterType (i);
3520 Parameter.Modifier mod = pd.ParameterModifier (i);
3521 if (array_param_index < 0 && (mod & Parameter.Modifier.PARAMS) != 0)
3522 array_param_index = i;
3524 bool IsDelegate = TypeManager.IsDelegateType (param_type);
3527 if (a.ArgType == Argument.AType.AddressOf) {
3528 a = new Argument ((Expression) a.Expr, Argument.AType.Expression);
3529 ArrayList args = new ArrayList();
3531 string param_name = pd.ParameterDesc(i).Replace('+', '.');
3532 Expression pname = MonoBASIC.Parser.DecomposeQI (param_name, Location.Null);
3534 New temp_new = new New ((Expression)pname, args, Location.Null);
3535 Expression del_temp = temp_new.DoResolve(ec);
3537 if (del_temp == null)
3538 return ConversionType.None;
3540 a = new Argument (del_temp, Argument.AType.Expression);
3541 if (!a.Resolve(ec, Location.Null))
3542 return ConversionType.None;
3546 if (a.ArgType == Argument.AType.AddressOf)
3547 return ConversionType.None;
3550 if ((mod & Parameter.Modifier.REF) != 0) {
3551 a = new Argument (a.Expr, Argument.AType.Ref);
3552 if (!a.Resolve(ec,Location.Null))
3553 return ConversionType.None;
3556 ConversionType match = ConversionType.None;
3557 if (i == array_param_index)
3558 match = CheckParameterAgainstArgument (ec, pd, i, a, param_type);
3559 if (match == ConversionType.None && array_param_index >= 0 && i >= array_param_index) {
3561 param_type = param_type.GetElementType ();
3563 if (match == ConversionType.None)
3564 match = CheckParameterAgainstArgument (ec, pd, i, a, param_type);
3566 if (match == ConversionType.None)
3567 return ConversionType.None;
3568 if (result == ConversionType.None)
3570 else if (match == ConversionType.Narrowing)
3571 result = ConversionType.Narrowing;
3576 // We've found a candidate, so we exchange the dummy NoArg arguments
3577 // with new arguments containing the default value for that parameter
3579 ArrayList newarglist = new ArrayList();
3580 for (int i = 0; i < arg_count; i++) {
3581 Argument a = (Argument) arguments [i];
3585 p = (Parameter) ps.FixedParameters[i];
3587 if (a.ArgType == Argument.AType.NoArg){
3588 a = new Argument (p.ParameterInitializer, Argument.AType.Expression);
3589 a.Resolve(ec, Location.Null);
3592 // ToDo - This part is getting resolved second time within this function
3593 // This is a costly operation
3594 // The earlier resoved result should be used here.
3595 // Has to be done during compiler optimization.
3596 if (a.ArgType == Argument.AType.AddressOf) {
3597 param_type = pd.ParameterType (i);
3598 bool IsDelegate = TypeManager.IsDelegateType (param_type);
3600 a = new Argument ((Expression) a.Expr, Argument.AType.Expression);
3601 ArrayList args = new ArrayList();
3603 string param_name = pd.ParameterDesc(i).Replace('+', '.');
3604 Expression pname = MonoBASIC.Parser.DecomposeQI (param_name, Location.Null);
3606 New temp_new = new New ((Expression)pname, args, Location.Null);
3607 Expression del_temp = temp_new.DoResolve(ec);
3609 if (del_temp == null)
3610 return ConversionType.None;
3612 a = new Argument (del_temp, Argument.AType.Expression);
3613 if (!a.Resolve(ec, Location.Null))
3614 return ConversionType.None;
3617 if ((p != null) && ((p.ModFlags & Parameter.Modifier.REF) != 0)) {
3618 a.ArgType = Argument.AType.Ref;
3619 a.Resolve(ec, Location.Null);
3620 } else if ((pd.ParameterModifier (i) & Parameter.Modifier.REF) != 0) {
3621 a.ArgType = Argument.AType.Ref;
3622 a.Resolve(ec, Location.Null);
3625 int n = pd_count - arg_count;
3627 for (int x = 0; x < n; x++) {
3628 Parameter op = (Parameter) ps.FixedParameters[x + arg_count];
3629 Argument b = new Argument (op.ParameterInitializer, Argument.AType.Expression);
3630 b.Resolve(ec, Location.Null);
3639 static bool compare_name_filter (MemberInfo m, object filterCriteria)
3641 return (m.Name == ((string) filterCriteria));
3644 // We need an overload for OverloadResolve because Invocation.DoResolve
3645 // must pass Arguments by reference, since a later call to IsApplicable
3646 // can change the argument list if optional parameters are defined
3647 // in the method declaration
3648 public static MethodBase OverloadResolve (EmitContext ec, MethodGroupExpr me,
3649 ArrayList Arguments, Location loc)
3651 ArrayList a = Arguments;
3652 return OverloadResolve (ec, me, ref a, loc);
3655 static string ToString(MethodBase mbase)
3660 if (mbase is MethodBuilder)
3662 MethodBuilder mb = (MethodBuilder) mbase;
3663 String res = mb.ReturnType + " (";
3664 ParameterInfo [] parms = mb.GetParameters();
3665 for (int i = 0; i < parms.Length; i++) {
3668 res += parms[i].ParameterType;
3674 return mbase.ToString();
3678 /// Find the Applicable Function Members (7.4.2.1)
3680 /// me: Method Group expression with the members to select.
3681 /// it might contain constructors or methods (or anything
3682 /// that maps to a method).
3684 /// Arguments: ArrayList containing resolved Argument objects.
3686 /// loc: The location if we want an error to be reported, or a Null
3687 /// location for "probing" purposes.
3689 /// Returns: The MethodBase (either a ConstructorInfo or a MethodInfo)
3690 /// that is the best match of me on Arguments.
3693 public static MethodBase OverloadResolve (EmitContext ec, MethodGroupExpr me,
3694 ref ArrayList Arguments, Location loc)
3696 ArrayList afm = new ArrayList ();
3697 MethodBase method = null;
3698 Type current_type = null;
3700 ArrayList candidates = new ArrayList ();
3701 Hashtable expanded_candidates = new Hashtable();
3702 int narrow_count = 0;
3703 bool narrowing_candidate = false;
3705 foreach (MethodBase candidate in me.Methods){
3706 bool candidate_expanded;
3707 ConversionType m = IsApplicable (ec, Arguments, candidate, out candidate_expanded);
3708 if (candidate_expanded)
3709 expanded_candidates [candidate] = candidate;
3710 if (m == ConversionType.None)
3712 else if (m == ConversionType.Narrowing) {
3713 if (method == null) {
3715 narrowing_candidate = true;
3718 } else if (m == ConversionType.Widening) {
3719 if (method == null || narrowing_candidate) {
3721 narrowing_candidate = false;
3723 Applicability res = BetterFunction (ec, Arguments, candidate, method, true, loc);
3724 if (res == Applicability.Same)
3725 continue; // should check it overrides?
3726 if (res == Applicability.Better)
3729 candidates.Add (candidate);
3733 if (candidates.Count == 0) {
3734 if (narrow_count > 1)
3736 else if (narrow_count == 1)
3738 } else if (candidates.Count == 1) {
3739 method = (MethodBase)candidates [0];
3744 if (Arguments == null)
3747 argument_count = Arguments.Count;
3750 if (method == null) {
3752 // Okay so we have failed to find anything so we
3753 // return by providing info about the closest match
3755 for (int i = 0; i < me.Methods.Length; ++i) {
3757 MethodBase c = (MethodBase) me.Methods [i];
3758 ParameterData pd = GetParameterData (c);
3760 if (pd.Count != argument_count)
3764 if (narrow_count != 0) {
3765 if (IsApplicable (ec, Arguments, c, out dummy) == ConversionType.None)
3767 Report.Error (1502, loc,
3768 "Overloaded match for method '" +
3769 FullMethodDesc (c) +
3770 "' requires narrowing conversionss");
3773 VerifyArgumentsCompat (ec, Arguments, argument_count, c, false,
3781 // Now check that there are no ambiguities i.e the selected method
3782 // should be better than all the others
3785 if (candidates != null) {
3786 foreach (MethodBase candidate in candidates){
3787 if (candidate == method)
3790 if (BetterFunction (ec, Arguments, candidate, method,
3791 false, loc) == Applicability.Better) {
3794 "Ambiguous call of '" + me.Name + "' when selecting function due to implicit casts");
3801 // And now check if the arguments are all compatible, perform conversions
3802 // if necessary etc. and return if everything is all right
3807 bool chose_params_expanded = expanded_candidates.Contains (method);
3809 Arguments = ConstructArgumentList(ec, Arguments, method);
3810 if (VerifyArgumentsCompat (ec, Arguments, argument_count, method,
3811 chose_params_expanded, null, loc))
3819 public static ArrayList ConstructArgumentList (EmitContext ec, ArrayList Arguments, MethodBase method)
3821 ArrayList newarglist = new ArrayList();
3822 int arg_count = Arguments == null ? 0 : Arguments.Count;
3824 ParameterData pd = GetParameterData (method);
3827 for (int i = 0; i < arg_count; i++) {
3828 Argument a = (Argument) Arguments [i];
3829 Type param_type = pd.ParameterType (i);
3831 bool IsDelegate = TypeManager.IsDelegateType (param_type);
3833 if (a.ArgType == Argument.AType.AddressOf) {
3834 a = new Argument ((Expression) a.Expr, Argument.AType.Expression);
3835 ArrayList args = new ArrayList();
3837 string param_name = pd.ParameterDesc(i).Replace('+', '.');
3838 Expression pname = MonoBASIC.Parser.DecomposeQI (param_name, Location.Null);
3840 New temp_new = new New ((Expression)pname, args, Location.Null);
3841 Expression del_temp = temp_new.DoResolve(ec);
3842 a = new Argument (del_temp, Argument.AType.Expression);
3843 a.Resolve(ec, Location.Null);
3846 if ((pd.ParameterModifier (i) & Parameter.Modifier.REF) != 0) {
3847 a.ArgType = Argument.AType.Ref;
3848 a.Resolve(ec, Location.Null);
3854 if (HasArrayParameter (pd) && arg_count == pd.Count - 1)
3857 for (int i = arg_count; i < pd.Count; i++) {
3858 Expression e = pd.DefaultValue (i);
3859 Argument a = new Argument (e, Argument.AType.Expression);
3860 if ((pd.ParameterModifier (i) & Parameter.Modifier.REF) != 0)
3861 a.ArgType = Argument.AType.Ref;
3863 a.Resolve (ec, Location.Null);
3870 public static bool VerifyArgumentsCompat (EmitContext ec, ArrayList Arguments,
3873 bool chose_params_expanded,
3877 return (VerifyArgumentsCompat (ec, Arguments, argument_count,
3878 method, chose_params_expanded, delegate_type, loc, null));
3881 public static bool VerifyArgumentsCompat (EmitContext ec,
3882 ArrayList Arguments,
3885 bool chose_params_expanded,
3888 string InvokingProperty)
3890 ParameterData pd = GetParameterData (method);
3891 int pd_count = pd.Count;
3893 for (int j = 0; j < argument_count; j++) {
3894 Argument a = (Argument) Arguments [j];
3895 Expression a_expr = a.Expr;
3896 Type parameter_type = pd.ParameterType(j);
3898 if (parameter_type == null)
3900 Error_WrongNumArguments(loc, (InvokingProperty == null)?((delegate_type == null)?FullMethodDesc (method):delegate_type.ToString ()):InvokingProperty, argument_count);
3903 if (pd.ParameterModifier (j) == Parameter.Modifier.PARAMS &&
3904 chose_params_expanded)
3905 parameter_type = TypeManager.TypeToCoreType (parameter_type.GetElementType ());
3906 if (a.Type != parameter_type){
3909 conv = ConvertImplicit (ec, a_expr, parameter_type, loc);
3912 if (!Location.IsNull (loc)) {
3913 if (delegate_type == null)
3914 if (InvokingProperty == null)
3915 Report.Error (1502, loc,
3916 "The best overloaded match for method '" +
3917 FullMethodDesc (method) +
3918 "' has some invalid arguments");
3920 Report.Error (1502, loc,
3923 "' has some invalid arguments");
3925 Report.Error (1594, loc,
3926 "Delegate '" + delegate_type.ToString () +
3927 "' has some invalid arguments.");
3928 Report.Error (1503, loc,
3929 "Argument " + (j+1) +
3930 ": Cannot convert from '" + Argument.FullDesc (a)
3931 + "' to '" + pd.ParameterDesc (j) + "'");
3938 // Update the argument with the implicit conversion
3944 Parameter.Modifier a_mod = a.GetParameterModifier () &
3945 ~(Parameter.Modifier.OUT | Parameter.Modifier.REF);
3946 Parameter.Modifier p_mod = pd.ParameterModifier (j) &
3947 ~(Parameter.Modifier.OUT | Parameter.Modifier.REF | Parameter.Modifier.OPTIONAL);
3949 if (a_mod != p_mod &&
3950 pd.ParameterModifier (pd_count - 1) != Parameter.Modifier.PARAMS) {
3951 if (!Location.IsNull (loc)) {
3952 Report.Error (1502, loc,
3953 "The best overloaded match for method '" + FullMethodDesc (method)+
3954 "' has some invalid arguments");
3955 Report.Error (1503, loc,
3956 "Argument " + (j+1) +
3957 ": Cannot convert from '" + Argument.FullDesc (a)
3958 + "' to '" + pd.ParameterDesc (j) + "'");
3968 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
3970 this.is_left_hand = true;
3971 Expression expr_to_return = DoResolve (ec);
3973 if (expr_to_return is IndexerAccess) {
3974 IndexerAccess ia = expr_to_return as IndexerAccess;
3975 expr_to_return = ia.DoResolveLValue (ec, right_side);
3978 return expr_to_return;
3981 public override Expression DoResolve (EmitContext ec)
3984 // First, resolve the expression that is used to
3985 // trigger the invocation
3987 Expression expr_to_return = null;
3989 if (expr is BaseAccess)
3992 if ((ec.ReturnType != null) && (expr.ToString() == ec.BlockName)) {
3993 ec.InvokingOwnOverload = true;
3994 expr = expr.Resolve (ec, ResolveFlags.MethodGroup);
3995 ec.InvokingOwnOverload = false;
3999 ec.InvokingOwnOverload = false;
4000 expr = expr.Resolve (ec, ResolveFlags.VariableOrValue | ResolveFlags.MethodGroup);
4005 if (expr is Invocation) {
4006 // FIXME Calls which return an Array are not resolved (here or in the grammar)
4007 expr = expr.Resolve(ec);
4010 if (!(expr is MethodGroupExpr))
4012 Type expr_type = expr.Type;
4014 if (expr_type != null)
4016 bool IsDelegate = TypeManager.IsDelegateType (expr_type);
4018 return (new DelegateInvocation (
4019 this.expr, Arguments, loc)).Resolve (ec);
4024 // Next, evaluate all the expressions in the argument list
4026 if (Arguments != null)
4028 foreach (Argument a in Arguments)
4030 if ((a.ArgType == Argument.AType.NoArg) && (!(expr is MethodGroupExpr)))
4031 Report.Error (999, "This item cannot have empty arguments");
4033 if (!a.Resolve (ec, loc))
4038 if (expr is MethodGroupExpr)
4040 MethodGroupExpr mg = (MethodGroupExpr) expr;
4041 method = OverloadResolve (ec, mg, ref Arguments, loc);
4046 "Could not find any applicable function to invoke for this argument list");
4050 if ((method as MethodInfo) != null)
4052 MethodInfo mi = method as MethodInfo;
4053 type = TypeManager.TypeToCoreType (mi.ReturnType);
4054 if (!mi.IsStatic && !mg.IsExplicitImpl && (mg.InstanceExpression == null))
4055 SimpleName.Error_ObjectRefRequired (ec, loc, mi.Name);
4058 if ((method as ConstructorInfo) != null)
4060 ConstructorInfo ci = method as ConstructorInfo;
4061 type = TypeManager.void_type;
4062 if (!ci.IsStatic && !mg.IsExplicitImpl && (mg.InstanceExpression == null))
4063 SimpleName.Error_ObjectRefRequired (ec, loc, ci.Name);
4074 eclass = ExprClass.Value;
4075 expr_to_return = this;
4078 if (expr is PropertyExpr)
4080 PropertyExpr pe = ((PropertyExpr) expr);
4081 pe.PropertyArgs = (ArrayList) Arguments.Clone();
4083 Arguments = new ArrayList();
4084 MethodBase mi = pe.PropertyInfo.GetGetMethod(true);
4086 if(VerifyArgumentsCompat (ec, pe.PropertyArgs,
4087 pe.PropertyArgs.Count, mi, false, null, loc, pe.Name))
4090 expr_to_return = pe.DoResolve (ec);
4091 expr_to_return.eclass = ExprClass.PropertyAccess;
4095 throw new Exception("Error resolving Property Access expression\n" + pe.ToString());
4099 if (expr is FieldExpr || expr is LocalVariableReference || expr is ParameterReference) {
4100 if (expr.Type.IsArray) {
4101 // If we are here, expr must be an ArrayAccess
4102 ArrayList idxs = new ArrayList();
4103 foreach (Argument a in Arguments)
4107 ElementAccess ea = new ElementAccess (expr, idxs, expr.Location);
4108 ArrayAccess aa = new ArrayAccess (ea, expr.Location);
4109 expr_to_return = aa.DoResolve(ec);
4110 expr_to_return.eclass = ExprClass.Variable;
4113 // check whether this is a indexer
4115 ArrayList idxs = new ArrayList();
4116 foreach (Argument a in Arguments) {
4119 ElementAccess ea = new ElementAccess (expr, idxs, expr.Location);
4120 IndexerAccess ia = new IndexerAccess (ea, expr.Location);
4122 expr_to_return = ia.DoResolve(ec);
4124 expr_to_return = ia.DoResolve(ec);
4126 // Since all the above are failed we need to do
4129 if (expr_to_return == null) {
4131 // We can't resolve now, but we
4132 // have to try to access the array with a call
4133 // to LateIndexGet/Set in the runtime
4134 Expression lig_call_expr;
4137 lig_call_expr = Mono.MonoBASIC.Parser.DecomposeQI("Microsoft.VisualBasic.CompilerServices.LateBinding.LateIndexGet", Location.Null);
4139 lig_call_expr = Mono.MonoBASIC.Parser.DecomposeQI("Microsoft.VisualBasic.CompilerServices.LateBinding.LateIndexSet", Location.Null);
4140 Expression obj_type = Mono.MonoBASIC.Parser.DecomposeQI("System.Object", Location.Null);
4141 ArrayList adims = new ArrayList();
4143 ArrayList ainit = new ArrayList();
4144 foreach (Argument a in Arguments)
4145 ainit.Add ((Expression) a.Expr);
4147 adims.Add ((Expression) new IntLiteral (Arguments.Count));
4149 Expression oace = new ArrayCreation (obj_type, adims, "", ainit, Location.Null);
4151 ArrayList args = new ArrayList();
4152 args.Add (new Argument(expr, Argument.AType.Expression));
4153 args.Add (new Argument(oace, Argument.AType.Expression));
4154 args.Add (new Argument(NullLiteral.Null, Argument.AType.Expression));
4156 Expression lig_call = new Invocation (lig_call_expr, args, Location.Null);
4157 expr_to_return = lig_call.Resolve(ec);
4158 expr_to_return.eclass = ExprClass.Variable;
4163 return expr_to_return;
4166 static void Error_WrongNumArguments (Location loc, String name, int arg_count)
4168 Report.Error (1501, loc, "No overload for method `" + name + "' takes `" +
4169 arg_count + "' arguments");
4173 // Emits the list of arguments as an array
4175 static void EmitParams (EmitContext ec, int idx, ArrayList arguments)
4177 ILGenerator ig = ec.ig;
4178 int count = arguments.Count - idx;
4179 Argument a = (Argument) arguments [idx];
4180 Type t = a.Expr.Type;
4181 string array_type = t.FullName + "[]";
4184 array = ig.DeclareLocal (TypeManager.LookupType (array_type));
4185 IntConstant.EmitInt (ig, count);
4186 ig.Emit (OpCodes.Newarr, TypeManager.TypeToCoreType (t));
4187 ig.Emit (OpCodes.Stloc, array);
4189 int top = arguments.Count;
4190 for (int j = idx; j < top; j++){
4191 a = (Argument) arguments [j];
4193 ig.Emit (OpCodes.Ldloc, array);
4194 IntConstant.EmitInt (ig, j - idx);
4197 ArrayAccess.EmitStoreOpcode (ig, t);
4199 ig.Emit (OpCodes.Ldloc, array);
4203 /// Emits a list of resolved Arguments that are in the arguments
4206 public static void EmitArguments (EmitContext ec, MethodBase mb, ArrayList arguments)
4208 ParameterData pd = GetParameterData (mb);
4211 // If we are calling a params method with no arguments, special case it
4213 if (arguments == null){
4215 pd.ParameterModifier (0) == Parameter.Modifier.PARAMS){
4216 ILGenerator ig = ec.ig;
4218 IntConstant.EmitInt (ig, 0);
4219 ig.Emit (OpCodes.Newarr, pd.ParameterType (0).GetElementType ());
4224 int top = arguments.Count;
4226 for (int i = 0; i < top; i++){
4227 Argument a = (Argument) arguments [i];
4229 if (pd.ParameterModifier (i) == Parameter.Modifier.PARAMS){
4231 // Special case if we are passing the same data as the
4232 // params argument, do not put it in an array.
4234 if (pd.ParameterType (i) == a.Type)
4237 EmitParams (ec, i, arguments);
4241 if ((a.ArgType == Argument.AType.Ref || a.ArgType == Argument.AType.Out) &&
4242 !(a.Expr is IMemoryLocation)) {
4243 LocalTemporary tmp = new LocalTemporary (ec, pd.ParameterType (i));
4247 a = new Argument (tmp, a.ArgType);
4253 if (pd.Count > top &&
4254 pd.ParameterModifier (top) == Parameter.Modifier.PARAMS){
4255 ILGenerator ig = ec.ig;
4257 IntConstant.EmitInt (ig, 0);
4258 ig.Emit (OpCodes.Newarr, pd.ParameterType (top).GetElementType ());
4263 /// is_base tells whether we want to force the use of the 'call'
4264 /// opcode instead of using callvirt. Call is required to call
4265 /// a specific method, while callvirt will always use the most
4266 /// recent method in the vtable.
4268 /// is_static tells whether this is an invocation on a static method
4270 /// instance_expr is an expression that represents the instance
4271 /// it must be non-null if is_static is false.
4273 /// method is the method to invoke.
4275 /// Arguments is the list of arguments to pass to the method or constructor.
4277 public static void EmitCall (EmitContext ec, bool is_base,
4278 bool is_static, Expression instance_expr,
4279 MethodBase method, ArrayList Arguments, Location loc)
4281 EmitCall (ec, is_base, is_static, instance_expr, method, Arguments, null, loc);
4284 public static void EmitCall (EmitContext ec, bool is_base,
4285 bool is_static, Expression instance_expr,
4286 MethodBase method, ArrayList Arguments, ArrayList prop_args, Location loc)
4288 ILGenerator ig = ec.ig;
4289 bool struct_call = false;
4291 Type decl_type = method.DeclaringType;
4293 if (!RootContext.StdLib)
4295 // Replace any calls to the system's System.Array type with calls to
4296 // the newly created one.
4297 if (method == TypeManager.system_int_array_get_length)
4298 method = TypeManager.int_array_get_length;
4299 else if (method == TypeManager.system_int_array_get_rank)
4300 method = TypeManager.int_array_get_rank;
4301 else if (method == TypeManager.system_object_array_clone)
4302 method = TypeManager.object_array_clone;
4303 else if (method == TypeManager.system_int_array_get_length_int)
4304 method = TypeManager.int_array_get_length_int;
4305 else if (method == TypeManager.system_int_array_get_lower_bound_int)
4306 method = TypeManager.int_array_get_lower_bound_int;
4307 else if (method == TypeManager.system_int_array_get_upper_bound_int)
4308 method = TypeManager.int_array_get_upper_bound_int;
4309 else if (method == TypeManager.system_void_array_copyto_array_int)
4310 method = TypeManager.void_array_copyto_array_int;
4314 // This checks the 'ConditionalAttribute' on the method, and the
4315 // ObsoleteAttribute
4317 TypeManager.MethodFlags flags = TypeManager.GetMethodFlags (method, loc);
4318 if ((flags & TypeManager.MethodFlags.IsObsoleteError) != 0)
4320 if ((flags & TypeManager.MethodFlags.ShouldIgnore) != 0)
4325 if (decl_type.IsValueType)
4328 // If this is ourselves, push "this"
4330 if (instance_expr == null)
4332 ig.Emit (OpCodes.Ldarg_0);
4337 // Push the instance expression
4339 if (instance_expr.Type.IsValueType)
4342 // Special case: calls to a function declared in a
4343 // reference-type with a value-type argument need
4344 // to have their value boxed.
4347 if (decl_type.IsValueType)
4350 // If the expression implements IMemoryLocation, then
4351 // we can optimize and use AddressOf on the
4354 // If not we have to use some temporary storage for
4356 if (instance_expr is IMemoryLocation)
4358 ((IMemoryLocation)instance_expr).
4359 AddressOf (ec, AddressOp.LoadStore);
4363 Type t = instance_expr.Type;
4365 instance_expr.Emit (ec);
4366 LocalBuilder temp = ig.DeclareLocal (t);
4367 ig.Emit (OpCodes.Stloc, temp);
4368 ig.Emit (OpCodes.Ldloca, temp);
4373 instance_expr.Emit (ec);
4374 ig.Emit (OpCodes.Box, instance_expr.Type);
4378 instance_expr.Emit (ec);
4382 if (prop_args != null && prop_args.Count > 0)
4384 if (Arguments == null)
4385 Arguments = new ArrayList();
4387 for (int i = prop_args.Count-1; i >=0 ; i--)
4389 Arguments.Insert (0,prop_args[i]);
4394 EmitArguments (ec, method, Arguments);
4396 if (is_static || struct_call || is_base)
4398 if (method is MethodInfo)
4400 ig.Emit (OpCodes.Call, (MethodInfo) method);
4403 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
4407 if (method is MethodInfo)
4408 ig.Emit (OpCodes.Callvirt, (MethodInfo) method);
4410 ig.Emit (OpCodes.Callvirt, (ConstructorInfo) method);
4414 static void EmitPropertyArgs (EmitContext ec, ArrayList prop_args)
4416 int top = prop_args.Count;
4418 for (int i = 0; i < top; i++)
4420 Argument a = (Argument) prop_args [i];
4425 public override void Emit (EmitContext ec)
4427 MethodGroupExpr mg = (MethodGroupExpr) this.expr;
4430 ec, is_base, method.IsStatic, mg.InstanceExpression, method, Arguments, loc);
4433 public override void EmitStatement (EmitContext ec)
4438 // Pop the return value if there is one
4440 if (method is MethodInfo){
4441 Type ret = ((MethodInfo)method).ReturnType;
4442 if (TypeManager.TypeToCoreType (ret) != TypeManager.void_type)
4443 ec.ig.Emit (OpCodes.Pop);
4449 // This class is used to "disable" the code generation for the
4450 // temporary variable when initializing value types.
4452 class EmptyAddressOf : EmptyExpression, IMemoryLocation {
4453 public void AddressOf (EmitContext ec, AddressOp Mode)
4460 /// Implements the new expression
4462 public class New : ExpressionStatement {
4463 public readonly ArrayList Arguments;
4464 public readonly Expression RequestedType;
4466 MethodBase method = null;
4469 // If set, the new expression is for a value_target, and
4470 // we will not leave anything on the stack.
4472 Expression value_target;
4473 bool value_target_set = false;
4474 public bool isDelegate = false;
4476 public New (Expression requested_type, ArrayList arguments, Location l)
4478 RequestedType = requested_type;
4479 Arguments = arguments;
4483 public Expression ValueTypeVariable {
4485 return value_target;
4489 value_target = value;
4490 value_target_set = true;
4495 // This function is used to disable the following code sequence for
4496 // value type initialization:
4498 // AddressOf (temporary)
4502 // Instead the provide will have provided us with the address on the
4503 // stack to store the results.
4505 static Expression MyEmptyExpression;
4507 public void DisableTemporaryValueType ()
4509 if (MyEmptyExpression == null)
4510 MyEmptyExpression = new EmptyAddressOf ();
4513 // To enable this, look into:
4514 // test-34 and test-89 and self bootstrapping.
4516 // For instance, we can avoid a copy by using 'newobj'
4517 // instead of Call + Push-temp on value types.
4518 // value_target = MyEmptyExpression;
4521 public override Expression DoResolve (EmitContext ec)
4523 if (this.isDelegate) {
4524 // if its a delegate resolve the type of RequestedType first
4525 Expression dtype = RequestedType.Resolve(ec);
4526 string ts = (dtype.Type.ToString()).Replace ('+','.');
4527 dtype = Mono.MonoBASIC.Parser.DecomposeQI (ts, Location.Null);
4529 type = ec.DeclSpace.ResolveType (dtype, false, loc);
4532 type = ec.DeclSpace.ResolveType (RequestedType, false, loc);
4537 bool IsDelegate = TypeManager.IsDelegateType (type);
4540 return (new NewDelegate (type, Arguments, loc)).Resolve (ec);
4542 if (type.IsInterface || type.IsAbstract){
4544 30376, "It is not possible to create instances of Interfaces " +
4545 "or classes marked as MustInherit");
4549 bool is_struct = false;
4550 is_struct = type.IsValueType;
4551 eclass = ExprClass.Value;
4554 // SRE returns a match for .ctor () on structs (the object constructor),
4555 // so we have to manually ignore it.
4557 if (is_struct && Arguments == null)
4561 ml = MemberLookupFinal (ec, type, ".ctor",
4562 MemberTypes.Constructor,
4563 AllBindingFlags | BindingFlags.Public, loc);
4568 if (! (ml is MethodGroupExpr)){
4570 ml.Error118 ("method group");
4576 if (Arguments != null){
4577 foreach (Argument a in Arguments){
4578 if (!a.Resolve (ec, loc))
4583 method = Invocation.OverloadResolve (ec, (MethodGroupExpr) ml,
4588 if (method == null) {
4589 if (!is_struct || Arguments.Count > 0) {
4591 "New invocation: Can not find a constructor for " +
4592 "this argument list");
4600 // This DoEmit can be invoked in two contexts:
4601 // * As a mechanism that will leave a value on the stack (new object)
4602 // * As one that wont (init struct)
4604 // You can control whether a value is required on the stack by passing
4605 // need_value_on_stack. The code *might* leave a value on the stack
4606 // so it must be popped manually
4608 // If we are dealing with a ValueType, we have a few
4609 // situations to deal with:
4611 // * The target is a ValueType, and we have been provided
4612 // the instance (this is easy, we are being assigned).
4614 // * The target of New is being passed as an argument,
4615 // to a boxing operation or a function that takes a
4618 // In this case, we need to create a temporary variable
4619 // that is the argument of New.
4621 // Returns whether a value is left on the stack
4623 bool DoEmit (EmitContext ec, bool need_value_on_stack)
4625 bool is_value_type = type.IsValueType;
4626 ILGenerator ig = ec.ig;
4631 // Allow DoEmit() to be called multiple times.
4632 // We need to create a new LocalTemporary each time since
4633 // you can't share LocalBuilders among ILGeneators.
4634 if (!value_target_set)
4635 value_target = new LocalTemporary (ec, type);
4637 ml = (IMemoryLocation) value_target;
4638 ml.AddressOf (ec, AddressOp.Store);
4642 Invocation.EmitArguments (ec, method, Arguments);
4646 ig.Emit (OpCodes.Initobj, type);
4648 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
4649 if (need_value_on_stack){
4650 value_target.Emit (ec);
4655 ig.Emit (OpCodes.Newobj, (ConstructorInfo) method);
4660 public override void Emit (EmitContext ec)
4665 public override void EmitStatement (EmitContext ec)
4667 if (DoEmit (ec, false))
4668 ec.ig.Emit (OpCodes.Pop);
4673 /// 14.5.10.2: Represents an array creation expression.
4677 /// There are two possible scenarios here: one is an array creation
4678 /// expression that specifies the dimensions and optionally the
4679 /// initialization data and the other which does not need dimensions
4680 /// specified but where initialization data is mandatory.
4682 public class ArrayCreation : ExpressionStatement {
4683 Expression requested_base_type;
4684 ArrayList initializers;
4687 // The list of Argument types.
4688 // This is used to construct the 'newarray' or constructor signature
4690 ArrayList arguments;
4693 // Method used to create the array object.
4695 MethodBase new_method = null;
4697 Type array_element_type;
4698 Type underlying_type;
4699 bool is_one_dimensional = false;
4700 bool is_builtin_type = false;
4701 bool expect_initializers = false;
4702 int num_arguments = 0;
4706 ArrayList array_data;
4711 // The number of array initializers that we can handle
4712 // via the InitializeArray method - through EmitStaticInitializers
4714 int num_automatic_initializers;
4716 public ArrayCreation (Expression requested_base_type, ArrayList exprs, string rank, ArrayList initializers, Location l)
4718 this.requested_base_type = requested_base_type;
4719 this.initializers = initializers;
4723 arguments = new ArrayList ();
4725 foreach (Expression e in exprs) {
4726 arguments.Add (new Argument (e, Argument.AType.Expression));
4731 public ArrayCreation (Expression requested_base_type, string rank, ArrayList initializers, Location l)
4733 this.requested_base_type = requested_base_type;
4734 this.initializers = initializers;
4738 //this.rank = rank.Substring (0, rank.LastIndexOf ("["));
4740 //string tmp = rank.Substring (rank.LastIndexOf ("["));
4742 //dimensions = tmp.Length - 1;
4743 expect_initializers = true;
4746 public Expression FormArrayType (Expression base_type, int idx_count, string rank)
4748 StringBuilder sb = new StringBuilder (rank);
4751 for (int i = 1; i < idx_count; i++)
4756 return new ComposedCast (base_type, sb.ToString (), loc);
4759 void Error_IncorrectArrayInitializer ()
4761 Error (30567, "Incorrectly structured array initializer");
4764 public bool CheckIndices (EmitContext ec, ArrayList probe, int idx, bool specified_dims)
4766 if (specified_dims) {
4767 Argument a = (Argument) arguments [idx];
4769 if (!a.Resolve (ec, loc))
4772 if (!(a.Expr is Constant)) {
4773 Error (150, "A constant value is expected");
4777 int value = (int) ((Constant) a.Expr).GetValue ();
4779 if (value != probe.Count) {
4780 Error_IncorrectArrayInitializer ();
4784 bounds [idx] = value;
4787 int child_bounds = -1;
4788 foreach (object o in probe) {
4789 if (o is ArrayList) {
4790 int current_bounds = ((ArrayList) o).Count;
4792 if (child_bounds == -1)
4793 child_bounds = current_bounds;
4795 else if (child_bounds != current_bounds){
4796 Error_IncorrectArrayInitializer ();
4799 bool ret = CheckIndices (ec, (ArrayList) o, idx + 1, specified_dims);
4803 if (child_bounds != -1){
4804 Error_IncorrectArrayInitializer ();
4808 Expression tmp = (Expression) o;
4809 tmp = tmp.Resolve (ec);
4813 // Console.WriteLine ("I got: " + tmp);
4814 // Handle initialization from vars, fields etc.
4816 Expression conv = ConvertImplicitRequired (
4817 ec, tmp, underlying_type, loc);
4822 if (conv is StringConstant)
4823 array_data.Add (conv);
4824 else if (conv is Constant) {
4825 array_data.Add (conv);
4826 num_automatic_initializers++;
4828 array_data.Add (conv);
4835 public void UpdateIndices (EmitContext ec)
4838 for (ArrayList probe = initializers; probe != null;) {
4839 if (probe.Count > 0 && probe [0] is ArrayList) {
4840 Expression e = new IntConstant (probe.Count);
4841 arguments.Add (new Argument (e, Argument.AType.Expression));
4843 bounds [i++] = probe.Count;
4845 probe = (ArrayList) probe [0];
4848 Expression e = new IntConstant (probe.Count);
4849 arguments.Add (new Argument (e, Argument.AType.Expression));
4851 bounds [i++] = probe.Count;
4858 public bool ValidateInitializers (EmitContext ec, Type array_type)
4860 if (initializers == null) {
4861 if (expect_initializers)
4867 if (underlying_type == null)
4871 // We use this to store all the date values in the order in which we
4872 // will need to store them in the byte blob later
4874 array_data = new ArrayList ();
4875 bounds = new Hashtable ();
4879 if (arguments != null) {
4880 ret = CheckIndices (ec, initializers, 0, true);
4883 arguments = new ArrayList ();
4885 ret = CheckIndices (ec, initializers, 0, false);
4892 if (arguments.Count != dimensions) {
4893 Error_IncorrectArrayInitializer ();
4901 void Error_NegativeArrayIndex ()
4903 Error (284, "Can not create array with a negative size");
4907 // Converts 'source' to an int, uint, long or ulong.
4909 Expression ExpressionToArrayArgument (EmitContext ec, Expression source)
4913 bool old_checked = ec.CheckState;
4914 ec.CheckState = true;
4916 target = ConvertImplicit (ec, source, TypeManager.int32_type, loc);
4917 if (target == null){
4918 target = ConvertImplicit (ec, source, TypeManager.uint32_type, loc);
4919 if (target == null){
4920 target = ConvertImplicit (ec, source, TypeManager.int64_type, loc);
4921 if (target == null){
4922 target = ConvertImplicit (ec, source, TypeManager.uint64_type, loc);
4924 Expression.Error_CannotConvertImplicit (loc, source.Type, TypeManager.int32_type);
4928 ec.CheckState = old_checked;
4931 // Only positive constants are allowed at compile time
4933 if (target is Constant){
4934 if (target is IntConstant){
4935 if (((IntConstant) target).Value < 0){
4936 Error_NegativeArrayIndex ();
4941 if (target is LongConstant){
4942 if (((LongConstant) target).Value < 0){
4943 Error_NegativeArrayIndex ();
4954 // Creates the type of the array
4956 bool LookupType (EmitContext ec)
4958 StringBuilder array_qualifier = new StringBuilder (rank);
4961 // 'In the first form allocates an array instace of the type that results
4962 // from deleting each of the individual expression from the expression list'
4964 if (num_arguments > 0) {
4965 array_qualifier.Append ("[");
4966 for (int i = num_arguments-1; i > 0; i--)
4967 array_qualifier.Append (",");
4968 array_qualifier.Append ("]");
4974 Expression array_type_expr;
4975 array_type_expr = new ComposedCast (requested_base_type, array_qualifier.ToString (), loc);
4976 string sss = array_qualifier.ToString ();
4977 type = ec.DeclSpace.ResolveType (array_type_expr, false, loc);
4982 underlying_type = type;
4983 if (underlying_type.IsArray)
4984 underlying_type = TypeManager.TypeToCoreType (underlying_type.GetElementType ());
4985 dimensions = type.GetArrayRank ();
4990 public override Expression DoResolve (EmitContext ec)
4994 if (!LookupType (ec))
4998 // First step is to validate the initializers and fill
4999 // in any missing bits
5001 if (!ValidateInitializers (ec, type))
5004 if (arguments == null)
5007 arg_count = arguments.Count;
5008 foreach (Argument a in arguments){
5009 if (!a.Resolve (ec, loc))
5012 Expression real_arg = ExpressionToArrayArgument (ec, a.Expr, loc);
5013 if (real_arg == null)
5020 array_element_type = TypeManager.TypeToCoreType (type.GetElementType ());
5022 if (arg_count == 1) {
5023 is_one_dimensional = true;
5024 eclass = ExprClass.Value;
5028 is_builtin_type = TypeManager.IsBuiltinType (type);
5030 if (is_builtin_type) {
5033 ml = MemberLookup (ec, type, ".ctor", MemberTypes.Constructor,
5034 AllBindingFlags, loc);
5036 if (!(ml is MethodGroupExpr)) {
5037 ml.Error118 ("method group");
5042 Error (-6, "New invocation: Can not find a constructor for " +
5043 "this argument list");
5047 new_method = Invocation.OverloadResolve (ec, (MethodGroupExpr) ml, arguments, loc);
5049 if (new_method == null) {
5050 Error (-6, "New invocation: Can not find a constructor for " +
5051 "this argument list");
5055 eclass = ExprClass.Value;
5058 ModuleBuilder mb = CodeGen.ModuleBuilder;
5059 ArrayList args = new ArrayList ();
5061 if (arguments != null) {
5062 for (int i = 0; i < arg_count; i++)
5063 args.Add (TypeManager.int32_type);
5066 Type [] arg_types = null;
5069 arg_types = new Type [args.Count];
5071 args.CopyTo (arg_types, 0);
5073 new_method = mb.GetArrayMethod (type, ".ctor", CallingConventions.HasThis, null,
5076 if (new_method == null) {
5077 Error (-6, "New invocation: Can not find a constructor for " +
5078 "this argument list");
5082 eclass = ExprClass.Value;
5087 public static byte [] MakeByteBlob (ArrayList array_data, Type underlying_type, Location loc)
5092 int count = array_data.Count;
5094 if (underlying_type.IsEnum)
5095 underlying_type = TypeManager.EnumToUnderlying (underlying_type);
5097 factor = GetTypeSize (underlying_type);
5099 throw new Exception ("unrecognized type in MakeByteBlob: " + underlying_type);
5101 data = new byte [(count * factor + 4) & ~3];
5104 for (int i = 0; i < count; ++i) {
5105 object v = array_data [i];
5107 if (v is EnumConstant)
5108 v = ((EnumConstant) v).Child;
5110 if (v is Constant && !(v is StringConstant))
5111 v = ((Constant) v).GetValue ();
5117 if (underlying_type == TypeManager.int64_type){
5118 if (!(v is Expression)){
5119 long val = (long) v;
5121 for (int j = 0; j < factor; ++j) {
5122 data [idx + j] = (byte) (val & 0xFF);
5126 } else if (underlying_type == TypeManager.uint64_type){
5127 if (!(v is Expression)){
5128 ulong val = (ulong) v;
5130 for (int j = 0; j < factor; ++j) {
5131 data [idx + j] = (byte) (val & 0xFF);
5135 } else if (underlying_type == TypeManager.float_type) {
5136 if (!(v is Expression)){
5137 element = BitConverter.GetBytes ((float) v);
5139 for (int j = 0; j < factor; ++j)
5140 data [idx + j] = element [j];
5142 } else if (underlying_type == TypeManager.double_type) {
5143 if (!(v is Expression)){
5144 element = BitConverter.GetBytes ((double) v);
5146 for (int j = 0; j < factor; ++j)
5147 data [idx + j] = element [j];
5149 } else if (underlying_type == TypeManager.char_type){
5150 if (!(v is Expression)){
5151 int val = (int) ((char) v);
5153 data [idx] = (byte) (val & 0xff);
5154 data [idx+1] = (byte) (val >> 8);
5156 } else if (underlying_type == TypeManager.short_type){
5157 if (!(v is Expression)){
5158 int val = (int) ((short) v);
5160 data [idx] = (byte) (val & 0xff);
5161 data [idx+1] = (byte) (val >> 8);
5163 } else if (underlying_type == TypeManager.ushort_type){
5164 if (!(v is Expression)){
5165 int val = (int) ((ushort) v);
5167 data [idx] = (byte) (val & 0xff);
5168 data [idx+1] = (byte) (val >> 8);
5170 } else if (underlying_type == TypeManager.int32_type) {
5171 if (!(v is Expression)){
5174 data [idx] = (byte) (val & 0xff);
5175 data [idx+1] = (byte) ((val >> 8) & 0xff);
5176 data [idx+2] = (byte) ((val >> 16) & 0xff);
5177 data [idx+3] = (byte) (val >> 24);
5179 } else if (underlying_type == TypeManager.uint32_type) {
5180 if (!(v is Expression)){
5181 uint val = (uint) v;
5183 data [idx] = (byte) (val & 0xff);
5184 data [idx+1] = (byte) ((val >> 8) & 0xff);
5185 data [idx+2] = (byte) ((val >> 16) & 0xff);
5186 data [idx+3] = (byte) (val >> 24);
5188 } else if (underlying_type == TypeManager.sbyte_type) {
5189 if (!(v is Expression)){
5190 sbyte val = (sbyte) v;
5191 data [idx] = (byte) val;
5193 } else if (underlying_type == TypeManager.byte_type) {
5194 if (!(v is Expression)){
5195 byte val = (byte) v;
5196 data [idx] = (byte) val;
5198 } else if (underlying_type == TypeManager.bool_type) {
5199 if (!(v is Expression)){
5200 bool val = (bool) v;
5201 data [idx] = (byte) (val ? 1 : 0);
5203 } else if (underlying_type == TypeManager.decimal_type){
5204 if (!(v is Expression)){
5205 int [] bits = Decimal.GetBits ((decimal) v);
5208 for (int j = 0; j < 4; j++){
5209 data [p++] = (byte) (bits [j] & 0xff);
5210 data [p++] = (byte) ((bits [j] >> 8) & 0xff);
5211 data [p++] = (byte) ((bits [j] >> 16) & 0xff);
5212 data [p++] = (byte) (bits [j] >> 24);
5216 throw new Exception ("Unrecognized type in MakeByteBlob: " + underlying_type);
5225 // Emits the initializers for the array
5227 void EmitStaticInitializers (EmitContext ec, bool is_expression)
5230 // First, the static data
5233 ILGenerator ig = ec.ig;
5235 byte [] data = MakeByteBlob (array_data, underlying_type, loc);
5237 fb = RootContext.MakeStaticData (data);
5240 ig.Emit (OpCodes.Dup);
5241 ig.Emit (OpCodes.Ldtoken, fb);
5242 ig.Emit (OpCodes.Call,
5243 TypeManager.void_initializearray_array_fieldhandle);
5247 // Emits pieces of the array that can not be computed at compile
5248 // time (variables and string locations).
5250 // This always expect the top value on the stack to be the array
5252 void EmitDynamicInitializers (EmitContext ec, bool is_expression)
5254 ILGenerator ig = ec.ig;
5255 int dims = bounds.Count;
5256 int [] current_pos = new int [dims];
5257 int top = array_data.Count;
5258 LocalBuilder temp = ig.DeclareLocal (type);
5260 ig.Emit (OpCodes.Stloc, temp);
5262 MethodInfo set = null;
5266 ModuleBuilder mb = null;
5267 mb = CodeGen.ModuleBuilder;
5268 args = new Type [dims + 1];
5271 for (j = 0; j < dims; j++)
5272 args [j] = TypeManager.int32_type;
5274 args [j] = array_element_type;
5276 set = mb.GetArrayMethod (
5278 CallingConventions.HasThis | CallingConventions.Standard,
5279 TypeManager.void_type, args);
5282 for (int i = 0; i < top; i++){
5284 Expression e = null;
5286 if (array_data [i] is Expression)
5287 e = (Expression) array_data [i];
5291 // Basically we do this for string literals and
5292 // other non-literal expressions
5294 if (e is StringConstant || !(e is Constant) ||
5295 num_automatic_initializers <= 2) {
5296 Type etype = e.Type;
5298 ig.Emit (OpCodes.Ldloc, temp);
5300 for (int idx = 0; idx < dims; idx++)
5301 IntConstant.EmitInt (ig, current_pos [idx]);
5304 // If we are dealing with a struct, get the
5305 // address of it, so we can store it.
5308 etype.IsSubclassOf (TypeManager.value_type) &&
5309 (!TypeManager.IsBuiltinType (etype) ||
5310 etype == TypeManager.decimal_type)) {
5315 // Let new know that we are providing
5316 // the address where to store the results
5318 n.DisableTemporaryValueType ();
5321 ig.Emit (OpCodes.Ldelema, etype);
5327 ArrayAccess.EmitStoreOpcode (ig, array_element_type);
5329 ig.Emit (OpCodes.Call, set);
5336 for (int j = dims - 1; j >= 0; j--){
5338 if (current_pos [j] < (int) bounds [j])
5340 current_pos [j] = 0;
5345 ig.Emit (OpCodes.Ldloc, temp);
5348 void EmitArrayArguments (EmitContext ec)
5350 ILGenerator ig = ec.ig;
5352 foreach (Argument a in arguments) {
5353 Type atype = a.Type;
5356 if (atype == TypeManager.uint64_type)
5357 ig.Emit (OpCodes.Conv_Ovf_U4);
5358 else if (atype == TypeManager.int64_type)
5359 ig.Emit (OpCodes.Conv_Ovf_I4);
5363 void DoEmit (EmitContext ec, bool is_statement)
5365 ILGenerator ig = ec.ig;
5367 EmitArrayArguments (ec);
5368 if (is_one_dimensional)
5369 ig.Emit (OpCodes.Newarr, array_element_type);
5371 if (is_builtin_type)
5372 ig.Emit (OpCodes.Newobj, (ConstructorInfo) new_method);
5374 ig.Emit (OpCodes.Newobj, (MethodInfo) new_method);
5377 if (initializers != null){
5379 // FIXME: Set this variable correctly.
5381 bool dynamic_initializers = true;
5383 if (underlying_type != TypeManager.string_type &&
5384 underlying_type != TypeManager.object_type) {
5385 if (num_automatic_initializers > 2)
5386 EmitStaticInitializers (ec, dynamic_initializers || !is_statement);
5389 if (dynamic_initializers)
5390 EmitDynamicInitializers (ec, !is_statement);
5394 public override void Emit (EmitContext ec)
5399 public override void EmitStatement (EmitContext ec)
5407 /// Represents the 'this' construct
5409 public class This : Expression, IAssignMethod, IMemoryLocation, IVariable {
5414 public This (Block block, Location loc)
5420 public This (Location loc)
5425 public bool IsAssigned (EmitContext ec, Location loc)
5430 return vi.IsAssigned (ec, loc);
5433 public bool IsFieldAssigned (EmitContext ec, string field_name, Location loc)
5438 return vi.IsFieldAssigned (ec, field_name, loc);
5441 public void SetAssigned (EmitContext ec)
5444 vi.SetAssigned (ec);
5447 public void SetFieldAssigned (EmitContext ec, string field_name)
5450 vi.SetFieldAssigned (ec, field_name);
5453 public override Expression DoResolve (EmitContext ec)
5455 eclass = ExprClass.Variable;
5456 type = ec.ContainerType;
5459 Error (26, "Keyword this not valid in static code");
5464 vi = block.ThisVariable;
5469 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
5473 VariableInfo vi = ec.CurrentBlock.ThisVariable;
5475 vi.SetAssigned (ec);
5477 if (ec.TypeContainer is Class){
5478 Error (1604, "Cannot assign to 'this'");
5485 public override void Emit (EmitContext ec)
5487 ILGenerator ig = ec.ig;
5489 ig.Emit (OpCodes.Ldarg_0);
5490 if (ec.TypeContainer is Struct)
5491 ig.Emit (OpCodes.Ldobj, type);
5494 public void EmitAssign (EmitContext ec, Expression source)
5496 ILGenerator ig = ec.ig;
5498 if (ec.TypeContainer is Struct){
5499 ig.Emit (OpCodes.Ldarg_0);
5501 ig.Emit (OpCodes.Stobj, type);
5504 ig.Emit (OpCodes.Starg, 0);
5508 public void AddressOf (EmitContext ec, AddressOp mode)
5510 ec.ig.Emit (OpCodes.Ldarg_0);
5513 // FIGURE OUT WHY LDARG_S does not work
5515 // consider: struct X { int val; int P { set { val = value; }}}
5517 // Yes, this looks very bad. Look at 'NOTAS' for
5519 // ec.ig.Emit (OpCodes.Ldarga_S, (byte) 0);
5524 /// Implements the typeof operator
5526 public class TypeOf : Expression {
5527 public readonly Expression QueriedType;
5530 public TypeOf (Expression queried_type, Location l)
5532 QueriedType = queried_type;
5536 public override Expression DoResolve (EmitContext ec)
5538 typearg = ec.DeclSpace.ResolveType (QueriedType, false, loc);
5540 if (typearg == null)
5543 type = TypeManager.type_type;
5544 eclass = ExprClass.Type;
5548 public override void Emit (EmitContext ec)
5550 ec.ig.Emit (OpCodes.Ldtoken, typearg);
5551 ec.ig.Emit (OpCodes.Call, TypeManager.system_type_get_type_from_handle);
5554 public Type TypeArg {
5555 get { return typearg; }
5560 /// Implements the sizeof expression
5562 public class SizeOf : Expression {
5563 public readonly Expression QueriedType;
5566 public SizeOf (Expression queried_type, Location l)
5568 this.QueriedType = queried_type;
5572 public override Expression DoResolve (EmitContext ec)
5575 Error (233, "Sizeof may only be used in an unsafe context " +
5576 "(consider using System.Runtime.InteropServices.Marshal.Sizeof");
5580 type_queried = ec.DeclSpace.ResolveType (QueriedType, false, loc);
5581 if (type_queried == null)
5584 if (!TypeManager.IsUnmanagedType (type_queried)){
5585 Report.Error (208, "Cannot take the size of an unmanaged type (" + TypeManager.MonoBASIC_Name (type_queried) + ")");
5589 type = TypeManager.int32_type;
5590 eclass = ExprClass.Value;
5594 public override void Emit (EmitContext ec)
5596 int size = GetTypeSize (type_queried);
5599 ec.ig.Emit (OpCodes.Sizeof, type_queried);
5601 IntConstant.EmitInt (ec.ig, size);
5606 /// Implements the member access expression
5608 public class MemberAccess : Expression, ITypeExpression {
5609 public readonly string Identifier;
5611 Expression member_lookup;
5613 public MemberAccess (Expression expr, string id, Location l)
5620 public Expression Expr {
5626 static void error176 (Location loc, string name)
5628 Report.Error (176, loc, "Static member '" +
5629 name + "' cannot be accessed " +
5630 "with an instance reference, qualify with a " +
5631 "type name instead");
5634 static bool IdenticalNameAndTypeName (EmitContext ec, Expression left_original, Location loc)
5636 if (left_original == null)
5639 if (!(left_original is SimpleName))
5642 SimpleName sn = (SimpleName) left_original;
5644 Type t = RootContext.LookupType (ec.DeclSpace, sn.Name, true, loc);
5651 public static Expression ResolveMemberAccess (EmitContext ec, Expression member_lookup,
5652 Expression left, Location loc,
5653 Expression left_original)
5655 bool left_is_type, left_is_explicit;
5657 // If 'left' is null, then we're called from SimpleNameResolve and this is
5658 // a member in the currently defining class.
5660 left_is_type = ec.IsStatic || ec.IsFieldInitializer;
5661 left_is_explicit = false;
5663 // Implicitly default to 'this' unless we're static.
5664 if (!ec.IsStatic && !ec.IsFieldInitializer && !ec.InEnumContext)
5667 left_is_type = left is TypeExpr;
5668 left_is_explicit = true;
5671 if (member_lookup is FieldExpr){
5672 FieldExpr fe = (FieldExpr) member_lookup;
5673 FieldInfo fi = fe.FieldInfo;
5674 Type decl_type = fi.DeclaringType;
5676 if (fi is FieldBuilder) {
5677 Const c = TypeManager.LookupConstant ((FieldBuilder) fi);
5680 object o = c.LookupConstantValue (ec);
5681 object real_value = ((Constant) c.Expr).GetValue ();
5683 return Constantify (real_value, fi.FieldType);
5688 Type t = fi.FieldType;
5692 if (fi is FieldBuilder)
5693 o = TypeManager.GetValue ((FieldBuilder) fi);
5695 o = fi.GetValue (fi);
5697 if (decl_type.IsSubclassOf (TypeManager.enum_type)) {
5698 if (left_is_explicit && !left_is_type &&
5699 !IdenticalNameAndTypeName (ec, left_original, loc)) {
5700 error176 (loc, fe.FieldInfo.Name);
5704 Expression enum_member = MemberLookup (
5705 ec, decl_type, "value__", MemberTypes.Field,
5706 AllBindingFlags, loc);
5708 Enum en = TypeManager.LookupEnum (decl_type);
5712 c = Constantify (o, en.UnderlyingType);
5714 c = Constantify (o, enum_member.Type);
5716 return new EnumConstant (c, decl_type);
5719 Expression exp = Constantify (o, t);
5721 if (left_is_explicit && !left_is_type) {
5722 error176 (loc, fe.FieldInfo.Name);
5729 if (fi.FieldType.IsPointer && !ec.InUnsafe){
5736 if (member_lookup is IMemberExpr) {
5737 IMemberExpr me = (IMemberExpr) member_lookup;
5740 MethodGroupExpr mg = me as MethodGroupExpr;
5741 if ((mg != null) && left_is_explicit && left.Type.IsInterface)
5742 mg.IsExplicitImpl = left_is_explicit;
5745 if (IdenticalNameAndTypeName (ec, left_original, loc))
5746 return member_lookup;
5748 SimpleName.Error_ObjectRefRequired (ec, loc, me.Name);
5753 if (!me.IsInstance){
5754 if (IdenticalNameAndTypeName (ec, left_original, loc))
5755 return member_lookup;
5757 /*if (left_is_explicit) {
5758 error176 (loc, me.Name);
5764 // Since we can not check for instance objects in SimpleName,
5765 // becaue of the rule that allows types and variables to share
5766 // the name (as long as they can be de-ambiguated later, see
5767 // IdenticalNameAndTypeName), we have to check whether left
5768 // is an instance variable in a static context
5770 // However, if the left-hand value is explicitly given, then
5771 // it is already our instance expression, so we aren't in
5775 if (ec.IsStatic && !left_is_explicit && left is IMemberExpr){
5776 IMemberExpr mexp = (IMemberExpr) left;
5778 if (!mexp.IsStatic){
5779 SimpleName.Error_ObjectRefRequired (ec, loc, mexp.Name);
5784 me.InstanceExpression = left;
5787 return member_lookup;
5790 if (member_lookup is TypeExpr){
5791 member_lookup.Resolve (ec, ResolveFlags.Type);
5792 return member_lookup;
5795 Console.WriteLine ("Left is: " + left);
5796 Report.Error (-100, loc, "Support for [" + member_lookup + "] is not present yet");
5797 Environment.Exit (0);
5801 public Expression DoResolve (EmitContext ec, Expression right_side, ResolveFlags flags)
5804 throw new Exception ();
5806 // Resolve the expression with flow analysis turned off, we'll do the definite
5807 // assignment checks later. This is because we don't know yet what the expression
5808 // will resolve to - it may resolve to a FieldExpr and in this case we must do the
5809 // definite assignment check on the actual field and not on the whole struct.
5812 Expression original = expr;
5813 expr = expr.Resolve (ec, flags | ResolveFlags.DisableFlowAnalysis);
5818 if (expr is SimpleName){
5819 SimpleName child_expr = (SimpleName) expr;
5821 Expression new_expr = new SimpleName (child_expr.Name + "." + Identifier, loc);
5823 if ((flags & ResolveFlags.MaskExprClass) == ResolveFlags.Type)
5824 return new_expr.Resolve (ec, flags);
5826 return new_expr.Resolve (ec, flags | ResolveFlags.MethodGroup | ResolveFlags.VariableOrValue);
5829 int errors = Report.Errors;
5831 Type expr_type = expr.Type;
5833 if (expr is TypeExpr){
5834 //FIXME: add access level check
5835 //if (!ec.DeclSpace.CheckAccessLevel (expr_type)) {
5836 // Error (30390, "'" + TypeManager.MonoBASIC_Name (expr_type) + "' " +
5837 // "is inaccessible because of its protection level");
5841 if (expr_type == TypeManager.enum_type || expr_type.IsSubclassOf (TypeManager.enum_type)){
5842 Enum en = TypeManager.LookupEnum (expr_type);
5845 object value = en.LookupEnumValue (ec, Identifier, loc);
5848 Constant c = Constantify (value, en.UnderlyingType);
5849 return new EnumConstant (c, expr_type);
5855 if (expr_type.IsPointer){
5856 Error (23, "The '.' operator can not be applied to pointer operands (" +
5857 TypeManager.MonoBASIC_Name (expr_type) + ")");
5861 member_lookup = MemberLookup (ec, expr_type, Identifier, loc);
5863 if (member_lookup == null)
5865 // Error has already been reported.
5866 if (errors < Report.Errors)
5870 // Try looking the member up from the same type, if we find
5871 // it, we know that the error was due to limited visibility
5873 object lookup = TypeManager.MemberLookup (
5874 expr_type, expr_type, AllMemberTypes, AllBindingFlags |
5875 BindingFlags.NonPublic, Identifier);
5878 Error (30456, "'" + expr_type + "' does not contain a definition for '" + Identifier + "'");
5881 if ((expr_type != ec.ContainerType) &&
5882 ec.ContainerType.IsSubclassOf (expr_type))
5885 // Although a derived class can access protected members of
5886 // its base class it cannot do so through an instance of the
5887 // base class (CS1540). If the expr_type is a parent of the
5888 // ec.ContainerType and the lookup succeeds with the latter one,
5889 // then we are in this situation.
5891 lookup = TypeManager.MemberLookup(
5892 ec.ContainerType, ec.ContainerType, AllMemberTypes,
5893 AllBindingFlags, Identifier);
5896 Error (1540, "Cannot access protected member '" +
5897 expr_type + "." + Identifier + "' " +
5898 "via a qualifier of type '" + TypeManager.MonoBASIC_Name (expr_type) + "'; the " +
5899 "qualifier must be of type '" + TypeManager.MonoBASIC_Name (ec.ContainerType) + "' " +
5900 "(or derived from it)");
5902 Error (30390, "'" + expr_type + "." + Identifier + "' " +
5903 "is inaccessible because of its protection level");
5905 Error (30390, "'" + expr_type + "." + Identifier + "' " +
5906 "is inaccessible because of its protection level");
5911 if ((expr is TypeExpr) && (expr_type.IsSubclassOf (TypeManager.enum_type))) {
5912 Enum en = TypeManager.LookupEnum (expr_type);
5915 object value = en.LookupEnumValue (ec, Identifier, loc);
5916 expr_type = TypeManager.int32_type;
5917 if (value != null) {
5918 Constant c = Constantify (value, en.UnderlyingType);
5919 return new EnumConstant (c, en.UnderlyingType);
5924 if (member_lookup is TypeExpr){
5925 member_lookup.Resolve (ec, ResolveFlags.Type);
5927 return member_lookup;
5928 } else if ((flags & ResolveFlags.MaskExprClass) == ResolveFlags.Type)
5931 member_lookup = ResolveMemberAccess (ec, member_lookup, expr, loc, original);
5932 if (member_lookup == null)
5935 // The following DoResolve/DoResolveLValue will do the definite assignment
5937 if (right_side != null)
5938 member_lookup = member_lookup.DoResolveLValue (ec, right_side);
5940 member_lookup = member_lookup.DoResolve (ec);
5942 return member_lookup;
5945 public override Expression DoResolve (EmitContext ec)
5947 return DoResolve (ec, null, ResolveFlags.VariableOrValue |
5948 ResolveFlags.SimpleName | ResolveFlags.Type);
5951 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
5953 return DoResolve (ec, right_side, ResolveFlags.VariableOrValue |
5954 ResolveFlags.SimpleName | ResolveFlags.Type);
5957 public Expression DoResolveType (EmitContext ec)
5959 return DoResolve (ec, null, ResolveFlags.Type);
5962 public override void Emit (EmitContext ec)
5964 throw new Exception ("Should not happen");
5967 public override string ToString ()
5969 return expr + "." + Identifier;
5976 /// Implements checked expressions
5978 public class CheckedExpr : Expression {
5980 public Expression Expr;
5982 public CheckedExpr (Expression e, Location l)
5988 public override Expression DoResolve (EmitContext ec)
5990 bool last_const_check = ec.ConstantCheckState;
5992 ec.ConstantCheckState = true;
5993 Expr = Expr.Resolve (ec);
5994 ec.ConstantCheckState = last_const_check;
5999 if (Expr is Constant)
6002 eclass = Expr.eclass;
6007 public override void Emit (EmitContext ec)
6009 bool last_check = ec.CheckState;
6010 bool last_const_check = ec.ConstantCheckState;
6012 ec.CheckState = true;
6013 ec.ConstantCheckState = true;
6015 ec.CheckState = last_check;
6016 ec.ConstantCheckState = last_const_check;
6022 /// Implements the unchecked expression
6024 public class UnCheckedExpr : Expression {
6026 public Expression Expr;
6028 public UnCheckedExpr (Expression e, Location l)
6034 public override Expression DoResolve (EmitContext ec)
6036 bool last_const_check = ec.ConstantCheckState;
6038 ec.ConstantCheckState = false;
6039 Expr = Expr.Resolve (ec);
6040 ec.ConstantCheckState = last_const_check;
6045 if (Expr is Constant)
6048 eclass = Expr.eclass;
6053 public override void Emit (EmitContext ec)
6055 bool last_check = ec.CheckState;
6056 bool last_const_check = ec.ConstantCheckState;
6058 ec.CheckState = false;
6059 ec.ConstantCheckState = false;
6061 ec.CheckState = last_check;
6062 ec.ConstantCheckState = last_const_check;
6068 /// An Element Access expression.
6070 /// During semantic analysis these are transformed into
6071 /// IndexerAccess or ArrayAccess
6073 public class ElementAccess : Expression {
6074 public ArrayList Arguments;
6075 public Expression Expr;
6077 public ElementAccess (Expression e, ArrayList e_list, Location l)
6086 Arguments = new ArrayList ();
6087 foreach (Expression tmp in e_list)
6088 Arguments.Add (new Argument (tmp, Argument.AType.Expression));
6092 bool CommonResolve (EmitContext ec)
6094 Expr = Expr.Resolve (ec);
6099 if (Arguments == null)
6102 foreach (Argument a in Arguments){
6103 if (!a.Resolve (ec, loc))
6110 Expression MakePointerAccess ()
6114 if (t == TypeManager.void_ptr_type){
6117 "The array index operation is not valid for void pointers");
6120 if (Arguments.Count != 1){
6123 "A pointer must be indexed by a single value");
6126 Expression p = new PointerArithmetic (true, Expr, ((Argument)Arguments [0]).Expr,
6128 return new Indirection (p, loc);
6131 public override Expression DoResolve (EmitContext ec)
6133 if (!CommonResolve (ec))
6137 // We perform some simple tests, and then to "split" the emit and store
6138 // code we create an instance of a different class, and return that.
6140 // I am experimenting with this pattern.
6145 return (new ArrayAccess (this, loc)).Resolve (ec);
6146 else if (t.IsPointer)
6147 return MakePointerAccess ();
6149 return (new IndexerAccess (this, loc)).Resolve (ec);
6152 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
6154 if (!CommonResolve (ec))
6159 return (new ArrayAccess (this, loc)).ResolveLValue (ec, right_side);
6160 else if (t.IsPointer)
6161 return MakePointerAccess ();
6163 return (new IndexerAccess (this, loc)).ResolveLValue (ec, right_side);
6166 public override void Emit (EmitContext ec)
6168 throw new Exception ("Should never be reached");
6173 /// Implements array access
6175 public class ArrayAccess : Expression, IAssignMethod, IMemoryLocation {
6177 // Points to our "data" repository
6181 LocalTemporary [] cached_locations;
6183 public ArrayAccess (ElementAccess ea_data, Location l)
6186 eclass = ExprClass.Variable;
6190 public override Expression DoResolve (EmitContext ec)
6192 ExprClass eclass = ea.Expr.eclass;
6195 // As long as the type is valid
6196 if (!(eclass == ExprClass.Variable || eclass == ExprClass.PropertyAccess ||
6197 eclass == ExprClass.Value)) {
6198 ea.Expr.Error118 ("variable or value");
6203 Type t = ea.Expr.Type;
6205 if (t == typeof (System.Object))
6207 // We can't resolve now, but we
6208 // have to try to access the array with a call
6209 // to LateIndexGet in the runtime
6211 Expression lig_call_expr = Mono.MonoBASIC.Parser.DecomposeQI("Microsoft.VisualBasic.CompilerServices.LateBinding.LateIndexGet", Location.Null);
6212 Expression obj_type = Mono.MonoBASIC.Parser.DecomposeQI("System.Object", Location.Null);
6213 ArrayList adims = new ArrayList();
6215 ArrayList ainit = new ArrayList();
6216 foreach (Argument a in ea.Arguments)
6217 ainit.Add ((Expression) a.Expr);
6219 adims.Add ((Expression) new IntLiteral (ea.Arguments.Count));
6221 Expression oace = new ArrayCreation (obj_type, adims, "", ainit, Location.Null);
6223 ArrayList args = new ArrayList();
6224 args.Add (new Argument(ea.Expr, Argument.AType.Expression));
6225 args.Add (new Argument(oace, Argument.AType.Expression));
6226 args.Add (new Argument(NullLiteral.Null, Argument.AType.Expression));
6228 Expression lig_call = new Invocation (lig_call_expr, args, Location.Null);
6229 lig_call = lig_call.Resolve(ec);
6233 if (t.GetArrayRank () != ea.Arguments.Count){
6235 "Incorrect number of indexes for array " +
6236 " expected: " + t.GetArrayRank () + " got: " +
6237 ea.Arguments.Count);
6240 type = TypeManager.TypeToCoreType (t.GetElementType ());
6241 if (type.IsPointer && !ec.InUnsafe){
6242 UnsafeError (ea.Location);
6246 foreach (Argument a in ea.Arguments){
6247 Type argtype = a.Type;
6249 if (argtype == TypeManager.int32_type ||
6250 argtype == TypeManager.uint32_type ||
6251 argtype == TypeManager.int64_type ||
6252 argtype == TypeManager.uint64_type)
6256 // Mhm. This is strage, because the Argument.Type is not the same as
6257 // Argument.Expr.Type: the value changes depending on the ref/out setting.
6259 // Wonder if I will run into trouble for this.
6261 a.Expr = ExpressionToArrayArgument (ec, a.Expr, ea.Location);
6266 eclass = ExprClass.Variable;
6272 /// Emits the right opcode to load an object of Type 't'
6273 /// from an array of T
6275 static public void EmitLoadOpcode (ILGenerator ig, Type type)
6277 if (type == TypeManager.byte_type || type == TypeManager.bool_type)
6278 ig.Emit (OpCodes.Ldelem_U1);
6279 else if (type == TypeManager.sbyte_type)
6280 ig.Emit (OpCodes.Ldelem_I1);
6281 else if (type == TypeManager.short_type)
6282 ig.Emit (OpCodes.Ldelem_I2);
6283 else if (type == TypeManager.ushort_type || type == TypeManager.char_type)
6284 ig.Emit (OpCodes.Ldelem_U2);
6285 else if (type == TypeManager.int32_type)
6286 ig.Emit (OpCodes.Ldelem_I4);
6287 else if (type == TypeManager.uint32_type)
6288 ig.Emit (OpCodes.Ldelem_U4);
6289 else if (type == TypeManager.uint64_type)
6290 ig.Emit (OpCodes.Ldelem_I8);
6291 else if (type == TypeManager.int64_type)
6292 ig.Emit (OpCodes.Ldelem_I8);
6293 else if (type == TypeManager.float_type)
6294 ig.Emit (OpCodes.Ldelem_R4);
6295 else if (type == TypeManager.double_type)
6296 ig.Emit (OpCodes.Ldelem_R8);
6297 else if (type == TypeManager.intptr_type)
6298 ig.Emit (OpCodes.Ldelem_I);
6299 else if (type.IsValueType){
6300 ig.Emit (OpCodes.Ldelema, type);
6301 ig.Emit (OpCodes.Ldobj, type);
6303 ig.Emit (OpCodes.Ldelem_Ref);
6307 /// Emits the right opcode to store an object of Type 't'
6308 /// from an array of T.
6310 static public void EmitStoreOpcode (ILGenerator ig, Type t)
6312 t = TypeManager.TypeToCoreType (t);
6313 if (TypeManager.IsEnumType (t) && t != TypeManager.enum_type)
6314 t = TypeManager.EnumToUnderlying (t);
6315 if (t == TypeManager.byte_type || t == TypeManager.sbyte_type ||
6316 t == TypeManager.bool_type)
6317 ig.Emit (OpCodes.Stelem_I1);
6318 else if (t == TypeManager.short_type || t == TypeManager.ushort_type || t == TypeManager.char_type)
6319 ig.Emit (OpCodes.Stelem_I2);
6320 else if (t == TypeManager.int32_type || t == TypeManager.uint32_type)
6321 ig.Emit (OpCodes.Stelem_I4);
6322 else if (t == TypeManager.int64_type || t == TypeManager.uint64_type)
6323 ig.Emit (OpCodes.Stelem_I8);
6324 else if (t == TypeManager.float_type)
6325 ig.Emit (OpCodes.Stelem_R4);
6326 else if (t == TypeManager.double_type)
6327 ig.Emit (OpCodes.Stelem_R8);
6328 else if (t == TypeManager.intptr_type)
6329 ig.Emit (OpCodes.Stelem_I);
6330 else if (t.IsValueType){
6331 ig.Emit (OpCodes.Stobj, t);
6333 ig.Emit (OpCodes.Stelem_Ref);
6336 MethodInfo FetchGetMethod ()
6338 ModuleBuilder mb = CodeGen.ModuleBuilder;
6339 int arg_count = ea.Arguments.Count;
6340 Type [] args = new Type [arg_count];
6343 for (int i = 0; i < arg_count; i++){
6344 //args [i++] = a.Type;
6345 args [i] = TypeManager.int32_type;
6348 get = mb.GetArrayMethod (
6349 ea.Expr.Type, "Get",
6350 CallingConventions.HasThis |
6351 CallingConventions.Standard,
6357 MethodInfo FetchAddressMethod ()
6359 ModuleBuilder mb = CodeGen.ModuleBuilder;
6360 int arg_count = ea.Arguments.Count;
6361 Type [] args = new Type [arg_count];
6363 string ptr_type_name;
6366 ptr_type_name = type.FullName + "&";
6367 ret_type = Type.GetType (ptr_type_name);
6370 // It is a type defined by the source code we are compiling
6372 if (ret_type == null){
6373 ret_type = mb.GetType (ptr_type_name);
6376 for (int i = 0; i < arg_count; i++){
6377 //args [i++] = a.Type;
6378 args [i] = TypeManager.int32_type;
6381 address = mb.GetArrayMethod (
6382 ea.Expr.Type, "Address",
6383 CallingConventions.HasThis |
6384 CallingConventions.Standard,
6391 // Load the array arguments into the stack.
6393 // If we have been requested to cache the values (cached_locations array
6394 // initialized), then load the arguments the first time and store them
6395 // in locals. otherwise load from local variables.
6397 void LoadArrayAndArguments (EmitContext ec)
6399 ILGenerator ig = ec.ig;
6401 if (cached_locations == null){
6403 foreach (Argument a in ea.Arguments){
6404 Type argtype = a.Expr.Type;
6408 if (argtype == TypeManager.int64_type)
6409 ig.Emit (OpCodes.Conv_Ovf_I);
6410 else if (argtype == TypeManager.uint64_type)
6411 ig.Emit (OpCodes.Conv_Ovf_I_Un);
6416 if (cached_locations [0] == null){
6417 cached_locations [0] = new LocalTemporary (ec, ea.Expr.Type);
6419 ig.Emit (OpCodes.Dup);
6420 cached_locations [0].Store (ec);
6424 foreach (Argument a in ea.Arguments){
6425 Type argtype = a.Expr.Type;
6427 cached_locations [j] = new LocalTemporary (ec, TypeManager.intptr_type /* a.Expr.Type */);
6429 if (argtype == TypeManager.int64_type)
6430 ig.Emit (OpCodes.Conv_Ovf_I);
6431 else if (argtype == TypeManager.uint64_type)
6432 ig.Emit (OpCodes.Conv_Ovf_I_Un);
6434 ig.Emit (OpCodes.Dup);
6435 cached_locations [j].Store (ec);
6441 foreach (LocalTemporary lt in cached_locations)
6445 public new void CacheTemporaries (EmitContext ec)
6447 cached_locations = new LocalTemporary [ea.Arguments.Count + 1];
6450 public override void Emit (EmitContext ec)
6452 int rank = ea.Expr.Type.GetArrayRank ();
6453 ILGenerator ig = ec.ig;
6455 LoadArrayAndArguments (ec);
6458 EmitLoadOpcode (ig, type);
6462 method = FetchGetMethod ();
6463 ig.Emit (OpCodes.Call, method);
6467 public void EmitAssign (EmitContext ec, Expression source)
6469 int rank = ea.Expr.Type.GetArrayRank ();
6470 ILGenerator ig = ec.ig;
6471 Type t = source.Type;
6473 LoadArrayAndArguments (ec);
6476 // The stobj opcode used by value types will need
6477 // an address on the stack, not really an array/array
6481 if (t == TypeManager.enum_type || t == TypeManager.decimal_type ||
6482 (t.IsSubclassOf (TypeManager.value_type) && !TypeManager.IsEnumType (t) && !TypeManager.IsBuiltinType (t)))
6483 ig.Emit (OpCodes.Ldelema, t);
6489 EmitStoreOpcode (ig, t);
6491 ModuleBuilder mb = CodeGen.ModuleBuilder;
6492 int arg_count = ea.Arguments.Count;
6493 Type [] args = new Type [arg_count + 1];
6496 for (int i = 0; i < arg_count; i++){
6497 //args [i++] = a.Type;
6498 args [i] = TypeManager.int32_type;
6501 args [arg_count] = type;
6503 set = mb.GetArrayMethod (
6504 ea.Expr.Type, "Set",
6505 CallingConventions.HasThis |
6506 CallingConventions.Standard,
6507 TypeManager.void_type, args);
6509 ig.Emit (OpCodes.Call, set);
6513 public void AddressOf (EmitContext ec, AddressOp mode)
6515 int rank = ea.Expr.Type.GetArrayRank ();
6516 ILGenerator ig = ec.ig;
6518 LoadArrayAndArguments (ec);
6521 ig.Emit (OpCodes.Ldelema, type);
6523 MethodInfo address = FetchAddressMethod ();
6524 ig.Emit (OpCodes.Call, address);
6531 public ArrayList getters, setters;
6532 static Hashtable map;
6536 map = new Hashtable ();
6539 Indexers (MemberInfo [] mi)
6541 foreach (PropertyInfo property in mi){
6542 MethodInfo get, set;
6544 get = property.GetGetMethod (true);
6546 if (getters == null)
6547 getters = new ArrayList ();
6552 set = property.GetSetMethod (true);
6554 if (setters == null)
6555 setters = new ArrayList ();
6561 static private Indexers GetIndexersForTypeOrInterface (Type caller_type, Type lookup_type)
6563 Indexers ix = (Indexers) map [lookup_type];
6568 string p_name = TypeManager.IndexerPropertyName (lookup_type);
6570 MemberInfo [] mi = TypeManager.MemberLookup (
6571 caller_type, lookup_type, MemberTypes.Property,
6572 BindingFlags.Public | BindingFlags.Instance, p_name);
6574 if (mi == null || mi.Length == 0)
6577 ix = new Indexers (mi);
6578 map [lookup_type] = ix;
6583 static public Indexers GetIndexersForType (Type caller_type, Type lookup_type, Location loc)
6585 Indexers ix = (Indexers) map [lookup_type];
6590 ix = GetIndexersForTypeOrInterface (caller_type, lookup_type);
6594 Type [] ifaces = TypeManager.GetInterfaces (lookup_type);
6595 if (ifaces != null) {
6596 foreach (Type itype in ifaces) {
6597 ix = GetIndexersForTypeOrInterface (caller_type, itype);
6603 Report.Error (21, loc,
6604 "Type '" + TypeManager.MonoBASIC_Name (lookup_type) +
6605 "' does not have any indexers defined");
6611 /// Expressions that represent an indexer call.
6613 public class IndexerAccess : Expression, IAssignMethod {
6615 // Points to our "data" repository
6617 MethodInfo get, set;
6619 ArrayList set_arguments;
6620 bool is_base_indexer;
6622 protected Type indexer_type;
6623 protected Type current_type;
6624 protected Expression instance_expr;
6625 protected ArrayList arguments;
6627 public IndexerAccess (ElementAccess ea, Location loc)
6628 : this (ea.Expr, false, loc)
6630 this.arguments = ea.Arguments;
6633 protected IndexerAccess (Expression instance_expr, bool is_base_indexer,
6636 this.instance_expr = instance_expr;
6637 this.is_base_indexer = is_base_indexer;
6638 this.eclass = ExprClass.Value;
6642 protected virtual bool CommonResolve (EmitContext ec)
6644 indexer_type = instance_expr.Type;
6645 current_type = ec.ContainerType;
6650 public override Expression DoResolve (EmitContext ec)
6652 if (!CommonResolve (ec))
6656 // Step 1: Query for all 'Item' *properties*. Notice
6657 // that the actual methods are pointed from here.
6659 // This is a group of properties, piles of them.
6662 ilist = Indexers.GetIndexersForType (
6663 current_type, indexer_type, loc);
6666 // Step 2: find the proper match
6668 if (ilist != null && ilist.getters != null && ilist.getters.Count > 0)
6669 get = (MethodInfo) Invocation.OverloadResolve (
6670 ec, new MethodGroupExpr (ilist.getters, loc), arguments, loc);
6673 Error (154, "indexer can not be used in this context, because " +
6674 "it lacks a 'get' accessor");
6678 type = get.ReturnType;
6679 if (type.IsPointer && !ec.InUnsafe){
6684 eclass = ExprClass.IndexerAccess;
6688 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
6690 if (!CommonResolve (ec))
6693 Type right_type = right_side.Type;
6696 ilist = Indexers.GetIndexersForType (
6697 current_type, indexer_type, loc);
6699 if (ilist != null && ilist.setters != null && ilist.setters.Count > 0){
6700 set_arguments = (ArrayList) arguments.Clone ();
6701 set_arguments.Add (new Argument (right_side, Argument.AType.Expression));
6703 set = (MethodInfo) Invocation.OverloadResolve (
6704 ec, new MethodGroupExpr (ilist.setters, loc), set_arguments, loc);
6708 Error (200, "indexer X.this [" + TypeManager.MonoBASIC_Name (right_type) +
6709 "] lacks a 'set' accessor");
6713 type = TypeManager.void_type;
6714 eclass = ExprClass.IndexerAccess;
6718 public override void Emit (EmitContext ec)
6720 Invocation.EmitCall (ec, false, false, instance_expr, get, arguments, loc);
6724 // source is ignored, because we already have a copy of it from the
6725 // LValue resolution and we have already constructed a pre-cached
6726 // version of the arguments (ea.set_arguments);
6728 public void EmitAssign (EmitContext ec, Expression source)
6730 Invocation.EmitCall (ec, false, false, instance_expr, set, set_arguments, loc);
6735 /// The base operator for method names
6737 public class BaseAccess : Expression {
6738 public string member;
6740 public BaseAccess (string member, Location l)
6742 this.member = member;
6746 public override Expression DoResolve (EmitContext ec)
6748 Expression member_lookup;
6749 Type current_type = ec.ContainerType;
6750 Type base_type = current_type.BaseType;
6754 Error (1511, "Keyword MyBase is not allowed in static method");
6758 if (member == "New")
6761 member_lookup = MemberLookup (ec, current_type, base_type, member,
6762 AllMemberTypes, AllBindingFlags, loc);
6764 if (member_lookup == null) {
6766 TypeManager.MonoBASIC_Name (base_type) + " does not " +
6767 "contain a definition for '" + member + "'");
6774 left = new TypeExpr (base_type, loc);
6778 e = MemberAccess.ResolveMemberAccess (ec, member_lookup, left, loc, null);
6780 if (e is PropertyExpr) {
6781 PropertyExpr pe = (PropertyExpr) e;
6789 public override void Emit (EmitContext ec)
6791 throw new Exception ("Should never be called");
6796 /// The base indexer operator
6798 public class BaseIndexerAccess : IndexerAccess {
6799 public BaseIndexerAccess (ArrayList args, Location loc)
6800 : base (null, true, loc)
6802 arguments = new ArrayList ();
6803 foreach (Expression tmp in args)
6804 arguments.Add (new Argument (tmp, Argument.AType.Expression));
6807 protected override bool CommonResolve (EmitContext ec)
6809 instance_expr = ec.This;
6811 current_type = ec.ContainerType.BaseType;
6812 indexer_type = current_type;
6814 foreach (Argument a in arguments){
6815 if (!a.Resolve (ec, loc))
6824 /// This class exists solely to pass the Type around and to be a dummy
6825 /// that can be passed to the conversion functions (this is used by
6826 /// foreach implementation to typecast the object return value from
6827 /// get_Current into the proper type. All code has been generated and
6828 /// we only care about the side effect conversions to be performed
6830 /// This is also now used as a placeholder where a no-action expression
6831 /// is needed (the 'New' class).
6833 public class EmptyExpression : Expression {
6834 public EmptyExpression ()
6836 type = TypeManager.object_type;
6837 eclass = ExprClass.Value;
6838 loc = Location.Null;
6841 public EmptyExpression (Type t)
6844 eclass = ExprClass.Value;
6845 loc = Location.Null;
6848 public override Expression DoResolve (EmitContext ec)
6853 public override void Emit (EmitContext ec)
6855 // nothing, as we only exist to not do anything.
6859 // This is just because we might want to reuse this bad boy
6860 // instead of creating gazillions of EmptyExpressions.
6861 // (CanConvertImplicit uses it)
6863 public void SetType (Type t)
6869 public class UserCast : Expression {
6873 public UserCast (MethodInfo method, Expression source, Location l)
6875 this.method = method;
6876 this.source = source;
6877 type = method.ReturnType;
6878 eclass = ExprClass.Value;
6882 public override Expression DoResolve (EmitContext ec)
6885 // We are born fully resolved
6890 public override void Emit (EmitContext ec)
6892 ILGenerator ig = ec.ig;
6896 if (method is MethodInfo)
6897 ig.Emit (OpCodes.Call, (MethodInfo) method);
6899 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
6905 // This class is used to "construct" the type during a typecast
6906 // operation. Since the Type.GetType class in .NET can parse
6907 // the type specification, we just use this to construct the type
6908 // one bit at a time.
6910 public class ComposedCast : Expression, ITypeExpression {
6914 public ComposedCast (Expression left, string dim, Location l)
6921 public Expression DoResolveType (EmitContext ec)
6923 Type ltype = ec.DeclSpace.ResolveType (left, false, loc);
6928 // ltype.Fullname is already fully qualified, so we can skip
6929 // a lot of probes, and go directly to TypeManager.LookupType
6931 string cname = ltype.FullName + dim;
6932 type = TypeManager.LookupTypeDirect (cname);
6935 // For arrays of enumerations we are having a problem
6936 // with the direct lookup. Need to investigate.
6938 // For now, fall back to the full lookup in that case.
6940 type = RootContext.LookupType (
6941 ec.DeclSpace, cname, false, loc);
6947 if (!ec.ResolvingTypeTree){
6949 // If the above flag is set, this is being invoked from the ResolveType function.
6950 // Upper layers take care of the type validity in this context.
6952 if (!ec.InUnsafe && type.IsPointer){
6958 eclass = ExprClass.Type;
6962 public override Expression DoResolve (EmitContext ec)
6964 return DoResolveType (ec);
6967 public override void Emit (EmitContext ec)
6969 throw new Exception ("This should never be called");
6972 public override string ToString ()
6979 // This class is used to represent the address of an array, used
6980 // only by the Fixed statement, this is like the C "&a [0]" construct.
6982 public class ArrayPtr : Expression {
6985 public ArrayPtr (Expression array, Location l)
6987 Type array_type = array.Type.GetElementType ();
6991 string array_ptr_type_name = array_type.FullName + "*";
6993 type = Type.GetType (array_ptr_type_name);
6995 ModuleBuilder mb = CodeGen.ModuleBuilder;
6997 type = mb.GetType (array_ptr_type_name);
7000 eclass = ExprClass.Value;
7004 public override void Emit (EmitContext ec)
7006 ILGenerator ig = ec.ig;
7009 IntLiteral.EmitInt (ig, 0);
7010 ig.Emit (OpCodes.Ldelema, array.Type.GetElementType ());
7013 public override Expression DoResolve (EmitContext ec)
7016 // We are born fully resolved
7023 // Used by the fixed statement
7025 public class StringPtr : Expression {
7028 public StringPtr (LocalBuilder b, Location l)
7031 eclass = ExprClass.Value;
7032 type = TypeManager.char_ptr_type;
7036 public override Expression DoResolve (EmitContext ec)
7038 // This should never be invoked, we are born in fully
7039 // initialized state.
7044 public override void Emit (EmitContext ec)
7046 ILGenerator ig = ec.ig;
7048 ig.Emit (OpCodes.Ldloc, b);
7049 ig.Emit (OpCodes.Conv_I);
7050 ig.Emit (OpCodes.Call, TypeManager.int_get_offset_to_string_data);
7051 ig.Emit (OpCodes.Add);
7056 // Implements the 'stackalloc' keyword
7058 public class StackAlloc : Expression {
7063 public StackAlloc (Expression type, Expression count, Location l)
7070 public override Expression DoResolve (EmitContext ec)
7072 count = count.Resolve (ec);
7076 if (count.Type != TypeManager.int32_type){
7077 count = ConvertImplicitRequired (ec, count, TypeManager.int32_type, loc);
7082 if (ec.InCatch || ec.InFinally){
7084 "stackalloc can not be used in a catch or finally block");
7088 otype = ec.DeclSpace.ResolveType (t, false, loc);
7093 if (!TypeManager.VerifyUnManaged (otype, loc))
7096 string ptr_name = otype.FullName + "*";
7097 type = Type.GetType (ptr_name);
7099 ModuleBuilder mb = CodeGen.ModuleBuilder;
7101 type = mb.GetType (ptr_name);
7103 eclass = ExprClass.Value;
7108 public override void Emit (EmitContext ec)
7110 int size = GetTypeSize (otype);
7111 ILGenerator ig = ec.ig;
7114 ig.Emit (OpCodes.Sizeof, otype);
7116 IntConstant.EmitInt (ig, size);
7118 ig.Emit (OpCodes.Mul);
7119 ig.Emit (OpCodes.Localloc);