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.
64 // Disable control flow analysis _of struct_ while resolving the expression.
65 // This is used when resolving the instance expression of a field expression.
66 DisableStructFlowAnalysis = 32,
71 // This is just as a hint to AddressOf of what will be done with the
74 public enum AddressOp {
81 /// This interface is implemented by variables
83 public interface IMemoryLocation {
85 /// The AddressOf method should generate code that loads
86 /// the address of the object and leaves it on the stack.
88 /// The `mode' argument is used to notify the expression
89 /// of whether this will be used to read from the address or
90 /// write to the address.
92 /// This is just a hint that can be used to provide good error
93 /// reporting, and should have no other side effects.
95 void AddressOf (EmitContext ec, AddressOp mode);
99 /// This interface is implemented by variables
101 public interface IVariable {
102 VariableInfo VariableInfo {
110 /// Base class for expressions
112 public abstract class Expression {
113 public ExprClass eclass;
115 protected Location loc;
119 set { type = value; }
122 public Location Location {
127 /// Utility wrapper routine for Error, just to beautify the code
129 public void Error (int error, string s)
132 Report.Error (error, s);
134 Report.Error (error, loc, s);
138 /// Utility wrapper routine for Warning, just to beautify the code
140 public void Warning (int code, string format, params object[] args)
142 Report.Warning (code, loc, format, args);
145 // Not nice but we have broken hierarchy
146 public virtual void CheckMarshallByRefAccess (Type container) {}
149 /// Tests presence of ObsoleteAttribute and report proper error
151 protected void CheckObsoleteAttribute (Type type)
153 ObsoleteAttribute obsolete_attr = AttributeTester.GetObsoleteAttribute (type);
154 if (obsolete_attr == null)
157 AttributeTester.Report_ObsoleteMessage (obsolete_attr, type.FullName, loc);
160 public virtual string GetSignatureForError ()
162 return TypeManager.CSharpName (type);
165 public static bool IsAccessorAccessible (Type invocation_type, MethodInfo mi, out bool must_do_cs1540_check)
167 MethodAttributes ma = mi.Attributes & MethodAttributes.MemberAccessMask;
169 must_do_cs1540_check = false; // by default we do not check for this
172 // If only accessible to the current class or children
174 if (ma == MethodAttributes.Private)
175 return TypeManager.IsPrivateAccessible (invocation_type, mi.DeclaringType) ||
176 TypeManager.IsNestedChildOf (invocation_type, mi.DeclaringType);
178 if (mi.DeclaringType.Assembly == invocation_type.Assembly) {
179 if (ma == MethodAttributes.Assembly || ma == MethodAttributes.FamORAssem)
182 if (ma == MethodAttributes.Assembly || ma == MethodAttributes.FamANDAssem)
186 // Family and FamANDAssem require that we derive.
187 // FamORAssem requires that we derive if in different assemblies.
188 if (ma == MethodAttributes.Family ||
189 ma == MethodAttributes.FamANDAssem ||
190 ma == MethodAttributes.FamORAssem) {
191 if (!TypeManager.IsNestedFamilyAccessible (invocation_type, mi.DeclaringType))
194 if (!TypeManager.IsNestedChildOf (invocation_type, mi.DeclaringType))
195 must_do_cs1540_check = true;
204 /// Performs semantic analysis on the Expression
208 /// The Resolve method is invoked to perform the semantic analysis
211 /// The return value is an expression (it can be the
212 /// same expression in some cases) or a new
213 /// expression that better represents this node.
215 /// For example, optimizations of Unary (LiteralInt)
216 /// would return a new LiteralInt with a negated
219 /// If there is an error during semantic analysis,
220 /// then an error should be reported (using Report)
221 /// and a null value should be returned.
223 /// There are two side effects expected from calling
224 /// Resolve(): the the field variable "eclass" should
225 /// be set to any value of the enumeration
226 /// `ExprClass' and the type variable should be set
227 /// to a valid type (this is the type of the
230 public abstract Expression DoResolve (EmitContext ec);
232 public virtual Expression DoResolveLValue (EmitContext ec, Expression right_side)
238 // This is used if the expression should be resolved as a type or namespace name.
239 // the default implementation fails.
241 public FullNamedExpression ResolveAsTypeStep (EmitContext ec)
243 return ResolveAsTypeStep (ec, false);
246 public virtual FullNamedExpression ResolveAsTypeStep (EmitContext ec, bool silent)
252 // This is used to resolve the expression as a type, a null
253 // value will be returned if the expression is not a type
256 public TypeExpr ResolveAsTypeTerminal (EmitContext ec)
258 return ResolveAsTypeTerminal (ec, false);
261 public virtual TypeExpr ResolveAsTypeTerminal (EmitContext ec, bool silent)
263 int errors = Report.Errors;
265 FullNamedExpression fne = ResolveAsTypeStep (ec, silent);
270 if (fne.eclass != ExprClass.Type) {
271 if (!silent && (errors == Report.Errors))
272 fne.Error_UnexpectedKind (null, "type", loc);
276 TypeExpr te = fne as TypeExpr;
278 if (!te.CheckAccessLevel (ec.DeclSpace)) {
279 ErrorIsInaccesible (loc, TypeManager.CSharpName (te.Type));
283 ConstructedType ct = te as ConstructedType;
284 if ((ct != null) && !ec.ResolvingTypeTree && !ct.CheckConstraints (ec))
290 public static void ErrorIsInaccesible (Location loc, string name)
292 Report.Error (122, loc, "`{0}' is inaccessible due to its protection level", name);
295 public virtual void Error_ValueCannotBeConverted (Location loc, Type t)
297 Convert.Error_CannotImplicitConversion (loc, Type, t);
300 protected static void Error_TypeDoesNotContainDefinition (Location loc, Type type, string name)
302 Report.Error (117, loc, "`{0}' does not contain a definition for `{1}'",
303 TypeManager.CSharpName (type), name);
306 ResolveFlags ExprClassToResolveFlags ()
310 case ExprClass.Namespace:
311 return ResolveFlags.Type;
313 case ExprClass.MethodGroup:
314 return ResolveFlags.MethodGroup;
316 case ExprClass.Value:
317 case ExprClass.Variable:
318 case ExprClass.PropertyAccess:
319 case ExprClass.EventAccess:
320 case ExprClass.IndexerAccess:
321 return ResolveFlags.VariableOrValue;
324 throw new Exception ("Expression " + GetType () +
325 " ExprClass is Invalid after resolve");
331 /// Resolves an expression and performs semantic analysis on it.
335 /// Currently Resolve wraps DoResolve to perform sanity
336 /// checking and assertion checking on what we expect from Resolve.
338 public Expression Resolve (EmitContext ec, ResolveFlags flags)
340 if ((flags & ResolveFlags.MaskExprClass) == ResolveFlags.Type)
341 return ResolveAsTypeStep (ec, false);
343 bool old_do_flow_analysis = ec.DoFlowAnalysis;
344 bool old_omit_struct_analysis = ec.OmitStructFlowAnalysis;
345 if ((flags & ResolveFlags.DisableFlowAnalysis) != 0)
346 ec.DoFlowAnalysis = false;
347 if ((flags & ResolveFlags.DisableStructFlowAnalysis) != 0)
348 ec.OmitStructFlowAnalysis = true;
351 bool intermediate = (flags & ResolveFlags.Intermediate) == ResolveFlags.Intermediate;
352 if (this is SimpleName)
353 e = ((SimpleName) this).DoResolve (ec, intermediate);
358 ec.DoFlowAnalysis = old_do_flow_analysis;
359 ec.OmitStructFlowAnalysis = old_omit_struct_analysis;
364 if ((flags & e.ExprClassToResolveFlags ()) == 0) {
365 e.Error_UnexpectedKind (flags, loc);
369 if (e.type == null && !(e is Namespace)) {
370 throw new Exception (
371 "Expression " + e.GetType () +
372 " did not set its type after Resolve\n" +
373 "called from: " + this.GetType ());
380 /// Resolves an expression and performs semantic analysis on it.
382 public Expression Resolve (EmitContext ec)
384 Expression e = Resolve (ec, ResolveFlags.VariableOrValue | ResolveFlags.MethodGroup);
386 if (e != null && e.eclass == ExprClass.MethodGroup && RootContext.Version == LanguageVersion.ISO_1) {
387 ((MethodGroupExpr) e).ReportUsageError ();
393 public Constant ResolveAsConstant (EmitContext ec, MemberCore mc)
395 Expression e = Resolve (ec);
397 Constant c = e as Constant;
401 EmptyCast empty = e as EmptyCast;
403 c = empty.Child as Constant;
405 // TODO: not sure about this maybe there is easier way how to use EmptyCast
414 Const.Error_ExpressionMustBeConstant (loc, mc.GetSignatureForError ());
419 /// Resolves an expression for LValue assignment
423 /// Currently ResolveLValue wraps DoResolveLValue to perform sanity
424 /// checking and assertion checking on what we expect from Resolve
426 public Expression ResolveLValue (EmitContext ec, Expression right_side, Location loc)
428 int errors = Report.Errors;
429 Expression e = DoResolveLValue (ec, right_side);
432 if (errors == Report.Errors)
433 Report.Error (131, loc, "The left-hand side of an assignment or mutating operation must be a variable, property or indexer");
438 if (e.eclass == ExprClass.Invalid)
439 throw new Exception ("Expression " + e +
440 " ExprClass is Invalid after resolve");
442 if (e.eclass == ExprClass.MethodGroup) {
443 ((MethodGroupExpr) e).ReportUsageError ();
447 if ((e.type == null) && !(e is ConstructedType))
448 throw new Exception ("Expression " + e +
449 " did not set its type after Resolve");
456 /// Emits the code for the expression
460 /// The Emit method is invoked to generate the code
461 /// for the expression.
463 public abstract void Emit (EmitContext ec);
465 public virtual void EmitBranchable (EmitContext ec, Label target, bool onTrue)
468 ec.ig.Emit (onTrue ? OpCodes.Brtrue : OpCodes.Brfalse, target);
472 /// Protected constructor. Only derivate types should
473 /// be able to be created
476 protected Expression ()
478 eclass = ExprClass.Invalid;
483 /// Returns a literalized version of a literal FieldInfo
487 /// The possible return values are:
488 /// IntConstant, UIntConstant
489 /// LongLiteral, ULongConstant
490 /// FloatConstant, DoubleConstant
493 /// The value returned is already resolved.
495 public static Constant Constantify (object v, Type t)
497 if (t == TypeManager.int32_type)
498 return new IntConstant ((int) v);
499 else if (t == TypeManager.uint32_type)
500 return new UIntConstant ((uint) v);
501 else if (t == TypeManager.int64_type)
502 return new LongConstant ((long) v);
503 else if (t == TypeManager.uint64_type)
504 return new ULongConstant ((ulong) v);
505 else if (t == TypeManager.float_type)
506 return new FloatConstant ((float) v);
507 else if (t == TypeManager.double_type)
508 return new DoubleConstant ((double) v);
509 else if (t == TypeManager.string_type)
510 return new StringConstant ((string) v);
511 else if (t == TypeManager.short_type)
512 return new ShortConstant ((short)v);
513 else if (t == TypeManager.ushort_type)
514 return new UShortConstant ((ushort)v);
515 else if (t == TypeManager.sbyte_type)
516 return new SByteConstant (((sbyte)v));
517 else if (t == TypeManager.byte_type)
518 return new ByteConstant ((byte)v);
519 else if (t == TypeManager.char_type)
520 return new CharConstant ((char)v);
521 else if (t == TypeManager.bool_type)
522 return new BoolConstant ((bool) v);
523 else if (t == TypeManager.decimal_type)
524 return new DecimalConstant ((decimal) v);
525 else if (TypeManager.IsEnumType (t)){
526 Type real_type = TypeManager.TypeToCoreType (v.GetType ());
528 real_type = System.Enum.GetUnderlyingType (real_type);
530 Constant e = Constantify (v, real_type);
532 return new EnumConstant (e, t);
533 } else if (v == null && !TypeManager.IsValueType (t))
534 return NullLiteral.Null;
536 throw new Exception ("Unknown type for constant (" + t +
541 /// Returns a fully formed expression after a MemberLookup
544 // TODO: This can be heavily cached
545 public static Expression ExprClassFromMemberInfo (EmitContext ec, MemberInfo mi, Location loc)
548 return new EventExpr ((EventInfo) mi, loc);
549 else if (mi is FieldInfo)
550 return new FieldExpr ((FieldInfo) mi, loc);
551 else if (mi is PropertyInfo)
552 return new PropertyExpr (ec, (PropertyInfo) mi, loc);
553 else if (mi is Type){
554 return new TypeExpression ((System.Type) mi, loc);
560 protected static ArrayList almostMatchedMembers = new ArrayList (4);
563 // FIXME: Probably implement a cache for (t,name,current_access_set)?
565 // This code could use some optimizations, but we need to do some
566 // measurements. For example, we could use a delegate to `flag' when
567 // something can not any longer be a method-group (because it is something
571 // If the return value is an Array, then it is an array of
574 // If the return value is an MemberInfo, it is anything, but a Method
578 // FIXME: When calling MemberLookup inside an `Invocation', we should pass
579 // the arguments here and have MemberLookup return only the methods that
580 // match the argument count/type, unlike we are doing now (we delay this
583 // This is so we can catch correctly attempts to invoke instance methods
584 // from a static body (scan for error 120 in ResolveSimpleName).
587 // FIXME: Potential optimization, have a static ArrayList
590 public static Expression MemberLookup (EmitContext ec, Type queried_type, string name,
591 MemberTypes mt, BindingFlags bf, Location loc)
593 return MemberLookup (ec, ec.ContainerType, null, queried_type, name, mt, bf, loc);
597 // Lookup type `queried_type' for code in class `container_type' with a qualifier of
598 // `qualifier_type' or null to lookup members in the current class.
601 public static Expression MemberLookup (EmitContext ec, Type container_type,
602 Type qualifier_type, Type queried_type,
603 string name, MemberTypes mt,
604 BindingFlags bf, Location loc)
606 almostMatchedMembers.Clear ();
608 MemberInfo [] mi = TypeManager.MemberLookup (
609 container_type, qualifier_type, queried_type, mt, bf, name,
610 almostMatchedMembers);
615 int count = mi.Length;
617 if (mi [0] is MethodBase)
618 return new MethodGroupExpr (mi, loc);
623 return ExprClassFromMemberInfo (ec, mi [0], loc);
626 public const MemberTypes AllMemberTypes =
627 MemberTypes.Constructor |
631 MemberTypes.NestedType |
632 MemberTypes.Property;
634 public const BindingFlags AllBindingFlags =
635 BindingFlags.Public |
636 BindingFlags.Static |
637 BindingFlags.Instance;
639 public static Expression MemberLookup (EmitContext ec, Type queried_type,
640 string name, Location loc)
642 return MemberLookup (ec, ec.ContainerType, null, queried_type, name,
643 AllMemberTypes, AllBindingFlags, loc);
646 public static Expression MemberLookup (EmitContext ec, Type qualifier_type,
647 Type queried_type, string name, Location loc)
649 if (ec.ResolvingTypeTree)
650 return MemberLookup (ec, ec.ContainerType, qualifier_type,
651 queried_type, name, MemberTypes.NestedType,
652 AllBindingFlags, loc);
654 return MemberLookup (ec, ec.ContainerType, qualifier_type,
655 queried_type, name, AllMemberTypes,
656 AllBindingFlags, loc);
659 public static Expression MethodLookup (EmitContext ec, Type queried_type,
660 string name, Location loc)
662 return MemberLookup (ec, ec.ContainerType, null, queried_type, name,
663 MemberTypes.Method, AllBindingFlags, loc);
667 /// This is a wrapper for MemberLookup that is not used to "probe", but
668 /// to find a final definition. If the final definition is not found, we
669 /// look for private members and display a useful debugging message if we
672 public static Expression MemberLookupFinal (EmitContext ec, Type qualifier_type,
673 Type queried_type, string name,
676 return MemberLookupFinal (ec, qualifier_type, queried_type, name,
677 AllMemberTypes, AllBindingFlags, loc);
680 public static Expression MemberLookupFinal (EmitContext ec, Type qualifier_type,
681 Type queried_type, string name,
682 MemberTypes mt, BindingFlags bf,
687 int errors = Report.Errors;
689 e = MemberLookup (ec, ec.ContainerType, qualifier_type, queried_type,
692 if (e == null && errors == Report.Errors)
693 // No errors were reported by MemberLookup, but there was an error.
694 MemberLookupFailed (ec, qualifier_type, queried_type, name, null, true, loc);
699 public static void MemberLookupFailed (EmitContext ec, Type qualifier_type,
700 Type queried_type, string name,
701 string class_name, bool complain_if_none_found,
704 if (almostMatchedMembers.Count != 0) {
705 for (int i = 0; i < almostMatchedMembers.Count; ++i) {
706 MemberInfo m = (MemberInfo) almostMatchedMembers [i];
707 for (int j = 0; j < i; ++j) {
708 if (m == almostMatchedMembers [j]) {
716 Type declaring_type = m.DeclaringType;
718 Report.SymbolRelatedToPreviousError (m);
719 if (qualifier_type == null) {
720 Report.Error (38, loc, "Cannot access a nonstatic member of outer type `{0}' via nested type `{1}'",
721 TypeManager.CSharpName (m.DeclaringType),
722 TypeManager.CSharpName (ec.ContainerType));
723 } else if (qualifier_type != ec.ContainerType &&
724 TypeManager.IsNestedFamilyAccessible (ec.ContainerType, declaring_type)) {
725 // Although a derived class can access protected members of
726 // its base class it cannot do so through an instance of the
727 // base class (CS1540). If the qualifier_type is a base of the
728 // ec.ContainerType and the lookup succeeds with the latter one,
729 // then we are in this situation.
730 Report.Error (1540, loc,
731 "Cannot access protected member `{0}' via a qualifier of type `{1}';"
732 + " the qualifier must be of type `{2}' (or derived from it)",
733 TypeManager.GetFullNameSignature (m),
734 TypeManager.CSharpName (qualifier_type),
735 TypeManager.CSharpName (ec.ContainerType));
737 ErrorIsInaccesible (loc, TypeManager.GetFullNameSignature (m));
740 almostMatchedMembers.Clear ();
744 MemberInfo[] lookup = TypeManager.MemberLookup (queried_type, null, queried_type,
745 AllMemberTypes, AllBindingFlags |
746 BindingFlags.NonPublic, name, null);
748 if (lookup == null) {
749 if (!complain_if_none_found)
752 if (class_name != null)
753 Report.Error (103, loc, "The name `{0}' does not exist in the context of `{1}'",
756 Error_TypeDoesNotContainDefinition (loc, queried_type, name);
760 if (TypeManager.MemberLookup (queried_type, null, queried_type,
761 AllMemberTypes, AllBindingFlags |
762 BindingFlags.NonPublic, name, null) == null) {
763 if ((lookup.Length == 1) && (lookup [0] is Type)) {
764 Type t = (Type) lookup [0];
766 Report.Error (305, loc,
767 "Using the generic type `{0}' " +
768 "requires {1} type arguments",
769 TypeManager.GetFullName (t),
770 TypeManager.GetNumberOfTypeArguments (t));
775 MemberList ml = TypeManager.FindMembers (queried_type, MemberTypes.Constructor,
776 BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly, null, null);
777 if (name == ".ctor" && ml.Count == 0)
779 Report.Error (143, loc, String.Format ("The type `{0}' has no constructors defined", TypeManager.CSharpName (queried_type)));
783 ErrorIsInaccesible (loc, TypeManager.GetFullNameSignature (lookup [0]));
787 /// Returns an expression that can be used to invoke operator true
788 /// on the expression if it exists.
790 static public Expression GetOperatorTrue (EmitContext ec, Expression e, Location loc)
792 return GetOperatorTrueOrFalse (ec, e, true, loc);
796 /// Returns an expression that can be used to invoke operator false
797 /// on the expression if it exists.
799 static public Expression GetOperatorFalse (EmitContext ec, Expression e, Location loc)
801 return GetOperatorTrueOrFalse (ec, e, false, loc);
804 static Expression GetOperatorTrueOrFalse (EmitContext ec, Expression e, bool is_true, Location loc)
807 Expression operator_group;
809 if (TypeManager.IsNullableType (e.Type))
810 return new Nullable.OperatorTrueOrFalse (e, is_true, loc).Resolve (ec);
812 operator_group = MethodLookup (ec, e.Type, is_true ? "op_True" : "op_False", loc);
813 if (operator_group == null)
816 ArrayList arguments = new ArrayList ();
817 arguments.Add (new Argument (e, Argument.AType.Expression));
818 method = Invocation.OverloadResolve (
819 ec, (MethodGroupExpr) operator_group, arguments, false, loc);
824 return new StaticCallExpr ((MethodInfo) method, arguments, loc);
828 /// Resolves the expression `e' into a boolean expression: either through
829 /// an implicit conversion, or through an `operator true' invocation
831 public static Expression ResolveBoolean (EmitContext ec, Expression e, Location loc)
837 if (e.Type == TypeManager.bool_type)
840 Expression converted = Convert.ImplicitConversion (ec, e, TypeManager.bool_type, Location.Null);
842 if (converted != null)
846 // If no implicit conversion to bool exists, try using `operator true'
848 Expression operator_true = Expression.GetOperatorTrue (ec, e, loc);
849 if (operator_true == null){
850 Report.Error (31, loc, "Can not convert the expression to a boolean");
853 return operator_true;
856 string ExprClassName ()
859 case ExprClass.Invalid:
861 case ExprClass.Value:
863 case ExprClass.Variable:
865 case ExprClass.Namespace:
869 case ExprClass.MethodGroup:
870 return "method group";
871 case ExprClass.PropertyAccess:
872 return "property access";
873 case ExprClass.EventAccess:
874 return "event access";
875 case ExprClass.IndexerAccess:
876 return "indexer access";
877 case ExprClass.Nothing:
880 throw new Exception ("Should not happen");
884 /// Reports that we were expecting `expr' to be of class `expected'
886 public void Error_UnexpectedKind (EmitContext ec, string expected, Location loc)
888 Error_UnexpectedKind (ec, expected, ExprClassName (), loc);
891 public void Error_UnexpectedKind (EmitContext ec, string expected, string was, Location loc)
893 string name = GetSignatureForError ();
895 name = ec.DeclSpace.GetSignatureForError () + '.' + name;
897 Report.Error (118, loc, "`{0}' is a `{1}' but a `{2}' was expected",
898 name, was, expected);
901 public void Error_UnexpectedKind (ResolveFlags flags, Location loc)
903 string [] valid = new string [4];
906 if ((flags & ResolveFlags.VariableOrValue) != 0) {
907 valid [count++] = "variable";
908 valid [count++] = "value";
911 if ((flags & ResolveFlags.Type) != 0)
912 valid [count++] = "type";
914 if ((flags & ResolveFlags.MethodGroup) != 0)
915 valid [count++] = "method group";
918 valid [count++] = "unknown";
920 StringBuilder sb = new StringBuilder (valid [0]);
921 for (int i = 1; i < count - 1; i++) {
923 sb.Append (valid [i]);
926 sb.Append ("' or `");
927 sb.Append (valid [count - 1]);
930 Report.Error (119, loc,
931 "Expression denotes a `{0}', where a `{1}' was expected", ExprClassName (), sb);
934 public static void UnsafeError (Location loc)
936 Report.Error (214, loc, "Pointers and fixed size buffers may only be used in an unsafe context");
940 // Load the object from the pointer.
942 public static void LoadFromPtr (ILGenerator ig, Type t)
944 if (t == TypeManager.int32_type)
945 ig.Emit (OpCodes.Ldind_I4);
946 else if (t == TypeManager.uint32_type)
947 ig.Emit (OpCodes.Ldind_U4);
948 else if (t == TypeManager.short_type)
949 ig.Emit (OpCodes.Ldind_I2);
950 else if (t == TypeManager.ushort_type)
951 ig.Emit (OpCodes.Ldind_U2);
952 else if (t == TypeManager.char_type)
953 ig.Emit (OpCodes.Ldind_U2);
954 else if (t == TypeManager.byte_type)
955 ig.Emit (OpCodes.Ldind_U1);
956 else if (t == TypeManager.sbyte_type)
957 ig.Emit (OpCodes.Ldind_I1);
958 else if (t == TypeManager.uint64_type)
959 ig.Emit (OpCodes.Ldind_I8);
960 else if (t == TypeManager.int64_type)
961 ig.Emit (OpCodes.Ldind_I8);
962 else if (t == TypeManager.float_type)
963 ig.Emit (OpCodes.Ldind_R4);
964 else if (t == TypeManager.double_type)
965 ig.Emit (OpCodes.Ldind_R8);
966 else if (t == TypeManager.bool_type)
967 ig.Emit (OpCodes.Ldind_I1);
968 else if (t == TypeManager.intptr_type)
969 ig.Emit (OpCodes.Ldind_I);
970 else if (TypeManager.IsEnumType (t)) {
971 if (t == TypeManager.enum_type)
972 ig.Emit (OpCodes.Ldind_Ref);
974 LoadFromPtr (ig, TypeManager.EnumToUnderlying (t));
975 } else if (t.IsValueType || t.IsGenericParameter)
976 ig.Emit (OpCodes.Ldobj, t);
977 else if (t.IsPointer)
978 ig.Emit (OpCodes.Ldind_I);
980 ig.Emit (OpCodes.Ldind_Ref);
984 // The stack contains the pointer and the value of type `type'
986 public static void StoreFromPtr (ILGenerator ig, Type type)
988 if (TypeManager.IsEnumType (type))
989 type = TypeManager.EnumToUnderlying (type);
990 if (type == TypeManager.int32_type || type == TypeManager.uint32_type)
991 ig.Emit (OpCodes.Stind_I4);
992 else if (type == TypeManager.int64_type || type == TypeManager.uint64_type)
993 ig.Emit (OpCodes.Stind_I8);
994 else if (type == TypeManager.char_type || type == TypeManager.short_type ||
995 type == TypeManager.ushort_type)
996 ig.Emit (OpCodes.Stind_I2);
997 else if (type == TypeManager.float_type)
998 ig.Emit (OpCodes.Stind_R4);
999 else if (type == TypeManager.double_type)
1000 ig.Emit (OpCodes.Stind_R8);
1001 else if (type == TypeManager.byte_type || type == TypeManager.sbyte_type ||
1002 type == TypeManager.bool_type)
1003 ig.Emit (OpCodes.Stind_I1);
1004 else if (type == TypeManager.intptr_type)
1005 ig.Emit (OpCodes.Stind_I);
1006 else if (type.IsValueType || type.IsGenericParameter)
1007 ig.Emit (OpCodes.Stobj, type);
1009 ig.Emit (OpCodes.Stind_Ref);
1013 // Returns the size of type `t' if known, otherwise, 0
1015 public static int GetTypeSize (Type t)
1017 t = TypeManager.TypeToCoreType (t);
1018 if (t == TypeManager.int32_type ||
1019 t == TypeManager.uint32_type ||
1020 t == TypeManager.float_type)
1022 else if (t == TypeManager.int64_type ||
1023 t == TypeManager.uint64_type ||
1024 t == TypeManager.double_type)
1026 else if (t == TypeManager.byte_type ||
1027 t == TypeManager.sbyte_type ||
1028 t == TypeManager.bool_type)
1030 else if (t == TypeManager.short_type ||
1031 t == TypeManager.char_type ||
1032 t == TypeManager.ushort_type)
1034 else if (t == TypeManager.decimal_type)
1040 public static void Error_NegativeArrayIndex (Location loc)
1042 Report.Error (248, loc, "Cannot create an array with a negative size");
1045 protected void Error_CannotCallAbstractBase (string name)
1047 Report.Error (205, loc, "Cannot call an abstract base member `{0}'", name);
1051 // Converts `source' to an int, uint, long or ulong.
1053 public Expression ExpressionToArrayArgument (EmitContext ec, Expression source, Location loc)
1057 bool old_checked = ec.CheckState;
1058 ec.CheckState = true;
1060 target = Convert.ImplicitConversion (ec, source, TypeManager.int32_type, loc);
1061 if (target == null){
1062 target = Convert.ImplicitConversion (ec, source, TypeManager.uint32_type, loc);
1063 if (target == null){
1064 target = Convert.ImplicitConversion (ec, source, TypeManager.int64_type, loc);
1065 if (target == null){
1066 target = Convert.ImplicitConversion (ec, source, TypeManager.uint64_type, loc);
1068 Convert.Error_CannotImplicitConversion (loc, source.Type, TypeManager.int32_type);
1072 ec.CheckState = old_checked;
1075 // Only positive constants are allowed at compile time
1077 if (target is Constant){
1078 if (target is IntConstant){
1079 if (((IntConstant) target).Value < 0){
1080 Error_NegativeArrayIndex (loc);
1085 if (target is LongConstant){
1086 if (((LongConstant) target).Value < 0){
1087 Error_NegativeArrayIndex (loc);
1100 /// This is just a base class for expressions that can
1101 /// appear on statements (invocations, object creation,
1102 /// assignments, post/pre increment and decrement). The idea
1103 /// being that they would support an extra Emition interface that
1104 /// does not leave a result on the stack.
1106 public abstract class ExpressionStatement : Expression {
1108 public virtual ExpressionStatement ResolveStatement (EmitContext ec)
1110 Expression e = Resolve (ec);
1114 ExpressionStatement es = e as ExpressionStatement;
1116 Error (201, "Only assignment, call, increment, decrement and new object " +
1117 "expressions can be used as a statement");
1123 /// Requests the expression to be emitted in a `statement'
1124 /// context. This means that no new value is left on the
1125 /// stack after invoking this method (constrasted with
1126 /// Emit that will always leave a value on the stack).
1128 public abstract void EmitStatement (EmitContext ec);
1132 /// This kind of cast is used to encapsulate the child
1133 /// whose type is child.Type into an expression that is
1134 /// reported to return "return_type". This is used to encapsulate
1135 /// expressions which have compatible types, but need to be dealt
1136 /// at higher levels with.
1138 /// For example, a "byte" expression could be encapsulated in one
1139 /// of these as an "unsigned int". The type for the expression
1140 /// would be "unsigned int".
1143 public class EmptyCast : Expression {
1144 protected Expression child;
1146 public Expression Child {
1152 public EmptyCast (Expression child, Type return_type)
1154 eclass = child.eclass;
1155 loc = child.Location;
1160 public override Expression DoResolve (EmitContext ec)
1162 // This should never be invoked, we are born in fully
1163 // initialized state.
1168 public override void Emit (EmitContext ec)
1174 /// This is a numeric cast to a Decimal
1176 public class CastToDecimal : EmptyCast {
1178 MethodInfo conversion_operator;
1180 public CastToDecimal (EmitContext ec, Expression child)
1181 : this (ec, child, false)
1185 public CastToDecimal (EmitContext ec, Expression child, bool find_explicit)
1186 : base (child, TypeManager.decimal_type)
1188 conversion_operator = GetConversionOperator (ec, find_explicit);
1190 if (conversion_operator == null)
1191 Convert.Error_CannotImplicitConversion (loc, child.Type, type);
1194 // Returns the implicit operator that converts from
1195 // 'child.Type' to System.Decimal.
1196 MethodInfo GetConversionOperator (EmitContext ec, bool find_explicit)
1198 string operator_name = "op_Implicit";
1201 operator_name = "op_Explicit";
1203 MethodGroupExpr opers = Expression.MethodLookup (
1204 ec, type, operator_name, loc) as MethodGroupExpr;
1207 Convert.Error_CannotImplicitConversion (loc, child.Type, type);
1209 foreach (MethodInfo oper in opers.Methods) {
1210 ParameterData pd = TypeManager.GetParameterData (oper);
1212 if (pd.ParameterType (0) == child.Type && oper.ReturnType == type)
1218 public override void Emit (EmitContext ec)
1220 ILGenerator ig = ec.ig;
1223 ig.Emit (OpCodes.Call, conversion_operator);
1227 /// This is an explicit numeric cast from a Decimal
1229 public class CastFromDecimal : EmptyCast
1231 MethodInfo conversion_operator;
1232 public CastFromDecimal (EmitContext ec, Expression child, Type return_type)
1233 : base (child, return_type)
1235 if (child.Type != TypeManager.decimal_type)
1236 throw new InternalErrorException (
1237 "The expected type is Decimal, instead it is " + child.Type.FullName);
1239 conversion_operator = GetConversionOperator (ec);
1240 if (conversion_operator == null)
1241 Convert.Error_CannotImplicitConversion (loc, child.Type, type);
1244 // Returns the explicit operator that converts from an
1245 // express of type System.Decimal to 'type'.
1246 MethodInfo GetConversionOperator (EmitContext ec)
1248 MethodGroupExpr opers = Expression.MethodLookup (
1249 ec, child.Type, "op_Explicit", loc) as MethodGroupExpr;
1252 Convert.Error_CannotImplicitConversion (loc, child.Type, type);
1254 foreach (MethodInfo oper in opers.Methods) {
1255 ParameterData pd = TypeManager.GetParameterData (oper);
1257 if (pd.ParameterType (0) == child.Type && oper.ReturnType == type)
1263 public override void Emit (EmitContext ec)
1265 ILGenerator ig = ec.ig;
1268 ig.Emit (OpCodes.Call, conversion_operator);
1273 // We need to special case this since an empty cast of
1274 // a NullLiteral is still a Constant
1276 public class NullCast : Constant {
1277 protected Expression child;
1279 public NullCast (Expression child, Type return_type)
1281 eclass = child.eclass;
1286 override public string AsString ()
1291 public override object GetValue ()
1296 public override Expression DoResolve (EmitContext ec)
1298 // This should never be invoked, we are born in fully
1299 // initialized state.
1304 public override void Emit (EmitContext ec)
1309 public override Constant Increment ()
1311 throw new NotSupportedException ();
1314 public override bool IsDefaultValue {
1316 throw new NotImplementedException ();
1320 public override bool IsNegative {
1329 /// This class is used to wrap literals which belong inside Enums
1331 public class EnumConstant : Constant {
1332 public Constant Child;
1334 public EnumConstant (Constant child, Type enum_type)
1336 eclass = child.eclass;
1341 public override Expression DoResolve (EmitContext ec)
1343 // This should never be invoked, we are born in fully
1344 // initialized state.
1349 public override void Emit (EmitContext ec)
1354 public override object GetValue ()
1356 return Child.GetValue ();
1359 public override object GetTypedValue ()
1361 // FIXME: runtime is not ready to work with just emited enums
1362 if (!RootContext.StdLib) {
1363 return Child.GetValue ();
1366 return System.Enum.ToObject (type, Child.GetValue ());
1369 public override void Error_ValueCannotBeConverted (Location loc, Type t)
1371 Convert.Error_CannotImplicitConversion (loc, Type, t);
1374 public override string AsString ()
1376 return Child.AsString ();
1379 public override DoubleConstant ConvertToDouble ()
1381 return Child.ConvertToDouble ();
1384 public override FloatConstant ConvertToFloat ()
1386 return Child.ConvertToFloat ();
1389 public override ULongConstant ConvertToULong ()
1391 return Child.ConvertToULong ();
1394 public override LongConstant ConvertToLong ()
1396 return Child.ConvertToLong ();
1399 public override UIntConstant ConvertToUInt ()
1401 return Child.ConvertToUInt ();
1404 public override IntConstant ConvertToInt ()
1406 return Child.ConvertToInt ();
1409 public override Constant Increment()
1411 return new EnumConstant (Child.Increment (), type);
1414 public override bool IsDefaultValue {
1416 return Child.IsDefaultValue;
1420 public override bool IsZeroInteger {
1421 get { return Child.IsZeroInteger; }
1424 public override bool IsNegative {
1426 return Child.IsNegative;
1430 public override Constant ToType (Type type, Location loc)
1433 // This is workaround of mono bug. It can be removed when the latest corlib spreads enough
1434 if (TypeManager.IsEnumType (type.UnderlyingSystemType))
1437 if (type.UnderlyingSystemType != Child.Type)
1438 Child = Child.ToType (type.UnderlyingSystemType, loc);
1442 if (!Convert.ImplicitStandardConversionExists (Convert.ConstantEC, this, type)){
1443 Error_ValueCannotBeConverted (loc, type);
1447 return Child.ToType (type, loc);
1453 /// This kind of cast is used to encapsulate Value Types in objects.
1455 /// The effect of it is to box the value type emitted by the previous
1458 public class BoxedCast : EmptyCast {
1460 public BoxedCast (Expression expr, Type target_type)
1461 : base (expr, target_type)
1463 eclass = ExprClass.Value;
1466 public override Expression DoResolve (EmitContext ec)
1468 // This should never be invoked, we are born in fully
1469 // initialized state.
1474 public override void Emit (EmitContext ec)
1478 ec.ig.Emit (OpCodes.Box, child.Type);
1482 public class UnboxCast : EmptyCast {
1483 public UnboxCast (Expression expr, Type return_type)
1484 : base (expr, return_type)
1488 public override Expression DoResolve (EmitContext ec)
1490 // This should never be invoked, we are born in fully
1491 // initialized state.
1496 public override void Emit (EmitContext ec)
1499 ILGenerator ig = ec.ig;
1502 if (t.IsGenericParameter)
1503 ig.Emit (OpCodes.Unbox_Any, t);
1505 ig.Emit (OpCodes.Unbox, t);
1507 LoadFromPtr (ig, t);
1513 /// This is used to perform explicit numeric conversions.
1515 /// Explicit numeric conversions might trigger exceptions in a checked
1516 /// context, so they should generate the conv.ovf opcodes instead of
1519 public class ConvCast : EmptyCast {
1520 public enum Mode : byte {
1521 I1_U1, I1_U2, I1_U4, I1_U8, I1_CH,
1523 I2_I1, I2_U1, I2_U2, I2_U4, I2_U8, I2_CH,
1524 U2_I1, U2_U1, U2_I2, U2_CH,
1525 I4_I1, I4_U1, I4_I2, I4_U2, I4_U4, I4_U8, I4_CH,
1526 U4_I1, U4_U1, U4_I2, U4_U2, U4_I4, U4_CH,
1527 I8_I1, I8_U1, I8_I2, I8_U2, I8_I4, I8_U4, I8_U8, I8_CH,
1528 U8_I1, U8_U1, U8_I2, U8_U2, U8_I4, U8_U4, U8_I8, U8_CH,
1529 CH_I1, CH_U1, CH_I2,
1530 R4_I1, R4_U1, R4_I2, R4_U2, R4_I4, R4_U4, R4_I8, R4_U8, R4_CH,
1531 R8_I1, R8_U1, R8_I2, R8_U2, R8_I4, R8_U4, R8_I8, R8_U8, R8_CH, R8_R4
1537 public ConvCast (EmitContext ec, Expression child, Type return_type, Mode m)
1538 : base (child, return_type)
1540 checked_state = ec.CheckState;
1544 public override Expression DoResolve (EmitContext ec)
1546 // This should never be invoked, we are born in fully
1547 // initialized state.
1552 public override string ToString ()
1554 return String.Format ("ConvCast ({0}, {1})", mode, child);
1557 public override void Emit (EmitContext ec)
1559 ILGenerator ig = ec.ig;
1565 case Mode.I1_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1566 case Mode.I1_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1567 case Mode.I1_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1568 case Mode.I1_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1569 case Mode.I1_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1571 case Mode.U1_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1572 case Mode.U1_CH: /* nothing */ break;
1574 case Mode.I2_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1575 case Mode.I2_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1576 case Mode.I2_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1577 case Mode.I2_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1578 case Mode.I2_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1579 case Mode.I2_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1581 case Mode.U2_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1582 case Mode.U2_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
1583 case Mode.U2_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
1584 case Mode.U2_CH: /* nothing */ break;
1586 case Mode.I4_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1587 case Mode.I4_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1588 case Mode.I4_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
1589 case Mode.I4_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1590 case Mode.I4_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1591 case Mode.I4_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1592 case Mode.I4_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1594 case Mode.U4_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1595 case Mode.U4_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
1596 case Mode.U4_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
1597 case Mode.U4_U2: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
1598 case Mode.U4_I4: ig.Emit (OpCodes.Conv_Ovf_I4_Un); break;
1599 case Mode.U4_CH: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
1601 case Mode.I8_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1602 case Mode.I8_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1603 case Mode.I8_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
1604 case Mode.I8_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1605 case Mode.I8_I4: ig.Emit (OpCodes.Conv_Ovf_I4); break;
1606 case Mode.I8_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1607 case Mode.I8_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1608 case Mode.I8_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1610 case Mode.U8_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1611 case Mode.U8_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
1612 case Mode.U8_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
1613 case Mode.U8_U2: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
1614 case Mode.U8_I4: ig.Emit (OpCodes.Conv_Ovf_I4_Un); break;
1615 case Mode.U8_U4: ig.Emit (OpCodes.Conv_Ovf_U4_Un); break;
1616 case Mode.U8_I8: ig.Emit (OpCodes.Conv_Ovf_I8_Un); break;
1617 case Mode.U8_CH: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
1619 case Mode.CH_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1620 case Mode.CH_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
1621 case Mode.CH_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
1623 case Mode.R4_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1624 case Mode.R4_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1625 case Mode.R4_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
1626 case Mode.R4_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1627 case Mode.R4_I4: ig.Emit (OpCodes.Conv_Ovf_I4); break;
1628 case Mode.R4_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1629 case Mode.R4_I8: ig.Emit (OpCodes.Conv_Ovf_I8); break;
1630 case Mode.R4_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1631 case Mode.R4_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1633 case Mode.R8_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1634 case Mode.R8_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1635 case Mode.R8_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
1636 case Mode.R8_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1637 case Mode.R8_I4: ig.Emit (OpCodes.Conv_Ovf_I4); break;
1638 case Mode.R8_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1639 case Mode.R8_I8: ig.Emit (OpCodes.Conv_Ovf_I8); break;
1640 case Mode.R8_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1641 case Mode.R8_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1642 case Mode.R8_R4: ig.Emit (OpCodes.Conv_R4); break;
1646 case Mode.I1_U1: ig.Emit (OpCodes.Conv_U1); break;
1647 case Mode.I1_U2: ig.Emit (OpCodes.Conv_U2); break;
1648 case Mode.I1_U4: ig.Emit (OpCodes.Conv_U4); break;
1649 case Mode.I1_U8: ig.Emit (OpCodes.Conv_I8); break;
1650 case Mode.I1_CH: ig.Emit (OpCodes.Conv_U2); break;
1652 case Mode.U1_I1: ig.Emit (OpCodes.Conv_I1); break;
1653 case Mode.U1_CH: ig.Emit (OpCodes.Conv_U2); break;
1655 case Mode.I2_I1: ig.Emit (OpCodes.Conv_I1); break;
1656 case Mode.I2_U1: ig.Emit (OpCodes.Conv_U1); break;
1657 case Mode.I2_U2: ig.Emit (OpCodes.Conv_U2); break;
1658 case Mode.I2_U4: ig.Emit (OpCodes.Conv_U4); break;
1659 case Mode.I2_U8: ig.Emit (OpCodes.Conv_I8); break;
1660 case Mode.I2_CH: ig.Emit (OpCodes.Conv_U2); break;
1662 case Mode.U2_I1: ig.Emit (OpCodes.Conv_I1); break;
1663 case Mode.U2_U1: ig.Emit (OpCodes.Conv_U1); break;
1664 case Mode.U2_I2: ig.Emit (OpCodes.Conv_I2); break;
1665 case Mode.U2_CH: /* nothing */ break;
1667 case Mode.I4_I1: ig.Emit (OpCodes.Conv_I1); break;
1668 case Mode.I4_U1: ig.Emit (OpCodes.Conv_U1); break;
1669 case Mode.I4_I2: ig.Emit (OpCodes.Conv_I2); break;
1670 case Mode.I4_U4: /* nothing */ break;
1671 case Mode.I4_U2: ig.Emit (OpCodes.Conv_U2); break;
1672 case Mode.I4_U8: ig.Emit (OpCodes.Conv_I8); break;
1673 case Mode.I4_CH: ig.Emit (OpCodes.Conv_U2); break;
1675 case Mode.U4_I1: ig.Emit (OpCodes.Conv_I1); break;
1676 case Mode.U4_U1: ig.Emit (OpCodes.Conv_U1); break;
1677 case Mode.U4_I2: ig.Emit (OpCodes.Conv_I2); break;
1678 case Mode.U4_U2: ig.Emit (OpCodes.Conv_U2); break;
1679 case Mode.U4_I4: /* nothing */ break;
1680 case Mode.U4_CH: ig.Emit (OpCodes.Conv_U2); break;
1682 case Mode.I8_I1: ig.Emit (OpCodes.Conv_I1); break;
1683 case Mode.I8_U1: ig.Emit (OpCodes.Conv_U1); break;
1684 case Mode.I8_I2: ig.Emit (OpCodes.Conv_I2); break;
1685 case Mode.I8_U2: ig.Emit (OpCodes.Conv_U2); break;
1686 case Mode.I8_I4: ig.Emit (OpCodes.Conv_I4); break;
1687 case Mode.I8_U4: ig.Emit (OpCodes.Conv_U4); break;
1688 case Mode.I8_U8: /* nothing */ break;
1689 case Mode.I8_CH: ig.Emit (OpCodes.Conv_U2); break;
1691 case Mode.U8_I1: ig.Emit (OpCodes.Conv_I1); break;
1692 case Mode.U8_U1: ig.Emit (OpCodes.Conv_U1); break;
1693 case Mode.U8_I2: ig.Emit (OpCodes.Conv_I2); break;
1694 case Mode.U8_U2: ig.Emit (OpCodes.Conv_U2); break;
1695 case Mode.U8_I4: ig.Emit (OpCodes.Conv_I4); break;
1696 case Mode.U8_U4: ig.Emit (OpCodes.Conv_U4); break;
1697 case Mode.U8_I8: /* nothing */ break;
1698 case Mode.U8_CH: ig.Emit (OpCodes.Conv_U2); break;
1700 case Mode.CH_I1: ig.Emit (OpCodes.Conv_I1); break;
1701 case Mode.CH_U1: ig.Emit (OpCodes.Conv_U1); break;
1702 case Mode.CH_I2: ig.Emit (OpCodes.Conv_I2); break;
1704 case Mode.R4_I1: ig.Emit (OpCodes.Conv_I1); break;
1705 case Mode.R4_U1: ig.Emit (OpCodes.Conv_U1); break;
1706 case Mode.R4_I2: ig.Emit (OpCodes.Conv_I2); break;
1707 case Mode.R4_U2: ig.Emit (OpCodes.Conv_U2); break;
1708 case Mode.R4_I4: ig.Emit (OpCodes.Conv_I4); break;
1709 case Mode.R4_U4: ig.Emit (OpCodes.Conv_U4); break;
1710 case Mode.R4_I8: ig.Emit (OpCodes.Conv_I8); break;
1711 case Mode.R4_U8: ig.Emit (OpCodes.Conv_U8); break;
1712 case Mode.R4_CH: ig.Emit (OpCodes.Conv_U2); break;
1714 case Mode.R8_I1: ig.Emit (OpCodes.Conv_I1); break;
1715 case Mode.R8_U1: ig.Emit (OpCodes.Conv_U1); break;
1716 case Mode.R8_I2: ig.Emit (OpCodes.Conv_I2); break;
1717 case Mode.R8_U2: ig.Emit (OpCodes.Conv_U2); break;
1718 case Mode.R8_I4: ig.Emit (OpCodes.Conv_I4); break;
1719 case Mode.R8_U4: ig.Emit (OpCodes.Conv_U4); break;
1720 case Mode.R8_I8: ig.Emit (OpCodes.Conv_I8); break;
1721 case Mode.R8_U8: ig.Emit (OpCodes.Conv_U8); break;
1722 case Mode.R8_CH: ig.Emit (OpCodes.Conv_U2); break;
1723 case Mode.R8_R4: ig.Emit (OpCodes.Conv_R4); break;
1729 public class OpcodeCast : EmptyCast {
1733 public OpcodeCast (Expression child, Type return_type, OpCode op)
1734 : base (child, return_type)
1738 second_valid = false;
1741 public OpcodeCast (Expression child, Type return_type, OpCode op, OpCode op2)
1742 : base (child, return_type)
1747 second_valid = true;
1750 public override Expression DoResolve (EmitContext ec)
1752 // This should never be invoked, we are born in fully
1753 // initialized state.
1758 public override void Emit (EmitContext ec)
1769 /// This kind of cast is used to encapsulate a child and cast it
1770 /// to the class requested
1772 public class ClassCast : EmptyCast {
1773 public ClassCast (Expression child, Type return_type)
1774 : base (child, return_type)
1779 public override Expression DoResolve (EmitContext ec)
1781 // This should never be invoked, we are born in fully
1782 // initialized state.
1787 public override void Emit (EmitContext ec)
1791 if (child.Type.IsGenericParameter)
1792 ec.ig.Emit (OpCodes.Box, child.Type);
1794 if (type.IsGenericParameter)
1795 ec.ig.Emit (OpCodes.Unbox_Any, type);
1797 ec.ig.Emit (OpCodes.Castclass, type);
1802 /// SimpleName expressions are formed of a single word and only happen at the beginning
1803 /// of a dotted-name.
1805 public class SimpleName : Expression {
1807 public readonly TypeArguments Arguments;
1810 public SimpleName (string name, Location l)
1816 public SimpleName (string name, TypeArguments args, Location l)
1823 public SimpleName (string name, TypeParameter[] type_params, Location l)
1828 Arguments = new TypeArguments (l);
1829 foreach (TypeParameter type_param in type_params)
1830 Arguments.Add (new TypeParameterExpr (type_param, l));
1833 public static string RemoveGenericArity (string name)
1836 StringBuilder sb = new StringBuilder ();
1837 while (start < name.Length) {
1838 int pos = name.IndexOf ('`', start);
1840 sb.Append (name.Substring (start));
1844 sb.Append (name.Substring (start, pos-start));
1847 while ((pos < name.Length) && Char.IsNumber (name [pos]))
1853 return sb.ToString ();
1856 public SimpleName GetMethodGroup ()
1858 return new SimpleName (RemoveGenericArity (Name), Arguments, loc);
1861 public static void Error_ObjectRefRequired (EmitContext ec, Location l, string name)
1863 if (ec.IsFieldInitializer)
1864 Report.Error (236, l,
1865 "A field initializer cannot reference the nonstatic field, method, or property `{0}'",
1868 if (name.LastIndexOf ('.') > 0)
1869 name = name.Substring (name.LastIndexOf ('.') + 1);
1872 120, l, "`{0}': An object reference is required for the nonstatic field, method or property",
1877 public bool IdenticalNameAndTypeName (EmitContext ec, Expression resolved_to, Location loc)
1879 return resolved_to != null && resolved_to.Type != null &&
1880 resolved_to.Type.Name == Name &&
1881 (ec.DeclSpace.LookupType (Name, loc, /* ignore_cs0104 = */ true) != null);
1884 public override Expression DoResolve (EmitContext ec)
1886 return SimpleNameResolve (ec, null, false);
1889 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
1891 return SimpleNameResolve (ec, right_side, false);
1895 public Expression DoResolve (EmitContext ec, bool intermediate)
1897 return SimpleNameResolve (ec, null, intermediate);
1900 private bool IsNestedChild (Type t, Type parent)
1905 while (parent != null) {
1906 if (parent.IsGenericInstance)
1907 parent = parent.GetGenericTypeDefinition ();
1909 if (TypeManager.IsNestedChildOf (t, parent))
1912 parent = parent.BaseType;
1918 FullNamedExpression ResolveNested (EmitContext ec, Type t)
1920 if (!t.IsGenericTypeDefinition)
1923 DeclSpace ds = ec.DeclSpace;
1924 while (ds != null) {
1925 if (IsNestedChild (t, ds.TypeBuilder))
1934 Type[] gen_params = t.GetGenericArguments ();
1936 int arg_count = Arguments != null ? Arguments.Count : 0;
1938 for (; (ds != null) && ds.IsGeneric; ds = ds.Parent) {
1939 if (arg_count + ds.CountTypeParameters == gen_params.Length) {
1940 TypeArguments new_args = new TypeArguments (loc);
1941 foreach (TypeParameter param in ds.TypeParameters)
1942 new_args.Add (new TypeParameterExpr (param, loc));
1944 if (Arguments != null)
1945 new_args.Add (Arguments);
1947 return new ConstructedType (t, new_args, loc);
1954 public override FullNamedExpression ResolveAsTypeStep (EmitContext ec, bool silent)
1956 FullNamedExpression fne = ec.DeclSpace.LookupGeneric (Name, loc);
1958 return fne.ResolveAsTypeStep (ec, silent);
1960 int errors = Report.Errors;
1961 fne = ec.DeclSpace.LookupType (Name, loc, /*ignore_cs0104=*/ false);
1964 if (fne.Type == null)
1967 FullNamedExpression nested = ResolveNested (ec, fne.Type);
1969 return nested.ResolveAsTypeStep (ec);
1971 if (Arguments != null) {
1972 ConstructedType ct = new ConstructedType (fne, Arguments, loc);
1973 return ct.ResolveAsTypeStep (ec);
1979 if (silent || errors != Report.Errors)
1982 MemberCore mc = ec.DeclSpace.GetDefinition (Name);
1984 Error_UnexpectedKind (ec, "type", GetMemberType (mc), loc);
1986 NamespaceEntry.Error_NamespaceNotFound (loc, Name);
1992 // TODO: I am still not convinced about this. If someone else will need it
1993 // implement this as virtual property in MemberCore hierarchy
1994 string GetMemberType (MemberCore mc)
1996 if (mc is PropertyBase)
2000 if (mc is FieldBase)
2006 Expression SimpleNameResolve (EmitContext ec, Expression right_side, bool intermediate)
2012 Expression e = DoSimpleNameResolve (ec, right_side, intermediate);
2016 if (ec.CurrentBlock == null || ec.CurrentBlock.CheckInvariantMeaningInBlock (Name, e, Location))
2023 /// 7.5.2: Simple Names.
2025 /// Local Variables and Parameters are handled at
2026 /// parse time, so they never occur as SimpleNames.
2028 /// The `intermediate' flag is used by MemberAccess only
2029 /// and it is used to inform us that it is ok for us to
2030 /// avoid the static check, because MemberAccess might end
2031 /// up resolving the Name as a Type name and the access as
2032 /// a static type access.
2034 /// ie: Type Type; .... { Type.GetType (""); }
2036 /// Type is both an instance variable and a Type; Type.GetType
2037 /// is the static method not an instance method of type.
2039 Expression DoSimpleNameResolve (EmitContext ec, Expression right_side, bool intermediate)
2041 Expression e = null;
2044 // Stage 1: Performed by the parser (binding to locals or parameters).
2046 Block current_block = ec.CurrentBlock;
2047 if (current_block != null){
2048 LocalInfo vi = current_block.GetLocalInfo (Name);
2050 LocalVariableReference var = new LocalVariableReference (ec.CurrentBlock, Name, loc);
2051 if (right_side != null) {
2052 return var.ResolveLValue (ec, right_side, loc);
2054 ResolveFlags rf = ResolveFlags.VariableOrValue;
2056 rf |= ResolveFlags.DisableFlowAnalysis;
2057 return var.Resolve (ec, rf);
2061 ParameterReference pref = current_block.Toplevel.GetParameterReference (Name, loc);
2063 if (right_side != null)
2064 return pref.ResolveLValue (ec, right_side, loc);
2066 return pref.Resolve (ec);
2071 // Stage 2: Lookup members
2074 DeclSpace lookup_ds = ec.DeclSpace;
2075 Type almost_matched_type = null;
2076 ArrayList almost_matched = null;
2078 if (lookup_ds.TypeBuilder == null)
2081 e = MemberLookup (ec, lookup_ds.TypeBuilder, Name, loc);
2085 if (almost_matched == null && almostMatchedMembers.Count > 0) {
2086 almost_matched_type = lookup_ds.TypeBuilder;
2087 almost_matched = (ArrayList) almostMatchedMembers.Clone ();
2090 lookup_ds =lookup_ds.Parent;
2091 } while (lookup_ds != null);
2093 if (e == null && ec.ContainerType != null)
2094 e = MemberLookup (ec, ec.ContainerType, Name, loc);
2097 if (almost_matched == null && almostMatchedMembers.Count > 0) {
2098 almost_matched_type = ec.ContainerType;
2099 almost_matched = (ArrayList) almostMatchedMembers.Clone ();
2101 e = ResolveAsTypeStep (ec, false);
2105 if (almost_matched != null)
2106 almostMatchedMembers = almost_matched;
2107 if (almost_matched_type == null)
2108 almost_matched_type = ec.ContainerType;
2109 MemberLookupFailed (ec, null, almost_matched_type, ((SimpleName) this).Name, ec.DeclSpace.Name, true, loc);
2116 if (e is MemberExpr) {
2117 MemberExpr me = (MemberExpr) e;
2120 if (me.IsInstance) {
2121 if (ec.IsStatic || ec.IsFieldInitializer) {
2123 // Note that an MemberExpr can be both IsInstance and IsStatic.
2124 // An unresolved MethodGroupExpr can contain both kinds of methods
2125 // and each predicate is true if the MethodGroupExpr contains
2126 // at least one of that kind of method.
2130 (!intermediate || !IdenticalNameAndTypeName (ec, me, loc))) {
2131 Error_ObjectRefRequired (ec, loc, me.GetSignatureForError ());
2136 // Pass the buck to MemberAccess and Invocation.
2138 left = EmptyExpression.Null;
2140 left = ec.GetThis (loc);
2143 left = new TypeExpression (ec.ContainerType, loc);
2146 e = me.ResolveMemberAccess (ec, left, loc, null);
2150 me = e as MemberExpr;
2154 if (Arguments != null) {
2155 MethodGroupExpr mg = me as MethodGroupExpr;
2159 return mg.ResolveGeneric (ec, Arguments);
2163 TypeManager.IsNestedFamilyAccessible (me.InstanceExpression.Type, me.DeclaringType) &&
2164 me.InstanceExpression.Type != me.DeclaringType &&
2165 !TypeManager.IsFamilyAccessible (me.InstanceExpression.Type, me.DeclaringType) &&
2166 (!intermediate || !IdenticalNameAndTypeName (ec, e, loc))) {
2167 Report.Error (38, loc, "Cannot access a nonstatic member of outer type `{0}' via nested type `{1}'",
2168 TypeManager.CSharpName (me.DeclaringType), TypeManager.CSharpName (me.InstanceExpression.Type));
2172 return (right_side != null)
2173 ? me.DoResolveLValue (ec, right_side)
2174 : me.DoResolve (ec);
2180 public override void Emit (EmitContext ec)
2183 // If this is ever reached, then we failed to
2184 // find the name as a namespace
2187 Error (103, "The name `" + Name +
2188 "' does not exist in the class `" +
2189 ec.DeclSpace.Name + "'");
2192 public override string ToString ()
2197 public override string GetSignatureForError ()
2204 /// Represents a namespace or a type. The name of the class was inspired by
2205 /// section 10.8.1 (Fully Qualified Names).
2207 public abstract class FullNamedExpression : Expression {
2208 public override FullNamedExpression ResolveAsTypeStep (EmitContext ec, bool silent)
2213 public abstract string FullName {
2219 /// Fully resolved expression that evaluates to a type
2221 public abstract class TypeExpr : FullNamedExpression {
2222 override public FullNamedExpression ResolveAsTypeStep (EmitContext ec, bool silent)
2224 TypeExpr t = DoResolveAsTypeStep (ec);
2228 eclass = ExprClass.Type;
2232 override public Expression DoResolve (EmitContext ec)
2234 return ResolveAsTypeTerminal (ec);
2237 override public void Emit (EmitContext ec)
2239 throw new Exception ("Should never be called");
2242 public virtual bool CheckAccessLevel (DeclSpace ds)
2244 return ds.CheckAccessLevel (Type);
2247 public virtual bool AsAccessible (DeclSpace ds, int flags)
2249 return ds.AsAccessible (Type, flags);
2252 public virtual bool IsClass {
2253 get { return Type.IsClass; }
2256 public virtual bool IsValueType {
2257 get { return Type.IsValueType; }
2260 public virtual bool IsInterface {
2261 get { return Type.IsInterface; }
2264 public virtual bool IsSealed {
2265 get { return Type.IsSealed; }
2268 public virtual bool CanInheritFrom ()
2270 if (Type == TypeManager.enum_type ||
2271 (Type == TypeManager.value_type && RootContext.StdLib) ||
2272 Type == TypeManager.multicast_delegate_type ||
2273 Type == TypeManager.delegate_type ||
2274 Type == TypeManager.array_type)
2280 protected abstract TypeExpr DoResolveAsTypeStep (EmitContext ec);
2282 public virtual Type ResolveType (EmitContext ec)
2284 TypeExpr t = ResolveAsTypeTerminal (ec);
2291 public abstract string Name {
2295 public override bool Equals (object obj)
2297 TypeExpr tobj = obj as TypeExpr;
2301 return Type == tobj.Type;
2304 public override int GetHashCode ()
2306 return Type.GetHashCode ();
2309 public override string ToString ()
2315 public class TypeExpression : TypeExpr {
2316 public TypeExpression (Type t, Location l)
2319 eclass = ExprClass.Type;
2323 protected override TypeExpr DoResolveAsTypeStep (EmitContext ec)
2328 public override string Name {
2329 get { return Type.ToString (); }
2332 public override string FullName {
2333 get { return Type.FullName; }
2338 /// Used to create types from a fully qualified name. These are just used
2339 /// by the parser to setup the core types. A TypeLookupExpression is always
2340 /// classified as a type.
2342 public class TypeLookupExpression : TypeExpr {
2345 public TypeLookupExpression (string name)
2350 static readonly char [] dot_array = { '.' };
2351 protected override TypeExpr DoResolveAsTypeStep (EmitContext ec)
2356 // If name is of the form `N.I', first lookup `N', then search a member `I' in it.
2358 string lookup_name = name;
2359 int pos = name.IndexOf ('.');
2361 rest = name.Substring (pos + 1);
2362 lookup_name = name.Substring (0, pos);
2365 FullNamedExpression resolved = Namespace.Root.Lookup (ec.DeclSpace, lookup_name, Location.Null);
2367 if (resolved != null && rest != null) {
2368 // Now handle the rest of the the name.
2369 string [] elements = rest.Split (dot_array);
2371 int count = elements.Length;
2373 while (i < count && resolved != null && resolved is Namespace) {
2374 Namespace ns = resolved as Namespace;
2375 element = elements [i++];
2376 lookup_name += "." + element;
2377 resolved = ns.Lookup (ec.DeclSpace, element, Location.Null);
2380 if (resolved != null && resolved is TypeExpr) {
2381 Type t = ((TypeExpr) resolved).Type;
2383 if (!ec.DeclSpace.CheckAccessLevel (t)) {
2385 lookup_name = t.FullName;
2392 t = TypeManager.GetNestedType (t, elements [i++]);
2397 if (resolved == null) {
2398 NamespaceEntry.Error_NamespaceNotFound (loc, lookup_name);
2402 if (!(resolved is TypeExpr)) {
2403 resolved.Error_UnexpectedKind (ec, "type", loc);
2407 type = ((TypeExpr) resolved).ResolveType (ec);
2411 public override string Name {
2412 get { return name; }
2415 public override string FullName {
2416 get { return name; }
2421 /// Represents an "unbound generic type", ie. typeof (Foo<>).
2424 public class UnboundTypeExpression : TypeExpr
2428 public UnboundTypeExpression (MemberName name, Location l)
2434 protected override TypeExpr DoResolveAsTypeStep (EmitContext ec)
2437 if (name.Left != null) {
2438 Expression lexpr = name.Left.GetTypeExpression ();
2439 expr = new MemberAccess (lexpr, name.Basename, loc);
2441 expr = new SimpleName (name.Basename, loc);
2444 FullNamedExpression fne = expr.ResolveAsTypeStep (ec);
2449 return new TypeExpression (type, loc);
2452 public override string Name {
2453 get { return name.FullName; }
2456 public override string FullName {
2457 get { return name.FullName; }
2461 public class TypeAliasExpression : TypeExpr {
2462 FullNamedExpression alias;
2467 public TypeAliasExpression (FullNamedExpression alias, TypeArguments args, Location l)
2473 eclass = ExprClass.Type;
2475 name = alias.FullName + "<" + args.ToString () + ">";
2477 name = alias.FullName;
2480 public override string Name {
2481 get { return alias.FullName; }
2484 public override string FullName {
2485 get { return name; }
2488 protected override TypeExpr DoResolveAsTypeStep (EmitContext ec)
2490 texpr = alias.ResolveAsTypeTerminal (ec);
2494 Type type = texpr.Type;
2495 int num_args = TypeManager.GetNumberOfTypeArguments (type);
2498 if (num_args == 0) {
2499 Report.Error (308, loc,
2500 "The non-generic type `{0}' cannot " +
2501 "be used with type arguments.",
2502 TypeManager.CSharpName (type));
2506 ConstructedType ctype = new ConstructedType (type, args, loc);
2507 return ctype.ResolveAsTypeTerminal (ec);
2508 } else if (num_args > 0) {
2509 Report.Error (305, loc,
2510 "Using the generic type `{0}' " +
2511 "requires {1} type arguments",
2512 TypeManager.GetFullName (type), num_args);
2516 return new TypeExpression (type, loc);
2519 public override bool CheckAccessLevel (DeclSpace ds)
2521 return texpr.CheckAccessLevel (ds);
2524 public override bool AsAccessible (DeclSpace ds, int flags)
2526 return texpr.AsAccessible (ds, flags);
2529 public override bool IsClass {
2530 get { return texpr.IsClass; }
2533 public override bool IsValueType {
2534 get { return texpr.IsValueType; }
2537 public override bool IsInterface {
2538 get { return texpr.IsInterface; }
2541 public override bool IsSealed {
2542 get { return texpr.IsSealed; }
2547 /// This class denotes an expression which evaluates to a member
2548 /// of a struct or a class.
2550 public abstract class MemberExpr : Expression
2553 /// The name of this member.
2555 public abstract string Name {
2560 /// Whether this is an instance member.
2562 public abstract bool IsInstance {
2567 /// Whether this is a static member.
2569 public abstract bool IsStatic {
2574 /// The type which declares this member.
2576 public abstract Type DeclaringType {
2581 /// The instance expression associated with this member, if it's a
2582 /// non-static member.
2584 public Expression InstanceExpression;
2586 public static void error176 (Location loc, string name)
2588 Report.Error (176, loc, "Static member `{0}' cannot be accessed " +
2589 "with an instance reference, qualify it with a type name instead", name);
2593 // TODO: possible optimalization
2594 // Cache resolved constant result in FieldBuilder <-> expression map
2595 public virtual Expression ResolveMemberAccess (EmitContext ec, Expression left, Location loc,
2596 SimpleName original)
2600 // original == null || original.Resolve (...) ==> left
2603 if (left is TypeExpr) {
2605 SimpleName.Error_ObjectRefRequired (ec, loc, Name);
2613 if (original != null && original.IdenticalNameAndTypeName (ec, left, loc))
2616 error176 (loc, GetSignatureForError ());
2620 InstanceExpression = left;
2625 protected void EmitInstance (EmitContext ec, bool prepare_for_load)
2630 if (InstanceExpression == EmptyExpression.Null) {
2631 SimpleName.Error_ObjectRefRequired (ec, loc, Name);
2635 if (InstanceExpression.Type.IsValueType) {
2636 if (InstanceExpression is IMemoryLocation) {
2637 ((IMemoryLocation) InstanceExpression).AddressOf (ec, AddressOp.LoadStore);
2639 LocalTemporary t = new LocalTemporary (ec, InstanceExpression.Type);
2640 InstanceExpression.Emit (ec);
2642 t.AddressOf (ec, AddressOp.Store);
2645 InstanceExpression.Emit (ec);
2647 if (prepare_for_load)
2648 ec.ig.Emit (OpCodes.Dup);
2653 /// MethodGroup Expression.
2655 /// This is a fully resolved expression that evaluates to a type
2657 public class MethodGroupExpr : MemberExpr {
2658 public MethodBase [] Methods;
2659 bool has_type_arguments = false;
2660 bool identical_type_name = false;
2663 public MethodGroupExpr (MemberInfo [] mi, Location l)
2665 Methods = new MethodBase [mi.Length];
2666 mi.CopyTo (Methods, 0);
2667 eclass = ExprClass.MethodGroup;
2668 type = TypeManager.object_type;
2672 public MethodGroupExpr (ArrayList list, Location l)
2674 Methods = new MethodBase [list.Count];
2677 list.CopyTo (Methods, 0);
2679 foreach (MemberInfo m in list){
2680 if (!(m is MethodBase)){
2681 Console.WriteLine ("Name " + m.Name);
2682 Console.WriteLine ("Found a: " + m.GetType ().FullName);
2689 eclass = ExprClass.MethodGroup;
2690 type = TypeManager.object_type;
2693 public override Type DeclaringType {
2696 // We assume that the top-level type is in the end
2698 return Methods [Methods.Length - 1].DeclaringType;
2699 //return Methods [0].DeclaringType;
2703 public bool HasTypeArguments {
2705 return has_type_arguments;
2709 has_type_arguments = value;
2713 public bool IdenticalTypeName {
2715 return identical_type_name;
2719 identical_type_name = value;
2723 public bool IsBase {
2732 public override string GetSignatureForError ()
2734 return TypeManager.CSharpSignature (Methods [0]);
2737 public override string Name {
2739 return Methods [0].Name;
2743 public override bool IsInstance {
2745 foreach (MethodBase mb in Methods)
2753 public override bool IsStatic {
2755 foreach (MethodBase mb in Methods)
2763 public override Expression ResolveMemberAccess (EmitContext ec, Expression left, Location loc,
2764 SimpleName original)
2766 if (!(left is TypeExpr) &&
2767 original != null && original.IdenticalNameAndTypeName (ec, left, loc))
2768 IdenticalTypeName = true;
2770 return base.ResolveMemberAccess (ec, left, loc, original);
2773 override public Expression DoResolve (EmitContext ec)
2776 InstanceExpression = null;
2778 if (InstanceExpression != null) {
2779 InstanceExpression = InstanceExpression.DoResolve (ec);
2780 if (InstanceExpression == null)
2787 public void ReportUsageError ()
2789 Report.Error (654, loc, "Method `" + DeclaringType + "." +
2790 Name + "()' is referenced without parentheses");
2793 override public void Emit (EmitContext ec)
2795 ReportUsageError ();
2798 bool RemoveMethods (bool keep_static)
2800 ArrayList smethods = new ArrayList ();
2802 foreach (MethodBase mb in Methods){
2803 if (mb.IsStatic == keep_static)
2807 if (smethods.Count == 0)
2810 Methods = new MethodBase [smethods.Count];
2811 smethods.CopyTo (Methods, 0);
2817 /// Removes any instance methods from the MethodGroup, returns
2818 /// false if the resulting set is empty.
2820 public bool RemoveInstanceMethods ()
2822 return RemoveMethods (true);
2826 /// Removes any static methods from the MethodGroup, returns
2827 /// false if the resulting set is empty.
2829 public bool RemoveStaticMethods ()
2831 return RemoveMethods (false);
2834 public Expression ResolveGeneric (EmitContext ec, TypeArguments args)
2836 if (args.Resolve (ec) == false)
2839 Type[] atypes = args.Arguments;
2841 int first_count = 0;
2842 MethodInfo first = null;
2844 ArrayList list = new ArrayList ();
2845 foreach (MethodBase mb in Methods) {
2846 MethodInfo mi = mb as MethodInfo;
2847 if ((mi == null) || !mi.HasGenericParameters)
2850 Type[] gen_params = mi.GetGenericArguments ();
2852 if (first == null) {
2854 first_count = gen_params.Length;
2857 if (gen_params.Length != atypes.Length)
2860 list.Add (mi.MakeGenericMethod (atypes));
2863 if (list.Count > 0) {
2864 MethodGroupExpr new_mg = new MethodGroupExpr (list, Location);
2865 new_mg.InstanceExpression = InstanceExpression;
2866 new_mg.HasTypeArguments = true;
2872 305, loc, "Using the generic method `{0}' " +
2873 "requires {1} type arguments", Name,
2877 308, loc, "The non-generic method `{0}' " +
2878 "cannot be used with type arguments", Name);
2885 /// Fully resolved expression that evaluates to a Field
2887 public class FieldExpr : MemberExpr, IAssignMethod, IMemoryLocation, IVariable {
2888 public readonly FieldInfo FieldInfo;
2889 VariableInfo variable_info;
2891 LocalTemporary temp;
2893 bool in_initializer;
2895 public FieldExpr (FieldInfo fi, Location l, bool in_initializer):
2898 this.in_initializer = in_initializer;
2901 public FieldExpr (FieldInfo fi, Location l)
2904 eclass = ExprClass.Variable;
2905 type = TypeManager.TypeToCoreType (fi.FieldType);
2909 public override string Name {
2911 return FieldInfo.Name;
2915 public override bool IsInstance {
2917 return !FieldInfo.IsStatic;
2921 public override bool IsStatic {
2923 return FieldInfo.IsStatic;
2927 public override Type DeclaringType {
2929 return FieldInfo.DeclaringType;
2933 public override string GetSignatureForError ()
2935 return TypeManager.GetFullNameSignature (FieldInfo);
2938 public VariableInfo VariableInfo {
2940 return variable_info;
2944 public override Expression ResolveMemberAccess (EmitContext ec, Expression left, Location loc,
2945 SimpleName original)
2947 FieldInfo fi = FieldInfo.Mono_GetGenericFieldDefinition ();
2950 IConstant ic = TypeManager.GetConstant (fi);
2952 ic = new ExternalConstant (fi);
2953 TypeManager.RegisterConstant (fi, ic);
2956 bool left_is_type = left is TypeExpr;
2957 if (!left_is_type && (original == null || !original.IdenticalNameAndTypeName (ec, left, loc))) {
2958 Report.SymbolRelatedToPreviousError (FieldInfo);
2959 error176 (loc, TypeManager.GetFullNameSignature (FieldInfo));
2963 if (ic.ResolveValue ())
2964 ic.CheckObsoleteness (loc);
2969 bool is_emitted = fi is FieldBuilder;
2970 Type t = fi.FieldType;
2973 // Decimal constants cannot be encoded in the constant blob, and thus are marked
2974 // as IsInitOnly ('readonly' in C# parlance). We get its value from the
2975 // DecimalConstantAttribute metadata.
2977 if (fi.IsInitOnly && !is_emitted && t == TypeManager.decimal_type) {
2978 object[] attrs = fi.GetCustomAttributes (TypeManager.decimal_constant_attribute_type, false);
2979 if (attrs.Length == 1)
2980 return new DecimalConstant (((System.Runtime.CompilerServices.DecimalConstantAttribute) attrs [0]).Value);
2983 if (t.IsPointer && !ec.InUnsafe) {
2988 return base.ResolveMemberAccess (ec, left, loc, original);
2991 override public Expression DoResolve (EmitContext ec)
2993 if (ec.InRefOutArgumentResolving && FieldInfo.IsInitOnly && !ec.IsConstructor && FieldInfo.FieldType.IsValueType) {
2994 if (FieldInfo.FieldType is TypeBuilder) {
2995 if (FieldInfo.IsStatic)
2996 Report.Error (1651, loc, "Fields of static readonly field `{0}' cannot be passed ref or out (except in a static constructor)",
2997 GetSignatureForError ());
2999 Report.Error (1649, loc, "Members of readonly field `{0}.{1}' cannot be passed ref or out (except in a constructor)",
3000 TypeManager.CSharpName (DeclaringType), Name);
3002 if (FieldInfo.IsStatic)
3003 Report.Error (199, loc, "A static readonly field `{0}' cannot be passed ref or out (except in a static constructor)",
3006 Report.Error (192, loc, "A readonly field `{0}' cannot be passed ref or out (except in a constructor)",
3012 if (!FieldInfo.IsStatic){
3013 if (InstanceExpression == null){
3015 // This can happen when referencing an instance field using
3016 // a fully qualified type expression: TypeName.InstanceField = xxx
3018 SimpleName.Error_ObjectRefRequired (ec, loc, FieldInfo.Name);
3022 // Resolve the field's instance expression while flow analysis is turned
3023 // off: when accessing a field "a.b", we must check whether the field
3024 // "a.b" is initialized, not whether the whole struct "a" is initialized.
3025 InstanceExpression = InstanceExpression.Resolve (
3026 ec, ResolveFlags.VariableOrValue | ResolveFlags.DisableFlowAnalysis);
3027 if (InstanceExpression == null)
3031 if (!in_initializer) {
3032 ObsoleteAttribute oa;
3033 FieldBase f = TypeManager.GetField (FieldInfo);
3035 f.CheckObsoleteness (loc);
3036 // To be sure that type is external because we do not register generated fields
3037 } else if (!(FieldInfo.DeclaringType is TypeBuilder)) {
3038 oa = AttributeTester.GetMemberObsoleteAttribute (FieldInfo);
3040 AttributeTester.Report_ObsoleteMessage (oa, TypeManager.GetFullNameSignature (FieldInfo), loc);
3044 AnonymousContainer am = ec.CurrentAnonymousMethod;
3046 if (!FieldInfo.IsStatic){
3047 if (!am.IsIterator && (ec.TypeContainer is Struct)){
3048 Report.Error (1673, loc,
3049 "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",
3053 if ((am.ContainerAnonymousMethod == null) && (InstanceExpression is This))
3054 ec.CaptureField (this);
3058 // If the instance expression is a local variable or parameter.
3059 IVariable var = InstanceExpression as IVariable;
3060 if ((var == null) || (var.VariableInfo == null))
3063 VariableInfo vi = var.VariableInfo;
3064 if (!vi.IsFieldAssigned (ec, FieldInfo.Name, loc))
3067 variable_info = vi.GetSubStruct (FieldInfo.Name);
3071 void Report_AssignToReadonly (bool is_instance)
3076 msg = "A readonly field cannot be assigned to (except in a constructor or a variable initializer)";
3078 msg = "A static readonly field cannot be assigned to (except in a static constructor or a variable initializer)";
3080 Report.Error (is_instance ? 191 : 198, loc, msg);
3083 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
3085 IVariable var = InstanceExpression as IVariable;
3086 if ((var != null) && (var.VariableInfo != null))
3087 var.VariableInfo.SetFieldAssigned (ec, FieldInfo.Name);
3089 Expression e = DoResolve (ec);
3094 if (!FieldInfo.IsStatic && (InstanceExpression.Type.IsValueType && !(InstanceExpression is IMemoryLocation))) {
3095 Report.Error (1612, loc, "Cannot modify the return value of `{0}' because it is not a variable",
3096 InstanceExpression.GetSignatureForError ());
3100 FieldBase fb = TypeManager.GetField (FieldInfo);
3104 if (!FieldInfo.IsInitOnly)
3108 // InitOnly fields can only be assigned in constructors
3111 if (ec.IsConstructor){
3112 if (IsStatic && !ec.IsStatic)
3113 Report_AssignToReadonly (false);
3116 if (ec.TypeContainer.CurrentType != null)
3117 ctype = ec.TypeContainer.CurrentType;
3119 ctype = ec.ContainerType;
3121 if (TypeManager.IsEqual (ctype, FieldInfo.DeclaringType))
3125 Report_AssignToReadonly (!IsStatic);
3130 public override void CheckMarshallByRefAccess (Type container)
3132 if (!IsStatic && Type.IsValueType && !container.IsSubclassOf (TypeManager.mbr_type) && DeclaringType.IsSubclassOf (TypeManager.mbr_type)) {
3133 Report.SymbolRelatedToPreviousError (DeclaringType);
3134 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",
3135 GetSignatureForError ());
3139 public bool VerifyFixed ()
3141 IVariable variable = InstanceExpression as IVariable;
3142 // A variable of the form V.I is fixed when V is a fixed variable of a struct type.
3143 // We defer the InstanceExpression check after the variable check to avoid a
3144 // separate null check on InstanceExpression.
3145 return variable != null && InstanceExpression.Type.IsValueType && variable.VerifyFixed ();
3148 public override int GetHashCode()
3150 return FieldInfo.GetHashCode ();
3153 public override bool Equals (object obj)
3155 FieldExpr fe = obj as FieldExpr;
3159 if (FieldInfo != fe.FieldInfo)
3162 if (InstanceExpression == null || fe.InstanceExpression == null)
3165 return InstanceExpression.Equals (fe.InstanceExpression);
3168 public void Emit (EmitContext ec, bool leave_copy)
3170 ILGenerator ig = ec.ig;
3171 bool is_volatile = false;
3173 FieldInfo the_fi = FieldInfo.Mono_GetGenericFieldDefinition ();
3174 if (the_fi is FieldBuilder){
3175 FieldBase f = TypeManager.GetField (the_fi);
3177 if ((f.ModFlags & Modifiers.VOLATILE) != 0)
3180 f.SetMemberIsUsed ();
3184 if (FieldInfo.IsStatic){
3186 ig.Emit (OpCodes.Volatile);
3188 ig.Emit (OpCodes.Ldsfld, FieldInfo);
3191 EmitInstance (ec, false);
3194 ig.Emit (OpCodes.Volatile);
3196 IFixedBuffer ff = AttributeTester.GetFixedBuffer (FieldInfo);
3199 ig.Emit (OpCodes.Ldflda, FieldInfo);
3200 ig.Emit (OpCodes.Ldflda, ff.Element);
3203 ig.Emit (OpCodes.Ldfld, FieldInfo);
3208 ec.ig.Emit (OpCodes.Dup);
3209 if (!FieldInfo.IsStatic) {
3210 temp = new LocalTemporary (ec, this.Type);
3216 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
3218 FieldAttributes fa = FieldInfo.Attributes;
3219 bool is_static = (fa & FieldAttributes.Static) != 0;
3220 bool is_readonly = (fa & FieldAttributes.InitOnly) != 0;
3221 ILGenerator ig = ec.ig;
3222 prepared = prepare_for_load;
3224 if (is_readonly && !ec.IsConstructor){
3225 Report_AssignToReadonly (!is_static);
3229 EmitInstance (ec, prepare_for_load);
3233 ec.ig.Emit (OpCodes.Dup);
3234 if (!FieldInfo.IsStatic) {
3235 temp = new LocalTemporary (ec, this.Type);
3240 if (FieldInfo is FieldBuilder){
3241 FieldBase f = TypeManager.GetField (FieldInfo);
3243 if ((f.ModFlags & Modifiers.VOLATILE) != 0)
3244 ig.Emit (OpCodes.Volatile);
3251 ig.Emit (OpCodes.Stsfld, FieldInfo);
3253 ig.Emit (OpCodes.Stfld, FieldInfo);
3259 public override void Emit (EmitContext ec)
3264 public void AddressOf (EmitContext ec, AddressOp mode)
3266 ILGenerator ig = ec.ig;
3268 if (FieldInfo is FieldBuilder){
3269 FieldBase f = TypeManager.GetField (FieldInfo);
3271 if ((f.ModFlags & Modifiers.VOLATILE) != 0){
3272 Report.Warning (420, 1, loc, "`{0}': A volatile fields cannot be passed using a ref or out parameter",
3273 f.GetSignatureForError ());
3277 if ((mode & AddressOp.Store) != 0)
3279 if ((mode & AddressOp.Load) != 0)
3280 f.SetMemberIsUsed ();
3285 // Handle initonly fields specially: make a copy and then
3286 // get the address of the copy.
3289 if (FieldInfo.IsInitOnly){
3291 if (ec.IsConstructor){
3292 if (FieldInfo.IsStatic){
3304 local = ig.DeclareLocal (type);
3305 ig.Emit (OpCodes.Stloc, local);
3306 ig.Emit (OpCodes.Ldloca, local);
3311 if (FieldInfo.IsStatic){
3312 ig.Emit (OpCodes.Ldsflda, FieldInfo);
3314 EmitInstance (ec, false);
3315 ig.Emit (OpCodes.Ldflda, FieldInfo);
3321 // A FieldExpr whose address can not be taken
3323 public class FieldExprNoAddress : FieldExpr, IMemoryLocation {
3324 public FieldExprNoAddress (FieldInfo fi, Location loc) : base (fi, loc)
3328 public new void AddressOf (EmitContext ec, AddressOp mode)
3330 Report.Error (-215, "Report this: Taking the address of a remapped parameter not supported");
3335 /// Expression that evaluates to a Property. The Assign class
3336 /// might set the `Value' expression if we are in an assignment.
3338 /// This is not an LValue because we need to re-write the expression, we
3339 /// can not take data from the stack and store it.
3341 public class PropertyExpr : MemberExpr, IAssignMethod {
3342 public readonly PropertyInfo PropertyInfo;
3345 // This is set externally by the `BaseAccess' class
3348 MethodInfo getter, setter;
3353 LocalTemporary temp;
3356 internal static PtrHashtable AccessorTable = new PtrHashtable ();
3358 public PropertyExpr (EmitContext ec, PropertyInfo pi, Location l)
3361 eclass = ExprClass.PropertyAccess;
3365 type = TypeManager.TypeToCoreType (pi.PropertyType);
3367 ResolveAccessors (ec);
3370 public override string Name {
3372 return PropertyInfo.Name;
3376 public override bool IsInstance {
3382 public override bool IsStatic {
3388 public override Type DeclaringType {
3390 return PropertyInfo.DeclaringType;
3394 public override string GetSignatureForError ()
3396 return TypeManager.GetFullNameSignature (PropertyInfo);
3399 void FindAccessors (Type invocation_type)
3401 BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic |
3402 BindingFlags.Static | BindingFlags.Instance |
3403 BindingFlags.DeclaredOnly;
3405 Type current = PropertyInfo.DeclaringType;
3406 for (; current != null; current = current.BaseType) {
3407 MemberInfo[] group = TypeManager.MemberLookup (
3408 invocation_type, invocation_type, current,
3409 MemberTypes.Property, flags, PropertyInfo.Name, null);
3414 if (group.Length != 1)
3415 // Oooops, can this ever happen ?
3418 PropertyInfo pi = (PropertyInfo) group [0];
3421 getter = pi.GetGetMethod (true);
3424 setter = pi.GetSetMethod (true);
3426 MethodInfo accessor = getter != null ? getter : setter;
3428 if (!accessor.IsVirtual)
3434 // We also perform the permission checking here, as the PropertyInfo does not
3435 // hold the information for the accessibility of its setter/getter
3437 void ResolveAccessors (EmitContext ec)
3439 FindAccessors (ec.ContainerType);
3441 if (getter != null) {
3442 IMethodData md = TypeManager.GetMethod (getter);
3444 md.SetMemberIsUsed ();
3446 AccessorTable [getter] = PropertyInfo;
3447 is_static = getter.IsStatic;
3450 if (setter != null) {
3451 IMethodData md = TypeManager.GetMethod (setter);
3453 md.SetMemberIsUsed ();
3455 AccessorTable [setter] = PropertyInfo;
3456 is_static = setter.IsStatic;
3460 bool InstanceResolve (EmitContext ec, bool must_do_cs1540_check)
3463 InstanceExpression = null;
3467 if (InstanceExpression == null) {
3468 SimpleName.Error_ObjectRefRequired (ec, loc, PropertyInfo.Name);
3472 InstanceExpression = InstanceExpression.DoResolve (ec);
3473 if (InstanceExpression == null)
3476 InstanceExpression.CheckMarshallByRefAccess (ec.ContainerType);
3478 if (must_do_cs1540_check && InstanceExpression != EmptyExpression.Null) {
3479 if ((InstanceExpression.Type != ec.ContainerType) &&
3480 ec.ContainerType.IsSubclassOf (InstanceExpression.Type)) {
3481 Report.Error (1540, loc, "Cannot access protected member `" +
3482 PropertyInfo.DeclaringType + "." + PropertyInfo.Name +
3483 "' via a qualifier of type `" +
3484 TypeManager.CSharpName (InstanceExpression.Type) +
3485 "'; the qualifier must be of type `" +
3486 TypeManager.CSharpName (ec.ContainerType) +
3487 "' (or derived from it)");
3495 void Error_PropertyNotFound (MethodInfo mi, bool getter)
3497 // TODO: correctly we should compare arguments but it will lead to bigger changes
3498 if (mi is MethodBuilder) {
3499 Error_TypeDoesNotContainDefinition (loc, PropertyInfo.DeclaringType, Name);
3503 StringBuilder sig = new StringBuilder (TypeManager.CSharpName (mi.DeclaringType));
3505 ParameterData iparams = TypeManager.GetParameterData (mi);
3506 sig.Append (getter ? "get_" : "set_");
3508 sig.Append (iparams.GetSignatureForError ());
3510 Report.SymbolRelatedToPreviousError (mi);
3511 Report.Error (1546, loc, "Property `{0}' is not supported by the C# language. Try to call the accessor method `{1}' directly",
3512 Name, sig.ToString ());
3515 override public Expression DoResolve (EmitContext ec)
3520 if (getter != null){
3521 if (TypeManager.GetArgumentTypes (getter).Length != 0){
3522 Error_PropertyNotFound (getter, true);
3527 if (getter == null){
3529 // The following condition happens if the PropertyExpr was
3530 // created, but is invalid (ie, the property is inaccessible),
3531 // and we did not want to embed the knowledge about this in
3532 // the caller routine. This only avoids double error reporting.
3537 if (InstanceExpression != EmptyExpression.Null) {
3538 Report.Error (154, loc, "The property or indexer `{0}' cannot be used in this context because it lacks the `get' accessor",
3539 TypeManager.GetFullNameSignature (PropertyInfo));
3544 bool must_do_cs1540_check = false;
3545 if (getter != null &&
3546 !IsAccessorAccessible (ec.ContainerType, getter, out must_do_cs1540_check)) {
3547 PropertyBase.PropertyMethod pm = TypeManager.GetMethod (getter) as PropertyBase.PropertyMethod;
3548 if (pm != null && pm.HasCustomAccessModifier) {
3549 Report.SymbolRelatedToPreviousError (pm);
3550 Report.Error (271, loc, "The property or indexer `{0}' cannot be used in this context because the get accessor is inaccessible",
3551 TypeManager.CSharpSignature (getter));
3554 ErrorIsInaccesible (loc, TypeManager.CSharpSignature (getter));
3558 if (!InstanceResolve (ec, must_do_cs1540_check))
3562 // Only base will allow this invocation to happen.
3564 if (IsBase && getter.IsAbstract) {
3565 Error_CannotCallAbstractBase (TypeManager.GetFullNameSignature (PropertyInfo));
3569 if (PropertyInfo.PropertyType.IsPointer && !ec.InUnsafe){
3579 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
3581 if (setter == null){
3583 // The following condition happens if the PropertyExpr was
3584 // created, but is invalid (ie, the property is inaccessible),
3585 // and we did not want to embed the knowledge about this in
3586 // the caller routine. This only avoids double error reporting.
3591 Report.Error (200, loc, " Property or indexer `{0}' cannot be assigned to (it is read only)",
3592 TypeManager.GetFullNameSignature (PropertyInfo));
3596 if (TypeManager.GetArgumentTypes (setter).Length != 1){
3597 Error_PropertyNotFound (setter, false);
3601 bool must_do_cs1540_check;
3602 if (!IsAccessorAccessible (ec.ContainerType, setter, out must_do_cs1540_check)) {
3603 PropertyBase.PropertyMethod pm = TypeManager.GetMethod (setter) as PropertyBase.PropertyMethod;
3604 if (pm != null && pm.HasCustomAccessModifier) {
3605 Report.SymbolRelatedToPreviousError (pm);
3606 Report.Error (272, loc, "The property or indexer `{0}' cannot be used in this context because the set accessor is inaccessible",
3607 TypeManager.CSharpSignature (setter));
3610 ErrorIsInaccesible (loc, TypeManager.CSharpSignature (setter));
3614 if (!InstanceResolve (ec, must_do_cs1540_check))
3618 // Only base will allow this invocation to happen.
3620 if (IsBase && setter.IsAbstract){
3621 Error_CannotCallAbstractBase (TypeManager.GetFullNameSignature (PropertyInfo));
3626 // Check that we are not making changes to a temporary memory location
3628 if (InstanceExpression != null && InstanceExpression.Type.IsValueType && !(InstanceExpression is IMemoryLocation)) {
3629 Report.Error (1612, loc, "Cannot modify the return value of `{0}' because it is not a variable",
3630 InstanceExpression.GetSignatureForError ());
3637 public override void Emit (EmitContext ec)
3642 public void Emit (EmitContext ec, bool leave_copy)
3645 EmitInstance (ec, false);
3648 // Special case: length of single dimension array property is turned into ldlen
3650 if ((getter == TypeManager.system_int_array_get_length) ||
3651 (getter == TypeManager.int_array_get_length)){
3652 Type iet = InstanceExpression.Type;
3655 // System.Array.Length can be called, but the Type does not
3656 // support invoking GetArrayRank, so test for that case first
3658 if (iet != TypeManager.array_type && (iet.GetArrayRank () == 1)) {
3659 ec.ig.Emit (OpCodes.Ldlen);
3660 ec.ig.Emit (OpCodes.Conv_I4);
3665 Invocation.EmitCall (ec, IsBase, IsStatic, new EmptyAddressOf (), getter, null, loc);
3670 ec.ig.Emit (OpCodes.Dup);
3672 temp = new LocalTemporary (ec, this.Type);
3678 // Implements the IAssignMethod interface for assignments
3680 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
3682 prepared = prepare_for_load;
3684 EmitInstance (ec, prepare_for_load);
3688 ec.ig.Emit (OpCodes.Dup);
3690 temp = new LocalTemporary (ec, this.Type);
3695 ArrayList args = new ArrayList (1);
3696 args.Add (new Argument (new EmptyAddressOf (), Argument.AType.Expression));
3698 Invocation.EmitCall (ec, IsBase, IsStatic, new EmptyAddressOf (), setter, args, loc);
3706 /// Fully resolved expression that evaluates to an Event
3708 public class EventExpr : MemberExpr {
3709 public readonly EventInfo EventInfo;
3712 MethodInfo add_accessor, remove_accessor;
3714 public EventExpr (EventInfo ei, Location loc)
3718 eclass = ExprClass.EventAccess;
3720 add_accessor = TypeManager.GetAddMethod (ei);
3721 remove_accessor = TypeManager.GetRemoveMethod (ei);
3723 if (add_accessor.IsStatic || remove_accessor.IsStatic)
3726 if (EventInfo is MyEventBuilder){
3727 MyEventBuilder eb = (MyEventBuilder) EventInfo;
3728 type = eb.EventType;
3731 type = EventInfo.EventHandlerType;
3734 public override string Name {
3736 return EventInfo.Name;
3740 public override bool IsInstance {
3746 public override bool IsStatic {
3752 public override Type DeclaringType {
3754 return EventInfo.DeclaringType;
3758 public override Expression ResolveMemberAccess (EmitContext ec, Expression left, Location loc,
3759 SimpleName original)
3762 // If the event is local to this class, we transform ourselves into a FieldExpr
3765 if (EventInfo.DeclaringType == ec.ContainerType ||
3766 TypeManager.IsNestedChildOf(ec.ContainerType, EventInfo.DeclaringType)) {
3767 MemberInfo mi = TypeManager.GetPrivateFieldOfEvent (EventInfo);
3770 MemberExpr ml = (MemberExpr) ExprClassFromMemberInfo (ec, mi, loc);
3773 Report.Error (-200, loc, "Internal error!!");
3777 InstanceExpression = null;
3779 return ml.ResolveMemberAccess (ec, left, loc, original);
3783 return base.ResolveMemberAccess (ec, left, loc, original);
3787 bool InstanceResolve (EmitContext ec, bool must_do_cs1540_check)
3790 InstanceExpression = null;
3794 if (InstanceExpression == null) {
3795 SimpleName.Error_ObjectRefRequired (ec, loc, EventInfo.Name);
3799 InstanceExpression = InstanceExpression.DoResolve (ec);
3800 if (InstanceExpression == null)
3804 // This is using the same mechanism as the CS1540 check in PropertyExpr.
3805 // However, in the Event case, we reported a CS0122 instead.
3807 if (must_do_cs1540_check && InstanceExpression != EmptyExpression.Null) {
3808 if ((InstanceExpression.Type != ec.ContainerType) &&
3809 ec.ContainerType.IsSubclassOf (InstanceExpression.Type)) {
3810 ErrorIsInaccesible (loc, TypeManager.CSharpSignature (EventInfo));
3818 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
3820 return DoResolve (ec);
3823 public override Expression DoResolve (EmitContext ec)
3825 bool must_do_cs1540_check;
3826 if (!(IsAccessorAccessible (ec.ContainerType, add_accessor, out must_do_cs1540_check) &&
3827 IsAccessorAccessible (ec.ContainerType, remove_accessor, out must_do_cs1540_check))) {
3828 ErrorIsInaccesible (loc, TypeManager.CSharpSignature (EventInfo));
3832 if (!InstanceResolve (ec, must_do_cs1540_check))
3838 public override void Emit (EmitContext ec)
3840 if (InstanceExpression is This)
3841 Report.Error (79, loc, "The event `{0}' can only appear on the left hand side of += or -=", GetSignatureForError ());
3843 Report.Error (70, loc, "The event `{0}' can only appear on the left hand side of += or -= "+
3844 "(except on the defining type)", Name);
3847 public override string GetSignatureForError ()
3849 return TypeManager.CSharpSignature (EventInfo);
3852 public void EmitAddOrRemove (EmitContext ec, Expression source)
3854 BinaryDelegate source_del = (BinaryDelegate) source;
3855 Expression handler = source_del.Right;
3857 Argument arg = new Argument (handler, Argument.AType.Expression);
3858 ArrayList args = new ArrayList ();
3862 if (source_del.IsAddition)
3863 Invocation.EmitCall (
3864 ec, false, IsStatic, InstanceExpression, add_accessor, args, loc);
3866 Invocation.EmitCall (
3867 ec, false, IsStatic, InstanceExpression, remove_accessor, args, loc);