2 // ecore.cs: Core of the Expression representation for the intermediate tree.
5 // Miguel de Icaza (miguel@ximian.com)
7 // (C) 2001, 2002, 2003 Ximian, Inc.
11 namespace Mono.CSharp {
13 using System.Collections;
14 using System.Diagnostics;
15 using System.Reflection;
16 using System.Reflection.Emit;
20 /// The ExprClass class contains the is used to pass the
21 /// classification of an expression (value, variable, namespace,
22 /// type, method group, property access, event access, indexer access,
25 public enum ExprClass : byte {
40 /// This is used to tell Resolve in which types of expressions we're
44 public enum ResolveFlags {
45 // Returns Value, Variable, PropertyAccess, EventAccess or IndexerAccess.
48 // Returns a type expression.
51 // Returns a method group.
54 // Mask of all the expression class flags.
57 // Disable control flow analysis while resolving the expression.
58 // This is used when resolving the instance expression of a field expression.
59 DisableFlowAnalysis = 8,
61 // Set if this is resolving the first part of a MemberAccess.
66 // This is just as a hint to AddressOf of what will be done with the
69 public enum AddressOp {
76 /// This interface is implemented by variables
78 public interface IMemoryLocation {
80 /// The AddressOf method should generate code that loads
81 /// the address of the object and leaves it on the stack.
83 /// The `mode' argument is used to notify the expression
84 /// of whether this will be used to read from the address or
85 /// write to the address.
87 /// This is just a hint that can be used to provide good error
88 /// reporting, and should have no other side effects.
90 void AddressOf (EmitContext ec, AddressOp mode);
94 /// This interface is implemented by variables
96 public interface IVariable {
97 VariableInfo VariableInfo {
105 /// Base class for expressions
107 public abstract class Expression {
108 public ExprClass eclass;
110 protected Location loc;
114 set { type = value; }
117 public Location Location {
122 /// Utility wrapper routine for Error, just to beautify the code
124 public void Error (int error, string s)
126 if (!Location.IsNull (loc))
127 Report.Error (error, loc, s);
129 Report.Error (error, s);
133 /// Utility wrapper routine for Warning, just to beautify the code
135 public void Warning (int code, string format, params object[] args)
137 Report.Warning (code, loc, format, args);
140 // Not nice but we have broken hierarchy
141 public virtual void CheckMarshallByRefAccess (Type container) {}
144 /// Tests presence of ObsoleteAttribute and report proper error
146 protected void CheckObsoleteAttribute (Type type)
148 ObsoleteAttribute obsolete_attr = AttributeTester.GetObsoleteAttribute (type);
149 if (obsolete_attr == null)
152 AttributeTester.Report_ObsoleteMessage (obsolete_attr, type.FullName, loc);
155 public virtual string GetSignatureForError ()
157 return TypeManager.CSharpName (type);
160 public static bool IsAccessorAccessible (Type invocation_type, MethodInfo mi, out bool must_do_cs1540_check)
162 MethodAttributes ma = mi.Attributes & MethodAttributes.MemberAccessMask;
164 must_do_cs1540_check = false; // by default we do not check for this
167 // If only accessible to the current class or children
169 if (ma == MethodAttributes.Private)
170 return invocation_type == mi.DeclaringType ||
171 TypeManager.IsNestedChildOf (invocation_type, mi.DeclaringType);
173 if (mi.DeclaringType.Assembly == invocation_type.Assembly) {
174 if (ma == MethodAttributes.Assembly || ma == MethodAttributes.FamORAssem)
177 if (ma == MethodAttributes.Assembly || ma == MethodAttributes.FamANDAssem)
181 // Family and FamANDAssem require that we derive.
182 // FamORAssem requires that we derive if in different assemblies.
183 if (ma == MethodAttributes.Family ||
184 ma == MethodAttributes.FamANDAssem ||
185 ma == MethodAttributes.FamORAssem) {
186 if (!TypeManager.IsNestedFamilyAccessible (invocation_type, mi.DeclaringType))
189 if (!TypeManager.IsNestedChildOf (invocation_type, mi.DeclaringType))
190 must_do_cs1540_check = true;
199 /// Performs semantic analysis on the Expression
203 /// The Resolve method is invoked to perform the semantic analysis
206 /// The return value is an expression (it can be the
207 /// same expression in some cases) or a new
208 /// expression that better represents this node.
210 /// For example, optimizations of Unary (LiteralInt)
211 /// would return a new LiteralInt with a negated
214 /// If there is an error during semantic analysis,
215 /// then an error should be reported (using Report)
216 /// and a null value should be returned.
218 /// There are two side effects expected from calling
219 /// Resolve(): the the field variable "eclass" should
220 /// be set to any value of the enumeration
221 /// `ExprClass' and the type variable should be set
222 /// to a valid type (this is the type of the
225 public abstract Expression DoResolve (EmitContext ec);
227 public virtual Expression DoResolveLValue (EmitContext ec, Expression right_side)
233 // This is used if the expression should be resolved as a type or namespace name.
234 // the default implementation fails.
236 public virtual FullNamedExpression ResolveAsTypeStep (EmitContext ec, bool silent)
242 // This is used to resolve the expression as a type, a null
243 // value will be returned if the expression is not a type
246 public TypeExpr ResolveAsTypeTerminal (EmitContext ec, bool silent)
248 int errors = Report.Errors;
250 FullNamedExpression fne = ResolveAsTypeStep (ec, silent);
255 if (fne.eclass != ExprClass.Type) {
256 if (!silent && errors == Report.Errors)
257 fne.Error_UnexpectedKind (null, "type", loc);
261 TypeExpr te = fne as TypeExpr;
263 if (!te.CheckAccessLevel (ec.DeclSpace)) {
264 ErrorIsInaccesible (loc, TypeManager.CSharpName (te.Type));
271 public static void ErrorIsInaccesible (Location loc, string name)
273 Report.Error (122, loc, "`{0}' is inaccessible due to its protection level", name);
276 ResolveFlags ExprClassToResolveFlags ()
280 case ExprClass.Namespace:
281 return ResolveFlags.Type;
283 case ExprClass.MethodGroup:
284 return ResolveFlags.MethodGroup;
286 case ExprClass.Value:
287 case ExprClass.Variable:
288 case ExprClass.PropertyAccess:
289 case ExprClass.EventAccess:
290 case ExprClass.IndexerAccess:
291 return ResolveFlags.VariableOrValue;
294 throw new Exception ("Expression " + GetType () +
295 " ExprClass is Invalid after resolve");
301 /// Resolves an expression and performs semantic analysis on it.
305 /// Currently Resolve wraps DoResolve to perform sanity
306 /// checking and assertion checking on what we expect from Resolve.
308 public Expression Resolve (EmitContext ec, ResolveFlags flags)
310 if ((flags & ResolveFlags.MaskExprClass) == ResolveFlags.Type)
311 return ResolveAsTypeStep (ec, false);
313 bool old_do_flow_analysis = ec.DoFlowAnalysis;
314 if ((flags & ResolveFlags.DisableFlowAnalysis) != 0)
315 ec.DoFlowAnalysis = false;
318 bool intermediate = (flags & ResolveFlags.Intermediate) == ResolveFlags.Intermediate;
319 if (this is SimpleName)
320 e = ((SimpleName) this).DoResolve (ec, intermediate);
325 ec.DoFlowAnalysis = old_do_flow_analysis;
330 if ((flags & e.ExprClassToResolveFlags ()) == 0) {
331 e.Error_UnexpectedKind (flags, loc);
335 if (e.type == null && !(e is Namespace)) {
336 throw new Exception (
337 "Expression " + e.GetType () +
338 " did not set its type after Resolve\n" +
339 "called from: " + this.GetType ());
346 /// Resolves an expression and performs semantic analysis on it.
348 public Expression Resolve (EmitContext ec)
350 Expression e = Resolve (ec, ResolveFlags.VariableOrValue | ResolveFlags.MethodGroup);
352 if (e != null && e.eclass == ExprClass.MethodGroup && RootContext.Version == LanguageVersion.ISO_1) {
353 ((MethodGroupExpr) e).ReportUsageError ();
360 /// Resolves an expression for LValue assignment
364 /// Currently ResolveLValue wraps DoResolveLValue to perform sanity
365 /// checking and assertion checking on what we expect from Resolve
367 public Expression ResolveLValue (EmitContext ec, Expression right_side, Location loc)
369 int errors = Report.Errors;
370 Expression e = DoResolveLValue (ec, right_side);
373 if (errors == Report.Errors)
374 Report.Error (131, loc, "The left-hand side of an assignment or mutating operation must be a variable, property or indexer");
379 if (e.eclass == ExprClass.Invalid)
380 throw new Exception ("Expression " + e +
381 " ExprClass is Invalid after resolve");
383 if (e.eclass == ExprClass.MethodGroup) {
384 ((MethodGroupExpr) e).ReportUsageError ();
389 throw new Exception ("Expression " + e +
390 " did not set its type after Resolve");
397 /// Emits the code for the expression
401 /// The Emit method is invoked to generate the code
402 /// for the expression.
404 public abstract void Emit (EmitContext ec);
406 public virtual void EmitBranchable (EmitContext ec, Label target, bool onTrue)
409 ec.ig.Emit (onTrue ? OpCodes.Brtrue : OpCodes.Brfalse, target);
413 /// Protected constructor. Only derivate types should
414 /// be able to be created
417 protected Expression ()
419 eclass = ExprClass.Invalid;
424 /// Returns a literalized version of a literal FieldInfo
428 /// The possible return values are:
429 /// IntConstant, UIntConstant
430 /// LongLiteral, ULongConstant
431 /// FloatConstant, DoubleConstant
434 /// The value returned is already resolved.
436 public static Constant Constantify (object v, Type t)
438 if (t == TypeManager.int32_type)
439 return new IntConstant ((int) v);
440 else if (t == TypeManager.uint32_type)
441 return new UIntConstant ((uint) v);
442 else if (t == TypeManager.int64_type)
443 return new LongConstant ((long) v);
444 else if (t == TypeManager.uint64_type)
445 return new ULongConstant ((ulong) v);
446 else if (t == TypeManager.float_type)
447 return new FloatConstant ((float) v);
448 else if (t == TypeManager.double_type)
449 return new DoubleConstant ((double) v);
450 else if (t == TypeManager.string_type)
451 return new StringConstant ((string) v);
452 else if (t == TypeManager.short_type)
453 return new ShortConstant ((short)v);
454 else if (t == TypeManager.ushort_type)
455 return new UShortConstant ((ushort)v);
456 else if (t == TypeManager.sbyte_type)
457 return new SByteConstant (((sbyte)v));
458 else if (t == TypeManager.byte_type)
459 return new ByteConstant ((byte)v);
460 else if (t == TypeManager.char_type)
461 return new CharConstant ((char)v);
462 else if (t == TypeManager.bool_type)
463 return new BoolConstant ((bool) v);
464 else if (t == TypeManager.decimal_type)
465 return new DecimalConstant ((decimal) v);
466 else if (TypeManager.IsEnumType (t)){
467 Type real_type = TypeManager.TypeToCoreType (v.GetType ());
469 real_type = System.Enum.GetUnderlyingType (real_type);
471 Constant e = Constantify (v, real_type);
473 return new EnumConstant (e, t);
474 } else if (v == null && !TypeManager.IsValueType (t))
475 return NullLiteral.Null;
477 throw new Exception ("Unknown type for constant (" + t +
482 /// Returns a fully formed expression after a MemberLookup
484 public static Expression ExprClassFromMemberInfo (EmitContext ec, MemberInfo mi, Location loc)
487 return new EventExpr ((EventInfo) mi, loc);
488 else if (mi is FieldInfo)
489 return new FieldExpr ((FieldInfo) mi, loc);
490 else if (mi is PropertyInfo)
491 return new PropertyExpr (ec, (PropertyInfo) mi, loc);
492 else if (mi is Type){
493 return new TypeExpression ((System.Type) mi, loc);
499 protected static ArrayList almostMatchedMembers = new ArrayList (4);
502 // FIXME: Probably implement a cache for (t,name,current_access_set)?
504 // This code could use some optimizations, but we need to do some
505 // measurements. For example, we could use a delegate to `flag' when
506 // something can not any longer be a method-group (because it is something
510 // If the return value is an Array, then it is an array of
513 // If the return value is an MemberInfo, it is anything, but a Method
517 // FIXME: When calling MemberLookup inside an `Invocation', we should pass
518 // the arguments here and have MemberLookup return only the methods that
519 // match the argument count/type, unlike we are doing now (we delay this
522 // This is so we can catch correctly attempts to invoke instance methods
523 // from a static body (scan for error 120 in ResolveSimpleName).
526 // FIXME: Potential optimization, have a static ArrayList
529 public static Expression MemberLookup (EmitContext ec, Type queried_type, string name,
530 MemberTypes mt, BindingFlags bf, Location loc)
532 return MemberLookup (ec, ec.ContainerType, null, queried_type, name, mt, bf, loc);
536 // Lookup type `queried_type' for code in class `container_type' with a qualifier of
537 // `qualifier_type' or null to lookup members in the current class.
540 public static Expression MemberLookup (EmitContext ec, Type container_type,
541 Type qualifier_type, Type queried_type,
542 string name, MemberTypes mt,
543 BindingFlags bf, Location loc)
545 almostMatchedMembers.Clear ();
547 MemberInfo [] mi = TypeManager.MemberLookup (container_type, qualifier_type,
548 queried_type, mt, bf, name, almostMatchedMembers);
553 int count = mi.Length;
555 if (mi [0] is MethodBase)
556 return new MethodGroupExpr (mi, loc);
561 return ExprClassFromMemberInfo (ec, mi [0], loc);
564 public const MemberTypes AllMemberTypes =
565 MemberTypes.Constructor |
569 MemberTypes.NestedType |
570 MemberTypes.Property;
572 public const BindingFlags AllBindingFlags =
573 BindingFlags.Public |
574 BindingFlags.Static |
575 BindingFlags.Instance;
577 public static Expression MemberLookup (EmitContext ec, Type queried_type,
578 string name, Location loc)
580 return MemberLookup (ec, ec.ContainerType, null, queried_type, name,
581 AllMemberTypes, AllBindingFlags, loc);
584 public static Expression MemberLookup (EmitContext ec, Type qualifier_type,
585 Type queried_type, string name, Location loc)
587 return MemberLookup (ec, ec.ContainerType, qualifier_type, queried_type,
588 name, AllMemberTypes, AllBindingFlags, loc);
591 public static Expression MethodLookup (EmitContext ec, Type queried_type,
592 string name, Location loc)
594 return MemberLookup (ec, ec.ContainerType, null, queried_type, name,
595 MemberTypes.Method, AllBindingFlags, loc);
599 /// This is a wrapper for MemberLookup that is not used to "probe", but
600 /// to find a final definition. If the final definition is not found, we
601 /// look for private members and display a useful debugging message if we
604 public static Expression MemberLookupFinal (EmitContext ec, Type qualifier_type,
605 Type queried_type, string name, Location loc)
607 return MemberLookupFinal (ec, qualifier_type, queried_type, name,
608 AllMemberTypes, AllBindingFlags, loc);
611 public static Expression MemberLookupFinal (EmitContext ec, Type qualifier_type,
612 Type queried_type, string name,
613 MemberTypes mt, BindingFlags bf,
618 int errors = Report.Errors;
620 e = MemberLookup (ec, ec.ContainerType, qualifier_type, queried_type, name, mt, bf, loc);
622 if (e == null && errors == Report.Errors)
623 // No errors were reported by MemberLookup, but there was an error.
624 MemberLookupFailed (ec, qualifier_type, queried_type, name, null, true, loc);
629 public static void MemberLookupFailed (EmitContext ec, Type qualifier_type,
630 Type queried_type, string name,
631 string class_name, bool complain_if_none_found,
634 if (almostMatchedMembers.Count != 0) {
635 for (int i = 0; i < almostMatchedMembers.Count; ++i) {
636 MemberInfo m = (MemberInfo) almostMatchedMembers [i];
637 for (int j = 0; j < i; ++j) {
638 if (m == almostMatchedMembers [j]) {
646 Type declaring_type = m.DeclaringType;
648 Report.SymbolRelatedToPreviousError (m);
649 if (qualifier_type == null) {
650 Report.Error (38, loc, "Cannot access a nonstatic member of outer type `{0}' via nested type `{1}'",
651 TypeManager.CSharpName (m.DeclaringType),
652 TypeManager.CSharpName (ec.ContainerType));
654 } else if (qualifier_type != ec.ContainerType &&
655 TypeManager.IsNestedFamilyAccessible (ec.ContainerType, declaring_type)) {
656 // Although a derived class can access protected members of
657 // its base class it cannot do so through an instance of the
658 // base class (CS1540). If the qualifier_type is a base of the
659 // ec.ContainerType and the lookup succeeds with the latter one,
660 // then we are in this situation.
661 Report.Error (1540, loc,
662 "Cannot access protected member `{0}' via a qualifier of type `{1}';"
663 + " the qualifier must be of type `{2}' (or derived from it)",
664 TypeManager.GetFullNameSignature (m),
665 TypeManager.CSharpName (qualifier_type),
666 TypeManager.CSharpName (ec.ContainerType));
668 ErrorIsInaccesible (loc, TypeManager.GetFullNameSignature (m));
671 almostMatchedMembers.Clear ();
675 MemberInfo[] lookup = TypeManager.MemberLookup (queried_type, null, queried_type,
676 AllMemberTypes, AllBindingFlags |
677 BindingFlags.NonPublic, name, null);
679 if (lookup == null) {
680 if (!complain_if_none_found)
683 if (class_name != null)
684 Report.Error (103, loc, "The name `{0}' does not exist in the context of `{1}'",
688 117, loc, "`" + TypeManager.CSharpName (queried_type) + "' does not contain a " +
689 "definition for `" + name + "'");
693 MemberList ml = TypeManager.FindMembers (qualifier_type, MemberTypes.Constructor,
694 BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly, null, null);
695 if (name == ".ctor" && ml.Count == 0)
697 Report.Error (143, loc, String.Format ("The type `{0}' has no constructors defined", TypeManager.CSharpName (queried_type)));
701 ErrorIsInaccesible (loc, TypeManager.GetFullNameSignature (lookup [0]));
705 /// Returns an expression that can be used to invoke operator true
706 /// on the expression if it exists.
708 static public StaticCallExpr GetOperatorTrue (EmitContext ec, Expression e, Location loc)
710 return GetOperatorTrueOrFalse (ec, e, true, loc);
714 /// Returns an expression that can be used to invoke operator false
715 /// on the expression if it exists.
717 static public StaticCallExpr GetOperatorFalse (EmitContext ec, Expression e, Location loc)
719 return GetOperatorTrueOrFalse (ec, e, false, loc);
722 static StaticCallExpr GetOperatorTrueOrFalse (EmitContext ec, Expression e, bool is_true, Location loc)
725 Expression operator_group;
727 operator_group = MethodLookup (ec, e.Type, is_true ? "op_True" : "op_False", loc);
728 if (operator_group == null)
731 ArrayList arguments = new ArrayList ();
732 arguments.Add (new Argument (e, Argument.AType.Expression));
733 method = Invocation.OverloadResolve (
734 ec, (MethodGroupExpr) operator_group, arguments, false, loc);
739 return new StaticCallExpr ((MethodInfo) method, arguments, loc);
743 /// Resolves the expression `e' into a boolean expression: either through
744 /// an implicit conversion, or through an `operator true' invocation
746 public static Expression ResolveBoolean (EmitContext ec, Expression e, Location loc)
752 if (e.Type == TypeManager.bool_type)
755 Expression converted = Convert.ImplicitConversion (ec, e, TypeManager.bool_type, Location.Null);
757 if (converted != null)
761 // If no implicit conversion to bool exists, try using `operator true'
763 Expression operator_true = Expression.GetOperatorTrue (ec, e, loc);
764 if (operator_true == null){
765 Report.Error (31, loc, "Can not convert the expression to a boolean");
768 return operator_true;
771 string ExprClassName ()
774 case ExprClass.Invalid:
776 case ExprClass.Value:
778 case ExprClass.Variable:
780 case ExprClass.Namespace:
784 case ExprClass.MethodGroup:
785 return "method group";
786 case ExprClass.PropertyAccess:
787 return "property access";
788 case ExprClass.EventAccess:
789 return "event access";
790 case ExprClass.IndexerAccess:
791 return "indexer access";
792 case ExprClass.Nothing:
795 throw new Exception ("Should not happen");
799 /// Reports that we were expecting `expr' to be of class `expected'
801 public void Error_UnexpectedKind (EmitContext ec, string expected, Location loc)
803 Error_UnexpectedKind (ec, expected, ExprClassName (), loc);
806 public void Error_UnexpectedKind (EmitContext ec, string expected, string was, Location loc)
808 string name = GetSignatureForError ();
810 name = ec.DeclSpace.GetSignatureForError () + '.' + name;
812 Report.Error (118, loc, "`{0}' is a `{1}' but a `{2}' was expected",
813 name, was, expected);
816 public void Error_UnexpectedKind (ResolveFlags flags, Location loc)
818 string [] valid = new string [4];
821 if ((flags & ResolveFlags.VariableOrValue) != 0) {
822 valid [count++] = "variable";
823 valid [count++] = "value";
826 if ((flags & ResolveFlags.Type) != 0)
827 valid [count++] = "type";
829 if ((flags & ResolveFlags.MethodGroup) != 0)
830 valid [count++] = "method group";
833 valid [count++] = "unknown";
835 StringBuilder sb = new StringBuilder (valid [0]);
836 for (int i = 1; i < count - 1; i++) {
838 sb.Append (valid [i]);
841 sb.Append ("' or `");
842 sb.Append (valid [count - 1]);
845 Report.Error (119, loc,
846 "Expression denotes a `{0}', where a `{1}' was expected", ExprClassName (), sb);
849 static public void Error_ConstantValueCannotBeConverted (Location l, string val, Type t)
851 Report.Error (31, l, "Constant value `" + val + "' cannot be converted to " +
852 TypeManager.CSharpName (t));
855 public static void UnsafeError (Location loc)
857 Report.Error (214, loc, "Pointers and fixed size buffers may only be used in an unsafe context");
861 /// Converts the IntConstant, UIntConstant, LongConstant or
862 /// ULongConstant into the integral target_type. Notice
863 /// that we do not return an `Expression' we do return
864 /// a boxed integral type.
866 /// FIXME: Since I added the new constants, we need to
867 /// also support conversions from CharConstant, ByteConstant,
868 /// SByteConstant, UShortConstant, ShortConstant
870 /// This is used by the switch statement, so the domain
871 /// of work is restricted to the literals above, and the
872 /// targets are int32, uint32, char, byte, sbyte, ushort,
873 /// short, uint64 and int64
875 public static object ConvertIntLiteral (Constant c, Type target_type, Location loc)
877 if (!Convert.ImplicitStandardConversionExists (Convert.ConstantEC, c, target_type)){
878 Convert.Error_CannotImplicitConversion (loc, c.Type, target_type);
884 if (c.Type == target_type)
885 return ((Constant) c).GetValue ();
888 // Make into one of the literals we handle, we dont really care
889 // about this value as we will just return a few limited types
891 if (c is EnumConstant)
892 c = ((EnumConstant)c).WidenToCompilerConstant ();
894 if (c is IntConstant){
895 int v = ((IntConstant) c).Value;
897 if (target_type == TypeManager.uint32_type){
900 } else if (target_type == TypeManager.char_type){
901 if (v >= Char.MinValue && v <= Char.MaxValue)
903 } else if (target_type == TypeManager.byte_type){
904 if (v >= Byte.MinValue && v <= Byte.MaxValue)
906 } else if (target_type == TypeManager.sbyte_type){
907 if (v >= SByte.MinValue && v <= SByte.MaxValue)
909 } else if (target_type == TypeManager.short_type){
910 if (v >= Int16.MinValue && v <= UInt16.MaxValue)
912 } else if (target_type == TypeManager.ushort_type){
913 if (v >= UInt16.MinValue && v <= UInt16.MaxValue)
915 } else if (target_type == TypeManager.int64_type)
917 else if (target_type == TypeManager.uint64_type){
923 } else if (c is UIntConstant){
924 uint v = ((UIntConstant) c).Value;
926 if (target_type == TypeManager.int32_type){
927 if (v <= Int32.MaxValue)
929 } else if (target_type == TypeManager.char_type){
930 if (v >= Char.MinValue && v <= Char.MaxValue)
932 } else if (target_type == TypeManager.byte_type){
933 if (v <= Byte.MaxValue)
935 } else if (target_type == TypeManager.sbyte_type){
936 if (v <= SByte.MaxValue)
938 } else if (target_type == TypeManager.short_type){
939 if (v <= UInt16.MaxValue)
941 } else if (target_type == TypeManager.ushort_type){
942 if (v <= UInt16.MaxValue)
944 } else if (target_type == TypeManager.int64_type)
946 else if (target_type == TypeManager.uint64_type)
949 } else if (c is LongConstant){
950 long v = ((LongConstant) c).Value;
952 if (target_type == TypeManager.int32_type){
953 if (v >= UInt32.MinValue && v <= UInt32.MaxValue)
955 } else if (target_type == TypeManager.uint32_type){
956 if (v >= 0 && v <= UInt32.MaxValue)
958 } else if (target_type == TypeManager.char_type){
959 if (v >= Char.MinValue && v <= Char.MaxValue)
961 } else if (target_type == TypeManager.byte_type){
962 if (v >= Byte.MinValue && v <= Byte.MaxValue)
964 } else if (target_type == TypeManager.sbyte_type){
965 if (v >= SByte.MinValue && v <= SByte.MaxValue)
967 } else if (target_type == TypeManager.short_type){
968 if (v >= Int16.MinValue && v <= UInt16.MaxValue)
970 } else if (target_type == TypeManager.ushort_type){
971 if (v >= UInt16.MinValue && v <= UInt16.MaxValue)
973 } else if (target_type == TypeManager.uint64_type){
978 } else if (c is ULongConstant){
979 ulong v = ((ULongConstant) c).Value;
981 if (target_type == TypeManager.int32_type){
982 if (v <= Int32.MaxValue)
984 } else if (target_type == TypeManager.uint32_type){
985 if (v <= UInt32.MaxValue)
987 } else if (target_type == TypeManager.char_type){
988 if (v >= Char.MinValue && v <= Char.MaxValue)
990 } else if (target_type == TypeManager.byte_type){
991 if (v >= Byte.MinValue && v <= Byte.MaxValue)
993 } else if (target_type == TypeManager.sbyte_type){
994 if (v <= (int) SByte.MaxValue)
996 } else if (target_type == TypeManager.short_type){
997 if (v <= UInt16.MaxValue)
999 } else if (target_type == TypeManager.ushort_type){
1000 if (v <= UInt16.MaxValue)
1002 } else if (target_type == TypeManager.int64_type){
1003 if (v <= Int64.MaxValue)
1007 } else if (c is ByteConstant){
1008 byte v = ((ByteConstant) c).Value;
1010 if (target_type == TypeManager.int32_type)
1012 else if (target_type == TypeManager.uint32_type)
1014 else if (target_type == TypeManager.char_type)
1016 else if (target_type == TypeManager.sbyte_type){
1017 if (v <= SByte.MaxValue)
1019 } else if (target_type == TypeManager.short_type)
1021 else if (target_type == TypeManager.ushort_type)
1023 else if (target_type == TypeManager.int64_type)
1025 else if (target_type == TypeManager.uint64_type)
1028 } else if (c is SByteConstant){
1029 sbyte v = ((SByteConstant) c).Value;
1031 if (target_type == TypeManager.int32_type)
1033 else if (target_type == TypeManager.uint32_type){
1036 } else if (target_type == TypeManager.char_type){
1039 } else if (target_type == TypeManager.byte_type){
1042 } else if (target_type == TypeManager.short_type)
1044 else if (target_type == TypeManager.ushort_type){
1047 } else if (target_type == TypeManager.int64_type)
1049 else if (target_type == TypeManager.uint64_type){
1054 } else if (c is ShortConstant){
1055 short v = ((ShortConstant) c).Value;
1057 if (target_type == TypeManager.int32_type){
1059 } else if (target_type == TypeManager.uint32_type){
1062 } else if (target_type == TypeManager.char_type){
1065 } else if (target_type == TypeManager.byte_type){
1066 if (v >= Byte.MinValue && v <= Byte.MaxValue)
1068 } else if (target_type == TypeManager.sbyte_type){
1069 if (v >= SByte.MinValue && v <= SByte.MaxValue)
1071 } else if (target_type == TypeManager.ushort_type){
1074 } else if (target_type == TypeManager.int64_type)
1076 else if (target_type == TypeManager.uint64_type)
1080 } else if (c is UShortConstant){
1081 ushort v = ((UShortConstant) c).Value;
1083 if (target_type == TypeManager.int32_type)
1085 else if (target_type == TypeManager.uint32_type)
1087 else if (target_type == TypeManager.char_type){
1088 if (v >= Char.MinValue && v <= Char.MaxValue)
1090 } else if (target_type == TypeManager.byte_type){
1091 if (v >= Byte.MinValue && v <= Byte.MaxValue)
1093 } else if (target_type == TypeManager.sbyte_type){
1094 if (v <= SByte.MaxValue)
1096 } else if (target_type == TypeManager.short_type){
1097 if (v <= Int16.MaxValue)
1099 } else if (target_type == TypeManager.int64_type)
1101 else if (target_type == TypeManager.uint64_type)
1105 } else if (c is CharConstant){
1106 char v = ((CharConstant) c).Value;
1108 if (target_type == TypeManager.int32_type)
1110 else if (target_type == TypeManager.uint32_type)
1112 else if (target_type == TypeManager.byte_type){
1113 if (v >= Byte.MinValue && v <= Byte.MaxValue)
1115 } else if (target_type == TypeManager.sbyte_type){
1116 if (v <= SByte.MaxValue)
1118 } else if (target_type == TypeManager.short_type){
1119 if (v <= Int16.MaxValue)
1121 } else if (target_type == TypeManager.ushort_type)
1123 else if (target_type == TypeManager.int64_type)
1125 else if (target_type == TypeManager.uint64_type)
1130 Error_ConstantValueCannotBeConverted (loc, s, target_type);
1135 // Load the object from the pointer.
1137 public static void LoadFromPtr (ILGenerator ig, Type t)
1139 if (t == TypeManager.int32_type)
1140 ig.Emit (OpCodes.Ldind_I4);
1141 else if (t == TypeManager.uint32_type)
1142 ig.Emit (OpCodes.Ldind_U4);
1143 else if (t == TypeManager.short_type)
1144 ig.Emit (OpCodes.Ldind_I2);
1145 else if (t == TypeManager.ushort_type)
1146 ig.Emit (OpCodes.Ldind_U2);
1147 else if (t == TypeManager.char_type)
1148 ig.Emit (OpCodes.Ldind_U2);
1149 else if (t == TypeManager.byte_type)
1150 ig.Emit (OpCodes.Ldind_U1);
1151 else if (t == TypeManager.sbyte_type)
1152 ig.Emit (OpCodes.Ldind_I1);
1153 else if (t == TypeManager.uint64_type)
1154 ig.Emit (OpCodes.Ldind_I8);
1155 else if (t == TypeManager.int64_type)
1156 ig.Emit (OpCodes.Ldind_I8);
1157 else if (t == TypeManager.float_type)
1158 ig.Emit (OpCodes.Ldind_R4);
1159 else if (t == TypeManager.double_type)
1160 ig.Emit (OpCodes.Ldind_R8);
1161 else if (t == TypeManager.bool_type)
1162 ig.Emit (OpCodes.Ldind_I1);
1163 else if (t == TypeManager.intptr_type)
1164 ig.Emit (OpCodes.Ldind_I);
1165 else if (TypeManager.IsEnumType (t)) {
1166 if (t == TypeManager.enum_type)
1167 ig.Emit (OpCodes.Ldind_Ref);
1169 LoadFromPtr (ig, TypeManager.EnumToUnderlying (t));
1170 } else if (t.IsValueType)
1171 ig.Emit (OpCodes.Ldobj, t);
1172 else if (t.IsPointer)
1173 ig.Emit (OpCodes.Ldind_I);
1175 ig.Emit (OpCodes.Ldind_Ref);
1179 // The stack contains the pointer and the value of type `type'
1181 public static void StoreFromPtr (ILGenerator ig, Type type)
1183 if (TypeManager.IsEnumType (type))
1184 type = TypeManager.EnumToUnderlying (type);
1185 if (type == TypeManager.int32_type || type == TypeManager.uint32_type)
1186 ig.Emit (OpCodes.Stind_I4);
1187 else if (type == TypeManager.int64_type || type == TypeManager.uint64_type)
1188 ig.Emit (OpCodes.Stind_I8);
1189 else if (type == TypeManager.char_type || type == TypeManager.short_type ||
1190 type == TypeManager.ushort_type)
1191 ig.Emit (OpCodes.Stind_I2);
1192 else if (type == TypeManager.float_type)
1193 ig.Emit (OpCodes.Stind_R4);
1194 else if (type == TypeManager.double_type)
1195 ig.Emit (OpCodes.Stind_R8);
1196 else if (type == TypeManager.byte_type || type == TypeManager.sbyte_type ||
1197 type == TypeManager.bool_type)
1198 ig.Emit (OpCodes.Stind_I1);
1199 else if (type == TypeManager.intptr_type)
1200 ig.Emit (OpCodes.Stind_I);
1201 else if (type.IsValueType)
1202 ig.Emit (OpCodes.Stobj, type);
1204 ig.Emit (OpCodes.Stind_Ref);
1208 // Returns the size of type `t' if known, otherwise, 0
1210 public static int GetTypeSize (Type t)
1212 t = TypeManager.TypeToCoreType (t);
1213 if (t == TypeManager.int32_type ||
1214 t == TypeManager.uint32_type ||
1215 t == TypeManager.float_type)
1217 else if (t == TypeManager.int64_type ||
1218 t == TypeManager.uint64_type ||
1219 t == TypeManager.double_type)
1221 else if (t == TypeManager.byte_type ||
1222 t == TypeManager.sbyte_type ||
1223 t == TypeManager.bool_type)
1225 else if (t == TypeManager.short_type ||
1226 t == TypeManager.char_type ||
1227 t == TypeManager.ushort_type)
1229 else if (t == TypeManager.decimal_type)
1235 public static void Error_NegativeArrayIndex (Location loc)
1237 Report.Error (248, loc, "Cannot create an array with a negative size");
1240 protected void Error_CannotCallAbstractBase (string name)
1242 Report.Error (205, loc, "Cannot call an abstract base member `{0}'", name);
1246 // Converts `source' to an int, uint, long or ulong.
1248 public Expression ExpressionToArrayArgument (EmitContext ec, Expression source, Location loc)
1252 bool old_checked = ec.CheckState;
1253 ec.CheckState = true;
1255 target = Convert.ImplicitConversion (ec, source, TypeManager.int32_type, loc);
1256 if (target == null){
1257 target = Convert.ImplicitConversion (ec, source, TypeManager.uint32_type, loc);
1258 if (target == null){
1259 target = Convert.ImplicitConversion (ec, source, TypeManager.int64_type, loc);
1260 if (target == null){
1261 target = Convert.ImplicitConversion (ec, source, TypeManager.uint64_type, loc);
1263 Convert.Error_CannotImplicitConversion (loc, source.Type, TypeManager.int32_type);
1267 ec.CheckState = old_checked;
1270 // Only positive constants are allowed at compile time
1272 if (target is Constant){
1273 if (target is IntConstant){
1274 if (((IntConstant) target).Value < 0){
1275 Error_NegativeArrayIndex (loc);
1280 if (target is LongConstant){
1281 if (((LongConstant) target).Value < 0){
1282 Error_NegativeArrayIndex (loc);
1295 /// This is just a base class for expressions that can
1296 /// appear on statements (invocations, object creation,
1297 /// assignments, post/pre increment and decrement). The idea
1298 /// being that they would support an extra Emition interface that
1299 /// does not leave a result on the stack.
1301 public abstract class ExpressionStatement : Expression {
1303 public virtual ExpressionStatement ResolveStatement (EmitContext ec)
1305 Expression e = Resolve (ec);
1309 ExpressionStatement es = e as ExpressionStatement;
1311 Error (201, "Only assignment, call, increment, decrement and new object " +
1312 "expressions can be used as a statement");
1318 /// Requests the expression to be emitted in a `statement'
1319 /// context. This means that no new value is left on the
1320 /// stack after invoking this method (constrasted with
1321 /// Emit that will always leave a value on the stack).
1323 public abstract void EmitStatement (EmitContext ec);
1327 /// This kind of cast is used to encapsulate the child
1328 /// whose type is child.Type into an expression that is
1329 /// reported to return "return_type". This is used to encapsulate
1330 /// expressions which have compatible types, but need to be dealt
1331 /// at higher levels with.
1333 /// For example, a "byte" expression could be encapsulated in one
1334 /// of these as an "unsigned int". The type for the expression
1335 /// would be "unsigned int".
1338 public class EmptyCast : Expression {
1339 protected Expression child;
1341 public Expression Child {
1347 public EmptyCast (Expression child, Type return_type)
1349 eclass = child.eclass;
1350 loc = child.Location;
1355 public override Expression DoResolve (EmitContext ec)
1357 // This should never be invoked, we are born in fully
1358 // initialized state.
1363 public override void Emit (EmitContext ec)
1369 /// This is a numeric cast to a Decimal
1371 public class CastToDecimal : EmptyCast {
1373 MethodInfo conversion_operator;
1375 public CastToDecimal (EmitContext ec, Expression child)
1376 : this (ec, child, false)
1380 public CastToDecimal (EmitContext ec, Expression child, bool find_explicit)
1381 : base (child, TypeManager.decimal_type)
1383 conversion_operator = GetConversionOperator (ec, find_explicit);
1385 if (conversion_operator == null)
1386 Convert.Error_CannotImplicitConversion (loc, child.Type, type);
1389 // Returns the implicit operator that converts from
1390 // 'child.Type' to System.Decimal.
1391 MethodInfo GetConversionOperator (EmitContext ec, bool find_explicit)
1393 string operator_name = "op_Implicit";
1396 operator_name = "op_Explicit";
1398 MethodGroupExpr opers = Expression.MethodLookup (
1399 ec, type, operator_name, loc) as MethodGroupExpr;
1402 Convert.Error_CannotImplicitConversion (loc, child.Type, type);
1404 foreach (MethodInfo oper in opers.Methods) {
1405 ParameterData pd = TypeManager.GetParameterData (oper);
1407 if (pd.ParameterType (0) == child.Type && oper.ReturnType == type)
1413 public override void Emit (EmitContext ec)
1415 ILGenerator ig = ec.ig;
1418 ig.Emit (OpCodes.Call, conversion_operator);
1422 /// This is an explicit numeric cast from a Decimal
1424 public class CastFromDecimal : EmptyCast
1426 MethodInfo conversion_operator;
1427 public CastFromDecimal (EmitContext ec, Expression child, Type return_type)
1428 : base (child, return_type)
1430 if (child.Type != TypeManager.decimal_type)
1431 throw new InternalErrorException (
1432 "The expected type is Decimal, instead it is " + child.Type.FullName);
1434 conversion_operator = GetConversionOperator (ec);
1435 if (conversion_operator == null)
1436 Convert.Error_CannotImplicitConversion (loc, child.Type, type);
1439 // Returns the explicit operator that converts from an
1440 // express of type System.Decimal to 'type'.
1441 MethodInfo GetConversionOperator (EmitContext ec)
1443 MethodGroupExpr opers = Expression.MethodLookup (
1444 ec, child.Type, "op_Explicit", loc) as MethodGroupExpr;
1447 Convert.Error_CannotImplicitConversion (loc, child.Type, type);
1449 foreach (MethodInfo oper in opers.Methods) {
1450 ParameterData pd = TypeManager.GetParameterData (oper);
1452 if (pd.ParameterType (0) == child.Type && oper.ReturnType == type)
1458 public override void Emit (EmitContext ec)
1460 ILGenerator ig = ec.ig;
1463 ig.Emit (OpCodes.Call, conversion_operator);
1468 // We need to special case this since an empty cast of
1469 // a NullLiteral is still a Constant
1471 public class NullCast : Constant {
1472 protected Expression child;
1474 public NullCast (Expression child, Type return_type)
1476 eclass = child.eclass;
1481 override public string AsString ()
1486 public override object GetValue ()
1491 public override Expression DoResolve (EmitContext ec)
1493 // This should never be invoked, we are born in fully
1494 // initialized state.
1499 public override void Emit (EmitContext ec)
1504 public override bool IsDefaultValue {
1506 throw new NotImplementedException ();
1510 public override bool IsNegative {
1519 /// This class is used to wrap literals which belong inside Enums
1521 public class EnumConstant : Constant {
1522 public Constant Child;
1524 public EnumConstant (Constant child, Type enum_type)
1526 eclass = child.eclass;
1531 public override Expression DoResolve (EmitContext ec)
1533 // This should never be invoked, we are born in fully
1534 // initialized state.
1539 public override void Emit (EmitContext ec)
1544 public override object GetValue ()
1546 return Child.GetValue ();
1549 public object GetValueAsEnumType ()
1551 return System.Enum.ToObject (type, Child.GetValue ());
1555 // Converts from one of the valid underlying types for an enumeration
1556 // (int32, uint32, int64, uint64, short, ushort, byte, sbyte) to
1557 // one of the internal compiler literals: Int/UInt/Long/ULong Literals.
1559 public Constant WidenToCompilerConstant ()
1561 Type t = TypeManager.EnumToUnderlying (Child.Type);
1562 object v = ((Constant) Child).GetValue ();;
1564 if (t == TypeManager.int32_type)
1565 return new IntConstant ((int) v);
1566 if (t == TypeManager.uint32_type)
1567 return new UIntConstant ((uint) v);
1568 if (t == TypeManager.int64_type)
1569 return new LongConstant ((long) v);
1570 if (t == TypeManager.uint64_type)
1571 return new ULongConstant ((ulong) v);
1572 if (t == TypeManager.short_type)
1573 return new ShortConstant ((short) v);
1574 if (t == TypeManager.ushort_type)
1575 return new UShortConstant ((ushort) v);
1576 if (t == TypeManager.byte_type)
1577 return new ByteConstant ((byte) v);
1578 if (t == TypeManager.sbyte_type)
1579 return new SByteConstant ((sbyte) v);
1581 throw new Exception ("Invalid enumeration underlying type: " + t);
1585 // Extracts the value in the enumeration on its native representation
1587 public object GetPlainValue ()
1589 Type t = TypeManager.EnumToUnderlying (Child.Type);
1590 object v = ((Constant) Child).GetValue ();;
1592 if (t == TypeManager.int32_type)
1594 if (t == TypeManager.uint32_type)
1596 if (t == TypeManager.int64_type)
1598 if (t == TypeManager.uint64_type)
1600 if (t == TypeManager.short_type)
1602 if (t == TypeManager.ushort_type)
1604 if (t == TypeManager.byte_type)
1606 if (t == TypeManager.sbyte_type)
1612 public override string AsString ()
1614 return Child.AsString ();
1617 public override DoubleConstant ConvertToDouble ()
1619 return Child.ConvertToDouble ();
1622 public override FloatConstant ConvertToFloat ()
1624 return Child.ConvertToFloat ();
1627 public override ULongConstant ConvertToULong ()
1629 return Child.ConvertToULong ();
1632 public override LongConstant ConvertToLong ()
1634 return Child.ConvertToLong ();
1637 public override UIntConstant ConvertToUInt ()
1639 return Child.ConvertToUInt ();
1642 public override IntConstant ConvertToInt ()
1644 return Child.ConvertToInt ();
1647 public override bool IsDefaultValue {
1649 return Child.IsDefaultValue;
1653 public override bool IsZeroInteger {
1654 get { return Child.IsZeroInteger; }
1657 public override bool IsNegative {
1659 return Child.IsNegative;
1665 /// This kind of cast is used to encapsulate Value Types in objects.
1667 /// The effect of it is to box the value type emitted by the previous
1670 public class BoxedCast : EmptyCast {
1672 public BoxedCast (Expression expr)
1673 : base (expr, TypeManager.object_type)
1675 eclass = ExprClass.Value;
1678 public BoxedCast (Expression expr, Type target_type)
1679 : base (expr, target_type)
1681 eclass = ExprClass.Value;
1684 public override Expression DoResolve (EmitContext ec)
1686 // This should never be invoked, we are born in fully
1687 // initialized state.
1692 public override void Emit (EmitContext ec)
1696 ec.ig.Emit (OpCodes.Box, child.Type);
1700 public class UnboxCast : EmptyCast {
1701 public UnboxCast (Expression expr, Type return_type)
1702 : base (expr, return_type)
1706 public override Expression DoResolve (EmitContext ec)
1708 // This should never be invoked, we are born in fully
1709 // initialized state.
1714 public override void Emit (EmitContext ec)
1717 ILGenerator ig = ec.ig;
1720 ig.Emit (OpCodes.Unbox, t);
1722 LoadFromPtr (ig, t);
1727 /// This is used to perform explicit numeric conversions.
1729 /// Explicit numeric conversions might trigger exceptions in a checked
1730 /// context, so they should generate the conv.ovf opcodes instead of
1733 public class ConvCast : EmptyCast {
1734 public enum Mode : byte {
1735 I1_U1, I1_U2, I1_U4, I1_U8, I1_CH,
1737 I2_I1, I2_U1, I2_U2, I2_U4, I2_U8, I2_CH,
1738 U2_I1, U2_U1, U2_I2, U2_CH,
1739 I4_I1, I4_U1, I4_I2, I4_U2, I4_U4, I4_U8, I4_CH,
1740 U4_I1, U4_U1, U4_I2, U4_U2, U4_I4, U4_CH,
1741 I8_I1, I8_U1, I8_I2, I8_U2, I8_I4, I8_U4, I8_U8, I8_CH,
1742 U8_I1, U8_U1, U8_I2, U8_U2, U8_I4, U8_U4, U8_I8, U8_CH,
1743 CH_I1, CH_U1, CH_I2,
1744 R4_I1, R4_U1, R4_I2, R4_U2, R4_I4, R4_U4, R4_I8, R4_U8, R4_CH,
1745 R8_I1, R8_U1, R8_I2, R8_U2, R8_I4, R8_U4, R8_I8, R8_U8, R8_CH, R8_R4
1751 public ConvCast (EmitContext ec, Expression child, Type return_type, Mode m)
1752 : base (child, return_type)
1754 checked_state = ec.CheckState;
1758 public override Expression DoResolve (EmitContext ec)
1760 // This should never be invoked, we are born in fully
1761 // initialized state.
1766 public override string ToString ()
1768 return String.Format ("ConvCast ({0}, {1})", mode, child);
1771 public override void Emit (EmitContext ec)
1773 ILGenerator ig = ec.ig;
1779 case Mode.I1_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1780 case Mode.I1_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1781 case Mode.I1_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1782 case Mode.I1_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1783 case Mode.I1_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1785 case Mode.U1_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1786 case Mode.U1_CH: /* nothing */ break;
1788 case Mode.I2_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1789 case Mode.I2_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1790 case Mode.I2_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1791 case Mode.I2_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1792 case Mode.I2_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1793 case Mode.I2_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1795 case Mode.U2_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1796 case Mode.U2_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
1797 case Mode.U2_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
1798 case Mode.U2_CH: /* nothing */ break;
1800 case Mode.I4_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1801 case Mode.I4_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1802 case Mode.I4_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
1803 case Mode.I4_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1804 case Mode.I4_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1805 case Mode.I4_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1806 case Mode.I4_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1808 case Mode.U4_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1809 case Mode.U4_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
1810 case Mode.U4_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
1811 case Mode.U4_U2: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
1812 case Mode.U4_I4: ig.Emit (OpCodes.Conv_Ovf_I4_Un); break;
1813 case Mode.U4_CH: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
1815 case Mode.I8_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1816 case Mode.I8_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1817 case Mode.I8_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
1818 case Mode.I8_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1819 case Mode.I8_I4: ig.Emit (OpCodes.Conv_Ovf_I4); break;
1820 case Mode.I8_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1821 case Mode.I8_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1822 case Mode.I8_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1824 case Mode.U8_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1825 case Mode.U8_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
1826 case Mode.U8_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
1827 case Mode.U8_U2: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
1828 case Mode.U8_I4: ig.Emit (OpCodes.Conv_Ovf_I4_Un); break;
1829 case Mode.U8_U4: ig.Emit (OpCodes.Conv_Ovf_U4_Un); break;
1830 case Mode.U8_I8: ig.Emit (OpCodes.Conv_Ovf_I8_Un); break;
1831 case Mode.U8_CH: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
1833 case Mode.CH_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1834 case Mode.CH_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
1835 case Mode.CH_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
1837 case Mode.R4_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1838 case Mode.R4_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1839 case Mode.R4_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
1840 case Mode.R4_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1841 case Mode.R4_I4: ig.Emit (OpCodes.Conv_Ovf_I4); break;
1842 case Mode.R4_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1843 case Mode.R4_I8: ig.Emit (OpCodes.Conv_Ovf_I8); break;
1844 case Mode.R4_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1845 case Mode.R4_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1847 case Mode.R8_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1848 case Mode.R8_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1849 case Mode.R8_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
1850 case Mode.R8_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1851 case Mode.R8_I4: ig.Emit (OpCodes.Conv_Ovf_I4); break;
1852 case Mode.R8_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1853 case Mode.R8_I8: ig.Emit (OpCodes.Conv_Ovf_I8); break;
1854 case Mode.R8_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1855 case Mode.R8_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1856 case Mode.R8_R4: ig.Emit (OpCodes.Conv_R4); break;
1860 case Mode.I1_U1: ig.Emit (OpCodes.Conv_U1); break;
1861 case Mode.I1_U2: ig.Emit (OpCodes.Conv_U2); break;
1862 case Mode.I1_U4: ig.Emit (OpCodes.Conv_U4); break;
1863 case Mode.I1_U8: ig.Emit (OpCodes.Conv_I8); break;
1864 case Mode.I1_CH: ig.Emit (OpCodes.Conv_U2); break;
1866 case Mode.U1_I1: ig.Emit (OpCodes.Conv_I1); break;
1867 case Mode.U1_CH: ig.Emit (OpCodes.Conv_U2); break;
1869 case Mode.I2_I1: ig.Emit (OpCodes.Conv_I1); break;
1870 case Mode.I2_U1: ig.Emit (OpCodes.Conv_U1); break;
1871 case Mode.I2_U2: ig.Emit (OpCodes.Conv_U2); break;
1872 case Mode.I2_U4: ig.Emit (OpCodes.Conv_U4); break;
1873 case Mode.I2_U8: ig.Emit (OpCodes.Conv_I8); break;
1874 case Mode.I2_CH: ig.Emit (OpCodes.Conv_U2); break;
1876 case Mode.U2_I1: ig.Emit (OpCodes.Conv_I1); break;
1877 case Mode.U2_U1: ig.Emit (OpCodes.Conv_U1); break;
1878 case Mode.U2_I2: ig.Emit (OpCodes.Conv_I2); break;
1879 case Mode.U2_CH: /* nothing */ break;
1881 case Mode.I4_I1: ig.Emit (OpCodes.Conv_I1); break;
1882 case Mode.I4_U1: ig.Emit (OpCodes.Conv_U1); break;
1883 case Mode.I4_I2: ig.Emit (OpCodes.Conv_I2); break;
1884 case Mode.I4_U4: /* nothing */ break;
1885 case Mode.I4_U2: ig.Emit (OpCodes.Conv_U2); break;
1886 case Mode.I4_U8: ig.Emit (OpCodes.Conv_I8); break;
1887 case Mode.I4_CH: ig.Emit (OpCodes.Conv_U2); break;
1889 case Mode.U4_I1: ig.Emit (OpCodes.Conv_I1); break;
1890 case Mode.U4_U1: ig.Emit (OpCodes.Conv_U1); break;
1891 case Mode.U4_I2: ig.Emit (OpCodes.Conv_I2); break;
1892 case Mode.U4_U2: ig.Emit (OpCodes.Conv_U2); break;
1893 case Mode.U4_I4: /* nothing */ break;
1894 case Mode.U4_CH: ig.Emit (OpCodes.Conv_U2); break;
1896 case Mode.I8_I1: ig.Emit (OpCodes.Conv_I1); break;
1897 case Mode.I8_U1: ig.Emit (OpCodes.Conv_U1); break;
1898 case Mode.I8_I2: ig.Emit (OpCodes.Conv_I2); break;
1899 case Mode.I8_U2: ig.Emit (OpCodes.Conv_U2); break;
1900 case Mode.I8_I4: ig.Emit (OpCodes.Conv_I4); break;
1901 case Mode.I8_U4: ig.Emit (OpCodes.Conv_U4); break;
1902 case Mode.I8_U8: /* nothing */ break;
1903 case Mode.I8_CH: ig.Emit (OpCodes.Conv_U2); break;
1905 case Mode.U8_I1: ig.Emit (OpCodes.Conv_I1); break;
1906 case Mode.U8_U1: ig.Emit (OpCodes.Conv_U1); break;
1907 case Mode.U8_I2: ig.Emit (OpCodes.Conv_I2); break;
1908 case Mode.U8_U2: ig.Emit (OpCodes.Conv_U2); break;
1909 case Mode.U8_I4: ig.Emit (OpCodes.Conv_I4); break;
1910 case Mode.U8_U4: ig.Emit (OpCodes.Conv_U4); break;
1911 case Mode.U8_I8: /* nothing */ break;
1912 case Mode.U8_CH: ig.Emit (OpCodes.Conv_U2); break;
1914 case Mode.CH_I1: ig.Emit (OpCodes.Conv_I1); break;
1915 case Mode.CH_U1: ig.Emit (OpCodes.Conv_U1); break;
1916 case Mode.CH_I2: ig.Emit (OpCodes.Conv_I2); break;
1918 case Mode.R4_I1: ig.Emit (OpCodes.Conv_I1); break;
1919 case Mode.R4_U1: ig.Emit (OpCodes.Conv_U1); break;
1920 case Mode.R4_I2: ig.Emit (OpCodes.Conv_I2); break;
1921 case Mode.R4_U2: ig.Emit (OpCodes.Conv_U2); break;
1922 case Mode.R4_I4: ig.Emit (OpCodes.Conv_I4); break;
1923 case Mode.R4_U4: ig.Emit (OpCodes.Conv_U4); break;
1924 case Mode.R4_I8: ig.Emit (OpCodes.Conv_I8); break;
1925 case Mode.R4_U8: ig.Emit (OpCodes.Conv_U8); break;
1926 case Mode.R4_CH: ig.Emit (OpCodes.Conv_U2); break;
1928 case Mode.R8_I1: ig.Emit (OpCodes.Conv_I1); break;
1929 case Mode.R8_U1: ig.Emit (OpCodes.Conv_U1); break;
1930 case Mode.R8_I2: ig.Emit (OpCodes.Conv_I2); break;
1931 case Mode.R8_U2: ig.Emit (OpCodes.Conv_U2); break;
1932 case Mode.R8_I4: ig.Emit (OpCodes.Conv_I4); break;
1933 case Mode.R8_U4: ig.Emit (OpCodes.Conv_U4); break;
1934 case Mode.R8_I8: ig.Emit (OpCodes.Conv_I8); break;
1935 case Mode.R8_U8: ig.Emit (OpCodes.Conv_U8); break;
1936 case Mode.R8_CH: ig.Emit (OpCodes.Conv_U2); break;
1937 case Mode.R8_R4: ig.Emit (OpCodes.Conv_R4); break;
1943 public class OpcodeCast : EmptyCast {
1947 public OpcodeCast (Expression child, Type return_type, OpCode op)
1948 : base (child, return_type)
1952 second_valid = false;
1955 public OpcodeCast (Expression child, Type return_type, OpCode op, OpCode op2)
1956 : base (child, return_type)
1961 second_valid = true;
1964 public override Expression DoResolve (EmitContext ec)
1966 // This should never be invoked, we are born in fully
1967 // initialized state.
1972 public override void Emit (EmitContext ec)
1983 /// This kind of cast is used to encapsulate a child and cast it
1984 /// to the class requested
1986 public class ClassCast : EmptyCast {
1987 public ClassCast (Expression child, Type return_type)
1988 : base (child, return_type)
1993 public override Expression DoResolve (EmitContext ec)
1995 // This should never be invoked, we are born in fully
1996 // initialized state.
2001 public override void Emit (EmitContext ec)
2005 ec.ig.Emit (OpCodes.Castclass, type);
2011 /// SimpleName expressions are formed of a single word and only happen at the beginning
2012 /// of a dotted-name.
2014 public class SimpleName : Expression {
2018 public SimpleName (string name, Location l)
2024 public static void Error_ObjectRefRequired (EmitContext ec, Location l, string name)
2026 if (ec.IsFieldInitializer)
2027 Report.Error (236, l,
2028 "A field initializer cannot reference the nonstatic field, method, or property `{0}'",
2031 if (name.LastIndexOf ('.') > 0)
2032 name = name.Substring (name.LastIndexOf ('.') + 1);
2035 120, l, "`{0}': An object reference is required for the nonstatic field, method or property",
2040 public bool IdenticalNameAndTypeName (EmitContext ec, Expression resolved_to, Location loc)
2042 return resolved_to != null && resolved_to.Type != null &&
2043 resolved_to.Type.Name == Name &&
2044 (ec.DeclSpace.LookupType (Name, loc, /* ignore_cs0104 = */ true) != null);
2047 public override Expression DoResolve (EmitContext ec)
2049 return SimpleNameResolve (ec, null, false);
2052 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
2054 return SimpleNameResolve (ec, right_side, false);
2058 public Expression DoResolve (EmitContext ec, bool intermediate)
2060 return SimpleNameResolve (ec, null, intermediate);
2063 public override FullNamedExpression ResolveAsTypeStep (EmitContext ec, bool silent)
2065 int errors = Report.Errors;
2066 FullNamedExpression fne = ec.DeclSpace.LookupType (Name, loc, /*ignore_cs0104=*/ false);
2071 if (silent || errors != Report.Errors)
2074 MemberCore mc = ec.DeclSpace.GetDefinition (Name);
2076 Error_UnexpectedKind (ec, "type", GetMemberType (mc), loc);
2078 NamespaceEntry.Error_NamespaceNotFound (loc, Name);
2084 // TODO: I am still not convinced about this. If someone else will need it
2085 // implement this as virtual property in MemberCore hierarchy
2086 string GetMemberType (MemberCore mc)
2088 if (mc is PropertyBase)
2092 if (mc is FieldBase)
2098 Expression SimpleNameResolve (EmitContext ec, Expression right_side, bool intermediate)
2104 Expression e = DoSimpleNameResolve (ec, right_side, intermediate);
2108 if (ec.CurrentBlock == null || ec.CurrentBlock.CheckInvariantMeaningInBlock (Name, e, Location))
2115 /// 7.5.2: Simple Names.
2117 /// Local Variables and Parameters are handled at
2118 /// parse time, so they never occur as SimpleNames.
2120 /// The `intermediate' flag is used by MemberAccess only
2121 /// and it is used to inform us that it is ok for us to
2122 /// avoid the static check, because MemberAccess might end
2123 /// up resolving the Name as a Type name and the access as
2124 /// a static type access.
2126 /// ie: Type Type; .... { Type.GetType (""); }
2128 /// Type is both an instance variable and a Type; Type.GetType
2129 /// is the static method not an instance method of type.
2131 Expression DoSimpleNameResolve (EmitContext ec, Expression right_side, bool intermediate)
2133 Expression e = null;
2136 // Stage 1: Performed by the parser (binding to locals or parameters).
2138 Block current_block = ec.CurrentBlock;
2139 if (current_block != null){
2140 LocalInfo vi = current_block.GetLocalInfo (Name);
2144 var = new LocalVariableReference (ec.CurrentBlock, Name, loc);
2146 if (right_side != null)
2147 return var.ResolveLValue (ec, right_side, loc);
2149 return var.Resolve (ec);
2152 ParameterReference pref = current_block.Toplevel.GetParameterReference (Name, loc);
2154 if (right_side != null)
2155 return pref.ResolveLValue (ec, right_side, loc);
2157 return pref.Resolve (ec);
2162 // Stage 2: Lookup members
2165 DeclSpace lookup_ds = ec.DeclSpace;
2166 Type almost_matched_type = null;
2167 ArrayList almost_matched = null;
2169 if (lookup_ds.TypeBuilder == null)
2172 e = MemberLookup (ec, lookup_ds.TypeBuilder, Name, loc);
2176 if (almost_matched == null && almostMatchedMembers.Count > 0) {
2177 almost_matched_type = lookup_ds.TypeBuilder;
2178 almost_matched = (ArrayList) almostMatchedMembers.Clone ();
2181 lookup_ds =lookup_ds.Parent;
2182 } while (lookup_ds != null);
2184 if (e == null && ec.ContainerType != null)
2185 e = MemberLookup (ec, ec.ContainerType, Name, loc);
2188 if (almost_matched == null && almostMatchedMembers.Count > 0) {
2189 almost_matched_type = ec.ContainerType;
2190 almost_matched = (ArrayList) almostMatchedMembers.Clone ();
2192 e = ResolveAsTypeStep (ec, false);
2196 if (almost_matched != null)
2197 almostMatchedMembers = almost_matched;
2198 if (almost_matched_type == null)
2199 almost_matched_type = ec.ContainerType;
2200 MemberLookupFailed (ec, null, almost_matched_type, ((SimpleName) this).Name, ec.DeclSpace.Name, true, loc);
2207 if (e is MemberExpr) {
2208 MemberExpr me = (MemberExpr) e;
2211 if (me.IsInstance) {
2212 if (ec.IsStatic || ec.IsFieldInitializer) {
2214 // Note that an MemberExpr can be both IsInstance and IsStatic.
2215 // An unresolved MethodGroupExpr can contain both kinds of methods
2216 // and each predicate is true if the MethodGroupExpr contains
2217 // at least one of that kind of method.
2221 (!intermediate || !IdenticalNameAndTypeName (ec, me, loc))) {
2222 Error_ObjectRefRequired (ec, loc, me.GetSignatureForError ());
2227 // Pass the buck to MemberAccess and Invocation.
2229 left = EmptyExpression.Null;
2231 left = ec.GetThis (loc);
2234 left = new TypeExpression (ec.ContainerType, loc);
2237 e = me.ResolveMemberAccess (ec, left, loc, null);
2241 me = e as MemberExpr;
2246 TypeManager.IsNestedFamilyAccessible (me.InstanceExpression.Type, me.DeclaringType) &&
2247 me.InstanceExpression.Type != me.DeclaringType &&
2248 !me.InstanceExpression.Type.IsSubclassOf (me.DeclaringType) &&
2249 (!intermediate || !IdenticalNameAndTypeName (ec, e, loc))) {
2250 Report.Error (38, loc, "Cannot access a nonstatic member of outer type `{0}' via nested type `{1}'",
2251 TypeManager.CSharpName (me.DeclaringType), TypeManager.CSharpName (me.InstanceExpression.Type));
2255 return (right_side != null)
2256 ? me.DoResolveLValue (ec, right_side)
2257 : me.DoResolve (ec);
2263 public override void Emit (EmitContext ec)
2266 // If this is ever reached, then we failed to
2267 // find the name as a namespace
2270 Error (103, "The name `" + Name +
2271 "' does not exist in the class `" +
2272 ec.DeclSpace.Name + "'");
2275 public override string ToString ()
2280 public override string GetSignatureForError ()
2287 /// Represents a namespace or a type. The name of the class was inspired by
2288 /// section 10.8.1 (Fully Qualified Names).
2290 public abstract class FullNamedExpression : Expression {
2291 public override FullNamedExpression ResolveAsTypeStep (EmitContext ec, bool silent)
2296 public abstract string FullName {
2302 /// Fully resolved expression that evaluates to a type
2304 public abstract class TypeExpr : FullNamedExpression {
2305 override public FullNamedExpression ResolveAsTypeStep (EmitContext ec, bool silent)
2307 TypeExpr t = DoResolveAsTypeStep (ec);
2311 eclass = ExprClass.Type;
2315 override public Expression DoResolve (EmitContext ec)
2317 return ResolveAsTypeTerminal (ec, false);
2320 override public void Emit (EmitContext ec)
2322 throw new Exception ("Should never be called");
2325 public virtual bool CheckAccessLevel (DeclSpace ds)
2327 return ds.CheckAccessLevel (Type);
2330 public virtual bool AsAccessible (DeclSpace ds, int flags)
2332 return ds.AsAccessible (Type, flags);
2335 public virtual bool IsClass {
2336 get { return Type.IsClass; }
2339 public virtual bool IsValueType {
2340 get { return Type.IsValueType; }
2343 public virtual bool IsInterface {
2344 get { return Type.IsInterface; }
2347 public virtual bool IsSealed {
2348 get { return Type.IsSealed; }
2351 public virtual bool CanInheritFrom ()
2353 if (Type == TypeManager.enum_type ||
2354 (Type == TypeManager.value_type && RootContext.StdLib) ||
2355 Type == TypeManager.multicast_delegate_type ||
2356 Type == TypeManager.delegate_type ||
2357 Type == TypeManager.array_type)
2363 public abstract TypeExpr DoResolveAsTypeStep (EmitContext ec);
2365 public virtual Type ResolveType (EmitContext ec)
2367 TypeExpr t = ResolveAsTypeTerminal (ec, false);
2374 public abstract string Name {
2378 public override bool Equals (object obj)
2380 TypeExpr tobj = obj as TypeExpr;
2384 return Type == tobj.Type;
2387 public override int GetHashCode ()
2389 return Type.GetHashCode ();
2392 public override string ToString ()
2398 public class TypeExpression : TypeExpr {
2399 public TypeExpression (Type t, Location l)
2402 eclass = ExprClass.Type;
2406 public override TypeExpr DoResolveAsTypeStep (EmitContext ec)
2411 public override string Name {
2412 get { return Type.ToString (); }
2415 public override string FullName {
2416 get { return Type.FullName; }
2421 /// Used to create types from a fully qualified name. These are just used
2422 /// by the parser to setup the core types. A TypeLookupExpression is always
2423 /// classified as a type.
2425 public class TypeLookupExpression : TypeExpr {
2428 public TypeLookupExpression (string name)
2433 static readonly char [] dot_array = { '.' };
2434 public override TypeExpr DoResolveAsTypeStep (EmitContext ec)
2439 // If name is of the form `N.I', first lookup `N', then search a member `I' in it.
2441 string lookup_name = name;
2442 int pos = name.IndexOf ('.');
2444 rest = name.Substring (pos + 1);
2445 lookup_name = name.Substring (0, pos);
2448 FullNamedExpression resolved = Namespace.Root.Lookup (ec.DeclSpace, lookup_name, Location.Null);
2450 if (resolved != null && rest != null) {
2451 // Now handle the rest of the the name.
2452 string [] elements = rest.Split (dot_array);
2454 int count = elements.Length;
2456 while (i < count && resolved != null && resolved is Namespace) {
2457 Namespace ns = resolved as Namespace;
2458 element = elements [i++];
2459 lookup_name += "." + element;
2460 resolved = ns.Lookup (ec.DeclSpace, element, Location.Null);
2463 if (resolved != null && resolved is TypeExpr) {
2464 Type t = ((TypeExpr) resolved).Type;
2466 if (!ec.DeclSpace.CheckAccessLevel (t)) {
2468 lookup_name = t.FullName;
2475 t = TypeManager.GetNestedType (t, elements [i++]);
2480 if (resolved == null) {
2481 NamespaceEntry.Error_NamespaceNotFound (loc, lookup_name);
2485 if (!(resolved is TypeExpr)) {
2486 resolved.Error_UnexpectedKind (ec, "type", loc);
2490 type = ((TypeExpr) resolved).ResolveType (ec);
2494 public override string Name {
2495 get { return name; }
2498 public override string FullName {
2499 get { return name; }
2503 public class TypeAliasExpression : TypeExpr {
2506 public TypeAliasExpression (TypeExpr texpr, Location l)
2509 loc = texpr.Location;
2511 eclass = ExprClass.Type;
2514 public override string Name {
2515 get { return texpr.Name; }
2518 public override string FullName {
2519 get { return texpr.FullName; }
2522 public override TypeExpr DoResolveAsTypeStep (EmitContext ec)
2524 Type type = texpr.ResolveType (ec);
2528 return new TypeExpression (type, loc);
2531 public override bool CheckAccessLevel (DeclSpace ds)
2533 return texpr.CheckAccessLevel (ds);
2536 public override bool AsAccessible (DeclSpace ds, int flags)
2538 return texpr.AsAccessible (ds, flags);
2541 public override bool IsClass {
2542 get { return texpr.IsClass; }
2545 public override bool IsValueType {
2546 get { return texpr.IsValueType; }
2549 public override bool IsInterface {
2550 get { return texpr.IsInterface; }
2553 public override bool IsSealed {
2554 get { return texpr.IsSealed; }
2559 /// This class denotes an expression which evaluates to a member
2560 /// of a struct or a class.
2562 public abstract class MemberExpr : Expression
2565 /// The name of this member.
2567 public abstract string Name {
2572 /// Whether this is an instance member.
2574 public abstract bool IsInstance {
2579 /// Whether this is a static member.
2581 public abstract bool IsStatic {
2586 /// The type which declares this member.
2588 public abstract Type DeclaringType {
2593 /// The instance expression associated with this member, if it's a
2594 /// non-static member.
2596 public Expression InstanceExpression;
2598 public static void error176 (Location loc, string name)
2600 Report.Error (176, loc, "Static member `{0}' cannot be accessed " +
2601 "with an instance reference, qualify it with a type name instead", name);
2605 // TODO: possible optimalization
2606 // Cache resolved constant result in FieldBuilder <-> expression map
2607 public virtual Expression ResolveMemberAccess (EmitContext ec, Expression left, Location loc,
2608 SimpleName original)
2612 // original == null || original.Resolve (...) ==> left
2615 if (left is TypeExpr) {
2617 SimpleName.Error_ObjectRefRequired (ec, loc, Name);
2625 if (original != null && original.IdenticalNameAndTypeName (ec, left, loc))
2628 error176 (loc, GetSignatureForError ());
2632 InstanceExpression = left;
2637 protected void EmitInstance (EmitContext ec, bool prepare_for_load)
2642 if (InstanceExpression == EmptyExpression.Null) {
2643 SimpleName.Error_ObjectRefRequired (ec, loc, Name);
2647 if (InstanceExpression.Type.IsValueType) {
2648 if (InstanceExpression is IMemoryLocation) {
2649 ((IMemoryLocation) InstanceExpression).AddressOf (ec, AddressOp.LoadStore);
2651 LocalTemporary t = new LocalTemporary (ec, InstanceExpression.Type);
2652 InstanceExpression.Emit (ec);
2654 t.AddressOf (ec, AddressOp.Store);
2657 InstanceExpression.Emit (ec);
2659 if (prepare_for_load)
2660 ec.ig.Emit (OpCodes.Dup);
2665 /// MethodGroup Expression.
2667 /// This is a fully resolved expression that evaluates to a type
2669 public class MethodGroupExpr : MemberExpr {
2670 public MethodBase [] Methods;
2671 bool identical_type_name = false;
2674 public MethodGroupExpr (MemberInfo [] mi, Location l)
2676 Methods = new MethodBase [mi.Length];
2677 mi.CopyTo (Methods, 0);
2678 eclass = ExprClass.MethodGroup;
2679 type = TypeManager.object_type;
2683 public MethodGroupExpr (ArrayList list, Location l)
2685 Methods = new MethodBase [list.Count];
2688 list.CopyTo (Methods, 0);
2690 foreach (MemberInfo m in list){
2691 if (!(m is MethodBase)){
2692 Console.WriteLine ("Name " + m.Name);
2693 Console.WriteLine ("Found a: " + m.GetType ().FullName);
2700 eclass = ExprClass.MethodGroup;
2701 type = TypeManager.object_type;
2704 public override Type DeclaringType {
2707 // The methods are arranged in this order:
2708 // derived type -> base type
2710 return Methods [0].DeclaringType;
2714 public bool IdenticalTypeName {
2716 return identical_type_name;
2720 identical_type_name = value;
2724 public bool IsBase {
2733 public override string GetSignatureForError ()
2735 return TypeManager.CSharpSignature (Methods [0]);
2738 public override string Name {
2740 return Methods [0].Name;
2744 public override bool IsInstance {
2746 foreach (MethodBase mb in Methods)
2754 public override bool IsStatic {
2756 foreach (MethodBase mb in Methods)
2764 public override Expression ResolveMemberAccess (EmitContext ec, Expression left, Location loc,
2765 SimpleName original)
2767 if (!(left is TypeExpr) &&
2768 original != null && original.IdenticalNameAndTypeName (ec, left, loc))
2769 IdenticalTypeName = true;
2771 return base.ResolveMemberAccess (ec, left, loc, original);
2774 override public Expression DoResolve (EmitContext ec)
2777 InstanceExpression = null;
2779 if (InstanceExpression != null) {
2780 InstanceExpression = InstanceExpression.DoResolve (ec);
2781 if (InstanceExpression == null)
2788 public void ReportUsageError ()
2790 Report.Error (654, loc, "Method `" + DeclaringType + "." +
2791 Name + "()' is referenced without parentheses");
2794 override public void Emit (EmitContext ec)
2796 ReportUsageError ();
2799 bool RemoveMethods (bool keep_static)
2801 ArrayList smethods = new ArrayList ();
2803 foreach (MethodBase mb in Methods){
2804 if (mb.IsStatic == keep_static)
2808 if (smethods.Count == 0)
2811 Methods = new MethodBase [smethods.Count];
2812 smethods.CopyTo (Methods, 0);
2818 /// Removes any instance methods from the MethodGroup, returns
2819 /// false if the resulting set is empty.
2821 public bool RemoveInstanceMethods ()
2823 return RemoveMethods (true);
2827 /// Removes any static methods from the MethodGroup, returns
2828 /// false if the resulting set is empty.
2830 public bool RemoveStaticMethods ()
2832 return RemoveMethods (false);
2837 /// Fully resolved expression that evaluates to a Field
2839 public class FieldExpr : MemberExpr, IAssignMethod, IMemoryLocation, IVariable {
2840 public readonly FieldInfo FieldInfo;
2841 VariableInfo variable_info;
2843 LocalTemporary temp;
2845 bool in_initializer;
2847 public FieldExpr (FieldInfo fi, Location l, bool in_initializer):
2850 this.in_initializer = in_initializer;
2853 public FieldExpr (FieldInfo fi, Location l)
2856 eclass = ExprClass.Variable;
2857 type = fi.FieldType;
2861 public override string Name {
2863 return FieldInfo.Name;
2867 public override bool IsInstance {
2869 return !FieldInfo.IsStatic;
2873 public override bool IsStatic {
2875 return FieldInfo.IsStatic;
2879 public override Type DeclaringType {
2881 return FieldInfo.DeclaringType;
2885 public override string GetSignatureForError ()
2887 return TypeManager.GetFullNameSignature (FieldInfo);
2890 public VariableInfo VariableInfo {
2892 return variable_info;
2896 public override Expression ResolveMemberAccess (EmitContext ec, Expression left, Location loc,
2897 SimpleName original)
2899 bool left_is_type = left is TypeExpr;
2901 Type decl_type = FieldInfo.DeclaringType;
2903 bool is_emitted = FieldInfo is FieldBuilder;
2904 Type t = FieldInfo.FieldType;
2907 Const c = TypeManager.LookupConstant ((FieldBuilder) FieldInfo);
2911 if (!c.LookupConstantValue (out o))
2914 c.SetMemberIsUsed ();
2915 object real_value = ((Constant) c.Expr).GetValue ();
2917 Expression exp = Constantify (real_value, t);
2919 if (!left_is_type &&
2920 (original == null || !original.IdenticalNameAndTypeName (ec, left, loc))) {
2921 Report.SymbolRelatedToPreviousError (c);
2922 error176 (loc, c.GetSignatureForError ());
2931 // Decimal constants cannot be encoded in the constant blob, and thus are marked
2932 // as IsInitOnly ('readonly' in C# parlance). We get its value from the
2933 // DecimalConstantAttribute metadata.
2935 if (FieldInfo.IsInitOnly && !is_emitted && t == TypeManager.decimal_type) {
2936 object[] attrs = FieldInfo.GetCustomAttributes (TypeManager.decimal_constant_attribute_type, false);
2937 if (attrs.Length == 1)
2938 return new DecimalConstant (((System.Runtime.CompilerServices.DecimalConstantAttribute) attrs [0]).Value);
2941 if (FieldInfo.IsLiteral) {
2945 o = TypeManager.GetValue ((FieldBuilder) FieldInfo);
2947 o = FieldInfo.GetValue (FieldInfo);
2949 if (decl_type.IsSubclassOf (TypeManager.enum_type)) {
2950 if (!left_is_type &&
2951 (original == null || !original.IdenticalNameAndTypeName (ec, left, loc))) {
2952 error176 (loc, TypeManager.GetFullNameSignature (FieldInfo));
2956 Expression enum_member = MemberLookup (
2957 ec, decl_type, "value__", MemberTypes.Field,
2958 AllBindingFlags | BindingFlags.NonPublic, loc);
2960 Enum en = TypeManager.LookupEnum (decl_type);
2964 c = Constantify (o, en.UnderlyingType);
2966 c = Constantify (o, enum_member.Type);
2968 return new EnumConstant (c, decl_type);
2971 Expression exp = Constantify (o, t);
2973 if (!left_is_type) {
2974 error176 (loc, TypeManager.GetFullNameSignature (FieldInfo));
2981 if (t.IsPointer && !ec.InUnsafe) {
2986 return base.ResolveMemberAccess (ec, left, loc, original);
2989 override public Expression DoResolve (EmitContext ec)
2991 if (ec.InRefOutArgumentResolving && FieldInfo.IsInitOnly && !ec.IsConstructor && FieldInfo.FieldType.IsValueType) {
2992 if (FieldInfo.FieldType is TypeBuilder) {
2993 if (FieldInfo.IsStatic)
2994 Report.Error (1651, loc, "Fields of static readonly field `{0}' cannot be passed ref or out (except in a static constructor)",
2995 GetSignatureForError ());
2997 Report.Error (1649, loc, "Members of readonly field `{0}.{1}' cannot be passed ref or out (except in a constructor)",
2998 TypeManager.CSharpName (DeclaringType), Name);
3000 if (FieldInfo.IsStatic)
3001 Report.Error (199, loc, "A static readonly field `{0}' cannot be passed ref or out (except in a static constructor)",
3004 Report.Error (192, loc, "A readonly field `{0}' cannot be passed ref or out (except in a constructor)",
3010 if (!FieldInfo.IsStatic){
3011 if (InstanceExpression == null){
3013 // This can happen when referencing an instance field using
3014 // a fully qualified type expression: TypeName.InstanceField = xxx
3016 SimpleName.Error_ObjectRefRequired (ec, loc, FieldInfo.Name);
3020 // Resolve the field's instance expression while flow analysis is turned
3021 // off: when accessing a field "a.b", we must check whether the field
3022 // "a.b" is initialized, not whether the whole struct "a" is initialized.
3023 InstanceExpression = InstanceExpression.Resolve (
3024 ec, ResolveFlags.VariableOrValue | ResolveFlags.DisableFlowAnalysis);
3025 if (InstanceExpression == null)
3029 if (!in_initializer) {
3030 ObsoleteAttribute oa;
3031 FieldBase f = TypeManager.GetField (FieldInfo);
3033 oa = f.GetObsoleteAttribute (f.Parent);
3035 AttributeTester.Report_ObsoleteMessage (oa, f.GetSignatureForError (), loc);
3037 // To be sure that type is external because we do not register generated fields
3038 } else if (!(FieldInfo.DeclaringType is TypeBuilder)) {
3039 oa = AttributeTester.GetMemberObsoleteAttribute (FieldInfo);
3041 AttributeTester.Report_ObsoleteMessage (oa, TypeManager.GetFullNameSignature (FieldInfo), loc);
3045 AnonymousContainer am = ec.CurrentAnonymousMethod;
3047 if (!FieldInfo.IsStatic){
3048 if (!am.IsIterator && (ec.TypeContainer is Struct)){
3049 Report.Error (1673, loc,
3050 "Anonymous methods inside structs cannot access instance members of `{0}'. Consider copying `{0}' to a local variable outside the anonymous method and using the local instead",
3054 if ((am.ContainerAnonymousMethod == null) && (InstanceExpression is This))
3055 ec.CaptureField (this);
3059 // If the instance expression is a local variable or parameter.
3060 IVariable var = InstanceExpression as IVariable;
3061 if ((var == null) || (var.VariableInfo == null))
3064 VariableInfo vi = var.VariableInfo;
3065 if (!vi.IsFieldAssigned (ec, FieldInfo.Name, loc))
3068 variable_info = vi.GetSubStruct (FieldInfo.Name);
3072 void Report_AssignToReadonly (bool is_instance)
3077 msg = "A readonly field cannot be assigned to (except in a constructor or a variable initializer)";
3079 msg = "A static readonly field cannot be assigned to (except in a static constructor or a variable initializer)";
3081 Report.Error (is_instance ? 191 : 198, loc, msg);
3084 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
3086 IVariable var = InstanceExpression as IVariable;
3087 if ((var != null) && (var.VariableInfo != null))
3088 var.VariableInfo.SetFieldAssigned (ec, FieldInfo.Name);
3090 Expression e = DoResolve (ec);
3095 if (!FieldInfo.IsStatic && (InstanceExpression.Type.IsValueType && !(InstanceExpression is IMemoryLocation))) {
3096 Report.Error (1612, loc, "Cannot modify the return value of `{0}' because it is not a variable",
3097 InstanceExpression.GetSignatureForError ());
3101 FieldBase fb = TypeManager.GetField (FieldInfo);
3105 if (!FieldInfo.IsInitOnly)
3109 // InitOnly fields can only be assigned in constructors
3112 if (ec.IsConstructor){
3113 if (IsStatic && !ec.IsStatic)
3114 Report_AssignToReadonly (false);
3116 if (ec.ContainerType == FieldInfo.DeclaringType)
3120 Report_AssignToReadonly (!IsStatic);
3125 public override void CheckMarshallByRefAccess (Type container)
3127 if (!IsStatic && Type.IsValueType && !container.IsSubclassOf (TypeManager.mbr_type) && DeclaringType.IsSubclassOf (TypeManager.mbr_type)) {
3128 Report.SymbolRelatedToPreviousError (DeclaringType);
3129 Report.Error (1690, loc, "Cannot call methods, properties, or indexers on `{0}' because it is a value type member of a marshal-by-reference class",
3130 GetSignatureForError ());
3134 public bool VerifyFixed ()
3136 IVariable variable = InstanceExpression as IVariable;
3137 // A variable of the form V.I is fixed when V is a fixed variable of a struct type.
3138 // We defer the InstanceExpression check after the variable check to avoid a
3139 // separate null check on InstanceExpression.
3140 return variable != null && InstanceExpression.Type.IsValueType && variable.VerifyFixed ();
3143 public override int GetHashCode()
3145 return FieldInfo.GetHashCode ();
3148 public override bool Equals (object obj)
3150 FieldExpr fe = obj as FieldExpr;
3154 if (FieldInfo != fe.FieldInfo)
3157 if (InstanceExpression == null || fe.InstanceExpression == null)
3160 return InstanceExpression.Equals (fe.InstanceExpression);
3163 public void Emit (EmitContext ec, bool leave_copy)
3165 ILGenerator ig = ec.ig;
3166 bool is_volatile = false;
3168 if (FieldInfo is FieldBuilder){
3169 FieldBase f = TypeManager.GetField (FieldInfo);
3171 if ((f.ModFlags & Modifiers.VOLATILE) != 0)
3174 f.SetMemberIsUsed ();
3178 if (FieldInfo.IsStatic){
3180 ig.Emit (OpCodes.Volatile);
3182 ig.Emit (OpCodes.Ldsfld, FieldInfo);
3185 EmitInstance (ec, false);
3188 ig.Emit (OpCodes.Volatile);
3190 IFixedBuffer ff = AttributeTester.GetFixedBuffer (FieldInfo);
3193 ig.Emit (OpCodes.Ldflda, FieldInfo);
3194 ig.Emit (OpCodes.Ldflda, ff.Element);
3197 ig.Emit (OpCodes.Ldfld, FieldInfo);
3202 ec.ig.Emit (OpCodes.Dup);
3203 if (!FieldInfo.IsStatic) {
3204 temp = new LocalTemporary (ec, this.Type);
3210 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
3212 FieldAttributes fa = FieldInfo.Attributes;
3213 bool is_static = (fa & FieldAttributes.Static) != 0;
3214 bool is_readonly = (fa & FieldAttributes.InitOnly) != 0;
3215 ILGenerator ig = ec.ig;
3216 prepared = prepare_for_load;
3218 if (is_readonly && !ec.IsConstructor){
3219 Report_AssignToReadonly (!is_static);
3223 EmitInstance (ec, prepare_for_load);
3227 ec.ig.Emit (OpCodes.Dup);
3228 if (!FieldInfo.IsStatic) {
3229 temp = new LocalTemporary (ec, this.Type);
3234 if (FieldInfo is FieldBuilder){
3235 FieldBase f = TypeManager.GetField (FieldInfo);
3237 if ((f.ModFlags & Modifiers.VOLATILE) != 0)
3238 ig.Emit (OpCodes.Volatile);
3245 ig.Emit (OpCodes.Stsfld, FieldInfo);
3247 ig.Emit (OpCodes.Stfld, FieldInfo);
3253 public override void Emit (EmitContext ec)
3258 public void AddressOf (EmitContext ec, AddressOp mode)
3260 ILGenerator ig = ec.ig;
3262 if (FieldInfo is FieldBuilder){
3263 FieldBase f = TypeManager.GetField (FieldInfo);
3265 if ((f.ModFlags & Modifiers.VOLATILE) != 0){
3266 Report.Warning (420, 1, loc, "`{0}': A volatile fields cannot be passed using a ref or out parameter",
3267 f.GetSignatureForError ());
3271 if ((mode & AddressOp.Store) != 0)
3273 if ((mode & AddressOp.Load) != 0)
3274 f.SetMemberIsUsed ();
3279 // Handle initonly fields specially: make a copy and then
3280 // get the address of the copy.
3283 if (FieldInfo.IsInitOnly){
3285 if (ec.IsConstructor){
3286 if (FieldInfo.IsStatic){
3298 local = ig.DeclareLocal (type);
3299 ig.Emit (OpCodes.Stloc, local);
3300 ig.Emit (OpCodes.Ldloca, local);
3305 if (FieldInfo.IsStatic){
3306 ig.Emit (OpCodes.Ldsflda, FieldInfo);
3308 EmitInstance (ec, false);
3309 ig.Emit (OpCodes.Ldflda, FieldInfo);
3315 // A FieldExpr whose address can not be taken
3317 public class FieldExprNoAddress : FieldExpr, IMemoryLocation {
3318 public FieldExprNoAddress (FieldInfo fi, Location loc) : base (fi, loc)
3322 public new void AddressOf (EmitContext ec, AddressOp mode)
3324 Report.Error (-215, "Report this: Taking the address of a remapped parameter not supported");
3329 /// Expression that evaluates to a Property. The Assign class
3330 /// might set the `Value' expression if we are in an assignment.
3332 /// This is not an LValue because we need to re-write the expression, we
3333 /// can not take data from the stack and store it.
3335 public class PropertyExpr : MemberExpr, IAssignMethod {
3336 public readonly PropertyInfo PropertyInfo;
3339 // This is set externally by the `BaseAccess' class
3342 MethodInfo getter, setter;
3347 LocalTemporary temp;
3350 internal static PtrHashtable AccessorTable = new PtrHashtable ();
3352 public PropertyExpr (EmitContext ec, PropertyInfo pi, Location l)
3355 eclass = ExprClass.PropertyAccess;
3359 type = TypeManager.TypeToCoreType (pi.PropertyType);
3361 ResolveAccessors (ec);
3364 public override string Name {
3366 return PropertyInfo.Name;
3370 public override bool IsInstance {
3376 public override bool IsStatic {
3382 public override Type DeclaringType {
3384 return PropertyInfo.DeclaringType;
3388 public override string GetSignatureForError ()
3390 return TypeManager.GetFullNameSignature (PropertyInfo);
3393 void FindAccessors (Type invocation_type)
3395 BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic |
3396 BindingFlags.Static | BindingFlags.Instance |
3397 BindingFlags.DeclaredOnly;
3399 Type current = PropertyInfo.DeclaringType;
3400 for (; current != null; current = current.BaseType) {
3401 MemberInfo[] group = TypeManager.MemberLookup (
3402 invocation_type, invocation_type, current,
3403 MemberTypes.Property, flags, PropertyInfo.Name, null);
3408 if (group.Length != 1)
3409 // Oooops, can this ever happen ?
3412 PropertyInfo pi = (PropertyInfo) group [0];
3415 getter = pi.GetGetMethod (true);
3418 setter = pi.GetSetMethod (true);
3420 MethodInfo accessor = getter != null ? getter : setter;
3422 if (!accessor.IsVirtual)
3428 // We also perform the permission checking here, as the PropertyInfo does not
3429 // hold the information for the accessibility of its setter/getter
3431 void ResolveAccessors (EmitContext ec)
3433 FindAccessors (ec.ContainerType);
3435 if (getter != null) {
3436 IMethodData md = TypeManager.GetMethod (getter);
3438 md.SetMemberIsUsed ();
3440 AccessorTable [getter] = PropertyInfo;
3441 is_static = getter.IsStatic;
3444 if (setter != null) {
3445 IMethodData md = TypeManager.GetMethod (setter);
3447 md.SetMemberIsUsed ();
3449 AccessorTable [setter] = PropertyInfo;
3450 is_static = setter.IsStatic;
3454 bool InstanceResolve (EmitContext ec, bool must_do_cs1540_check)
3457 InstanceExpression = null;
3461 if (InstanceExpression == null) {
3462 SimpleName.Error_ObjectRefRequired (ec, loc, PropertyInfo.Name);
3466 InstanceExpression = InstanceExpression.DoResolve (ec);
3467 if (InstanceExpression == null)
3470 InstanceExpression.CheckMarshallByRefAccess (ec.ContainerType);
3472 if (must_do_cs1540_check && InstanceExpression != EmptyExpression.Null) {
3473 if ((InstanceExpression.Type != ec.ContainerType) &&
3474 ec.ContainerType.IsSubclassOf (InstanceExpression.Type)) {
3475 Report.Error (1540, loc, "Cannot access protected member `" +
3476 PropertyInfo.DeclaringType + "." + PropertyInfo.Name +
3477 "' via a qualifier of type `" +
3478 TypeManager.CSharpName (InstanceExpression.Type) +
3479 "'; the qualifier must be of type `" +
3480 TypeManager.CSharpName (ec.ContainerType) +
3481 "' (or derived from it)");
3489 override public Expression DoResolve (EmitContext ec)
3494 if (getter != null){
3495 if (TypeManager.GetArgumentTypes (getter).Length != 0){
3497 117, loc, "`{0}' does not contain a " +
3498 "definition for `{1}'.", getter.DeclaringType,
3504 if (getter == null){
3506 // The following condition happens if the PropertyExpr was
3507 // created, but is invalid (ie, the property is inaccessible),
3508 // and we did not want to embed the knowledge about this in
3509 // the caller routine. This only avoids double error reporting.
3514 if (InstanceExpression != EmptyExpression.Null) {
3515 Report.Error (154, loc, "The property or indexer `{0}' cannot be used in this context because it lacks the `get' accessor",
3516 TypeManager.GetFullNameSignature (PropertyInfo));
3521 bool must_do_cs1540_check = false;
3522 if (getter != null &&
3523 !IsAccessorAccessible (ec.ContainerType, getter, out must_do_cs1540_check)) {
3524 PropertyBase.PropertyMethod pm = TypeManager.GetMethod (getter) as PropertyBase.PropertyMethod;
3525 if (pm != null && pm.HasCustomAccessModifier) {
3526 Report.SymbolRelatedToPreviousError (pm);
3527 Report.Error (271, loc, "The property or indexer `{0}' cannot be used in this context because the get accessor is inaccessible",
3528 TypeManager.CSharpSignature (getter));
3531 ErrorIsInaccesible (loc, TypeManager.CSharpSignature (getter));
3535 if (!InstanceResolve (ec, must_do_cs1540_check))
3539 // Only base will allow this invocation to happen.
3541 if (IsBase && getter.IsAbstract) {
3542 Error_CannotCallAbstractBase (TypeManager.GetFullNameSignature (PropertyInfo));
3546 if (PropertyInfo.PropertyType.IsPointer && !ec.InUnsafe){
3556 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
3558 if (setter == null){
3560 // The following condition happens if the PropertyExpr was
3561 // created, but is invalid (ie, the property is inaccessible),
3562 // and we did not want to embed the knowledge about this in
3563 // the caller routine. This only avoids double error reporting.
3568 Report.Error (200, loc, " Property or indexer `{0}' cannot be assigned to (it is read only)",
3569 TypeManager.GetFullNameSignature (PropertyInfo));
3573 if (TypeManager.GetArgumentTypes (setter).Length != 1){
3575 117, loc, "`{0}' does not contain a " +
3576 "definition for `{1}'.", getter.DeclaringType,
3581 bool must_do_cs1540_check;
3582 if (!IsAccessorAccessible (ec.ContainerType, setter, out must_do_cs1540_check)) {
3583 PropertyBase.PropertyMethod pm = TypeManager.GetMethod (setter) as PropertyBase.PropertyMethod;
3584 if (pm != null && pm.HasCustomAccessModifier) {
3585 Report.SymbolRelatedToPreviousError (pm);
3586 Report.Error (272, loc, "The property or indexer `{0}' cannot be used in this context because the set accessor is inaccessible",
3587 TypeManager.CSharpSignature (setter));
3590 ErrorIsInaccesible (loc, TypeManager.CSharpSignature (setter));
3594 if (!InstanceResolve (ec, must_do_cs1540_check))
3598 // Only base will allow this invocation to happen.
3600 if (IsBase && setter.IsAbstract){
3601 Error_CannotCallAbstractBase (TypeManager.GetFullNameSignature (PropertyInfo));
3606 // Check that we are not making changes to a temporary memory location
3608 if (InstanceExpression != null && InstanceExpression.Type.IsValueType && !(InstanceExpression is IMemoryLocation)) {
3609 Report.Error (1612, loc, "Cannot modify the return value of `{0}' because it is not a variable",
3610 InstanceExpression.GetSignatureForError ());
3617 public override void Emit (EmitContext ec)
3622 public void Emit (EmitContext ec, bool leave_copy)
3625 EmitInstance (ec, false);
3628 // Special case: length of single dimension array property is turned into ldlen
3630 if ((getter == TypeManager.system_int_array_get_length) ||
3631 (getter == TypeManager.int_array_get_length)){
3632 Type iet = InstanceExpression.Type;
3635 // System.Array.Length can be called, but the Type does not
3636 // support invoking GetArrayRank, so test for that case first
3638 if (iet != TypeManager.array_type && (iet.GetArrayRank () == 1)) {
3639 ec.ig.Emit (OpCodes.Ldlen);
3640 ec.ig.Emit (OpCodes.Conv_I4);
3645 Invocation.EmitCall (ec, IsBase, IsStatic, new EmptyAddressOf (), getter, null, loc);
3650 ec.ig.Emit (OpCodes.Dup);
3652 temp = new LocalTemporary (ec, this.Type);
3658 // Implements the IAssignMethod interface for assignments
3660 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
3662 prepared = prepare_for_load;
3664 EmitInstance (ec, prepare_for_load);
3668 ec.ig.Emit (OpCodes.Dup);
3670 temp = new LocalTemporary (ec, this.Type);
3675 ArrayList args = new ArrayList (1);
3676 args.Add (new Argument (new EmptyAddressOf (), Argument.AType.Expression));
3678 Invocation.EmitCall (ec, IsBase, IsStatic, new EmptyAddressOf (), setter, args, loc);
3686 /// Fully resolved expression that evaluates to an Event
3688 public class EventExpr : MemberExpr {
3689 public readonly EventInfo EventInfo;
3692 MethodInfo add_accessor, remove_accessor;
3694 public EventExpr (EventInfo ei, Location loc)
3698 eclass = ExprClass.EventAccess;
3700 add_accessor = TypeManager.GetAddMethod (ei);
3701 remove_accessor = TypeManager.GetRemoveMethod (ei);
3703 if (add_accessor.IsStatic || remove_accessor.IsStatic)
3706 if (EventInfo is MyEventBuilder){
3707 MyEventBuilder eb = (MyEventBuilder) EventInfo;
3708 type = eb.EventType;
3711 type = EventInfo.EventHandlerType;
3714 public override string Name {
3716 return EventInfo.Name;
3720 public override bool IsInstance {
3726 public override bool IsStatic {
3732 public override Type DeclaringType {
3734 return EventInfo.DeclaringType;
3738 public override Expression ResolveMemberAccess (EmitContext ec, Expression left, Location loc,
3739 SimpleName original)
3742 // If the event is local to this class, we transform ourselves into a FieldExpr
3745 if (EventInfo.DeclaringType == ec.ContainerType ||
3746 TypeManager.IsNestedChildOf(ec.ContainerType, EventInfo.DeclaringType)) {
3747 MemberInfo mi = TypeManager.GetPrivateFieldOfEvent (EventInfo);
3750 MemberExpr ml = (MemberExpr) ExprClassFromMemberInfo (ec, mi, loc);
3753 Report.Error (-200, loc, "Internal error!!");
3757 InstanceExpression = null;
3759 return ml.ResolveMemberAccess (ec, left, loc, original);
3763 return base.ResolveMemberAccess (ec, left, loc, original);
3767 bool InstanceResolve (EmitContext ec, bool must_do_cs1540_check)
3770 InstanceExpression = null;
3774 if (InstanceExpression == null) {
3775 SimpleName.Error_ObjectRefRequired (ec, loc, EventInfo.Name);
3779 InstanceExpression = InstanceExpression.DoResolve (ec);
3780 if (InstanceExpression == null)
3784 // This is using the same mechanism as the CS1540 check in PropertyExpr.
3785 // However, in the Event case, we reported a CS0122 instead.
3787 if (must_do_cs1540_check && InstanceExpression != EmptyExpression.Null) {
3788 if ((InstanceExpression.Type != ec.ContainerType) &&
3789 ec.ContainerType.IsSubclassOf (InstanceExpression.Type)) {
3790 ErrorIsInaccesible (loc, TypeManager.CSharpSignature (EventInfo));
3798 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
3800 return DoResolve (ec);
3803 public override Expression DoResolve (EmitContext ec)
3805 bool must_do_cs1540_check;
3806 if (!(IsAccessorAccessible (ec.ContainerType, add_accessor, out must_do_cs1540_check) &&
3807 IsAccessorAccessible (ec.ContainerType, remove_accessor, out must_do_cs1540_check))) {
3808 ErrorIsInaccesible (loc, TypeManager.CSharpSignature (EventInfo));
3812 if (!InstanceResolve (ec, must_do_cs1540_check))
3818 public override void Emit (EmitContext ec)
3820 if (InstanceExpression is This)
3821 Report.Error (79, loc, "The event `{0}' can only appear on the left hand side of += or -=", GetSignatureForError ());
3823 Report.Error (70, loc, "The event `{0}' can only appear on the left hand side of += or -= "+
3824 "(except on the defining type)", Name);
3827 public override string GetSignatureForError ()
3829 return TypeManager.CSharpSignature (EventInfo);
3832 public void EmitAddOrRemove (EmitContext ec, Expression source)
3834 BinaryDelegate source_del = (BinaryDelegate) source;
3835 Expression handler = source_del.Right;
3837 Argument arg = new Argument (handler, Argument.AType.Expression);
3838 ArrayList args = new ArrayList ();
3842 if (source_del.IsAddition)
3843 Invocation.EmitCall (
3844 ec, false, IsStatic, InstanceExpression, add_accessor, args, loc);
3846 Invocation.EmitCall (
3847 ec, false, IsStatic, InstanceExpression, remove_accessor, args, loc);