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 /// We are either a namespace or a type.
95 /// If we're a type, `IsType' is true and we may use `Type' to get
96 /// a TypeExpr representing that type.
98 public interface IAlias {
107 TypeExpr ResolveAsType (EmitContext ec);
111 /// This interface is implemented by variables
113 public interface IVariable {
114 VariableInfo VariableInfo {
118 bool VerifyFixed (bool is_expression);
122 /// Base class for expressions
124 public abstract class Expression {
125 public ExprClass eclass;
127 protected Location loc;
139 public Location Location {
146 /// Utility wrapper routine for Error, just to beautify the code
148 public void Error (int error, string s)
150 if (!Location.IsNull (loc))
151 Report.Error (error, loc, s);
153 Report.Error (error, s);
157 /// Utility wrapper routine for Warning, just to beautify the code
159 public void Warning (int code, string format, params object[] args)
161 Report.Warning (code, loc, format, args);
164 // Not nice but we have broken hierarchy
165 public virtual void CheckMarshallByRefAccess (Type container) {}
168 /// Tests presence of ObsoleteAttribute and report proper error
170 protected void CheckObsoleteAttribute (Type type)
172 ObsoleteAttribute obsolete_attr = AttributeTester.GetObsoleteAttribute (type);
173 if (obsolete_attr == null)
176 AttributeTester.Report_ObsoleteMessage (obsolete_attr, type.FullName, loc);
179 public static bool IsAccessorAccessible (Type invocation_type, MethodInfo mi, out bool must_do_cs1540_check)
181 MethodAttributes ma = mi.Attributes & MethodAttributes.MemberAccessMask;
183 must_do_cs1540_check = false; // by default we do not check for this
186 // If only accessible to the current class or children
188 if (ma == MethodAttributes.Private)
189 return invocation_type == mi.DeclaringType ||
190 TypeManager.IsNestedChildOf (invocation_type, mi.DeclaringType);
192 if (mi.DeclaringType.Assembly == invocation_type.Assembly) {
193 if (ma == MethodAttributes.Assembly || ma == MethodAttributes.FamORAssem)
196 if (ma == MethodAttributes.Assembly || ma == MethodAttributes.FamANDAssem)
200 // Family and FamANDAssem require that we derive.
201 // FamORAssem requires that we derive if in different assemblies.
202 if (ma == MethodAttributes.Family ||
203 ma == MethodAttributes.FamANDAssem ||
204 ma == MethodAttributes.FamORAssem) {
205 if (!TypeManager.IsNestedFamilyAccessible (invocation_type, mi.DeclaringType))
208 if (!TypeManager.IsNestedChildOf (invocation_type, mi.DeclaringType))
209 must_do_cs1540_check = true;
218 /// Performs semantic analysis on the Expression
222 /// The Resolve method is invoked to perform the semantic analysis
225 /// The return value is an expression (it can be the
226 /// same expression in some cases) or a new
227 /// expression that better represents this node.
229 /// For example, optimizations of Unary (LiteralInt)
230 /// would return a new LiteralInt with a negated
233 /// If there is an error during semantic analysis,
234 /// then an error should be reported (using Report)
235 /// and a null value should be returned.
237 /// There are two side effects expected from calling
238 /// Resolve(): the the field variable "eclass" should
239 /// be set to any value of the enumeration
240 /// `ExprClass' and the type variable should be set
241 /// to a valid type (this is the type of the
244 public abstract Expression DoResolve (EmitContext ec);
246 public virtual Expression DoResolveLValue (EmitContext ec, Expression right_side)
252 // This is used if the expression should be resolved as a type or namespace name.
253 // the default implementation fails.
255 public virtual FullNamedExpression ResolveAsTypeStep (EmitContext ec)
261 // This is used to resolve the expression as a type, a null
262 // value will be returned if the expression is not a type
265 public TypeExpr ResolveAsTypeTerminal (EmitContext ec, bool silent)
267 int errors = Report.Errors;
269 FullNamedExpression fne = ResolveAsTypeStep (ec);
272 if (!silent && errors == Report.Errors)
273 Report.Error (246, Location, "Cannot find type '{0}'", ToString ());
277 if (fne.eclass != ExprClass.Type) {
278 if (!silent && errors == Report.Errors)
279 Report.Error (118, Location, "'{0}' denotes a '{1}', where a type was expected",
280 fne.FullName, fne.ExprClassName ());
284 TypeExpr te = fne as TypeExpr;
286 if (!te.CheckAccessLevel (ec.DeclSpace)) {
287 Report.Error (122, Location, "'{0}' is inaccessible due to its protection level", te.Name);
295 /// Resolves an expression and performs semantic analysis on it.
299 /// Currently Resolve wraps DoResolve to perform sanity
300 /// checking and assertion checking on what we expect from Resolve.
302 public Expression Resolve (EmitContext ec, ResolveFlags flags)
304 if ((flags & ResolveFlags.MaskExprClass) == ResolveFlags.Type)
305 return ResolveAsTypeStep (ec);
307 bool old_do_flow_analysis = ec.DoFlowAnalysis;
308 if ((flags & ResolveFlags.DisableFlowAnalysis) != 0)
309 ec.DoFlowAnalysis = false;
312 bool intermediate = (flags & ResolveFlags.Intermediate) == ResolveFlags.Intermediate;
313 if (this is SimpleName)
314 e = ((SimpleName) this).DoResolve (ec, intermediate);
319 ec.DoFlowAnalysis = old_do_flow_analysis;
324 if ((e is TypeExpr) || (e is ComposedCast) || (e is Namespace)) {
325 if ((flags & ResolveFlags.Type) == 0) {
326 e.Error_UnexpectedKind (flags, loc);
335 case ExprClass.Namespace:
336 if ((flags & ResolveFlags.VariableOrValue) == 0) {
337 e.Error_UnexpectedKind (flags, loc);
342 case ExprClass.MethodGroup:
343 if (RootContext.Version == LanguageVersion.ISO_1){
344 if ((flags & ResolveFlags.MethodGroup) == 0) {
345 ((MethodGroupExpr) e).ReportUsageError ();
351 case ExprClass.Value:
352 case ExprClass.Variable:
353 case ExprClass.PropertyAccess:
354 case ExprClass.EventAccess:
355 case ExprClass.IndexerAccess:
356 if ((flags & ResolveFlags.VariableOrValue) == 0) {
357 Console.WriteLine ("I got: {0} and {1}", e.GetType (), e);
358 Console.WriteLine ("I am {0} and {1}", this.GetType (), this);
359 FieldInfo fi = ((FieldExpr) e).FieldInfo;
361 Console.WriteLine ("{0} and {1}", fi.DeclaringType, fi.Name);
362 e.Error_UnexpectedKind (flags, loc);
368 throw new Exception ("Expression " + e.GetType () +
369 " ExprClass is Invalid after resolve");
372 if (e.type == null && !(e is Namespace)) {
373 throw new Exception (
374 "Expression " + e.GetType () +
375 " did not set its type after Resolve\n" +
376 "called from: " + this.GetType ());
383 /// Resolves an expression and performs semantic analysis on it.
385 public Expression Resolve (EmitContext ec)
387 return Resolve (ec, ResolveFlags.VariableOrValue);
391 /// Resolves an expression for LValue assignment
395 /// Currently ResolveLValue wraps DoResolveLValue to perform sanity
396 /// checking and assertion checking on what we expect from Resolve
398 public Expression ResolveLValue (EmitContext ec, Expression right_side)
400 int errors = Report.Errors;
401 Expression e = DoResolveLValue (ec, right_side);
404 if (errors == Report.Errors)
405 Report.Error (131, Location, "The left-hand side of an assignment or mutating operation must be a variable, property or indexer");
410 if (e.eclass == ExprClass.Invalid)
411 throw new Exception ("Expression " + e +
412 " ExprClass is Invalid after resolve");
414 if (e.eclass == ExprClass.MethodGroup) {
415 ((MethodGroupExpr) e).ReportUsageError ();
420 throw new Exception ("Expression " + e +
421 " did not set its type after Resolve");
428 /// Emits the code for the expression
432 /// The Emit method is invoked to generate the code
433 /// for the expression.
435 public abstract void Emit (EmitContext ec);
437 public virtual void EmitBranchable (EmitContext ec, Label target, bool onTrue)
440 ec.ig.Emit (onTrue ? OpCodes.Brtrue : OpCodes.Brfalse, target);
444 /// Protected constructor. Only derivate types should
445 /// be able to be created
448 protected Expression ()
450 eclass = ExprClass.Invalid;
455 /// Returns a literalized version of a literal FieldInfo
459 /// The possible return values are:
460 /// IntConstant, UIntConstant
461 /// LongLiteral, ULongConstant
462 /// FloatConstant, DoubleConstant
465 /// The value returned is already resolved.
467 public static Constant Constantify (object v, Type t)
469 if (t == TypeManager.int32_type)
470 return new IntConstant ((int) v);
471 else if (t == TypeManager.uint32_type)
472 return new UIntConstant ((uint) v);
473 else if (t == TypeManager.int64_type)
474 return new LongConstant ((long) v);
475 else if (t == TypeManager.uint64_type)
476 return new ULongConstant ((ulong) v);
477 else if (t == TypeManager.float_type)
478 return new FloatConstant ((float) v);
479 else if (t == TypeManager.double_type)
480 return new DoubleConstant ((double) v);
481 else if (t == TypeManager.string_type)
482 return new StringConstant ((string) v);
483 else if (t == TypeManager.short_type)
484 return new ShortConstant ((short)v);
485 else if (t == TypeManager.ushort_type)
486 return new UShortConstant ((ushort)v);
487 else if (t == TypeManager.sbyte_type)
488 return new SByteConstant (((sbyte)v));
489 else if (t == TypeManager.byte_type)
490 return new ByteConstant ((byte)v);
491 else if (t == TypeManager.char_type)
492 return new CharConstant ((char)v);
493 else if (t == TypeManager.bool_type)
494 return new BoolConstant ((bool) v);
495 else if (t == TypeManager.decimal_type)
496 return new DecimalConstant ((decimal) v);
497 else if (TypeManager.IsEnumType (t)){
498 Type real_type = TypeManager.TypeToCoreType (v.GetType ());
500 real_type = System.Enum.GetUnderlyingType (real_type);
502 Constant e = Constantify (v, real_type);
504 return new EnumConstant (e, t);
505 } else if (v == null && !TypeManager.IsValueType (t))
506 return NullLiteral.Null;
508 throw new Exception ("Unknown type for constant (" + t +
513 /// Returns a fully formed expression after a MemberLookup
515 public static Expression ExprClassFromMemberInfo (EmitContext ec, MemberInfo mi, Location loc)
518 return new EventExpr ((EventInfo) mi, loc);
519 else if (mi is FieldInfo)
520 return new FieldExpr ((FieldInfo) mi, loc);
521 else if (mi is PropertyInfo)
522 return new PropertyExpr (ec, (PropertyInfo) mi, loc);
523 else if (mi is Type){
524 return new TypeExpression ((System.Type) mi, loc);
530 protected static ArrayList almostMatchedMembers = new ArrayList (4);
533 // FIXME: Probably implement a cache for (t,name,current_access_set)?
535 // This code could use some optimizations, but we need to do some
536 // measurements. For example, we could use a delegate to `flag' when
537 // something can not any longer be a method-group (because it is something
541 // If the return value is an Array, then it is an array of
544 // If the return value is an MemberInfo, it is anything, but a Method
548 // FIXME: When calling MemberLookup inside an `Invocation', we should pass
549 // the arguments here and have MemberLookup return only the methods that
550 // match the argument count/type, unlike we are doing now (we delay this
553 // This is so we can catch correctly attempts to invoke instance methods
554 // from a static body (scan for error 120 in ResolveSimpleName).
557 // FIXME: Potential optimization, have a static ArrayList
560 public static Expression MemberLookup (EmitContext ec, Type queried_type, string name,
561 MemberTypes mt, BindingFlags bf, Location loc)
563 return MemberLookup (ec, ec.ContainerType, null, queried_type, name, mt, bf, loc);
567 // Lookup type `queried_type' for code in class `container_type' with a qualifier of
568 // `qualifier_type' or null to lookup members in the current class.
571 public static Expression MemberLookup (EmitContext ec, Type container_type,
572 Type qualifier_type, Type queried_type,
573 string name, MemberTypes mt,
574 BindingFlags bf, Location loc)
576 almostMatchedMembers.Clear ();
578 MemberInfo [] mi = TypeManager.MemberLookup (container_type, qualifier_type,
579 queried_type, mt, bf, name, almostMatchedMembers);
584 int count = mi.Length;
586 if (mi [0] is MethodBase)
587 return new MethodGroupExpr (mi, loc);
592 return ExprClassFromMemberInfo (ec, mi [0], loc);
595 public const MemberTypes AllMemberTypes =
596 MemberTypes.Constructor |
600 MemberTypes.NestedType |
601 MemberTypes.Property;
603 public const BindingFlags AllBindingFlags =
604 BindingFlags.Public |
605 BindingFlags.Static |
606 BindingFlags.Instance;
608 public static Expression MemberLookup (EmitContext ec, Type queried_type,
609 string name, Location loc)
611 return MemberLookup (ec, ec.ContainerType, null, queried_type, name,
612 AllMemberTypes, AllBindingFlags, loc);
615 public static Expression MemberLookup (EmitContext ec, Type qualifier_type,
616 Type queried_type, string name, Location loc)
618 return MemberLookup (ec, ec.ContainerType, qualifier_type, queried_type,
619 name, AllMemberTypes, AllBindingFlags, loc);
622 public static Expression MethodLookup (EmitContext ec, Type queried_type,
623 string name, Location loc)
625 return MemberLookup (ec, ec.ContainerType, null, queried_type, name,
626 MemberTypes.Method, AllBindingFlags, loc);
630 /// This is a wrapper for MemberLookup that is not used to "probe", but
631 /// to find a final definition. If the final definition is not found, we
632 /// look for private members and display a useful debugging message if we
635 public static Expression MemberLookupFinal (EmitContext ec, Type qualifier_type,
636 Type queried_type, string name, Location loc)
638 return MemberLookupFinal (ec, qualifier_type, queried_type, name,
639 AllMemberTypes, AllBindingFlags, loc);
642 public static Expression MemberLookupFinal (EmitContext ec, Type qualifier_type,
643 Type queried_type, string name,
644 MemberTypes mt, BindingFlags bf,
649 int errors = Report.Errors;
651 e = MemberLookup (ec, ec.ContainerType, qualifier_type, queried_type, name, mt, bf, loc);
653 if (e == null && errors == Report.Errors)
654 // No errors were reported by MemberLookup, but there was an error.
655 MemberLookupFailed (ec, qualifier_type, queried_type, name, null, true, loc);
660 public static void MemberLookupFailed (EmitContext ec, Type qualifier_type,
661 Type queried_type, string name,
662 string class_name, bool complain_if_none_found,
665 if (almostMatchedMembers.Count != 0) {
666 if (qualifier_type == null) {
667 foreach (MemberInfo m in almostMatchedMembers)
668 Report.Error (38, loc,
669 "Cannot access non-static member `{0}' via nested type `{1}'",
670 TypeManager.GetFullNameSignature (m),
671 TypeManager.CSharpName (ec.ContainerType));
675 if (qualifier_type != ec.ContainerType) {
676 // Although a derived class can access protected members of
677 // its base class it cannot do so through an instance of the
678 // base class (CS1540). If the qualifier_type is a base of the
679 // ec.ContainerType and the lookup succeeds with the latter one,
680 // then we are in this situation.
681 for (int i = 0; i < almostMatchedMembers.Count; ++i) {
682 MemberInfo m = (MemberInfo) almostMatchedMembers [i];
683 for (int j = 0; j < i; ++j) {
684 if (m == almostMatchedMembers [j]) {
692 Report.SymbolRelatedToPreviousError (m);
693 Report.Error (1540, loc,
694 "Cannot access protected member `{0}' via a qualifier of type `{1}';"
695 + " the qualifier must be of type `{2}' (or derived from it)",
696 TypeManager.GetFullNameSignature (m),
697 TypeManager.CSharpName (qualifier_type),
698 TypeManager.CSharpName (ec.ContainerType));
702 almostMatchedMembers.Clear ();
705 object lookup = TypeManager.MemberLookup (queried_type, null, queried_type,
706 AllMemberTypes, AllBindingFlags |
707 BindingFlags.NonPublic, name, null);
709 if (lookup == null) {
710 if (!complain_if_none_found)
713 if (class_name != null)
714 Report.Error (103, loc, "The name `" + name + "' could not be " +
715 "found in `" + class_name + "'");
718 117, loc, "`" + queried_type + "' does not contain a " +
719 "definition for `" + name + "'");
723 if (name == ".ctor" && TypeManager.FindMembers (qualifier_type, MemberTypes.Constructor,
724 BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly, null, null).Count == 0)
726 Report.Error (143, loc, String.Format ("The type '{0}' has no constructors defined", TypeManager.CSharpName (queried_type)));
730 if (qualifier_type != null) {
731 Report.Error (122, loc, "'{0}' is inaccessible due to its protection level", TypeManager.CSharpName (qualifier_type) + "." + name);
733 Report.Error (122, loc, "'{0}' is inaccessible due to its protection level", name);
738 /// Returns an expression that can be used to invoke operator true
739 /// on the expression if it exists.
741 static public StaticCallExpr GetOperatorTrue (EmitContext ec, Expression e, Location loc)
743 return GetOperatorTrueOrFalse (ec, e, true, loc);
747 /// Returns an expression that can be used to invoke operator false
748 /// on the expression if it exists.
750 static public StaticCallExpr GetOperatorFalse (EmitContext ec, Expression e, Location loc)
752 return GetOperatorTrueOrFalse (ec, e, false, loc);
755 static StaticCallExpr GetOperatorTrueOrFalse (EmitContext ec, Expression e, bool is_true, Location loc)
758 Expression operator_group;
760 operator_group = MethodLookup (ec, e.Type, is_true ? "op_True" : "op_False", loc);
761 if (operator_group == null)
764 ArrayList arguments = new ArrayList ();
765 arguments.Add (new Argument (e, Argument.AType.Expression));
766 method = Invocation.OverloadResolve (
767 ec, (MethodGroupExpr) operator_group, arguments, false, loc);
772 return new StaticCallExpr ((MethodInfo) method, arguments, loc);
776 /// Resolves the expression `e' into a boolean expression: either through
777 /// an implicit conversion, or through an `operator true' invocation
779 public static Expression ResolveBoolean (EmitContext ec, Expression e, Location loc)
785 if (e.Type == TypeManager.bool_type)
788 Expression converted = Convert.ImplicitConversion (ec, e, TypeManager.bool_type, Location.Null);
790 if (converted != null)
794 // If no implicit conversion to bool exists, try using `operator true'
796 Expression operator_true = Expression.GetOperatorTrue (ec, e, loc);
797 if (operator_true == null){
798 Report.Error (31, loc, "Can not convert the expression to a boolean");
801 return operator_true;
804 public string ExprClassName ()
807 case ExprClass.Invalid:
809 case ExprClass.Value:
811 case ExprClass.Variable:
813 case ExprClass.Namespace:
817 case ExprClass.MethodGroup:
818 return "method group";
819 case ExprClass.PropertyAccess:
820 return "property access";
821 case ExprClass.EventAccess:
822 return "event access";
823 case ExprClass.IndexerAccess:
824 return "indexer access";
825 case ExprClass.Nothing:
828 throw new Exception ("Should not happen");
832 /// Reports that we were expecting `expr' to be of class `expected'
834 public void Error_UnexpectedKind (string expected, Location loc)
836 Report.Error (118, loc, "Expression denotes a `" + ExprClassName () +
837 "' where a `" + expected + "' was expected");
840 public void Error_UnexpectedKind (ResolveFlags flags, Location loc)
842 ArrayList valid = new ArrayList (10);
844 if ((flags & ResolveFlags.VariableOrValue) != 0) {
845 valid.Add ("variable");
849 if ((flags & ResolveFlags.Type) != 0)
852 if ((flags & ResolveFlags.MethodGroup) != 0)
853 valid.Add ("method group");
855 if (valid.Count == 0)
856 valid.Add ("unknown");
858 StringBuilder sb = new StringBuilder ();
859 for (int i = 0; i < valid.Count; i++) {
862 else if (i == valid.Count)
864 sb.Append (valid [i]);
867 Report.Error (119, loc, "Expression denotes a `" + ExprClassName () + "' where " +
868 "a `" + sb.ToString () + "' was expected");
871 static public void Error_ConstantValueCannotBeConverted (Location l, string val, Type t)
873 Report.Error (31, l, "Constant value `" + val + "' cannot be converted to " +
874 TypeManager.CSharpName (t));
877 public static void UnsafeError (Location loc)
879 Report.Error (214, loc, "Pointers may only be used in an unsafe context");
883 /// Converts the IntConstant, UIntConstant, LongConstant or
884 /// ULongConstant into the integral target_type. Notice
885 /// that we do not return an `Expression' we do return
886 /// a boxed integral type.
888 /// FIXME: Since I added the new constants, we need to
889 /// also support conversions from CharConstant, ByteConstant,
890 /// SByteConstant, UShortConstant, ShortConstant
892 /// This is used by the switch statement, so the domain
893 /// of work is restricted to the literals above, and the
894 /// targets are int32, uint32, char, byte, sbyte, ushort,
895 /// short, uint64 and int64
897 public static object ConvertIntLiteral (Constant c, Type target_type, Location loc)
899 if (!Convert.ImplicitStandardConversionExists (Convert.ConstantEC, c, target_type)){
900 Convert.Error_CannotImplicitConversion (loc, c.Type, target_type);
906 if (c.Type == target_type)
907 return ((Constant) c).GetValue ();
910 // Make into one of the literals we handle, we dont really care
911 // about this value as we will just return a few limited types
913 if (c is EnumConstant)
914 c = ((EnumConstant)c).WidenToCompilerConstant ();
916 if (c is IntConstant){
917 int v = ((IntConstant) c).Value;
919 if (target_type == TypeManager.uint32_type){
922 } else if (target_type == TypeManager.char_type){
923 if (v >= Char.MinValue && v <= Char.MaxValue)
925 } else if (target_type == TypeManager.byte_type){
926 if (v >= Byte.MinValue && v <= Byte.MaxValue)
928 } else if (target_type == TypeManager.sbyte_type){
929 if (v >= SByte.MinValue && v <= SByte.MaxValue)
931 } else if (target_type == TypeManager.short_type){
932 if (v >= Int16.MinValue && v <= UInt16.MaxValue)
934 } else if (target_type == TypeManager.ushort_type){
935 if (v >= UInt16.MinValue && v <= UInt16.MaxValue)
937 } else if (target_type == TypeManager.int64_type)
939 else if (target_type == TypeManager.uint64_type){
945 } else if (c is UIntConstant){
946 uint v = ((UIntConstant) c).Value;
948 if (target_type == TypeManager.int32_type){
949 if (v <= Int32.MaxValue)
951 } else if (target_type == TypeManager.char_type){
952 if (v >= Char.MinValue && v <= Char.MaxValue)
954 } else if (target_type == TypeManager.byte_type){
955 if (v <= Byte.MaxValue)
957 } else if (target_type == TypeManager.sbyte_type){
958 if (v <= SByte.MaxValue)
960 } else if (target_type == TypeManager.short_type){
961 if (v <= UInt16.MaxValue)
963 } else if (target_type == TypeManager.ushort_type){
964 if (v <= UInt16.MaxValue)
966 } else if (target_type == TypeManager.int64_type)
968 else if (target_type == TypeManager.uint64_type)
971 } else if (c is LongConstant){
972 long v = ((LongConstant) c).Value;
974 if (target_type == TypeManager.int32_type){
975 if (v >= UInt32.MinValue && v <= UInt32.MaxValue)
977 } else if (target_type == TypeManager.uint32_type){
978 if (v >= 0 && v <= UInt32.MaxValue)
980 } else if (target_type == TypeManager.char_type){
981 if (v >= Char.MinValue && v <= Char.MaxValue)
983 } else if (target_type == TypeManager.byte_type){
984 if (v >= Byte.MinValue && v <= Byte.MaxValue)
986 } else if (target_type == TypeManager.sbyte_type){
987 if (v >= SByte.MinValue && v <= SByte.MaxValue)
989 } else if (target_type == TypeManager.short_type){
990 if (v >= Int16.MinValue && v <= UInt16.MaxValue)
992 } else if (target_type == TypeManager.ushort_type){
993 if (v >= UInt16.MinValue && v <= UInt16.MaxValue)
995 } else if (target_type == TypeManager.uint64_type){
1000 } else if (c is ULongConstant){
1001 ulong v = ((ULongConstant) c).Value;
1003 if (target_type == TypeManager.int32_type){
1004 if (v <= Int32.MaxValue)
1006 } else if (target_type == TypeManager.uint32_type){
1007 if (v <= UInt32.MaxValue)
1009 } else if (target_type == TypeManager.char_type){
1010 if (v >= Char.MinValue && v <= Char.MaxValue)
1012 } else if (target_type == TypeManager.byte_type){
1013 if (v >= Byte.MinValue && v <= Byte.MaxValue)
1015 } else if (target_type == TypeManager.sbyte_type){
1016 if (v <= (int) SByte.MaxValue)
1018 } else if (target_type == TypeManager.short_type){
1019 if (v <= UInt16.MaxValue)
1021 } else if (target_type == TypeManager.ushort_type){
1022 if (v <= UInt16.MaxValue)
1024 } else if (target_type == TypeManager.int64_type){
1025 if (v <= Int64.MaxValue)
1029 } else if (c is ByteConstant){
1030 byte v = ((ByteConstant) c).Value;
1032 if (target_type == TypeManager.int32_type)
1034 else if (target_type == TypeManager.uint32_type)
1036 else if (target_type == TypeManager.char_type)
1038 else if (target_type == TypeManager.sbyte_type){
1039 if (v <= SByte.MaxValue)
1041 } else if (target_type == TypeManager.short_type)
1043 else if (target_type == TypeManager.ushort_type)
1045 else if (target_type == TypeManager.int64_type)
1047 else if (target_type == TypeManager.uint64_type)
1050 } else if (c is SByteConstant){
1051 sbyte v = ((SByteConstant) c).Value;
1053 if (target_type == TypeManager.int32_type)
1055 else if (target_type == TypeManager.uint32_type){
1058 } else if (target_type == TypeManager.char_type){
1061 } else if (target_type == TypeManager.byte_type){
1064 } else if (target_type == TypeManager.short_type)
1066 else if (target_type == TypeManager.ushort_type){
1069 } else if (target_type == TypeManager.int64_type)
1071 else if (target_type == TypeManager.uint64_type){
1076 } else if (c is ShortConstant){
1077 short v = ((ShortConstant) c).Value;
1079 if (target_type == TypeManager.int32_type){
1081 } else if (target_type == TypeManager.uint32_type){
1084 } else if (target_type == TypeManager.char_type){
1087 } else if (target_type == TypeManager.byte_type){
1088 if (v >= Byte.MinValue && v <= Byte.MaxValue)
1090 } else if (target_type == TypeManager.sbyte_type){
1091 if (v >= SByte.MinValue && v <= SByte.MaxValue)
1093 } else if (target_type == TypeManager.ushort_type){
1096 } else if (target_type == TypeManager.int64_type)
1098 else if (target_type == TypeManager.uint64_type)
1102 } else if (c is UShortConstant){
1103 ushort v = ((UShortConstant) c).Value;
1105 if (target_type == TypeManager.int32_type)
1107 else if (target_type == TypeManager.uint32_type)
1109 else if (target_type == TypeManager.char_type){
1110 if (v >= Char.MinValue && v <= Char.MaxValue)
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.int64_type)
1123 else if (target_type == TypeManager.uint64_type)
1127 } else if (c is CharConstant){
1128 char v = ((CharConstant) c).Value;
1130 if (target_type == TypeManager.int32_type)
1132 else if (target_type == TypeManager.uint32_type)
1134 else if (target_type == TypeManager.byte_type){
1135 if (v >= Byte.MinValue && v <= Byte.MaxValue)
1137 } else if (target_type == TypeManager.sbyte_type){
1138 if (v <= SByte.MaxValue)
1140 } else if (target_type == TypeManager.short_type){
1141 if (v <= Int16.MaxValue)
1143 } else if (target_type == TypeManager.ushort_type)
1145 else if (target_type == TypeManager.int64_type)
1147 else if (target_type == TypeManager.uint64_type)
1152 Error_ConstantValueCannotBeConverted (loc, s, target_type);
1157 // Load the object from the pointer.
1159 public static void LoadFromPtr (ILGenerator ig, Type t)
1161 if (t == TypeManager.int32_type)
1162 ig.Emit (OpCodes.Ldind_I4);
1163 else if (t == TypeManager.uint32_type)
1164 ig.Emit (OpCodes.Ldind_U4);
1165 else if (t == TypeManager.short_type)
1166 ig.Emit (OpCodes.Ldind_I2);
1167 else if (t == TypeManager.ushort_type)
1168 ig.Emit (OpCodes.Ldind_U2);
1169 else if (t == TypeManager.char_type)
1170 ig.Emit (OpCodes.Ldind_U2);
1171 else if (t == TypeManager.byte_type)
1172 ig.Emit (OpCodes.Ldind_U1);
1173 else if (t == TypeManager.sbyte_type)
1174 ig.Emit (OpCodes.Ldind_I1);
1175 else if (t == TypeManager.uint64_type)
1176 ig.Emit (OpCodes.Ldind_I8);
1177 else if (t == TypeManager.int64_type)
1178 ig.Emit (OpCodes.Ldind_I8);
1179 else if (t == TypeManager.float_type)
1180 ig.Emit (OpCodes.Ldind_R4);
1181 else if (t == TypeManager.double_type)
1182 ig.Emit (OpCodes.Ldind_R8);
1183 else if (t == TypeManager.bool_type)
1184 ig.Emit (OpCodes.Ldind_I1);
1185 else if (t == TypeManager.intptr_type)
1186 ig.Emit (OpCodes.Ldind_I);
1187 else if (TypeManager.IsEnumType (t)) {
1188 if (t == TypeManager.enum_type)
1189 ig.Emit (OpCodes.Ldind_Ref);
1191 LoadFromPtr (ig, TypeManager.EnumToUnderlying (t));
1192 } else if (t.IsValueType)
1193 ig.Emit (OpCodes.Ldobj, t);
1194 else if (t.IsPointer)
1195 ig.Emit (OpCodes.Ldind_I);
1197 ig.Emit (OpCodes.Ldind_Ref);
1201 // The stack contains the pointer and the value of type `type'
1203 public static void StoreFromPtr (ILGenerator ig, Type type)
1205 if (TypeManager.IsEnumType (type))
1206 type = TypeManager.EnumToUnderlying (type);
1207 if (type == TypeManager.int32_type || type == TypeManager.uint32_type)
1208 ig.Emit (OpCodes.Stind_I4);
1209 else if (type == TypeManager.int64_type || type == TypeManager.uint64_type)
1210 ig.Emit (OpCodes.Stind_I8);
1211 else if (type == TypeManager.char_type || type == TypeManager.short_type ||
1212 type == TypeManager.ushort_type)
1213 ig.Emit (OpCodes.Stind_I2);
1214 else if (type == TypeManager.float_type)
1215 ig.Emit (OpCodes.Stind_R4);
1216 else if (type == TypeManager.double_type)
1217 ig.Emit (OpCodes.Stind_R8);
1218 else if (type == TypeManager.byte_type || type == TypeManager.sbyte_type ||
1219 type == TypeManager.bool_type)
1220 ig.Emit (OpCodes.Stind_I1);
1221 else if (type == TypeManager.intptr_type)
1222 ig.Emit (OpCodes.Stind_I);
1223 else if (type.IsValueType)
1224 ig.Emit (OpCodes.Stobj, type);
1226 ig.Emit (OpCodes.Stind_Ref);
1230 // Returns the size of type `t' if known, otherwise, 0
1232 public static int GetTypeSize (Type t)
1234 t = TypeManager.TypeToCoreType (t);
1235 if (t == TypeManager.int32_type ||
1236 t == TypeManager.uint32_type ||
1237 t == TypeManager.float_type)
1239 else if (t == TypeManager.int64_type ||
1240 t == TypeManager.uint64_type ||
1241 t == TypeManager.double_type)
1243 else if (t == TypeManager.byte_type ||
1244 t == TypeManager.sbyte_type ||
1245 t == TypeManager.bool_type)
1247 else if (t == TypeManager.short_type ||
1248 t == TypeManager.char_type ||
1249 t == TypeManager.ushort_type)
1251 else if (t == TypeManager.decimal_type)
1257 public static void Error_NegativeArrayIndex (Location loc)
1259 Report.Error (248, loc, "Cannot create an array with a negative size");
1263 // Converts `source' to an int, uint, long or ulong.
1265 public Expression ExpressionToArrayArgument (EmitContext ec, Expression source, Location loc)
1269 bool old_checked = ec.CheckState;
1270 ec.CheckState = true;
1272 target = Convert.ImplicitConversion (ec, source, TypeManager.int32_type, loc);
1273 if (target == null){
1274 target = Convert.ImplicitConversion (ec, source, TypeManager.uint32_type, loc);
1275 if (target == null){
1276 target = Convert.ImplicitConversion (ec, source, TypeManager.int64_type, loc);
1277 if (target == null){
1278 target = Convert.ImplicitConversion (ec, source, TypeManager.uint64_type, loc);
1280 Convert.Error_CannotImplicitConversion (loc, source.Type, TypeManager.int32_type);
1284 ec.CheckState = old_checked;
1287 // Only positive constants are allowed at compile time
1289 if (target is Constant){
1290 if (target is IntConstant){
1291 if (((IntConstant) target).Value < 0){
1292 Error_NegativeArrayIndex (loc);
1297 if (target is LongConstant){
1298 if (((LongConstant) target).Value < 0){
1299 Error_NegativeArrayIndex (loc);
1312 /// This is just a base class for expressions that can
1313 /// appear on statements (invocations, object creation,
1314 /// assignments, post/pre increment and decrement). The idea
1315 /// being that they would support an extra Emition interface that
1316 /// does not leave a result on the stack.
1318 public abstract class ExpressionStatement : Expression {
1320 public virtual ExpressionStatement ResolveStatement (EmitContext ec)
1322 Expression e = Resolve (ec);
1326 ExpressionStatement es = e as ExpressionStatement;
1328 Error (201, "Only assignment, call, increment, decrement and new object " +
1329 "expressions can be used as a statement");
1335 /// Requests the expression to be emitted in a `statement'
1336 /// context. This means that no new value is left on the
1337 /// stack after invoking this method (constrasted with
1338 /// Emit that will always leave a value on the stack).
1340 public abstract void EmitStatement (EmitContext ec);
1344 /// This kind of cast is used to encapsulate the child
1345 /// whose type is child.Type into an expression that is
1346 /// reported to return "return_type". This is used to encapsulate
1347 /// expressions which have compatible types, but need to be dealt
1348 /// at higher levels with.
1350 /// For example, a "byte" expression could be encapsulated in one
1351 /// of these as an "unsigned int". The type for the expression
1352 /// would be "unsigned int".
1355 public class EmptyCast : Expression {
1356 protected Expression child;
1358 public Expression Child {
1364 public EmptyCast (Expression child, Type return_type)
1366 eclass = child.eclass;
1367 loc = child.Location;
1372 public override Expression DoResolve (EmitContext ec)
1374 // This should never be invoked, we are born in fully
1375 // initialized state.
1380 public override void Emit (EmitContext ec)
1386 /// This is a numeric cast to a Decimal
1388 public class CastToDecimal : EmptyCast {
1390 MethodInfo conversion_operator;
1392 public CastToDecimal (EmitContext ec, Expression child)
1393 : this (ec, child, false)
1397 public CastToDecimal (EmitContext ec, Expression child, bool find_explicit)
1398 : base (child, TypeManager.decimal_type)
1400 conversion_operator = GetConversionOperator (ec, find_explicit);
1402 if (conversion_operator == null)
1403 Convert.Error_CannotImplicitConversion (loc, child.Type, type);
1406 // Returns the implicit operator that converts from
1407 // 'child.Type' to System.Decimal.
1408 MethodInfo GetConversionOperator (EmitContext ec, bool find_explicit)
1410 string operator_name = "op_Implicit";
1413 operator_name = "op_Explicit";
1415 MethodGroupExpr opers = Expression.MethodLookup (
1416 ec, type, operator_name, loc) as MethodGroupExpr;
1419 Convert.Error_CannotImplicitConversion (loc, child.Type, type);
1421 foreach (MethodInfo oper in opers.Methods) {
1422 ParameterData pd = TypeManager.GetParameterData (oper);
1424 if (pd.ParameterType (0) == child.Type && oper.ReturnType == type)
1430 public override void Emit (EmitContext ec)
1432 ILGenerator ig = ec.ig;
1435 ig.Emit (OpCodes.Call, conversion_operator);
1439 /// This is an explicit numeric cast from a Decimal
1441 public class CastFromDecimal : EmptyCast
1443 MethodInfo conversion_operator;
1444 public CastFromDecimal (EmitContext ec, Expression child, Type return_type)
1445 : base (child, return_type)
1447 if (child.Type != TypeManager.decimal_type)
1448 throw new InternalErrorException (
1449 "The expected type is Decimal, instead it is " + child.Type.FullName);
1451 conversion_operator = GetConversionOperator (ec);
1452 if (conversion_operator == null)
1453 Convert.Error_CannotImplicitConversion (loc, child.Type, type);
1456 // Returns the explicit operator that converts from an
1457 // express of type System.Decimal to 'type'.
1458 MethodInfo GetConversionOperator (EmitContext ec)
1460 MethodGroupExpr opers = Expression.MethodLookup (
1461 ec, child.Type, "op_Explicit", loc) as MethodGroupExpr;
1464 Convert.Error_CannotImplicitConversion (loc, child.Type, type);
1466 foreach (MethodInfo oper in opers.Methods) {
1467 ParameterData pd = TypeManager.GetParameterData (oper);
1469 if (pd.ParameterType (0) == child.Type && oper.ReturnType == type)
1475 public override void Emit (EmitContext ec)
1477 ILGenerator ig = ec.ig;
1480 ig.Emit (OpCodes.Call, conversion_operator);
1485 // We need to special case this since an empty cast of
1486 // a NullLiteral is still a Constant
1488 public class NullCast : Constant {
1489 protected Expression child;
1491 public NullCast (Expression child, Type return_type)
1493 eclass = child.eclass;
1498 override public string AsString ()
1503 public override object GetValue ()
1508 public override Expression DoResolve (EmitContext ec)
1510 // This should never be invoked, we are born in fully
1511 // initialized state.
1516 public override void Emit (EmitContext ec)
1521 public override bool IsDefaultValue {
1523 throw new NotImplementedException ();
1527 public override bool IsNegative {
1536 /// This class is used to wrap literals which belong inside Enums
1538 public class EnumConstant : Constant {
1539 public Constant Child;
1541 public EnumConstant (Constant child, Type enum_type)
1543 eclass = child.eclass;
1548 public override Expression DoResolve (EmitContext ec)
1550 // This should never be invoked, we are born in fully
1551 // initialized state.
1556 public override void Emit (EmitContext ec)
1561 public override object GetValue ()
1563 return Child.GetValue ();
1566 public object GetValueAsEnumType ()
1568 return System.Enum.ToObject (type, Child.GetValue ());
1572 // Converts from one of the valid underlying types for an enumeration
1573 // (int32, uint32, int64, uint64, short, ushort, byte, sbyte) to
1574 // one of the internal compiler literals: Int/UInt/Long/ULong Literals.
1576 public Constant WidenToCompilerConstant ()
1578 Type t = TypeManager.EnumToUnderlying (Child.Type);
1579 object v = ((Constant) Child).GetValue ();;
1581 if (t == TypeManager.int32_type)
1582 return new IntConstant ((int) v);
1583 if (t == TypeManager.uint32_type)
1584 return new UIntConstant ((uint) v);
1585 if (t == TypeManager.int64_type)
1586 return new LongConstant ((long) v);
1587 if (t == TypeManager.uint64_type)
1588 return new ULongConstant ((ulong) v);
1589 if (t == TypeManager.short_type)
1590 return new ShortConstant ((short) v);
1591 if (t == TypeManager.ushort_type)
1592 return new UShortConstant ((ushort) v);
1593 if (t == TypeManager.byte_type)
1594 return new ByteConstant ((byte) v);
1595 if (t == TypeManager.sbyte_type)
1596 return new SByteConstant ((sbyte) v);
1598 throw new Exception ("Invalid enumeration underlying type: " + t);
1602 // Extracts the value in the enumeration on its native representation
1604 public object GetPlainValue ()
1606 Type t = TypeManager.EnumToUnderlying (Child.Type);
1607 object v = ((Constant) Child).GetValue ();;
1609 if (t == TypeManager.int32_type)
1611 if (t == TypeManager.uint32_type)
1613 if (t == TypeManager.int64_type)
1615 if (t == TypeManager.uint64_type)
1617 if (t == TypeManager.short_type)
1619 if (t == TypeManager.ushort_type)
1621 if (t == TypeManager.byte_type)
1623 if (t == TypeManager.sbyte_type)
1629 public override string AsString ()
1631 return Child.AsString ();
1634 public override DoubleConstant ConvertToDouble ()
1636 return Child.ConvertToDouble ();
1639 public override FloatConstant ConvertToFloat ()
1641 return Child.ConvertToFloat ();
1644 public override ULongConstant ConvertToULong ()
1646 return Child.ConvertToULong ();
1649 public override LongConstant ConvertToLong ()
1651 return Child.ConvertToLong ();
1654 public override UIntConstant ConvertToUInt ()
1656 return Child.ConvertToUInt ();
1659 public override IntConstant ConvertToInt ()
1661 return Child.ConvertToInt ();
1664 public override bool IsDefaultValue {
1666 return Child.IsDefaultValue;
1670 public override bool IsZeroInteger {
1671 get { return Child.IsZeroInteger; }
1674 public override bool IsNegative {
1676 return Child.IsNegative;
1682 /// This kind of cast is used to encapsulate Value Types in objects.
1684 /// The effect of it is to box the value type emitted by the previous
1687 public class BoxedCast : EmptyCast {
1689 public BoxedCast (Expression expr)
1690 : base (expr, TypeManager.object_type)
1692 eclass = ExprClass.Value;
1695 public BoxedCast (Expression expr, Type target_type)
1696 : base (expr, target_type)
1698 eclass = ExprClass.Value;
1701 public override Expression DoResolve (EmitContext ec)
1703 // This should never be invoked, we are born in fully
1704 // initialized state.
1709 public override void Emit (EmitContext ec)
1713 ec.ig.Emit (OpCodes.Box, child.Type);
1717 public class UnboxCast : EmptyCast {
1718 public UnboxCast (Expression expr, Type return_type)
1719 : base (expr, return_type)
1723 public override Expression DoResolve (EmitContext ec)
1725 // This should never be invoked, we are born in fully
1726 // initialized state.
1731 public override void Emit (EmitContext ec)
1734 ILGenerator ig = ec.ig;
1737 ig.Emit (OpCodes.Unbox, t);
1739 LoadFromPtr (ig, t);
1744 /// This is used to perform explicit numeric conversions.
1746 /// Explicit numeric conversions might trigger exceptions in a checked
1747 /// context, so they should generate the conv.ovf opcodes instead of
1750 public class ConvCast : EmptyCast {
1751 public enum Mode : byte {
1752 I1_U1, I1_U2, I1_U4, I1_U8, I1_CH,
1754 I2_I1, I2_U1, I2_U2, I2_U4, I2_U8, I2_CH,
1755 U2_I1, U2_U1, U2_I2, U2_CH,
1756 I4_I1, I4_U1, I4_I2, I4_U2, I4_U4, I4_U8, I4_CH,
1757 U4_I1, U4_U1, U4_I2, U4_U2, U4_I4, U4_CH,
1758 I8_I1, I8_U1, I8_I2, I8_U2, I8_I4, I8_U4, I8_U8, I8_CH,
1759 U8_I1, U8_U1, U8_I2, U8_U2, U8_I4, U8_U4, U8_I8, U8_CH,
1760 CH_I1, CH_U1, CH_I2,
1761 R4_I1, R4_U1, R4_I2, R4_U2, R4_I4, R4_U4, R4_I8, R4_U8, R4_CH,
1762 R8_I1, R8_U1, R8_I2, R8_U2, R8_I4, R8_U4, R8_I8, R8_U8, R8_CH, R8_R4
1768 public ConvCast (EmitContext ec, Expression child, Type return_type, Mode m)
1769 : base (child, return_type)
1771 checked_state = ec.CheckState;
1775 public override Expression DoResolve (EmitContext ec)
1777 // This should never be invoked, we are born in fully
1778 // initialized state.
1783 public override string ToString ()
1785 return String.Format ("ConvCast ({0}, {1})", mode, child);
1788 public override void Emit (EmitContext ec)
1790 ILGenerator ig = ec.ig;
1796 case Mode.I1_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1797 case Mode.I1_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1798 case Mode.I1_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1799 case Mode.I1_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1800 case Mode.I1_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1802 case Mode.U1_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1803 case Mode.U1_CH: /* nothing */ break;
1805 case Mode.I2_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1806 case Mode.I2_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1807 case Mode.I2_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1808 case Mode.I2_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1809 case Mode.I2_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1810 case Mode.I2_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1812 case Mode.U2_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1813 case Mode.U2_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
1814 case Mode.U2_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
1815 case Mode.U2_CH: /* nothing */ break;
1817 case Mode.I4_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1818 case Mode.I4_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1819 case Mode.I4_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
1820 case Mode.I4_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1821 case Mode.I4_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1822 case Mode.I4_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1823 case Mode.I4_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1825 case Mode.U4_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1826 case Mode.U4_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
1827 case Mode.U4_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
1828 case Mode.U4_U2: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
1829 case Mode.U4_I4: ig.Emit (OpCodes.Conv_Ovf_I4_Un); break;
1830 case Mode.U4_CH: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
1832 case Mode.I8_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1833 case Mode.I8_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1834 case Mode.I8_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
1835 case Mode.I8_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1836 case Mode.I8_I4: ig.Emit (OpCodes.Conv_Ovf_I4); break;
1837 case Mode.I8_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1838 case Mode.I8_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1839 case Mode.I8_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1841 case Mode.U8_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1842 case Mode.U8_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
1843 case Mode.U8_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
1844 case Mode.U8_U2: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
1845 case Mode.U8_I4: ig.Emit (OpCodes.Conv_Ovf_I4_Un); break;
1846 case Mode.U8_U4: ig.Emit (OpCodes.Conv_Ovf_U4_Un); break;
1847 case Mode.U8_I8: ig.Emit (OpCodes.Conv_Ovf_I8_Un); break;
1848 case Mode.U8_CH: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
1850 case Mode.CH_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1851 case Mode.CH_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
1852 case Mode.CH_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
1854 case Mode.R4_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1855 case Mode.R4_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1856 case Mode.R4_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
1857 case Mode.R4_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1858 case Mode.R4_I4: ig.Emit (OpCodes.Conv_Ovf_I4); break;
1859 case Mode.R4_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1860 case Mode.R4_I8: ig.Emit (OpCodes.Conv_Ovf_I8); break;
1861 case Mode.R4_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1862 case Mode.R4_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1864 case Mode.R8_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1865 case Mode.R8_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1866 case Mode.R8_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
1867 case Mode.R8_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1868 case Mode.R8_I4: ig.Emit (OpCodes.Conv_Ovf_I4); break;
1869 case Mode.R8_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1870 case Mode.R8_I8: ig.Emit (OpCodes.Conv_Ovf_I8); break;
1871 case Mode.R8_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1872 case Mode.R8_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1873 case Mode.R8_R4: ig.Emit (OpCodes.Conv_R4); break;
1877 case Mode.I1_U1: ig.Emit (OpCodes.Conv_U1); break;
1878 case Mode.I1_U2: ig.Emit (OpCodes.Conv_U2); break;
1879 case Mode.I1_U4: ig.Emit (OpCodes.Conv_U4); break;
1880 case Mode.I1_U8: ig.Emit (OpCodes.Conv_I8); break;
1881 case Mode.I1_CH: ig.Emit (OpCodes.Conv_U2); break;
1883 case Mode.U1_I1: ig.Emit (OpCodes.Conv_I1); break;
1884 case Mode.U1_CH: ig.Emit (OpCodes.Conv_U2); break;
1886 case Mode.I2_I1: ig.Emit (OpCodes.Conv_I1); break;
1887 case Mode.I2_U1: ig.Emit (OpCodes.Conv_U1); break;
1888 case Mode.I2_U2: ig.Emit (OpCodes.Conv_U2); break;
1889 case Mode.I2_U4: ig.Emit (OpCodes.Conv_U4); break;
1890 case Mode.I2_U8: ig.Emit (OpCodes.Conv_I8); break;
1891 case Mode.I2_CH: ig.Emit (OpCodes.Conv_U2); break;
1893 case Mode.U2_I1: ig.Emit (OpCodes.Conv_I1); break;
1894 case Mode.U2_U1: ig.Emit (OpCodes.Conv_U1); break;
1895 case Mode.U2_I2: ig.Emit (OpCodes.Conv_I2); break;
1896 case Mode.U2_CH: /* nothing */ break;
1898 case Mode.I4_I1: ig.Emit (OpCodes.Conv_I1); break;
1899 case Mode.I4_U1: ig.Emit (OpCodes.Conv_U1); break;
1900 case Mode.I4_I2: ig.Emit (OpCodes.Conv_I2); break;
1901 case Mode.I4_U4: /* nothing */ break;
1902 case Mode.I4_U2: ig.Emit (OpCodes.Conv_U2); break;
1903 case Mode.I4_U8: ig.Emit (OpCodes.Conv_I8); break;
1904 case Mode.I4_CH: ig.Emit (OpCodes.Conv_U2); break;
1906 case Mode.U4_I1: ig.Emit (OpCodes.Conv_I1); break;
1907 case Mode.U4_U1: ig.Emit (OpCodes.Conv_U1); break;
1908 case Mode.U4_I2: ig.Emit (OpCodes.Conv_I2); break;
1909 case Mode.U4_U2: ig.Emit (OpCodes.Conv_U2); break;
1910 case Mode.U4_I4: /* nothing */ break;
1911 case Mode.U4_CH: ig.Emit (OpCodes.Conv_U2); break;
1913 case Mode.I8_I1: ig.Emit (OpCodes.Conv_I1); break;
1914 case Mode.I8_U1: ig.Emit (OpCodes.Conv_U1); break;
1915 case Mode.I8_I2: ig.Emit (OpCodes.Conv_I2); break;
1916 case Mode.I8_U2: ig.Emit (OpCodes.Conv_U2); break;
1917 case Mode.I8_I4: ig.Emit (OpCodes.Conv_I4); break;
1918 case Mode.I8_U4: ig.Emit (OpCodes.Conv_U4); break;
1919 case Mode.I8_U8: /* nothing */ break;
1920 case Mode.I8_CH: ig.Emit (OpCodes.Conv_U2); break;
1922 case Mode.U8_I1: ig.Emit (OpCodes.Conv_I1); break;
1923 case Mode.U8_U1: ig.Emit (OpCodes.Conv_U1); break;
1924 case Mode.U8_I2: ig.Emit (OpCodes.Conv_I2); break;
1925 case Mode.U8_U2: ig.Emit (OpCodes.Conv_U2); break;
1926 case Mode.U8_I4: ig.Emit (OpCodes.Conv_I4); break;
1927 case Mode.U8_U4: ig.Emit (OpCodes.Conv_U4); break;
1928 case Mode.U8_I8: /* nothing */ break;
1929 case Mode.U8_CH: ig.Emit (OpCodes.Conv_U2); break;
1931 case Mode.CH_I1: ig.Emit (OpCodes.Conv_I1); break;
1932 case Mode.CH_U1: ig.Emit (OpCodes.Conv_U1); break;
1933 case Mode.CH_I2: ig.Emit (OpCodes.Conv_I2); break;
1935 case Mode.R4_I1: ig.Emit (OpCodes.Conv_I1); break;
1936 case Mode.R4_U1: ig.Emit (OpCodes.Conv_U1); break;
1937 case Mode.R4_I2: ig.Emit (OpCodes.Conv_I2); break;
1938 case Mode.R4_U2: ig.Emit (OpCodes.Conv_U2); break;
1939 case Mode.R4_I4: ig.Emit (OpCodes.Conv_I4); break;
1940 case Mode.R4_U4: ig.Emit (OpCodes.Conv_U4); break;
1941 case Mode.R4_I8: ig.Emit (OpCodes.Conv_I8); break;
1942 case Mode.R4_U8: ig.Emit (OpCodes.Conv_U8); break;
1943 case Mode.R4_CH: ig.Emit (OpCodes.Conv_U2); break;
1945 case Mode.R8_I1: ig.Emit (OpCodes.Conv_I1); break;
1946 case Mode.R8_U1: ig.Emit (OpCodes.Conv_U1); break;
1947 case Mode.R8_I2: ig.Emit (OpCodes.Conv_I2); break;
1948 case Mode.R8_U2: ig.Emit (OpCodes.Conv_U2); break;
1949 case Mode.R8_I4: ig.Emit (OpCodes.Conv_I4); break;
1950 case Mode.R8_U4: ig.Emit (OpCodes.Conv_U4); break;
1951 case Mode.R8_I8: ig.Emit (OpCodes.Conv_I8); break;
1952 case Mode.R8_U8: ig.Emit (OpCodes.Conv_U8); break;
1953 case Mode.R8_CH: ig.Emit (OpCodes.Conv_U2); break;
1954 case Mode.R8_R4: ig.Emit (OpCodes.Conv_R4); break;
1960 public class OpcodeCast : EmptyCast {
1964 public OpcodeCast (Expression child, Type return_type, OpCode op)
1965 : base (child, return_type)
1969 second_valid = false;
1972 public OpcodeCast (Expression child, Type return_type, OpCode op, OpCode op2)
1973 : base (child, return_type)
1978 second_valid = true;
1981 public override Expression DoResolve (EmitContext ec)
1983 // This should never be invoked, we are born in fully
1984 // initialized state.
1989 public override void Emit (EmitContext ec)
2000 /// This kind of cast is used to encapsulate a child and cast it
2001 /// to the class requested
2003 public class ClassCast : EmptyCast {
2004 public ClassCast (Expression child, Type return_type)
2005 : base (child, return_type)
2010 public override Expression DoResolve (EmitContext ec)
2012 // This should never be invoked, we are born in fully
2013 // initialized state.
2018 public override void Emit (EmitContext ec)
2022 ec.ig.Emit (OpCodes.Castclass, type);
2028 /// SimpleName expressions are formed of a single word and only happen at the beginning
2029 /// of a dotted-name.
2031 public class SimpleName : Expression {
2035 public SimpleName (string name, Location l)
2041 public static void Error_ObjectRefRequired (EmitContext ec, Location l, string name)
2043 if (ec.IsFieldInitializer)
2046 "A field initializer cannot reference the non-static field, " +
2047 "method or property `"+name+"'");
2051 "An object reference is required " +
2052 "for the non-static field `"+name+"'");
2055 public bool IdenticalNameAndTypeName (EmitContext ec, Expression resolved_to, Location loc)
2057 return resolved_to != null && resolved_to.Type != null &&
2058 resolved_to.Type.Name == Name &&
2059 (ec.DeclSpace.LookupType (Name, loc, /* ignore_cs0104 = */ true) != null);
2062 public override Expression DoResolve (EmitContext ec)
2064 return SimpleNameResolve (ec, null, false);
2067 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
2069 return SimpleNameResolve (ec, right_side, false);
2073 public Expression DoResolve (EmitContext ec, bool intermediate)
2075 return SimpleNameResolve (ec, null, intermediate);
2078 public override FullNamedExpression ResolveAsTypeStep (EmitContext ec)
2080 int errors = Report.Errors;
2081 FullNamedExpression dt = ec.DeclSpace.LookupType (Name, loc, /*ignore_cs0104=*/ false);
2082 if (Report.Errors != errors)
2088 Expression SimpleNameResolve (EmitContext ec, Expression right_side, bool intermediate)
2094 Expression e = DoSimpleNameResolve (ec, right_side, intermediate);
2098 if (ec.CurrentBlock == null || ec.CurrentBlock.CheckInvariantMeaningInBlock (Name, e, Location))
2105 /// 7.5.2: Simple Names.
2107 /// Local Variables and Parameters are handled at
2108 /// parse time, so they never occur as SimpleNames.
2110 /// The `intermediate' flag is used by MemberAccess only
2111 /// and it is used to inform us that it is ok for us to
2112 /// avoid the static check, because MemberAccess might end
2113 /// up resolving the Name as a Type name and the access as
2114 /// a static type access.
2116 /// ie: Type Type; .... { Type.GetType (""); }
2118 /// Type is both an instance variable and a Type; Type.GetType
2119 /// is the static method not an instance method of type.
2121 Expression DoSimpleNameResolve (EmitContext ec, Expression right_side, bool intermediate)
2123 Expression e = null;
2126 // Stage 1: Performed by the parser (binding to locals or parameters).
2128 Block current_block = ec.CurrentBlock;
2129 if (current_block != null){
2130 LocalInfo vi = current_block.GetLocalInfo (Name);
2134 var = new LocalVariableReference (ec.CurrentBlock, Name, loc);
2136 if (right_side != null)
2137 return var.ResolveLValue (ec, right_side);
2139 return var.Resolve (ec);
2142 ParameterReference pref = current_block.Toplevel.GetParameterReference (Name, loc);
2144 if (right_side != null)
2145 return pref.ResolveLValue (ec, right_side);
2147 return pref.Resolve (ec);
2152 // Stage 2: Lookup members
2155 DeclSpace lookup_ds = ec.DeclSpace;
2156 Type almost_matched_type = null;
2157 ArrayList almost_matched = null;
2159 if (lookup_ds.TypeBuilder == null)
2162 e = MemberLookup (ec, lookup_ds.TypeBuilder, Name, loc);
2166 if (almost_matched == null && almostMatchedMembers.Count > 0) {
2167 almost_matched_type = lookup_ds.TypeBuilder;
2168 almost_matched = (ArrayList) almostMatchedMembers.Clone ();
2171 lookup_ds =lookup_ds.Parent;
2172 } while (lookup_ds != null);
2174 if (e == null && ec.ContainerType != null)
2175 e = MemberLookup (ec, ec.ContainerType, Name, loc);
2178 if (almost_matched == null && almostMatchedMembers.Count > 0) {
2179 almost_matched_type = ec.ContainerType;
2180 almost_matched = (ArrayList) almostMatchedMembers.Clone ();
2182 e = ResolveAsTypeStep (ec);
2186 if (almost_matched != null)
2187 almostMatchedMembers = almost_matched;
2188 if (almost_matched_type == null)
2189 almost_matched_type = ec.ContainerType;
2190 MemberLookupFailed (ec, null, almost_matched_type, ((SimpleName) this).Name, ec.DeclSpace.Name, true, loc);
2197 if (e is MemberExpr) {
2198 MemberExpr me = (MemberExpr) e;
2201 if (me.IsInstance) {
2202 if (ec.IsStatic || ec.IsFieldInitializer) {
2204 // Note that an MemberExpr can be both IsInstance and IsStatic.
2205 // An unresolved MethodGroupExpr can contain both kinds of methods
2206 // and each predicate is true if the MethodGroupExpr contains
2207 // at least one of that kind of method.
2211 (!intermediate || !IdenticalNameAndTypeName (ec, me, loc))) {
2212 Error_ObjectRefRequired (ec, loc, Name);
2217 // Pass the buck to MemberAccess and Invocation.
2219 left = EmptyExpression.Null;
2221 left = ec.GetThis (loc);
2224 left = new TypeExpression (ec.ContainerType, loc);
2227 e = me.ResolveMemberAccess (ec, left, loc, null);
2231 me = e as MemberExpr;
2236 TypeManager.IsNestedFamilyAccessible (me.InstanceExpression.Type, me.DeclaringType) &&
2237 me.InstanceExpression.Type != me.DeclaringType &&
2238 !me.InstanceExpression.Type.IsSubclassOf (me.DeclaringType) &&
2239 (!intermediate || !IdenticalNameAndTypeName (ec, e, loc))) {
2240 Error (38, "Cannot access nonstatic member `" + me.Name + "' of " +
2241 "outer type `" + me.DeclaringType + "' via nested type `" +
2242 me.InstanceExpression.Type + "'");
2246 return (right_side != null)
2247 ? me.DoResolveLValue (ec, right_side)
2248 : me.DoResolve (ec);
2254 public override void Emit (EmitContext ec)
2257 // If this is ever reached, then we failed to
2258 // find the name as a namespace
2261 Error (103, "The name `" + Name +
2262 "' does not exist in the class `" +
2263 ec.DeclSpace.Name + "'");
2266 public override string ToString ()
2273 /// Represents a namespace or a type. The name of the class was inspired by
2274 /// section 10.8.1 (Fully Qualified Names).
2276 public abstract class FullNamedExpression : Expression {
2277 public override FullNamedExpression ResolveAsTypeStep (EmitContext ec)
2282 public abstract string FullName {
2288 /// Fully resolved expression that evaluates to a type
2290 public abstract class TypeExpr : FullNamedExpression {
2291 override public FullNamedExpression ResolveAsTypeStep (EmitContext ec)
2293 TypeExpr t = DoResolveAsTypeStep (ec);
2297 eclass = ExprClass.Type;
2301 override public Expression DoResolve (EmitContext ec)
2303 return ResolveAsTypeTerminal (ec, false);
2306 override public void Emit (EmitContext ec)
2308 throw new Exception ("Should never be called");
2311 public virtual bool CheckAccessLevel (DeclSpace ds)
2313 return ds.CheckAccessLevel (Type);
2316 public virtual bool AsAccessible (DeclSpace ds, int flags)
2318 return ds.AsAccessible (Type, flags);
2321 public virtual bool IsClass {
2322 get { return Type.IsClass; }
2325 public virtual bool IsValueType {
2326 get { return Type.IsValueType; }
2329 public virtual bool IsInterface {
2330 get { return Type.IsInterface; }
2333 public virtual bool IsSealed {
2334 get { return Type.IsSealed; }
2337 public virtual bool CanInheritFrom ()
2339 if (Type == TypeManager.enum_type ||
2340 (Type == TypeManager.value_type && RootContext.StdLib) ||
2341 Type == TypeManager.multicast_delegate_type ||
2342 Type == TypeManager.delegate_type ||
2343 Type == TypeManager.array_type)
2349 public abstract TypeExpr DoResolveAsTypeStep (EmitContext ec);
2351 public virtual Type ResolveType (EmitContext ec)
2353 TypeExpr t = ResolveAsTypeTerminal (ec, false);
2360 public abstract string Name {
2364 public override bool Equals (object obj)
2366 TypeExpr tobj = obj as TypeExpr;
2370 return Type == tobj.Type;
2373 public override int GetHashCode ()
2375 return Type.GetHashCode ();
2378 public override string ToString ()
2384 public class TypeExpression : TypeExpr {
2385 public TypeExpression (Type t, Location l)
2388 eclass = ExprClass.Type;
2392 public override TypeExpr DoResolveAsTypeStep (EmitContext ec)
2397 public override string Name {
2399 return Type.ToString ();
2403 public override string FullName {
2405 return Type.FullName;
2411 /// Used to create types from a fully qualified name. These are just used
2412 /// by the parser to setup the core types. A TypeLookupExpression is always
2413 /// classified as a type.
2415 public class TypeLookupExpression : TypeExpr {
2418 public TypeLookupExpression (string name)
2423 public override TypeExpr DoResolveAsTypeStep (EmitContext ec)
2426 FullNamedExpression t = ec.DeclSpace.LookupType (name, Location.Null, /*ignore_cs0104=*/ false);
2428 Report.Error (246, loc, "Cannot find type `" + name + "'");
2431 if (!(t is TypeExpr)) {
2432 Report.Error (118, Location, "'{0}' denotes a '{1}', where a type was expected",
2433 t.FullName, t.ExprClassName ());
2437 type = ((TypeExpr) t).ResolveType (ec);
2443 public override string Name {
2449 public override string FullName {
2456 public class TypeAliasExpression : TypeExpr {
2459 public TypeAliasExpression (TypeExpr texpr, Location l)
2462 loc = texpr.Location;
2464 eclass = ExprClass.Type;
2467 public override string Name {
2468 get { return texpr.Name; }
2471 public override string FullName {
2472 get { return texpr.FullName; }
2475 public override TypeExpr DoResolveAsTypeStep (EmitContext ec)
2477 Type type = texpr.ResolveType (ec);
2481 return new TypeExpression (type, loc);
2484 public override bool CheckAccessLevel (DeclSpace ds)
2486 return texpr.CheckAccessLevel (ds);
2489 public override bool AsAccessible (DeclSpace ds, int flags)
2491 return texpr.AsAccessible (ds, flags);
2494 public override bool IsClass {
2495 get { return texpr.IsClass; }
2498 public override bool IsValueType {
2499 get { return texpr.IsValueType; }
2502 public override bool IsInterface {
2503 get { return texpr.IsInterface; }
2506 public override bool IsSealed {
2507 get { return texpr.IsSealed; }
2512 /// This class denotes an expression which evaluates to a member
2513 /// of a struct or a class.
2515 public abstract class MemberExpr : Expression
2518 /// The name of this member.
2520 public abstract string Name {
2525 /// Whether this is an instance member.
2527 public abstract bool IsInstance {
2532 /// Whether this is a static member.
2534 public abstract bool IsStatic {
2539 /// The type which declares this member.
2541 public abstract Type DeclaringType {
2546 /// The instance expression associated with this member, if it's a
2547 /// non-static member.
2549 public Expression InstanceExpression;
2551 public static void error176 (Location loc, string name)
2553 Report.Error (176, loc, "Static member `" + name + "' cannot be accessed " +
2554 "with an instance reference, qualify with a type name instead");
2558 // TODO: possible optimalization
2559 // Cache resolved constant result in FieldBuilder <-> expression map
2560 public virtual Expression ResolveMemberAccess (EmitContext ec, Expression left, Location loc,
2561 SimpleName original)
2565 // original == null || original.Resolve (...) ==> left
2568 if (left is TypeExpr) {
2570 SimpleName.Error_ObjectRefRequired (ec, loc, Name);
2578 if (original != null && original.IdenticalNameAndTypeName (ec, left, loc))
2581 error176 (loc, Name);
2585 InstanceExpression = left;
2592 /// MethodGroup Expression.
2594 /// This is a fully resolved expression that evaluates to a type
2596 public class MethodGroupExpr : MemberExpr {
2597 public MethodBase [] Methods;
2598 bool identical_type_name = false;
2601 public MethodGroupExpr (MemberInfo [] mi, Location l)
2603 Methods = new MethodBase [mi.Length];
2604 mi.CopyTo (Methods, 0);
2605 eclass = ExprClass.MethodGroup;
2606 type = TypeManager.object_type;
2610 public MethodGroupExpr (ArrayList list, Location l)
2612 Methods = new MethodBase [list.Count];
2615 list.CopyTo (Methods, 0);
2617 foreach (MemberInfo m in list){
2618 if (!(m is MethodBase)){
2619 Console.WriteLine ("Name " + m.Name);
2620 Console.WriteLine ("Found a: " + m.GetType ().FullName);
2627 eclass = ExprClass.MethodGroup;
2628 type = TypeManager.object_type;
2631 public override Type DeclaringType {
2634 // The methods are arranged in this order:
2635 // derived type -> base type
2637 return Methods [0].DeclaringType;
2641 public bool IdenticalTypeName {
2643 return identical_type_name;
2647 identical_type_name = value;
2651 public bool IsBase {
2660 public override string Name {
2662 return Methods [0].Name;
2666 public override bool IsInstance {
2668 foreach (MethodBase mb in Methods)
2676 public override bool IsStatic {
2678 foreach (MethodBase mb in Methods)
2686 public override Expression ResolveMemberAccess (EmitContext ec, Expression left, Location loc,
2687 SimpleName original)
2689 if (!(left is TypeExpr) &&
2690 original != null && original.IdenticalNameAndTypeName (ec, left, loc))
2691 IdenticalTypeName = true;
2693 return base.ResolveMemberAccess (ec, left, loc, original);
2696 override public Expression DoResolve (EmitContext ec)
2699 InstanceExpression = null;
2701 if (InstanceExpression != null) {
2702 InstanceExpression = InstanceExpression.DoResolve (ec);
2703 if (InstanceExpression == null)
2710 public void ReportUsageError ()
2712 Report.Error (654, loc, "Method `" + DeclaringType + "." +
2713 Name + "()' is referenced without parentheses");
2716 override public void Emit (EmitContext ec)
2718 ReportUsageError ();
2721 bool RemoveMethods (bool keep_static)
2723 ArrayList smethods = new ArrayList ();
2725 foreach (MethodBase mb in Methods){
2726 if (mb.IsStatic == keep_static)
2730 if (smethods.Count == 0)
2733 Methods = new MethodBase [smethods.Count];
2734 smethods.CopyTo (Methods, 0);
2740 /// Removes any instance methods from the MethodGroup, returns
2741 /// false if the resulting set is empty.
2743 public bool RemoveInstanceMethods ()
2745 return RemoveMethods (true);
2749 /// Removes any static methods from the MethodGroup, returns
2750 /// false if the resulting set is empty.
2752 public bool RemoveStaticMethods ()
2754 return RemoveMethods (false);
2759 /// Fully resolved expression that evaluates to a Field
2761 public class FieldExpr : MemberExpr, IAssignMethod, IMemoryLocation, IVariable {
2762 public readonly FieldInfo FieldInfo;
2763 VariableInfo variable_info;
2765 LocalTemporary temp;
2767 bool in_initializer;
2769 public FieldExpr (FieldInfo fi, Location l, bool in_initializer):
2772 this.in_initializer = in_initializer;
2775 public FieldExpr (FieldInfo fi, Location l)
2778 eclass = ExprClass.Variable;
2779 type = fi.FieldType;
2783 public override string Name {
2785 return FieldInfo.Name;
2789 public override bool IsInstance {
2791 return !FieldInfo.IsStatic;
2795 public override bool IsStatic {
2797 return FieldInfo.IsStatic;
2801 public override Type DeclaringType {
2803 return FieldInfo.DeclaringType;
2807 public VariableInfo VariableInfo {
2809 return variable_info;
2813 public override Expression ResolveMemberAccess (EmitContext ec, Expression left, Location loc,
2814 SimpleName original)
2816 bool left_is_type = left is TypeExpr;
2818 Type decl_type = FieldInfo.DeclaringType;
2820 bool is_emitted = FieldInfo is FieldBuilder;
2821 Type t = FieldInfo.FieldType;
2824 Const c = TypeManager.LookupConstant ((FieldBuilder) FieldInfo);
2828 if (!c.LookupConstantValue (out o))
2831 c.SetMemberIsUsed ();
2832 object real_value = ((Constant) c.Expr).GetValue ();
2834 Expression exp = Constantify (real_value, t);
2836 if (!left_is_type &&
2837 (original == null || !original.IdenticalNameAndTypeName (ec, left, loc))) {
2838 Report.SymbolRelatedToPreviousError (c);
2839 error176 (loc, c.GetSignatureForError ());
2848 // Decimal constants cannot be encoded in the constant blob, and thus are marked
2849 // as IsInitOnly ('readonly' in C# parlance). We get its value from the
2850 // DecimalConstantAttribute metadata.
2852 if (FieldInfo.IsInitOnly && !is_emitted && t == TypeManager.decimal_type) {
2853 object[] attrs = FieldInfo.GetCustomAttributes (TypeManager.decimal_constant_attribute_type, false);
2854 if (attrs.Length == 1)
2855 return new DecimalConstant (((System.Runtime.CompilerServices.DecimalConstantAttribute) attrs [0]).Value);
2858 if (FieldInfo.IsLiteral) {
2862 o = TypeManager.GetValue ((FieldBuilder) FieldInfo);
2864 o = FieldInfo.GetValue (FieldInfo);
2866 if (decl_type.IsSubclassOf (TypeManager.enum_type)) {
2867 if (!left_is_type &&
2868 (original == null || !original.IdenticalNameAndTypeName (ec, left, loc))) {
2869 error176 (loc, FieldInfo.Name);
2873 Expression enum_member = MemberLookup (
2874 ec, decl_type, "value__", MemberTypes.Field,
2875 AllBindingFlags | BindingFlags.NonPublic, loc);
2877 Enum en = TypeManager.LookupEnum (decl_type);
2881 c = Constantify (o, en.UnderlyingType);
2883 c = Constantify (o, enum_member.Type);
2885 return new EnumConstant (c, decl_type);
2888 Expression exp = Constantify (o, t);
2890 if (!left_is_type) {
2891 error176 (loc, FieldInfo.Name);
2898 if (t.IsPointer && !ec.InUnsafe) {
2903 return base.ResolveMemberAccess (ec, left, loc, original);
2906 override public Expression DoResolve (EmitContext ec)
2908 if (ec.InRefOutArgumentResolving && FieldInfo.IsInitOnly && !ec.IsConstructor && FieldInfo.FieldType.IsValueType) {
2909 if (FieldInfo.FieldType is TypeBuilder) {
2910 if (FieldInfo.IsStatic)
2911 Report.Error (1651, loc, "Members of readonly static field '{0}.{1}' cannot be passed ref or out (except in a constructor)",
2912 TypeManager.CSharpName (DeclaringType), Name);
2914 Report.Error (1649, loc, "Members of readonly field '{0}.{1}' cannot be passed ref or out (except in a constructor)",
2915 TypeManager.CSharpName (DeclaringType), Name);
2917 if (FieldInfo.IsStatic)
2918 Report.Error (199, loc, "A static readonly field '{0}' cannot be passed ref or out (except in a static constructor)",
2921 Report.Error (192, loc, "A readonly field '{0}' cannot be passed ref or out (except in a constructor)",
2927 if (!FieldInfo.IsStatic){
2928 if (InstanceExpression == null){
2930 // This can happen when referencing an instance field using
2931 // a fully qualified type expression: TypeName.InstanceField = xxx
2933 SimpleName.Error_ObjectRefRequired (ec, loc, FieldInfo.Name);
2937 // Resolve the field's instance expression while flow analysis is turned
2938 // off: when accessing a field "a.b", we must check whether the field
2939 // "a.b" is initialized, not whether the whole struct "a" is initialized.
2940 InstanceExpression = InstanceExpression.Resolve (ec, ResolveFlags.VariableOrValue |
2941 ResolveFlags.DisableFlowAnalysis);
2942 if (InstanceExpression == null)
2946 if (!in_initializer) {
2947 ObsoleteAttribute oa;
2948 FieldBase f = TypeManager.GetField (FieldInfo);
2950 oa = f.GetObsoleteAttribute (f.Parent);
2952 AttributeTester.Report_ObsoleteMessage (oa, f.GetSignatureForError (), loc);
2954 // To be sure that type is external because we do not register generated fields
2955 } else if (!(FieldInfo.DeclaringType is TypeBuilder)) {
2956 oa = AttributeTester.GetMemberObsoleteAttribute (FieldInfo);
2958 AttributeTester.Report_ObsoleteMessage (oa, TypeManager.GetFullNameSignature (FieldInfo), loc);
2962 if (ec.CurrentAnonymousMethod != null){
2963 if (!FieldInfo.IsStatic){
2964 if (ec.TypeContainer is Struct){
2965 Report.Error (1673, loc, "Can not reference instance variables in anonymous methods hosted in structs");
2968 ec.CaptureField (this);
2972 // If the instance expression is a local variable or parameter.
2973 IVariable var = InstanceExpression as IVariable;
2974 if ((var == null) || (var.VariableInfo == null))
2977 VariableInfo vi = var.VariableInfo;
2978 if (!vi.IsFieldAssigned (ec, FieldInfo.Name, loc))
2981 variable_info = vi.GetSubStruct (FieldInfo.Name);
2985 void Report_AssignToReadonly (bool is_instance)
2990 msg = "Readonly field can not be assigned outside " +
2991 "of constructor or variable initializer";
2993 msg = "A static readonly field can only be assigned in " +
2994 "a static constructor";
2996 Report.Error (is_instance ? 191 : 198, loc, msg);
2999 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
3001 IVariable var = InstanceExpression as IVariable;
3002 if ((var != null) && (var.VariableInfo != null))
3003 var.VariableInfo.SetFieldAssigned (ec, FieldInfo.Name);
3005 Expression e = DoResolve (ec);
3010 if (!FieldInfo.IsStatic && (InstanceExpression.Type.IsValueType && !(InstanceExpression is IMemoryLocation))) {
3011 // FIXME: Provide better error reporting.
3012 Error (1612, "Cannot modify expression because it is not a variable.");
3016 FieldBase fb = TypeManager.GetField (FieldInfo);
3020 if (!FieldInfo.IsInitOnly)
3024 // InitOnly fields can only be assigned in constructors
3027 if (ec.IsConstructor){
3028 if (IsStatic && !ec.IsStatic)
3029 Report_AssignToReadonly (false);
3031 if (ec.ContainerType == FieldInfo.DeclaringType)
3035 Report_AssignToReadonly (!IsStatic);
3040 public override void CheckMarshallByRefAccess (Type container)
3042 if (!IsStatic && Type.IsValueType && !container.IsSubclassOf (TypeManager.mbr_type) && DeclaringType.IsSubclassOf (TypeManager.mbr_type)) {
3043 Report.SymbolRelatedToPreviousError (DeclaringType);
3044 Report.Error (1690, loc, "Cannot call '{0}' method, property, or indexer because it is a value type member of a marshal-by-reference class", Name);
3048 public bool VerifyFixed (bool is_expression)
3050 IVariable variable = InstanceExpression as IVariable;
3051 if ((variable == null) || !variable.VerifyFixed (true))
3057 public override int GetHashCode()
3059 return FieldInfo.GetHashCode ();
3062 public override bool Equals (object obj)
3064 FieldExpr fe = obj as FieldExpr;
3068 if (FieldInfo != fe.FieldInfo)
3071 if (InstanceExpression == null || fe.InstanceExpression == null)
3074 return InstanceExpression.Equals (fe.InstanceExpression);
3077 public void Emit (EmitContext ec, bool leave_copy)
3079 ILGenerator ig = ec.ig;
3080 bool is_volatile = false;
3082 if (FieldInfo is FieldBuilder){
3083 FieldBase f = TypeManager.GetField (FieldInfo);
3085 if ((f.ModFlags & Modifiers.VOLATILE) != 0)
3088 f.SetMemberIsUsed ();
3092 if (FieldInfo.IsStatic){
3094 ig.Emit (OpCodes.Volatile);
3096 ig.Emit (OpCodes.Ldsfld, FieldInfo);
3102 ig.Emit (OpCodes.Volatile);
3104 IFixedBuffer ff = AttributeTester.GetFixedBuffer (FieldInfo);
3107 ig.Emit (OpCodes.Ldflda, FieldInfo);
3108 ig.Emit (OpCodes.Ldflda, ff.Element);
3111 ig.Emit (OpCodes.Ldfld, FieldInfo);
3116 ec.ig.Emit (OpCodes.Dup);
3117 if (!FieldInfo.IsStatic) {
3118 temp = new LocalTemporary (ec, this.Type);
3124 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
3126 FieldAttributes fa = FieldInfo.Attributes;
3127 bool is_static = (fa & FieldAttributes.Static) != 0;
3128 bool is_readonly = (fa & FieldAttributes.InitOnly) != 0;
3129 ILGenerator ig = ec.ig;
3130 prepared = prepare_for_load;
3132 if (is_readonly && !ec.IsConstructor){
3133 Report_AssignToReadonly (!is_static);
3139 if (prepare_for_load)
3140 ig.Emit (OpCodes.Dup);
3145 ec.ig.Emit (OpCodes.Dup);
3146 if (!FieldInfo.IsStatic) {
3147 temp = new LocalTemporary (ec, this.Type);
3152 if (FieldInfo is FieldBuilder){
3153 FieldBase f = TypeManager.GetField (FieldInfo);
3155 if ((f.ModFlags & Modifiers.VOLATILE) != 0)
3156 ig.Emit (OpCodes.Volatile);
3158 f.status |= Field.Status.ASSIGNED;
3163 ig.Emit (OpCodes.Stsfld, FieldInfo);
3165 ig.Emit (OpCodes.Stfld, FieldInfo);
3171 void EmitInstance (EmitContext ec)
3173 if (InstanceExpression.Type.IsValueType) {
3174 if (InstanceExpression is IMemoryLocation) {
3175 ((IMemoryLocation) InstanceExpression).AddressOf (ec, AddressOp.LoadStore);
3177 LocalTemporary t = new LocalTemporary (ec, InstanceExpression.Type);
3178 InstanceExpression.Emit (ec);
3180 t.AddressOf (ec, AddressOp.Store);
3183 InstanceExpression.Emit (ec);
3186 public override void Emit (EmitContext ec)
3191 public void AddressOf (EmitContext ec, AddressOp mode)
3193 ILGenerator ig = ec.ig;
3195 if (FieldInfo is FieldBuilder){
3196 FieldBase f = TypeManager.GetField (FieldInfo);
3198 if ((f.ModFlags & Modifiers.VOLATILE) != 0){
3199 Error (676, "volatile variable: can not take its address, or pass as ref/out parameter");
3203 if ((mode & AddressOp.Store) != 0)
3204 f.status |= Field.Status.ASSIGNED;
3205 if ((mode & AddressOp.Load) != 0)
3206 f.SetMemberIsUsed ();
3211 // Handle initonly fields specially: make a copy and then
3212 // get the address of the copy.
3215 if (FieldInfo.IsInitOnly){
3217 if (ec.IsConstructor){
3218 if (FieldInfo.IsStatic){
3230 local = ig.DeclareLocal (type);
3231 ig.Emit (OpCodes.Stloc, local);
3232 ig.Emit (OpCodes.Ldloca, local);
3237 if (FieldInfo.IsStatic){
3238 ig.Emit (OpCodes.Ldsflda, FieldInfo);
3241 ig.Emit (OpCodes.Ldflda, FieldInfo);
3247 // A FieldExpr whose address can not be taken
3249 public class FieldExprNoAddress : FieldExpr, IMemoryLocation {
3250 public FieldExprNoAddress (FieldInfo fi, Location loc) : base (fi, loc)
3254 public new void AddressOf (EmitContext ec, AddressOp mode)
3256 Report.Error (-215, "Report this: Taking the address of a remapped parameter not supported");
3261 /// Expression that evaluates to a Property. The Assign class
3262 /// might set the `Value' expression if we are in an assignment.
3264 /// This is not an LValue because we need to re-write the expression, we
3265 /// can not take data from the stack and store it.
3267 public class PropertyExpr : MemberExpr, IAssignMethod {
3268 public readonly PropertyInfo PropertyInfo;
3271 // This is set externally by the `BaseAccess' class
3274 MethodInfo getter, setter;
3279 LocalTemporary temp;
3282 internal static PtrHashtable AccessorTable = new PtrHashtable ();
3284 public PropertyExpr (EmitContext ec, PropertyInfo pi, Location l)
3287 eclass = ExprClass.PropertyAccess;
3291 type = TypeManager.TypeToCoreType (pi.PropertyType);
3293 ResolveAccessors (ec);
3296 public override string Name {
3298 return PropertyInfo.Name;
3302 public override bool IsInstance {
3308 public override bool IsStatic {
3314 public override Type DeclaringType {
3316 return PropertyInfo.DeclaringType;
3320 public bool VerifyAssignable ()
3322 if (setter == null) {
3323 Report.Error (200, loc,
3324 "The property `" + PropertyInfo.Name +
3325 "' can not be assigned to, as it has not set accessor");
3332 void FindAccessors (Type invocation_type)
3334 BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic |
3335 BindingFlags.Static | BindingFlags.Instance |
3336 BindingFlags.DeclaredOnly;
3338 Type current = PropertyInfo.DeclaringType;
3339 for (; current != null; current = current.BaseType) {
3340 MemberInfo[] group = TypeManager.MemberLookup (
3341 invocation_type, invocation_type, current,
3342 MemberTypes.Property, flags, PropertyInfo.Name, null);
3347 if (group.Length != 1)
3348 // Oooops, can this ever happen ?
3351 PropertyInfo pi = (PropertyInfo) group [0];
3354 getter = pi.GetGetMethod (true);
3357 setter = pi.GetSetMethod (true);
3359 MethodInfo accessor = getter != null ? getter : setter;
3361 if (!accessor.IsVirtual)
3367 // We also perform the permission checking here, as the PropertyInfo does not
3368 // hold the information for the accessibility of its setter/getter
3370 void ResolveAccessors (EmitContext ec)
3372 FindAccessors (ec.ContainerType);
3374 if (getter != null) {
3375 IMethodData md = TypeManager.GetMethod (getter);
3377 md.SetMemberIsUsed ();
3379 AccessorTable [getter] = PropertyInfo;
3380 is_static = getter.IsStatic;
3383 if (setter != null) {
3384 IMethodData md = TypeManager.GetMethod (setter);
3386 md.SetMemberIsUsed ();
3388 AccessorTable [setter] = PropertyInfo;
3389 is_static = setter.IsStatic;
3393 bool InstanceResolve (EmitContext ec, bool must_do_cs1540_check)
3395 if ((InstanceExpression == null) && ec.IsStatic && !is_static) {
3396 SimpleName.Error_ObjectRefRequired (ec, loc, PropertyInfo.Name);
3400 if (!IsInstance || InstanceExpression == EmptyExpression.Null)
3401 InstanceExpression = null;
3403 if (InstanceExpression != null) {
3404 InstanceExpression = InstanceExpression.DoResolve (ec);
3405 if (InstanceExpression == null)
3408 InstanceExpression.CheckMarshallByRefAccess (ec.ContainerType);
3411 if (must_do_cs1540_check && (InstanceExpression != null)) {
3412 if ((InstanceExpression.Type != ec.ContainerType) &&
3413 ec.ContainerType.IsSubclassOf (InstanceExpression.Type)) {
3414 Report.Error (1540, loc, "Cannot access protected member `" +
3415 PropertyInfo.DeclaringType + "." + PropertyInfo.Name +
3416 "' via a qualifier of type `" +
3417 TypeManager.CSharpName (InstanceExpression.Type) +
3418 "'; the qualifier must be of type `" +
3419 TypeManager.CSharpName (ec.ContainerType) +
3420 "' (or derived from it)");
3428 override public Expression DoResolve (EmitContext ec)
3431 Report.Debug ("Double resolve of " + Name);
3435 if (getter != null){
3436 if (TypeManager.GetArgumentTypes (getter).Length != 0){
3438 117, loc, "`{0}' does not contain a " +
3439 "definition for `{1}'.", getter.DeclaringType,
3445 if (getter == null){
3447 // The following condition happens if the PropertyExpr was
3448 // created, but is invalid (ie, the property is inaccessible),
3449 // and we did not want to embed the knowledge about this in
3450 // the caller routine. This only avoids double error reporting.
3455 if (InstanceExpression != EmptyExpression.Null) {
3456 Report.Error (154, loc,
3457 "The property `" + PropertyInfo.Name +
3458 "' can not be used in " +
3459 "this context because it lacks a get accessor");
3464 bool must_do_cs1540_check = false;
3465 if (getter != null &&
3466 !IsAccessorAccessible (ec.ContainerType, getter, out must_do_cs1540_check)) {
3467 PropertyBase.PropertyMethod pm = TypeManager.GetMethod (getter) as PropertyBase.PropertyMethod;
3468 if (pm != null && pm.HasCustomAccessModifier) {
3469 Report.SymbolRelatedToPreviousError (pm);
3470 Report.Error (271, loc, "The property or indexer '{0}' cannot be used in this context because the get accessor is inaccessible",
3471 TypeManager.CSharpSignature (getter));
3474 Report.Error (122, loc, "'{0}' is inaccessible due to its protection level",
3475 TypeManager.CSharpSignature (getter));
3479 if (!InstanceResolve (ec, must_do_cs1540_check))
3483 // Only base will allow this invocation to happen.
3485 if (IsBase && getter.IsAbstract){
3486 Report.Error (205, loc, "Cannot call an abstract base property: " +
3487 PropertyInfo.DeclaringType + "." +PropertyInfo.Name);
3491 if (PropertyInfo.PropertyType.IsPointer && !ec.InUnsafe){
3501 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
3503 if (setter == null){
3505 // The following condition happens if the PropertyExpr was
3506 // created, but is invalid (ie, the property is inaccessible),
3507 // and we did not want to embed the knowledge about this in
3508 // the caller routine. This only avoids double error reporting.
3513 // TODO: Print better property name
3514 Report.Error (200, loc, "Property or indexer '{0}' cannot be assigned to -- it is read only",
3519 if (TypeManager.GetArgumentTypes (setter).Length != 1){
3521 117, loc, "`{0}' does not contain a " +
3522 "definition for `{1}'.", getter.DeclaringType,
3527 bool must_do_cs1540_check;
3528 if (!IsAccessorAccessible (ec.ContainerType, setter, out must_do_cs1540_check)) {
3529 PropertyBase.PropertyMethod pm = TypeManager.GetMethod (setter) as PropertyBase.PropertyMethod;
3530 if (pm != null && pm.HasCustomAccessModifier) {
3531 Report.SymbolRelatedToPreviousError (pm);
3532 Report.Error (272, loc, "The property or indexer '{0}' cannot be used in this context because the set accessor is inaccessible",
3533 TypeManager.CSharpSignature (setter));
3536 Report.Error (122, loc, "'{0}' is inaccessible due to its protection level",
3537 TypeManager.CSharpSignature (setter));
3541 if (!InstanceResolve (ec, must_do_cs1540_check))
3545 // Only base will allow this invocation to happen.
3547 if (IsBase && setter.IsAbstract){
3548 Report.Error (205, loc, "Cannot call an abstract base property: " +
3549 PropertyInfo.DeclaringType + "." +PropertyInfo.Name);
3554 // Check that we are not making changes to a temporary memory location
3556 if (InstanceExpression != null && InstanceExpression.Type.IsValueType && !(InstanceExpression is IMemoryLocation)) {
3557 // FIXME: Provide better error reporting.
3558 Error (1612, "Cannot modify expression because it is not a variable.");
3567 public override void Emit (EmitContext ec)
3572 void EmitInstance (EmitContext ec)
3577 if (InstanceExpression.Type.IsValueType) {
3578 if (InstanceExpression is IMemoryLocation) {
3579 ((IMemoryLocation) InstanceExpression).AddressOf (ec, AddressOp.LoadStore);
3581 LocalTemporary t = new LocalTemporary (ec, InstanceExpression.Type);
3582 InstanceExpression.Emit (ec);
3584 t.AddressOf (ec, AddressOp.Store);
3587 InstanceExpression.Emit (ec);
3590 ec.ig.Emit (OpCodes.Dup);
3594 public void Emit (EmitContext ec, bool leave_copy)
3600 // Special case: length of single dimension array property is turned into ldlen
3602 if ((getter == TypeManager.system_int_array_get_length) ||
3603 (getter == TypeManager.int_array_get_length)){
3604 Type iet = InstanceExpression.Type;
3607 // System.Array.Length can be called, but the Type does not
3608 // support invoking GetArrayRank, so test for that case first
3610 if (iet != TypeManager.array_type && (iet.GetArrayRank () == 1)) {
3611 ec.ig.Emit (OpCodes.Ldlen);
3612 ec.ig.Emit (OpCodes.Conv_I4);
3617 Invocation.EmitCall (ec, IsBase, IsStatic, new EmptyAddressOf (), getter, null, loc);
3622 ec.ig.Emit (OpCodes.Dup);
3624 temp = new LocalTemporary (ec, this.Type);
3630 // Implements the IAssignMethod interface for assignments
3632 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
3634 prepared = prepare_for_load;
3640 ec.ig.Emit (OpCodes.Dup);
3642 temp = new LocalTemporary (ec, this.Type);
3647 ArrayList args = new ArrayList (1);
3648 args.Add (new Argument (new EmptyAddressOf (), Argument.AType.Expression));
3650 Invocation.EmitCall (ec, IsBase, IsStatic, new EmptyAddressOf (), setter, args, loc);
3658 /// Fully resolved expression that evaluates to an Event
3660 public class EventExpr : MemberExpr {
3661 public readonly EventInfo EventInfo;
3664 MethodInfo add_accessor, remove_accessor;
3666 public EventExpr (EventInfo ei, Location loc)
3670 eclass = ExprClass.EventAccess;
3672 add_accessor = TypeManager.GetAddMethod (ei);
3673 remove_accessor = TypeManager.GetRemoveMethod (ei);
3675 if (add_accessor.IsStatic || remove_accessor.IsStatic)
3678 if (EventInfo is MyEventBuilder){
3679 MyEventBuilder eb = (MyEventBuilder) EventInfo;
3680 type = eb.EventType;
3683 type = EventInfo.EventHandlerType;
3686 public override string Name {
3688 return EventInfo.Name;
3692 public override bool IsInstance {
3698 public override bool IsStatic {
3704 public override Type DeclaringType {
3706 return EventInfo.DeclaringType;
3710 public override Expression ResolveMemberAccess (EmitContext ec, Expression left, Location loc,
3711 SimpleName original)
3714 // If the event is local to this class, we transform ourselves into a FieldExpr
3717 if (EventInfo.DeclaringType == ec.ContainerType ||
3718 TypeManager.IsNestedChildOf(ec.ContainerType, EventInfo.DeclaringType)) {
3719 MemberInfo mi = TypeManager.GetPrivateFieldOfEvent (EventInfo);
3722 MemberExpr ml = (MemberExpr) ExprClassFromMemberInfo (ec, mi, loc);
3725 Report.Error (-200, loc, "Internal error!!");
3729 InstanceExpression = null;
3731 return ml.ResolveMemberAccess (ec, left, loc, original);
3735 return base.ResolveMemberAccess (ec, left, loc, original);
3739 bool InstanceResolve (EmitContext ec, bool must_do_cs1540_check)
3741 if ((InstanceExpression == null) && ec.IsStatic && !is_static) {
3742 SimpleName.Error_ObjectRefRequired (ec, loc, EventInfo.Name);
3746 if (!IsInstance || InstanceExpression == EmptyExpression.Null)
3747 InstanceExpression = null;
3749 if (InstanceExpression != null) {
3750 InstanceExpression = InstanceExpression.DoResolve (ec);
3751 if (InstanceExpression == null)
3756 // This is using the same mechanism as the CS1540 check in PropertyExpr.
3757 // However, in the Event case, we reported a CS0122 instead.
3759 if (must_do_cs1540_check && (InstanceExpression != null)) {
3760 if ((InstanceExpression.Type != ec.ContainerType) &&
3761 ec.ContainerType.IsSubclassOf (InstanceExpression.Type)) {
3762 Report.Error (122, loc, "'{0}' is inaccessible due to its protection level",
3763 DeclaringType.Name + "." + EventInfo.Name);
3772 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
3774 return DoResolve (ec);
3777 public override Expression DoResolve (EmitContext ec)
3780 InstanceExpression = null;
3782 if (InstanceExpression != null) {
3783 InstanceExpression = InstanceExpression.DoResolve (ec);
3784 if (InstanceExpression == null)
3788 bool must_do_cs1540_check;
3789 if (!(IsAccessorAccessible (ec.ContainerType, add_accessor, out must_do_cs1540_check) &&
3790 IsAccessorAccessible (ec.ContainerType, remove_accessor, out must_do_cs1540_check))) {
3792 Report.Error (122, loc, "'{0}' is inaccessible due to its protection level",
3793 DeclaringType.Name + "." + EventInfo.Name);
3797 if (!InstanceResolve (ec, must_do_cs1540_check))
3803 public override void Emit (EmitContext ec)
3805 if (InstanceExpression is This)
3806 Report.Error (79, loc, "The event `{0}' can only appear on the left hand side of += or -=, try calling the actual delegate", Name);
3808 Report.Error (70, loc, "The event `{0}' can only appear on the left hand side of += or -= "+
3809 "(except on the defining type)", Name);
3812 public void EmitAddOrRemove (EmitContext ec, Expression source)
3814 BinaryDelegate source_del = (BinaryDelegate) source;
3815 Expression handler = source_del.Right;
3817 Argument arg = new Argument (handler, Argument.AType.Expression);
3818 ArrayList args = new ArrayList ();
3822 if (source_del.IsAddition)
3823 Invocation.EmitCall (
3824 ec, false, IsStatic, InstanceExpression, add_accessor, args, loc);
3826 Invocation.EmitCall (
3827 ec, false, IsStatic, InstanceExpression, remove_accessor, args, loc);