2 // ecore.cs: Core of the Expression representation for the intermediate tree.
5 // Miguel de Icaza (miguel@ximian.com)
7 // (C) 2001, 2002, 2003 Ximian, Inc.
11 namespace Mono.CSharp {
13 using System.Collections;
14 using System.Diagnostics;
15 using System.Reflection;
16 using System.Reflection.Emit;
20 /// The ExprClass class contains the is used to pass the
21 /// classification of an expression (value, variable, namespace,
22 /// type, method group, property access, event access, indexer access,
25 public enum ExprClass : byte {
40 /// This is used to tell Resolve in which types of expressions we're
44 public enum ResolveFlags {
45 // Returns Value, Variable, PropertyAccess, EventAccess or IndexerAccess.
48 // Returns a type expression.
51 // Returns a method group.
54 // Mask of all the expression class flags.
57 // Disable control flow analysis while resolving the expression.
58 // This is used when resolving the instance expression of a field expression.
59 DisableFlowAnalysis = 8,
61 // Set if this is resolving the first part of a MemberAccess.
66 // This is just as a hint to AddressOf of what will be done with the
69 public enum AddressOp {
76 /// This interface is implemented by variables
78 public interface IMemoryLocation {
80 /// The AddressOf method should generate code that loads
81 /// the address of the object and leaves it on the stack.
83 /// The `mode' argument is used to notify the expression
84 /// of whether this will be used to read from the address or
85 /// write to the address.
87 /// This is just a hint that can be used to provide good error
88 /// reporting, and should have no other side effects.
90 void AddressOf (EmitContext ec, AddressOp mode);
94 /// This interface is implemented by variables
96 public interface IVariable {
97 VariableInfo VariableInfo {
105 /// Base class for expressions
107 public abstract class Expression {
108 public ExprClass eclass;
110 protected Location loc;
114 set { type = value; }
117 public Location Location {
122 /// Utility wrapper routine for Error, just to beautify the code
124 public void Error (int error, string s)
126 if (!Location.IsNull (loc))
127 Report.Error (error, loc, s);
129 Report.Error (error, s);
133 /// Utility wrapper routine for Warning, just to beautify the code
135 public void Warning (int code, string format, params object[] args)
137 Report.Warning (code, loc, format, args);
140 // Not nice but we have broken hierarchy
141 public virtual void CheckMarshallByRefAccess (Type container) {}
144 /// Tests presence of ObsoleteAttribute and report proper error
146 protected void CheckObsoleteAttribute (Type type)
148 ObsoleteAttribute obsolete_attr = AttributeTester.GetObsoleteAttribute (type);
149 if (obsolete_attr == null)
152 AttributeTester.Report_ObsoleteMessage (obsolete_attr, type.FullName, loc);
155 public virtual string GetSignatureForError ()
157 return TypeManager.CSharpName (type);
160 public static bool IsAccessorAccessible (Type invocation_type, MethodInfo mi, out bool must_do_cs1540_check)
162 MethodAttributes ma = mi.Attributes & MethodAttributes.MemberAccessMask;
164 must_do_cs1540_check = false; // by default we do not check for this
167 // If only accessible to the current class or children
169 if (ma == MethodAttributes.Private)
170 return TypeManager.IsPrivateAccessible (invocation_type, mi.DeclaringType) ||
171 TypeManager.IsNestedChildOf (invocation_type, mi.DeclaringType);
173 if (mi.DeclaringType.Assembly == invocation_type.Assembly) {
174 if (ma == MethodAttributes.Assembly || ma == MethodAttributes.FamORAssem)
177 if (ma == MethodAttributes.Assembly || ma == MethodAttributes.FamANDAssem)
181 // Family and FamANDAssem require that we derive.
182 // FamORAssem requires that we derive if in different assemblies.
183 if (ma == MethodAttributes.Family ||
184 ma == MethodAttributes.FamANDAssem ||
185 ma == MethodAttributes.FamORAssem) {
186 if (!TypeManager.IsNestedFamilyAccessible (invocation_type, mi.DeclaringType))
189 if (!TypeManager.IsNestedChildOf (invocation_type, mi.DeclaringType))
190 must_do_cs1540_check = true;
199 /// Performs semantic analysis on the Expression
203 /// The Resolve method is invoked to perform the semantic analysis
206 /// The return value is an expression (it can be the
207 /// same expression in some cases) or a new
208 /// expression that better represents this node.
210 /// For example, optimizations of Unary (LiteralInt)
211 /// would return a new LiteralInt with a negated
214 /// If there is an error during semantic analysis,
215 /// then an error should be reported (using Report)
216 /// and a null value should be returned.
218 /// There are two side effects expected from calling
219 /// Resolve(): the the field variable "eclass" should
220 /// be set to any value of the enumeration
221 /// `ExprClass' and the type variable should be set
222 /// to a valid type (this is the type of the
225 public abstract Expression DoResolve (EmitContext ec);
227 public virtual Expression DoResolveLValue (EmitContext ec, Expression right_side)
233 // This is used if the expression should be resolved as a type or namespace name.
234 // the default implementation fails.
236 public virtual FullNamedExpression ResolveAsTypeStep (EmitContext ec)
242 // This is used to resolve the expression as a type, a null
243 // value will be returned if the expression is not a type
246 public virtual TypeExpr ResolveAsTypeTerminal (EmitContext ec)
248 int errors = Report.Errors;
250 FullNamedExpression fne = ResolveAsTypeStep (ec);
253 if (errors == Report.Errors)
254 NamespaceEntry.Error_NamespaceNotFound (Location, ToString ());
258 if (fne.eclass != ExprClass.Type) {
259 if (errors == Report.Errors)
260 Report.Error (118, Location, "`{0}' denotes a `{1}', where a type was expected",
261 fne.FullName, fne.ExprClassName ());
265 TypeExpr te = fne as TypeExpr;
267 if (!te.CheckAccessLevel (ec.DeclSpace)) {
268 ErrorIsInaccesible (loc, TypeManager.CSharpName (te.Type));
272 ConstructedType ct = te as ConstructedType;
273 if ((ct != null) && !ec.ResolvingTypeTree && !ct.CheckConstraints (ec))
279 public static void ErrorIsInaccesible (Location loc, string name)
281 Report.Error (122, loc, "`{0}' is inaccessible due to its protection level", name);
284 ResolveFlags ExprClassToResolveFlags ()
288 case ExprClass.Namespace:
289 return ResolveFlags.Type;
291 case ExprClass.MethodGroup:
292 return ResolveFlags.MethodGroup;
294 case ExprClass.Value:
295 case ExprClass.Variable:
296 case ExprClass.PropertyAccess:
297 case ExprClass.EventAccess:
298 case ExprClass.IndexerAccess:
299 return ResolveFlags.VariableOrValue;
302 throw new Exception ("Expression " + GetType () +
303 " ExprClass is Invalid after resolve");
309 /// Resolves an expression and performs semantic analysis on it.
313 /// Currently Resolve wraps DoResolve to perform sanity
314 /// checking and assertion checking on what we expect from Resolve.
316 public Expression Resolve (EmitContext ec, ResolveFlags flags)
318 if ((flags & ResolveFlags.MaskExprClass) == ResolveFlags.Type)
319 return ResolveAsTypeStep (ec);
321 bool old_do_flow_analysis = ec.DoFlowAnalysis;
322 if ((flags & ResolveFlags.DisableFlowAnalysis) != 0)
323 ec.DoFlowAnalysis = false;
326 bool intermediate = (flags & ResolveFlags.Intermediate) == ResolveFlags.Intermediate;
327 if (this is SimpleName)
328 e = ((SimpleName) this).DoResolve (ec, intermediate);
333 ec.DoFlowAnalysis = old_do_flow_analysis;
338 if ((flags & e.ExprClassToResolveFlags ()) == 0) {
339 e.Error_UnexpectedKind (flags, loc);
343 if (e.type == null && !(e is Namespace)) {
344 throw new Exception (
345 "Expression " + e.GetType () +
346 " did not set its type after Resolve\n" +
347 "called from: " + this.GetType ());
354 /// Resolves an expression and performs semantic analysis on it.
356 public Expression Resolve (EmitContext ec)
358 Expression e = Resolve (ec, ResolveFlags.VariableOrValue | ResolveFlags.MethodGroup);
360 if (e != null && e.eclass == ExprClass.MethodGroup && RootContext.Version == LanguageVersion.ISO_1) {
361 ((MethodGroupExpr) e).ReportUsageError ();
368 /// Resolves an expression for LValue assignment
372 /// Currently ResolveLValue wraps DoResolveLValue to perform sanity
373 /// checking and assertion checking on what we expect from Resolve
375 public Expression ResolveLValue (EmitContext ec, Expression right_side, Location loc)
377 int errors = Report.Errors;
378 Expression e = DoResolveLValue (ec, right_side);
381 if (errors == Report.Errors)
382 Report.Error (131, loc, "The left-hand side of an assignment or mutating operation must be a variable, property or indexer");
387 if (e.eclass == ExprClass.Invalid)
388 throw new Exception ("Expression " + e +
389 " ExprClass is Invalid after resolve");
391 if (e.eclass == ExprClass.MethodGroup) {
392 ((MethodGroupExpr) e).ReportUsageError ();
396 if ((e.type == null) && !(e is ConstructedType))
397 throw new Exception ("Expression " + e +
398 " did not set its type after Resolve");
405 /// Emits the code for the expression
409 /// The Emit method is invoked to generate the code
410 /// for the expression.
412 public abstract void Emit (EmitContext ec);
414 public virtual void EmitBranchable (EmitContext ec, Label target, bool onTrue)
417 ec.ig.Emit (onTrue ? OpCodes.Brtrue : OpCodes.Brfalse, target);
421 /// Protected constructor. Only derivate types should
422 /// be able to be created
425 protected Expression ()
427 eclass = ExprClass.Invalid;
432 /// Returns a literalized version of a literal FieldInfo
436 /// The possible return values are:
437 /// IntConstant, UIntConstant
438 /// LongLiteral, ULongConstant
439 /// FloatConstant, DoubleConstant
442 /// The value returned is already resolved.
444 public static Constant Constantify (object v, Type t)
446 if (t == TypeManager.int32_type)
447 return new IntConstant ((int) v);
448 else if (t == TypeManager.uint32_type)
449 return new UIntConstant ((uint) v);
450 else if (t == TypeManager.int64_type)
451 return new LongConstant ((long) v);
452 else if (t == TypeManager.uint64_type)
453 return new ULongConstant ((ulong) v);
454 else if (t == TypeManager.float_type)
455 return new FloatConstant ((float) v);
456 else if (t == TypeManager.double_type)
457 return new DoubleConstant ((double) v);
458 else if (t == TypeManager.string_type)
459 return new StringConstant ((string) v);
460 else if (t == TypeManager.short_type)
461 return new ShortConstant ((short)v);
462 else if (t == TypeManager.ushort_type)
463 return new UShortConstant ((ushort)v);
464 else if (t == TypeManager.sbyte_type)
465 return new SByteConstant (((sbyte)v));
466 else if (t == TypeManager.byte_type)
467 return new ByteConstant ((byte)v);
468 else if (t == TypeManager.char_type)
469 return new CharConstant ((char)v);
470 else if (t == TypeManager.bool_type)
471 return new BoolConstant ((bool) v);
472 else if (t == TypeManager.decimal_type)
473 return new DecimalConstant ((decimal) v);
474 else if (TypeManager.IsEnumType (t)){
475 Type real_type = TypeManager.TypeToCoreType (v.GetType ());
477 real_type = System.Enum.GetUnderlyingType (real_type);
479 Constant e = Constantify (v, real_type);
481 return new EnumConstant (e, t);
482 } else if (v == null && !TypeManager.IsValueType (t))
483 return NullLiteral.Null;
485 throw new Exception ("Unknown type for constant (" + t +
490 /// Returns a fully formed expression after a MemberLookup
492 public static Expression ExprClassFromMemberInfo (EmitContext ec, MemberInfo mi, Location loc)
495 return new EventExpr ((EventInfo) mi, loc);
496 else if (mi is FieldInfo)
497 return new FieldExpr ((FieldInfo) mi, loc);
498 else if (mi is PropertyInfo)
499 return new PropertyExpr (ec, (PropertyInfo) mi, loc);
500 else if (mi is Type){
501 return new TypeExpression ((System.Type) mi, loc);
507 protected static ArrayList almostMatchedMembers = new ArrayList (4);
510 // FIXME: Probably implement a cache for (t,name,current_access_set)?
512 // This code could use some optimizations, but we need to do some
513 // measurements. For example, we could use a delegate to `flag' when
514 // something can not any longer be a method-group (because it is something
518 // If the return value is an Array, then it is an array of
521 // If the return value is an MemberInfo, it is anything, but a Method
525 // FIXME: When calling MemberLookup inside an `Invocation', we should pass
526 // the arguments here and have MemberLookup return only the methods that
527 // match the argument count/type, unlike we are doing now (we delay this
530 // This is so we can catch correctly attempts to invoke instance methods
531 // from a static body (scan for error 120 in ResolveSimpleName).
534 // FIXME: Potential optimization, have a static ArrayList
537 public static Expression MemberLookup (EmitContext ec, Type queried_type, string name,
538 MemberTypes mt, BindingFlags bf, Location loc)
540 return MemberLookup (ec, ec.ContainerType, null, queried_type, name, mt, bf, loc);
544 // Lookup type `queried_type' for code in class `container_type' with a qualifier of
545 // `qualifier_type' or null to lookup members in the current class.
548 public static Expression MemberLookup (EmitContext ec, Type container_type,
549 Type qualifier_type, Type queried_type,
550 string name, MemberTypes mt,
551 BindingFlags bf, Location loc)
553 almostMatchedMembers.Clear ();
555 MemberInfo [] mi = TypeManager.MemberLookup (
556 container_type, qualifier_type, queried_type, mt, bf, name,
557 almostMatchedMembers);
562 int count = mi.Length;
564 if (mi [0] is MethodBase)
565 return new MethodGroupExpr (mi, loc);
570 return ExprClassFromMemberInfo (ec, mi [0], loc);
573 public const MemberTypes AllMemberTypes =
574 MemberTypes.Constructor |
578 MemberTypes.NestedType |
579 MemberTypes.Property;
581 public const BindingFlags AllBindingFlags =
582 BindingFlags.Public |
583 BindingFlags.Static |
584 BindingFlags.Instance;
586 public static Expression MemberLookup (EmitContext ec, Type queried_type,
587 string name, Location loc)
589 return MemberLookup (ec, ec.ContainerType, null, queried_type, name,
590 AllMemberTypes, AllBindingFlags, loc);
593 public static Expression MemberLookup (EmitContext ec, Type qualifier_type,
594 Type queried_type, string name, Location loc)
596 if (ec.ResolvingTypeTree)
597 return MemberLookup (ec, ec.ContainerType, qualifier_type,
598 queried_type, name, MemberTypes.NestedType,
599 AllBindingFlags, loc);
601 return MemberLookup (ec, ec.ContainerType, qualifier_type,
602 queried_type, name, AllMemberTypes,
603 AllBindingFlags, loc);
606 public static Expression MethodLookup (EmitContext ec, Type queried_type,
607 string name, Location loc)
609 return MemberLookup (ec, ec.ContainerType, null, queried_type, name,
610 MemberTypes.Method, AllBindingFlags, loc);
614 /// This is a wrapper for MemberLookup that is not used to "probe", but
615 /// to find a final definition. If the final definition is not found, we
616 /// look for private members and display a useful debugging message if we
619 public static Expression MemberLookupFinal (EmitContext ec, Type qualifier_type,
620 Type queried_type, string name,
623 return MemberLookupFinal (ec, qualifier_type, queried_type, name,
624 AllMemberTypes, AllBindingFlags, loc);
627 public static Expression MemberLookupFinal (EmitContext ec, Type qualifier_type,
628 Type queried_type, string name,
629 MemberTypes mt, BindingFlags bf,
634 int errors = Report.Errors;
636 e = MemberLookup (ec, ec.ContainerType, qualifier_type, queried_type,
639 if (e == null && errors == Report.Errors)
640 // No errors were reported by MemberLookup, but there was an error.
641 MemberLookupFailed (ec, qualifier_type, queried_type, name, null, true, loc);
646 public static void MemberLookupFailed (EmitContext ec, Type qualifier_type,
647 Type queried_type, string name,
648 string class_name, bool complain_if_none_found,
651 if (almostMatchedMembers.Count != 0) {
652 for (int i = 0; i < almostMatchedMembers.Count; ++i) {
653 MemberInfo m = (MemberInfo) almostMatchedMembers [i];
654 for (int j = 0; j < i; ++j) {
655 if (m == almostMatchedMembers [j]) {
663 Type declaring_type = m.DeclaringType;
665 Report.SymbolRelatedToPreviousError (m);
666 if (qualifier_type == null) {
667 Report.Error (38, loc, "Cannot access a nonstatic member of outer type `{0}' via nested type `{1}'",
668 TypeManager.CSharpName (m.DeclaringType),
669 TypeManager.CSharpName (ec.ContainerType));
670 } else if (qualifier_type != ec.ContainerType &&
671 TypeManager.IsNestedFamilyAccessible (ec.ContainerType, declaring_type)) {
672 // Although a derived class can access protected members of
673 // its base class it cannot do so through an instance of the
674 // base class (CS1540). If the qualifier_type is a base of the
675 // ec.ContainerType and the lookup succeeds with the latter one,
676 // then we are in this situation.
677 Report.Error (1540, loc,
678 "Cannot access protected member `{0}' via a qualifier of type `{1}';"
679 + " the qualifier must be of type `{2}' (or derived from it)",
680 TypeManager.GetFullNameSignature (m),
681 TypeManager.CSharpName (qualifier_type),
682 TypeManager.CSharpName (ec.ContainerType));
684 ErrorIsInaccesible (loc, TypeManager.GetFullNameSignature (m));
687 almostMatchedMembers.Clear ();
691 MemberInfo[] lookup = TypeManager.MemberLookup (queried_type, null, queried_type,
692 AllMemberTypes, AllBindingFlags |
693 BindingFlags.NonPublic, name, null);
695 if (lookup == null) {
696 if (!complain_if_none_found)
699 if (class_name != null)
700 Report.Error (103, loc, "The name `{0}' does not exist in the context of `{1}'",
704 117, loc, "`" + TypeManager.CSharpName (queried_type) + "' does not contain a " +
705 "definition for `" + name + "'");
709 if (TypeManager.MemberLookup (queried_type, null, queried_type,
710 AllMemberTypes, AllBindingFlags |
711 BindingFlags.NonPublic, name, null) == null) {
712 if ((lookup.Length == 1) && (lookup [0] is Type)) {
713 Type t = (Type) lookup [0];
715 Report.Error (305, loc,
716 "Using the generic type `{0}' " +
717 "requires {1} type arguments",
718 TypeManager.GetFullName (t),
719 TypeManager.GetNumberOfTypeArguments (t));
724 MemberList ml = TypeManager.FindMembers (qualifier_type, MemberTypes.Constructor,
725 BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly, null, null);
726 if (name == ".ctor" && ml.Count == 0)
728 Report.Error (143, loc, String.Format ("The type `{0}' has no constructors defined", TypeManager.CSharpName (queried_type)));
732 ErrorIsInaccesible (loc, TypeManager.GetFullNameSignature (lookup [0]));
736 /// Returns an expression that can be used to invoke operator true
737 /// on the expression if it exists.
739 static public Expression GetOperatorTrue (EmitContext ec, Expression e, Location loc)
741 return GetOperatorTrueOrFalse (ec, e, true, loc);
745 /// Returns an expression that can be used to invoke operator false
746 /// on the expression if it exists.
748 static public Expression GetOperatorFalse (EmitContext ec, Expression e, Location loc)
750 return GetOperatorTrueOrFalse (ec, e, false, loc);
753 static Expression GetOperatorTrueOrFalse (EmitContext ec, Expression e, bool is_true, Location loc)
756 Expression operator_group;
758 if (TypeManager.IsNullableType (e.Type))
759 return new Nullable.OperatorTrueOrFalse (e, is_true, loc).Resolve (ec);
761 operator_group = MethodLookup (ec, e.Type, is_true ? "op_True" : "op_False", loc);
762 if (operator_group == null)
765 ArrayList arguments = new ArrayList ();
766 arguments.Add (new Argument (e, Argument.AType.Expression));
767 method = Invocation.OverloadResolve (
768 ec, (MethodGroupExpr) operator_group, arguments, false, loc);
773 return new StaticCallExpr ((MethodInfo) method, arguments, loc);
777 /// Resolves the expression `e' into a boolean expression: either through
778 /// an implicit conversion, or through an `operator true' invocation
780 public static Expression ResolveBoolean (EmitContext ec, Expression e, Location loc)
786 if (e.Type == TypeManager.bool_type)
789 Expression converted = Convert.ImplicitConversion (ec, e, TypeManager.bool_type, Location.Null);
791 if (converted != null)
795 // If no implicit conversion to bool exists, try using `operator true'
797 Expression operator_true = Expression.GetOperatorTrue (ec, e, loc);
798 if (operator_true == null){
799 Report.Error (31, loc, "Can not convert the expression to a boolean");
802 return operator_true;
805 public string ExprClassName ()
808 case ExprClass.Invalid:
810 case ExprClass.Value:
812 case ExprClass.Variable:
814 case ExprClass.Namespace:
818 case ExprClass.MethodGroup:
819 return "method group";
820 case ExprClass.PropertyAccess:
821 return "property access";
822 case ExprClass.EventAccess:
823 return "event access";
824 case ExprClass.IndexerAccess:
825 return "indexer access";
826 case ExprClass.Nothing:
829 throw new Exception ("Should not happen");
833 /// Reports that we were expecting `expr' to be of class `expected'
835 public void Error_UnexpectedKind (string expected, Location loc)
837 Report.Error (118, loc,
838 "Expression denotes a `{0}', where a `{1}' was expected", ExprClassName (), expected);
841 public void Error_UnexpectedKind (ResolveFlags flags, Location loc)
843 string [] valid = new string [4];
846 if ((flags & ResolveFlags.VariableOrValue) != 0) {
847 valid [count++] = "variable";
848 valid [count++] = "value";
851 if ((flags & ResolveFlags.Type) != 0)
852 valid [count++] = "type";
854 if ((flags & ResolveFlags.MethodGroup) != 0)
855 valid [count++] = "method group";
858 valid [count++] = "unknown";
860 StringBuilder sb = new StringBuilder (valid [0]);
861 for (int i = 1; i < count - 1; i++) {
863 sb.Append (valid [i]);
866 sb.Append ("' or `");
867 sb.Append (valid [count - 1]);
870 Report.Error (119, loc,
871 "Expression denotes a `{0}', where a `{1}' was expected", ExprClassName (), sb);
874 static public void Error_ConstantValueCannotBeConverted (Location l, string val, Type t)
876 Report.Error (31, l, "Constant value `" + val + "' cannot be converted to " +
877 TypeManager.CSharpName (t));
880 public static void UnsafeError (Location loc)
882 Report.Error (214, loc, "Pointers and fixed size buffers may only be used in an unsafe context");
886 /// Converts the IntConstant, UIntConstant, LongConstant or
887 /// ULongConstant into the integral target_type. Notice
888 /// that we do not return an `Expression' we do return
889 /// a boxed integral type.
891 /// FIXME: Since I added the new constants, we need to
892 /// also support conversions from CharConstant, ByteConstant,
893 /// SByteConstant, UShortConstant, ShortConstant
895 /// This is used by the switch statement, so the domain
896 /// of work is restricted to the literals above, and the
897 /// targets are int32, uint32, char, byte, sbyte, ushort,
898 /// short, uint64 and int64
900 public static object ConvertIntLiteral (Constant c, Type target_type, Location loc)
902 if (!Convert.ImplicitStandardConversionExists (Convert.ConstantEC, c, target_type)){
903 Convert.Error_CannotImplicitConversion (loc, c.Type, target_type);
909 if (c.Type == target_type)
910 return ((Constant) c).GetValue ();
913 // Make into one of the literals we handle, we dont really care
914 // about this value as we will just return a few limited types
916 if (c is EnumConstant)
917 c = ((EnumConstant)c).WidenToCompilerConstant ();
919 if (c is IntConstant){
920 int v = ((IntConstant) c).Value;
922 if (target_type == TypeManager.uint32_type){
925 } else if (target_type == TypeManager.char_type){
926 if (v >= Char.MinValue && v <= Char.MaxValue)
928 } else if (target_type == TypeManager.byte_type){
929 if (v >= Byte.MinValue && v <= Byte.MaxValue)
931 } else if (target_type == TypeManager.sbyte_type){
932 if (v >= SByte.MinValue && v <= SByte.MaxValue)
934 } else if (target_type == TypeManager.short_type){
935 if (v >= Int16.MinValue && v <= UInt16.MaxValue)
937 } else if (target_type == TypeManager.ushort_type){
938 if (v >= UInt16.MinValue && v <= UInt16.MaxValue)
940 } else if (target_type == TypeManager.int64_type)
942 else if (target_type == TypeManager.uint64_type){
948 } else if (c is UIntConstant){
949 uint v = ((UIntConstant) c).Value;
951 if (target_type == TypeManager.int32_type){
952 if (v <= Int32.MaxValue)
954 } else if (target_type == TypeManager.char_type){
955 if (v >= Char.MinValue && v <= Char.MaxValue)
957 } else if (target_type == TypeManager.byte_type){
958 if (v <= Byte.MaxValue)
960 } else if (target_type == TypeManager.sbyte_type){
961 if (v <= SByte.MaxValue)
963 } else if (target_type == TypeManager.short_type){
964 if (v <= UInt16.MaxValue)
966 } else if (target_type == TypeManager.ushort_type){
967 if (v <= UInt16.MaxValue)
969 } else if (target_type == TypeManager.int64_type)
971 else if (target_type == TypeManager.uint64_type)
974 } else if (c is LongConstant){
975 long v = ((LongConstant) c).Value;
977 if (target_type == TypeManager.int32_type){
978 if (v >= UInt32.MinValue && v <= UInt32.MaxValue)
980 } else if (target_type == TypeManager.uint32_type){
981 if (v >= 0 && v <= UInt32.MaxValue)
983 } else if (target_type == TypeManager.char_type){
984 if (v >= Char.MinValue && v <= Char.MaxValue)
986 } else if (target_type == TypeManager.byte_type){
987 if (v >= Byte.MinValue && v <= Byte.MaxValue)
989 } else if (target_type == TypeManager.sbyte_type){
990 if (v >= SByte.MinValue && v <= SByte.MaxValue)
992 } else if (target_type == TypeManager.short_type){
993 if (v >= Int16.MinValue && v <= UInt16.MaxValue)
995 } else if (target_type == TypeManager.ushort_type){
996 if (v >= UInt16.MinValue && v <= UInt16.MaxValue)
998 } else if (target_type == TypeManager.uint64_type){
1003 } else if (c is ULongConstant){
1004 ulong v = ((ULongConstant) c).Value;
1006 if (target_type == TypeManager.int32_type){
1007 if (v <= Int32.MaxValue)
1009 } else if (target_type == TypeManager.uint32_type){
1010 if (v <= UInt32.MaxValue)
1012 } else if (target_type == TypeManager.char_type){
1013 if (v >= Char.MinValue && v <= Char.MaxValue)
1015 } else if (target_type == TypeManager.byte_type){
1016 if (v >= Byte.MinValue && v <= Byte.MaxValue)
1018 } else if (target_type == TypeManager.sbyte_type){
1019 if (v <= (int) SByte.MaxValue)
1021 } else if (target_type == TypeManager.short_type){
1022 if (v <= UInt16.MaxValue)
1024 } else if (target_type == TypeManager.ushort_type){
1025 if (v <= UInt16.MaxValue)
1027 } else if (target_type == TypeManager.int64_type){
1028 if (v <= Int64.MaxValue)
1032 } else if (c is ByteConstant){
1033 byte v = ((ByteConstant) c).Value;
1035 if (target_type == TypeManager.int32_type)
1037 else if (target_type == TypeManager.uint32_type)
1039 else if (target_type == TypeManager.char_type)
1041 else if (target_type == TypeManager.sbyte_type){
1042 if (v <= SByte.MaxValue)
1044 } else if (target_type == TypeManager.short_type)
1046 else if (target_type == TypeManager.ushort_type)
1048 else if (target_type == TypeManager.int64_type)
1050 else if (target_type == TypeManager.uint64_type)
1053 } else if (c is SByteConstant){
1054 sbyte v = ((SByteConstant) c).Value;
1056 if (target_type == TypeManager.int32_type)
1058 else if (target_type == TypeManager.uint32_type){
1061 } else if (target_type == TypeManager.char_type){
1064 } else if (target_type == TypeManager.byte_type){
1067 } else if (target_type == TypeManager.short_type)
1069 else if (target_type == TypeManager.ushort_type){
1072 } else if (target_type == TypeManager.int64_type)
1074 else if (target_type == TypeManager.uint64_type){
1079 } else if (c is ShortConstant){
1080 short v = ((ShortConstant) c).Value;
1082 if (target_type == TypeManager.int32_type){
1084 } else if (target_type == TypeManager.uint32_type){
1087 } else if (target_type == TypeManager.char_type){
1090 } else if (target_type == TypeManager.byte_type){
1091 if (v >= Byte.MinValue && v <= Byte.MaxValue)
1093 } else if (target_type == TypeManager.sbyte_type){
1094 if (v >= SByte.MinValue && v <= SByte.MaxValue)
1096 } else if (target_type == TypeManager.ushort_type){
1099 } else if (target_type == TypeManager.int64_type)
1101 else if (target_type == TypeManager.uint64_type)
1105 } else if (c is UShortConstant){
1106 ushort v = ((UShortConstant) c).Value;
1108 if (target_type == TypeManager.int32_type)
1110 else if (target_type == TypeManager.uint32_type)
1112 else if (target_type == TypeManager.char_type){
1113 if (v >= Char.MinValue && v <= Char.MaxValue)
1115 } else if (target_type == TypeManager.byte_type){
1116 if (v >= Byte.MinValue && v <= Byte.MaxValue)
1118 } else if (target_type == TypeManager.sbyte_type){
1119 if (v <= SByte.MaxValue)
1121 } else if (target_type == TypeManager.short_type){
1122 if (v <= Int16.MaxValue)
1124 } else if (target_type == TypeManager.int64_type)
1126 else if (target_type == TypeManager.uint64_type)
1130 } else if (c is CharConstant){
1131 char v = ((CharConstant) c).Value;
1133 if (target_type == TypeManager.int32_type)
1135 else if (target_type == TypeManager.uint32_type)
1137 else if (target_type == TypeManager.byte_type){
1138 if (v >= Byte.MinValue && v <= Byte.MaxValue)
1140 } else if (target_type == TypeManager.sbyte_type){
1141 if (v <= SByte.MaxValue)
1143 } else if (target_type == TypeManager.short_type){
1144 if (v <= Int16.MaxValue)
1146 } else if (target_type == TypeManager.ushort_type)
1148 else if (target_type == TypeManager.int64_type)
1150 else if (target_type == TypeManager.uint64_type)
1155 Error_ConstantValueCannotBeConverted (loc, s, target_type);
1160 // Load the object from the pointer.
1162 public static void LoadFromPtr (ILGenerator ig, Type t)
1164 if (t == TypeManager.int32_type)
1165 ig.Emit (OpCodes.Ldind_I4);
1166 else if (t == TypeManager.uint32_type)
1167 ig.Emit (OpCodes.Ldind_U4);
1168 else if (t == TypeManager.short_type)
1169 ig.Emit (OpCodes.Ldind_I2);
1170 else if (t == TypeManager.ushort_type)
1171 ig.Emit (OpCodes.Ldind_U2);
1172 else if (t == TypeManager.char_type)
1173 ig.Emit (OpCodes.Ldind_U2);
1174 else if (t == TypeManager.byte_type)
1175 ig.Emit (OpCodes.Ldind_U1);
1176 else if (t == TypeManager.sbyte_type)
1177 ig.Emit (OpCodes.Ldind_I1);
1178 else if (t == TypeManager.uint64_type)
1179 ig.Emit (OpCodes.Ldind_I8);
1180 else if (t == TypeManager.int64_type)
1181 ig.Emit (OpCodes.Ldind_I8);
1182 else if (t == TypeManager.float_type)
1183 ig.Emit (OpCodes.Ldind_R4);
1184 else if (t == TypeManager.double_type)
1185 ig.Emit (OpCodes.Ldind_R8);
1186 else if (t == TypeManager.bool_type)
1187 ig.Emit (OpCodes.Ldind_I1);
1188 else if (t == TypeManager.intptr_type)
1189 ig.Emit (OpCodes.Ldind_I);
1190 else if (TypeManager.IsEnumType (t)) {
1191 if (t == TypeManager.enum_type)
1192 ig.Emit (OpCodes.Ldind_Ref);
1194 LoadFromPtr (ig, TypeManager.EnumToUnderlying (t));
1195 } else if (t.IsValueType || t.IsGenericParameter)
1196 ig.Emit (OpCodes.Ldobj, t);
1197 else if (t.IsPointer)
1198 ig.Emit (OpCodes.Ldind_I);
1200 ig.Emit (OpCodes.Ldind_Ref);
1204 // The stack contains the pointer and the value of type `type'
1206 public static void StoreFromPtr (ILGenerator ig, Type type)
1208 if (TypeManager.IsEnumType (type))
1209 type = TypeManager.EnumToUnderlying (type);
1210 if (type == TypeManager.int32_type || type == TypeManager.uint32_type)
1211 ig.Emit (OpCodes.Stind_I4);
1212 else if (type == TypeManager.int64_type || type == TypeManager.uint64_type)
1213 ig.Emit (OpCodes.Stind_I8);
1214 else if (type == TypeManager.char_type || type == TypeManager.short_type ||
1215 type == TypeManager.ushort_type)
1216 ig.Emit (OpCodes.Stind_I2);
1217 else if (type == TypeManager.float_type)
1218 ig.Emit (OpCodes.Stind_R4);
1219 else if (type == TypeManager.double_type)
1220 ig.Emit (OpCodes.Stind_R8);
1221 else if (type == TypeManager.byte_type || type == TypeManager.sbyte_type ||
1222 type == TypeManager.bool_type)
1223 ig.Emit (OpCodes.Stind_I1);
1224 else if (type == TypeManager.intptr_type)
1225 ig.Emit (OpCodes.Stind_I);
1226 else if (type.IsValueType || type.IsGenericParameter)
1227 ig.Emit (OpCodes.Stobj, type);
1229 ig.Emit (OpCodes.Stind_Ref);
1233 // Returns the size of type `t' if known, otherwise, 0
1235 public static int GetTypeSize (Type t)
1237 t = TypeManager.TypeToCoreType (t);
1238 if (t == TypeManager.int32_type ||
1239 t == TypeManager.uint32_type ||
1240 t == TypeManager.float_type)
1242 else if (t == TypeManager.int64_type ||
1243 t == TypeManager.uint64_type ||
1244 t == TypeManager.double_type)
1246 else if (t == TypeManager.byte_type ||
1247 t == TypeManager.sbyte_type ||
1248 t == TypeManager.bool_type)
1250 else if (t == TypeManager.short_type ||
1251 t == TypeManager.char_type ||
1252 t == TypeManager.ushort_type)
1254 else if (t == TypeManager.decimal_type)
1260 public static void Error_NegativeArrayIndex (Location loc)
1262 Report.Error (248, loc, "Cannot create an array with a negative size");
1265 protected void Error_CannotCallAbstractBase (string name)
1267 Report.Error (205, loc, "Cannot call an abstract base member `{0}'", name);
1271 // Converts `source' to an int, uint, long or ulong.
1273 public Expression ExpressionToArrayArgument (EmitContext ec, Expression source, Location loc)
1277 bool old_checked = ec.CheckState;
1278 ec.CheckState = true;
1280 target = Convert.ImplicitConversion (ec, source, TypeManager.int32_type, loc);
1281 if (target == null){
1282 target = Convert.ImplicitConversion (ec, source, TypeManager.uint32_type, loc);
1283 if (target == null){
1284 target = Convert.ImplicitConversion (ec, source, TypeManager.int64_type, loc);
1285 if (target == null){
1286 target = Convert.ImplicitConversion (ec, source, TypeManager.uint64_type, loc);
1288 Convert.Error_CannotImplicitConversion (loc, source.Type, TypeManager.int32_type);
1292 ec.CheckState = old_checked;
1295 // Only positive constants are allowed at compile time
1297 if (target is Constant){
1298 if (target is IntConstant){
1299 if (((IntConstant) target).Value < 0){
1300 Error_NegativeArrayIndex (loc);
1305 if (target is LongConstant){
1306 if (((LongConstant) target).Value < 0){
1307 Error_NegativeArrayIndex (loc);
1320 /// This is just a base class for expressions that can
1321 /// appear on statements (invocations, object creation,
1322 /// assignments, post/pre increment and decrement). The idea
1323 /// being that they would support an extra Emition interface that
1324 /// does not leave a result on the stack.
1326 public abstract class ExpressionStatement : Expression {
1328 public virtual ExpressionStatement ResolveStatement (EmitContext ec)
1330 Expression e = Resolve (ec);
1334 ExpressionStatement es = e as ExpressionStatement;
1336 Error (201, "Only assignment, call, increment, decrement and new object " +
1337 "expressions can be used as a statement");
1343 /// Requests the expression to be emitted in a `statement'
1344 /// context. This means that no new value is left on the
1345 /// stack after invoking this method (constrasted with
1346 /// Emit that will always leave a value on the stack).
1348 public abstract void EmitStatement (EmitContext ec);
1352 /// This kind of cast is used to encapsulate the child
1353 /// whose type is child.Type into an expression that is
1354 /// reported to return "return_type". This is used to encapsulate
1355 /// expressions which have compatible types, but need to be dealt
1356 /// at higher levels with.
1358 /// For example, a "byte" expression could be encapsulated in one
1359 /// of these as an "unsigned int". The type for the expression
1360 /// would be "unsigned int".
1363 public class EmptyCast : Expression {
1364 protected Expression child;
1366 public Expression Child {
1372 public EmptyCast (Expression child, Type return_type)
1374 eclass = child.eclass;
1375 loc = child.Location;
1380 public override Expression DoResolve (EmitContext ec)
1382 // This should never be invoked, we are born in fully
1383 // initialized state.
1388 public override void Emit (EmitContext ec)
1394 /// This is a numeric cast to a Decimal
1396 public class CastToDecimal : EmptyCast {
1398 MethodInfo conversion_operator;
1400 public CastToDecimal (EmitContext ec, Expression child)
1401 : this (ec, child, false)
1405 public CastToDecimal (EmitContext ec, Expression child, bool find_explicit)
1406 : base (child, TypeManager.decimal_type)
1408 conversion_operator = GetConversionOperator (ec, find_explicit);
1410 if (conversion_operator == null)
1411 Convert.Error_CannotImplicitConversion (loc, child.Type, type);
1414 // Returns the implicit operator that converts from
1415 // 'child.Type' to System.Decimal.
1416 MethodInfo GetConversionOperator (EmitContext ec, bool find_explicit)
1418 string operator_name = "op_Implicit";
1421 operator_name = "op_Explicit";
1423 MethodGroupExpr opers = Expression.MethodLookup (
1424 ec, type, operator_name, loc) as MethodGroupExpr;
1427 Convert.Error_CannotImplicitConversion (loc, child.Type, type);
1429 foreach (MethodInfo oper in opers.Methods) {
1430 ParameterData pd = TypeManager.GetParameterData (oper);
1432 if (pd.ParameterType (0) == child.Type && oper.ReturnType == type)
1438 public override void Emit (EmitContext ec)
1440 ILGenerator ig = ec.ig;
1443 ig.Emit (OpCodes.Call, conversion_operator);
1447 /// This is an explicit numeric cast from a Decimal
1449 public class CastFromDecimal : EmptyCast
1451 MethodInfo conversion_operator;
1452 public CastFromDecimal (EmitContext ec, Expression child, Type return_type)
1453 : base (child, return_type)
1455 if (child.Type != TypeManager.decimal_type)
1456 throw new InternalErrorException (
1457 "The expected type is Decimal, instead it is " + child.Type.FullName);
1459 conversion_operator = GetConversionOperator (ec);
1460 if (conversion_operator == null)
1461 Convert.Error_CannotImplicitConversion (loc, child.Type, type);
1464 // Returns the explicit operator that converts from an
1465 // express of type System.Decimal to 'type'.
1466 MethodInfo GetConversionOperator (EmitContext ec)
1468 MethodGroupExpr opers = Expression.MethodLookup (
1469 ec, child.Type, "op_Explicit", loc) as MethodGroupExpr;
1472 Convert.Error_CannotImplicitConversion (loc, child.Type, type);
1474 foreach (MethodInfo oper in opers.Methods) {
1475 ParameterData pd = TypeManager.GetParameterData (oper);
1477 if (pd.ParameterType (0) == child.Type && oper.ReturnType == type)
1483 public override void Emit (EmitContext ec)
1485 ILGenerator ig = ec.ig;
1488 ig.Emit (OpCodes.Call, conversion_operator);
1493 // We need to special case this since an empty cast of
1494 // a NullLiteral is still a Constant
1496 public class NullCast : Constant {
1497 protected Expression child;
1499 public NullCast (Expression child, Type return_type)
1501 eclass = child.eclass;
1506 override public string AsString ()
1511 public override object GetValue ()
1516 public override Expression DoResolve (EmitContext ec)
1518 // This should never be invoked, we are born in fully
1519 // initialized state.
1524 public override void Emit (EmitContext ec)
1529 public override bool IsDefaultValue {
1531 throw new NotImplementedException ();
1535 public override bool IsNegative {
1544 /// This class is used to wrap literals which belong inside Enums
1546 public class EnumConstant : Constant {
1547 public Constant Child;
1549 public EnumConstant (Constant child, Type enum_type)
1551 eclass = child.eclass;
1556 public override Expression DoResolve (EmitContext ec)
1558 // This should never be invoked, we are born in fully
1559 // initialized state.
1564 public override void Emit (EmitContext ec)
1569 public override object GetValue ()
1571 return Child.GetValue ();
1574 public object GetValueAsEnumType ()
1576 return System.Enum.ToObject (type, Child.GetValue ());
1580 // Converts from one of the valid underlying types for an enumeration
1581 // (int32, uint32, int64, uint64, short, ushort, byte, sbyte) to
1582 // one of the internal compiler literals: Int/UInt/Long/ULong Literals.
1584 public Constant WidenToCompilerConstant ()
1586 Type t = TypeManager.EnumToUnderlying (Child.Type);
1587 object v = ((Constant) Child).GetValue ();;
1589 if (t == TypeManager.int32_type)
1590 return new IntConstant ((int) v);
1591 if (t == TypeManager.uint32_type)
1592 return new UIntConstant ((uint) v);
1593 if (t == TypeManager.int64_type)
1594 return new LongConstant ((long) v);
1595 if (t == TypeManager.uint64_type)
1596 return new ULongConstant ((ulong) v);
1597 if (t == TypeManager.short_type)
1598 return new ShortConstant ((short) v);
1599 if (t == TypeManager.ushort_type)
1600 return new UShortConstant ((ushort) v);
1601 if (t == TypeManager.byte_type)
1602 return new ByteConstant ((byte) v);
1603 if (t == TypeManager.sbyte_type)
1604 return new SByteConstant ((sbyte) v);
1606 throw new Exception ("Invalid enumeration underlying type: " + t);
1610 // Extracts the value in the enumeration on its native representation
1612 public object GetPlainValue ()
1614 Type t = TypeManager.EnumToUnderlying (Child.Type);
1615 object v = ((Constant) Child).GetValue ();;
1617 if (t == TypeManager.int32_type)
1619 if (t == TypeManager.uint32_type)
1621 if (t == TypeManager.int64_type)
1623 if (t == TypeManager.uint64_type)
1625 if (t == TypeManager.short_type)
1627 if (t == TypeManager.ushort_type)
1629 if (t == TypeManager.byte_type)
1631 if (t == TypeManager.sbyte_type)
1637 public override string AsString ()
1639 return Child.AsString ();
1642 public override DoubleConstant ConvertToDouble ()
1644 return Child.ConvertToDouble ();
1647 public override FloatConstant ConvertToFloat ()
1649 return Child.ConvertToFloat ();
1652 public override ULongConstant ConvertToULong ()
1654 return Child.ConvertToULong ();
1657 public override LongConstant ConvertToLong ()
1659 return Child.ConvertToLong ();
1662 public override UIntConstant ConvertToUInt ()
1664 return Child.ConvertToUInt ();
1667 public override IntConstant ConvertToInt ()
1669 return Child.ConvertToInt ();
1672 public override bool IsDefaultValue {
1674 return Child.IsDefaultValue;
1678 public override bool IsZeroInteger {
1679 get { return Child.IsZeroInteger; }
1682 public override bool IsNegative {
1684 return Child.IsNegative;
1690 /// This kind of cast is used to encapsulate Value Types in objects.
1692 /// The effect of it is to box the value type emitted by the previous
1695 public class BoxedCast : EmptyCast {
1697 public BoxedCast (Expression expr)
1698 : base (expr, TypeManager.object_type)
1700 eclass = ExprClass.Value;
1703 public BoxedCast (Expression expr, Type target_type)
1704 : base (expr, target_type)
1706 eclass = ExprClass.Value;
1709 public override Expression DoResolve (EmitContext ec)
1711 // This should never be invoked, we are born in fully
1712 // initialized state.
1717 public override void Emit (EmitContext ec)
1721 ec.ig.Emit (OpCodes.Box, child.Type);
1725 public class UnboxCast : EmptyCast {
1726 public UnboxCast (Expression expr, Type return_type)
1727 : base (expr, return_type)
1731 public override Expression DoResolve (EmitContext ec)
1733 // This should never be invoked, we are born in fully
1734 // initialized state.
1739 public override void Emit (EmitContext ec)
1742 ILGenerator ig = ec.ig;
1745 if (t.IsGenericParameter)
1746 ig.Emit (OpCodes.Unbox_Any, t);
1748 ig.Emit (OpCodes.Unbox, t);
1750 LoadFromPtr (ig, t);
1756 /// This is used to perform explicit numeric conversions.
1758 /// Explicit numeric conversions might trigger exceptions in a checked
1759 /// context, so they should generate the conv.ovf opcodes instead of
1762 public class ConvCast : EmptyCast {
1763 public enum Mode : byte {
1764 I1_U1, I1_U2, I1_U4, I1_U8, I1_CH,
1766 I2_I1, I2_U1, I2_U2, I2_U4, I2_U8, I2_CH,
1767 U2_I1, U2_U1, U2_I2, U2_CH,
1768 I4_I1, I4_U1, I4_I2, I4_U2, I4_U4, I4_U8, I4_CH,
1769 U4_I1, U4_U1, U4_I2, U4_U2, U4_I4, U4_CH,
1770 I8_I1, I8_U1, I8_I2, I8_U2, I8_I4, I8_U4, I8_U8, I8_CH,
1771 U8_I1, U8_U1, U8_I2, U8_U2, U8_I4, U8_U4, U8_I8, U8_CH,
1772 CH_I1, CH_U1, CH_I2,
1773 R4_I1, R4_U1, R4_I2, R4_U2, R4_I4, R4_U4, R4_I8, R4_U8, R4_CH,
1774 R8_I1, R8_U1, R8_I2, R8_U2, R8_I4, R8_U4, R8_I8, R8_U8, R8_CH, R8_R4
1780 public ConvCast (EmitContext ec, Expression child, Type return_type, Mode m)
1781 : base (child, return_type)
1783 checked_state = ec.CheckState;
1787 public override Expression DoResolve (EmitContext ec)
1789 // This should never be invoked, we are born in fully
1790 // initialized state.
1795 public override string ToString ()
1797 return String.Format ("ConvCast ({0}, {1})", mode, child);
1800 public override void Emit (EmitContext ec)
1802 ILGenerator ig = ec.ig;
1808 case Mode.I1_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1809 case Mode.I1_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1810 case Mode.I1_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1811 case Mode.I1_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1812 case Mode.I1_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1814 case Mode.U1_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1815 case Mode.U1_CH: /* nothing */ break;
1817 case Mode.I2_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1818 case Mode.I2_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1819 case Mode.I2_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1820 case Mode.I2_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1821 case Mode.I2_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1822 case Mode.I2_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1824 case Mode.U2_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1825 case Mode.U2_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
1826 case Mode.U2_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
1827 case Mode.U2_CH: /* nothing */ break;
1829 case Mode.I4_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1830 case Mode.I4_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1831 case Mode.I4_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
1832 case Mode.I4_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1833 case Mode.I4_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1834 case Mode.I4_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1835 case Mode.I4_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1837 case Mode.U4_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1838 case Mode.U4_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
1839 case Mode.U4_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
1840 case Mode.U4_U2: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
1841 case Mode.U4_I4: ig.Emit (OpCodes.Conv_Ovf_I4_Un); break;
1842 case Mode.U4_CH: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
1844 case Mode.I8_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1845 case Mode.I8_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1846 case Mode.I8_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
1847 case Mode.I8_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1848 case Mode.I8_I4: ig.Emit (OpCodes.Conv_Ovf_I4); break;
1849 case Mode.I8_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1850 case Mode.I8_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1851 case Mode.I8_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1853 case Mode.U8_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1854 case Mode.U8_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
1855 case Mode.U8_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
1856 case Mode.U8_U2: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
1857 case Mode.U8_I4: ig.Emit (OpCodes.Conv_Ovf_I4_Un); break;
1858 case Mode.U8_U4: ig.Emit (OpCodes.Conv_Ovf_U4_Un); break;
1859 case Mode.U8_I8: ig.Emit (OpCodes.Conv_Ovf_I8_Un); break;
1860 case Mode.U8_CH: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
1862 case Mode.CH_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1863 case Mode.CH_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
1864 case Mode.CH_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
1866 case Mode.R4_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1867 case Mode.R4_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1868 case Mode.R4_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
1869 case Mode.R4_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1870 case Mode.R4_I4: ig.Emit (OpCodes.Conv_Ovf_I4); break;
1871 case Mode.R4_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1872 case Mode.R4_I8: ig.Emit (OpCodes.Conv_Ovf_I8); break;
1873 case Mode.R4_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1874 case Mode.R4_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1876 case Mode.R8_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1877 case Mode.R8_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1878 case Mode.R8_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
1879 case Mode.R8_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1880 case Mode.R8_I4: ig.Emit (OpCodes.Conv_Ovf_I4); break;
1881 case Mode.R8_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1882 case Mode.R8_I8: ig.Emit (OpCodes.Conv_Ovf_I8); break;
1883 case Mode.R8_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1884 case Mode.R8_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1885 case Mode.R8_R4: ig.Emit (OpCodes.Conv_R4); break;
1889 case Mode.I1_U1: ig.Emit (OpCodes.Conv_U1); break;
1890 case Mode.I1_U2: ig.Emit (OpCodes.Conv_U2); break;
1891 case Mode.I1_U4: ig.Emit (OpCodes.Conv_U4); break;
1892 case Mode.I1_U8: ig.Emit (OpCodes.Conv_I8); break;
1893 case Mode.I1_CH: ig.Emit (OpCodes.Conv_U2); break;
1895 case Mode.U1_I1: ig.Emit (OpCodes.Conv_I1); break;
1896 case Mode.U1_CH: ig.Emit (OpCodes.Conv_U2); break;
1898 case Mode.I2_I1: ig.Emit (OpCodes.Conv_I1); break;
1899 case Mode.I2_U1: ig.Emit (OpCodes.Conv_U1); break;
1900 case Mode.I2_U2: ig.Emit (OpCodes.Conv_U2); break;
1901 case Mode.I2_U4: ig.Emit (OpCodes.Conv_U4); break;
1902 case Mode.I2_U8: ig.Emit (OpCodes.Conv_I8); break;
1903 case Mode.I2_CH: ig.Emit (OpCodes.Conv_U2); break;
1905 case Mode.U2_I1: ig.Emit (OpCodes.Conv_I1); break;
1906 case Mode.U2_U1: ig.Emit (OpCodes.Conv_U1); break;
1907 case Mode.U2_I2: ig.Emit (OpCodes.Conv_I2); break;
1908 case Mode.U2_CH: /* nothing */ break;
1910 case Mode.I4_I1: ig.Emit (OpCodes.Conv_I1); break;
1911 case Mode.I4_U1: ig.Emit (OpCodes.Conv_U1); break;
1912 case Mode.I4_I2: ig.Emit (OpCodes.Conv_I2); break;
1913 case Mode.I4_U4: /* nothing */ break;
1914 case Mode.I4_U2: ig.Emit (OpCodes.Conv_U2); break;
1915 case Mode.I4_U8: ig.Emit (OpCodes.Conv_I8); break;
1916 case Mode.I4_CH: ig.Emit (OpCodes.Conv_U2); break;
1918 case Mode.U4_I1: ig.Emit (OpCodes.Conv_I1); break;
1919 case Mode.U4_U1: ig.Emit (OpCodes.Conv_U1); break;
1920 case Mode.U4_I2: ig.Emit (OpCodes.Conv_I2); break;
1921 case Mode.U4_U2: ig.Emit (OpCodes.Conv_U2); break;
1922 case Mode.U4_I4: /* nothing */ break;
1923 case Mode.U4_CH: ig.Emit (OpCodes.Conv_U2); break;
1925 case Mode.I8_I1: ig.Emit (OpCodes.Conv_I1); break;
1926 case Mode.I8_U1: ig.Emit (OpCodes.Conv_U1); break;
1927 case Mode.I8_I2: ig.Emit (OpCodes.Conv_I2); break;
1928 case Mode.I8_U2: ig.Emit (OpCodes.Conv_U2); break;
1929 case Mode.I8_I4: ig.Emit (OpCodes.Conv_I4); break;
1930 case Mode.I8_U4: ig.Emit (OpCodes.Conv_U4); break;
1931 case Mode.I8_U8: /* nothing */ break;
1932 case Mode.I8_CH: ig.Emit (OpCodes.Conv_U2); break;
1934 case Mode.U8_I1: ig.Emit (OpCodes.Conv_I1); break;
1935 case Mode.U8_U1: ig.Emit (OpCodes.Conv_U1); break;
1936 case Mode.U8_I2: ig.Emit (OpCodes.Conv_I2); break;
1937 case Mode.U8_U2: ig.Emit (OpCodes.Conv_U2); break;
1938 case Mode.U8_I4: ig.Emit (OpCodes.Conv_I4); break;
1939 case Mode.U8_U4: ig.Emit (OpCodes.Conv_U4); break;
1940 case Mode.U8_I8: /* nothing */ break;
1941 case Mode.U8_CH: ig.Emit (OpCodes.Conv_U2); break;
1943 case Mode.CH_I1: ig.Emit (OpCodes.Conv_I1); break;
1944 case Mode.CH_U1: ig.Emit (OpCodes.Conv_U1); break;
1945 case Mode.CH_I2: ig.Emit (OpCodes.Conv_I2); break;
1947 case Mode.R4_I1: ig.Emit (OpCodes.Conv_I1); break;
1948 case Mode.R4_U1: ig.Emit (OpCodes.Conv_U1); break;
1949 case Mode.R4_I2: ig.Emit (OpCodes.Conv_I2); break;
1950 case Mode.R4_U2: ig.Emit (OpCodes.Conv_U2); break;
1951 case Mode.R4_I4: ig.Emit (OpCodes.Conv_I4); break;
1952 case Mode.R4_U4: ig.Emit (OpCodes.Conv_U4); break;
1953 case Mode.R4_I8: ig.Emit (OpCodes.Conv_I8); break;
1954 case Mode.R4_U8: ig.Emit (OpCodes.Conv_U8); break;
1955 case Mode.R4_CH: ig.Emit (OpCodes.Conv_U2); break;
1957 case Mode.R8_I1: ig.Emit (OpCodes.Conv_I1); break;
1958 case Mode.R8_U1: ig.Emit (OpCodes.Conv_U1); break;
1959 case Mode.R8_I2: ig.Emit (OpCodes.Conv_I2); break;
1960 case Mode.R8_U2: ig.Emit (OpCodes.Conv_U2); break;
1961 case Mode.R8_I4: ig.Emit (OpCodes.Conv_I4); break;
1962 case Mode.R8_U4: ig.Emit (OpCodes.Conv_U4); break;
1963 case Mode.R8_I8: ig.Emit (OpCodes.Conv_I8); break;
1964 case Mode.R8_U8: ig.Emit (OpCodes.Conv_U8); break;
1965 case Mode.R8_CH: ig.Emit (OpCodes.Conv_U2); break;
1966 case Mode.R8_R4: ig.Emit (OpCodes.Conv_R4); break;
1972 public class OpcodeCast : EmptyCast {
1976 public OpcodeCast (Expression child, Type return_type, OpCode op)
1977 : base (child, return_type)
1981 second_valid = false;
1984 public OpcodeCast (Expression child, Type return_type, OpCode op, OpCode op2)
1985 : base (child, return_type)
1990 second_valid = true;
1993 public override Expression DoResolve (EmitContext ec)
1995 // This should never be invoked, we are born in fully
1996 // initialized state.
2001 public override void Emit (EmitContext ec)
2012 /// This kind of cast is used to encapsulate a child and cast it
2013 /// to the class requested
2015 public class ClassCast : EmptyCast {
2016 public ClassCast (Expression child, Type return_type)
2017 : base (child, return_type)
2022 public override Expression DoResolve (EmitContext ec)
2024 // This should never be invoked, we are born in fully
2025 // initialized state.
2030 public override void Emit (EmitContext ec)
2034 if (child.Type.IsGenericParameter)
2035 ec.ig.Emit (OpCodes.Box, child.Type);
2037 if (type.IsGenericParameter)
2038 ec.ig.Emit (OpCodes.Unbox_Any, type);
2040 ec.ig.Emit (OpCodes.Castclass, type);
2045 /// SimpleName expressions are formed of a single word and only happen at the beginning
2046 /// of a dotted-name.
2048 public class SimpleName : Expression {
2050 public readonly TypeArguments Arguments;
2053 public SimpleName (string name, Location l)
2059 public SimpleName (string name, TypeArguments args, Location l)
2066 public SimpleName (string name, TypeParameter[] type_params, Location l)
2071 Arguments = new TypeArguments (l);
2072 foreach (TypeParameter type_param in type_params)
2073 Arguments.Add (new TypeParameterExpr (type_param, l));
2076 public static string RemoveGenericArity (string name)
2079 StringBuilder sb = new StringBuilder ();
2080 while (start < name.Length) {
2081 int pos = name.IndexOf ('`', start);
2083 sb.Append (name.Substring (start));
2087 sb.Append (name.Substring (start, pos-start));
2090 while ((pos < name.Length) && Char.IsNumber (name [pos]))
2096 return sb.ToString ();
2099 public SimpleName GetMethodGroup ()
2101 return new SimpleName (RemoveGenericArity (Name), Arguments, loc);
2104 public static void Error_ObjectRefRequired (EmitContext ec, Location l, string name)
2106 if (ec.IsFieldInitializer)
2107 Report.Error (236, l,
2108 "A field initializer cannot reference the nonstatic field, method, or property `{0}'",
2111 if (name.LastIndexOf ('.') > 0)
2112 name = name.Substring (name.LastIndexOf ('.') + 1);
2115 120, l, "`{0}': An object reference is required for the nonstatic field, method or property",
2120 public bool IdenticalNameAndTypeName (EmitContext ec, Expression resolved_to, Location loc)
2122 return resolved_to != null && resolved_to.Type != null &&
2123 resolved_to.Type.Name == Name &&
2124 (ec.DeclSpace.LookupType (Name, loc, /* ignore_cs0104 = */ true) != null);
2127 public override Expression DoResolve (EmitContext ec)
2129 return SimpleNameResolve (ec, null, false);
2132 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
2134 return SimpleNameResolve (ec, right_side, false);
2138 public Expression DoResolve (EmitContext ec, bool intermediate)
2140 return SimpleNameResolve (ec, null, intermediate);
2143 private bool IsNestedChild (Type t, Type parent)
2148 while (parent != null) {
2149 if (parent.IsGenericInstance)
2150 parent = parent.GetGenericTypeDefinition ();
2152 if (TypeManager.IsNestedChildOf (t, parent))
2155 parent = parent.BaseType;
2161 FullNamedExpression ResolveNested (EmitContext ec, Type t)
2163 if (!t.IsGenericTypeDefinition)
2166 DeclSpace ds = ec.DeclSpace;
2167 while (ds != null) {
2168 if (IsNestedChild (t, ds.TypeBuilder))
2177 Type[] gen_params = t.GetGenericArguments ();
2179 int arg_count = Arguments != null ? Arguments.Count : 0;
2181 for (; (ds != null) && ds.IsGeneric; ds = ds.Parent) {
2182 if (arg_count + ds.CountTypeParameters == gen_params.Length) {
2183 TypeArguments new_args = new TypeArguments (loc);
2184 foreach (TypeParameter param in ds.TypeParameters)
2185 new_args.Add (new TypeParameterExpr (param, loc));
2187 if (Arguments != null)
2188 new_args.Add (Arguments);
2190 return new ConstructedType (t, new_args, loc);
2197 public override FullNamedExpression ResolveAsTypeStep (EmitContext ec)
2199 FullNamedExpression dt = ec.DeclSpace.LookupGeneric (Name, loc);
2201 return dt.ResolveAsTypeStep (ec);
2203 int errors = Report.Errors;
2204 dt = ec.DeclSpace.LookupType (Name, loc, /*ignore_cs0104=*/ false);
2205 if (Report.Errors != errors)
2208 if ((dt == null) || (dt.Type == null))
2211 FullNamedExpression nested = ResolveNested (ec, dt.Type);
2213 return nested.ResolveAsTypeStep (ec);
2215 if (Arguments != null) {
2216 ConstructedType ct = new ConstructedType (dt, Arguments, loc);
2217 return ct.ResolveAsTypeStep (ec);
2223 Expression SimpleNameResolve (EmitContext ec, Expression right_side, bool intermediate)
2229 Expression e = DoSimpleNameResolve (ec, right_side, intermediate);
2233 if (ec.CurrentBlock == null || ec.CurrentBlock.CheckInvariantMeaningInBlock (Name, e, Location))
2240 /// 7.5.2: Simple Names.
2242 /// Local Variables and Parameters are handled at
2243 /// parse time, so they never occur as SimpleNames.
2245 /// The `intermediate' flag is used by MemberAccess only
2246 /// and it is used to inform us that it is ok for us to
2247 /// avoid the static check, because MemberAccess might end
2248 /// up resolving the Name as a Type name and the access as
2249 /// a static type access.
2251 /// ie: Type Type; .... { Type.GetType (""); }
2253 /// Type is both an instance variable and a Type; Type.GetType
2254 /// is the static method not an instance method of type.
2256 Expression DoSimpleNameResolve (EmitContext ec, Expression right_side, bool intermediate)
2258 Expression e = null;
2261 // Stage 1: Performed by the parser (binding to locals or parameters).
2263 Block current_block = ec.CurrentBlock;
2264 if (current_block != null){
2265 LocalInfo vi = current_block.GetLocalInfo (Name);
2269 var = new LocalVariableReference (ec.CurrentBlock, Name, loc);
2271 if (right_side != null)
2272 return var.ResolveLValue (ec, right_side, loc);
2274 return var.Resolve (ec);
2277 ParameterReference pref = current_block.Toplevel.GetParameterReference (Name, loc);
2279 if (right_side != null)
2280 return pref.ResolveLValue (ec, right_side, loc);
2282 return pref.Resolve (ec);
2287 // Stage 2: Lookup members
2290 DeclSpace lookup_ds = ec.DeclSpace;
2291 Type almost_matched_type = null;
2292 ArrayList almost_matched = null;
2294 if (lookup_ds.TypeBuilder == null)
2297 e = MemberLookup (ec, lookup_ds.TypeBuilder, Name, loc);
2301 if (almost_matched == null && almostMatchedMembers.Count > 0) {
2302 almost_matched_type = lookup_ds.TypeBuilder;
2303 almost_matched = (ArrayList) almostMatchedMembers.Clone ();
2306 lookup_ds =lookup_ds.Parent;
2307 } while (lookup_ds != null);
2309 if (e == null && ec.ContainerType != null)
2310 e = MemberLookup (ec, ec.ContainerType, Name, loc);
2313 if (almost_matched == null && almostMatchedMembers.Count > 0) {
2314 almost_matched_type = ec.ContainerType;
2315 almost_matched = (ArrayList) almostMatchedMembers.Clone ();
2317 e = ResolveAsTypeStep (ec);
2321 if (almost_matched != null)
2322 almostMatchedMembers = almost_matched;
2323 if (almost_matched_type == null)
2324 almost_matched_type = ec.ContainerType;
2325 MemberLookupFailed (ec, null, almost_matched_type, ((SimpleName) this).Name, ec.DeclSpace.Name, true, loc);
2332 if (e is MemberExpr) {
2333 MemberExpr me = (MemberExpr) e;
2336 if (me.IsInstance) {
2337 if (ec.IsStatic || ec.IsFieldInitializer) {
2339 // Note that an MemberExpr can be both IsInstance and IsStatic.
2340 // An unresolved MethodGroupExpr can contain both kinds of methods
2341 // and each predicate is true if the MethodGroupExpr contains
2342 // at least one of that kind of method.
2346 (!intermediate || !IdenticalNameAndTypeName (ec, me, loc))) {
2347 Error_ObjectRefRequired (ec, loc, me.GetSignatureForError ());
2352 // Pass the buck to MemberAccess and Invocation.
2354 left = EmptyExpression.Null;
2356 left = ec.GetThis (loc);
2359 left = new TypeExpression (ec.ContainerType, loc);
2362 e = me.ResolveMemberAccess (ec, left, loc, null);
2366 me = e as MemberExpr;
2370 if (Arguments != null) {
2371 MethodGroupExpr mg = me as MethodGroupExpr;
2375 return mg.ResolveGeneric (ec, Arguments);
2379 TypeManager.IsNestedFamilyAccessible (me.InstanceExpression.Type, me.DeclaringType) &&
2380 me.InstanceExpression.Type != me.DeclaringType &&
2381 !TypeManager.IsFamilyAccessible (me.InstanceExpression.Type, me.DeclaringType) &&
2382 (!intermediate || !IdenticalNameAndTypeName (ec, e, loc))) {
2383 Report.Error (38, loc, "Cannot access a nonstatic member of outer type `{0}' via nested type `{1}'",
2384 TypeManager.CSharpName (me.DeclaringType), TypeManager.CSharpName (me.InstanceExpression.Type));
2388 return (right_side != null)
2389 ? me.DoResolveLValue (ec, right_side)
2390 : me.DoResolve (ec);
2396 public override void Emit (EmitContext ec)
2399 // If this is ever reached, then we failed to
2400 // find the name as a namespace
2403 Error (103, "The name `" + Name +
2404 "' does not exist in the class `" +
2405 ec.DeclSpace.Name + "'");
2408 public override string ToString ()
2413 public override string GetSignatureForError ()
2420 /// Represents a namespace or a type. The name of the class was inspired by
2421 /// section 10.8.1 (Fully Qualified Names).
2423 public abstract class FullNamedExpression : Expression {
2424 public override FullNamedExpression ResolveAsTypeStep (EmitContext ec)
2429 public abstract string FullName {
2435 /// Fully resolved expression that evaluates to a type
2437 public abstract class TypeExpr : FullNamedExpression {
2438 override public FullNamedExpression ResolveAsTypeStep (EmitContext ec)
2440 TypeExpr t = DoResolveAsTypeStep (ec);
2444 eclass = ExprClass.Type;
2448 override public Expression DoResolve (EmitContext ec)
2450 return ResolveAsTypeTerminal (ec);
2453 override public void Emit (EmitContext ec)
2455 throw new Exception ("Should never be called");
2458 public virtual bool CheckAccessLevel (DeclSpace ds)
2460 return ds.CheckAccessLevel (Type);
2463 public virtual bool AsAccessible (DeclSpace ds, int flags)
2465 return ds.AsAccessible (Type, flags);
2468 public virtual bool IsClass {
2469 get { return Type.IsClass; }
2472 public virtual bool IsValueType {
2473 get { return Type.IsValueType; }
2476 public virtual bool IsInterface {
2477 get { return Type.IsInterface; }
2480 public virtual bool IsSealed {
2481 get { return Type.IsSealed; }
2484 public virtual bool CanInheritFrom ()
2486 if (Type == TypeManager.enum_type ||
2487 (Type == TypeManager.value_type && RootContext.StdLib) ||
2488 Type == TypeManager.multicast_delegate_type ||
2489 Type == TypeManager.delegate_type ||
2490 Type == TypeManager.array_type)
2496 protected abstract TypeExpr DoResolveAsTypeStep (EmitContext ec);
2498 public virtual Type ResolveType (EmitContext ec)
2500 TypeExpr t = ResolveAsTypeTerminal (ec);
2507 public abstract string Name {
2511 public override bool Equals (object obj)
2513 TypeExpr tobj = obj as TypeExpr;
2517 return Type == tobj.Type;
2520 public override int GetHashCode ()
2522 return Type.GetHashCode ();
2525 public override string ToString ()
2531 public class TypeExpression : TypeExpr {
2532 public TypeExpression (Type t, Location l)
2535 eclass = ExprClass.Type;
2539 protected override TypeExpr DoResolveAsTypeStep (EmitContext ec)
2544 public override string Name {
2546 return Type.ToString ();
2550 public override string FullName {
2552 return Type.FullName != null ? Type.FullName : Type.Name;
2558 /// Used to create types from a fully qualified name. These are just used
2559 /// by the parser to setup the core types. A TypeLookupExpression is always
2560 /// classified as a type.
2562 public class TypeLookupExpression : TypeExpr {
2565 public TypeLookupExpression (string name)
2570 protected override TypeExpr DoResolveAsTypeStep (EmitContext ec)
2573 FullNamedExpression t = ec.DeclSpace.LookupType (name, Location.Null, /*ignore_cs0104=*/ false);
2575 NamespaceEntry.Error_NamespaceNotFound (loc, name);
2578 if (!(t is TypeExpr)) {
2579 Report.Error (118, Location, "`{0}' denotes a `{1}', where a type was expected",
2580 t.FullName, t.ExprClassName ());
2584 type = ((TypeExpr) t).ResolveType (ec);
2590 public override string Name {
2596 public override string FullName {
2604 /// Represents an "unbound generic type", ie. typeof (Foo<>).
2607 public class UnboundTypeExpression : TypeLookupExpression {
2608 public UnboundTypeExpression (string name)
2613 public class TypeAliasExpression : TypeExpr {
2614 FullNamedExpression alias;
2619 public TypeAliasExpression (FullNamedExpression alias, TypeArguments args, Location l)
2625 eclass = ExprClass.Type;
2627 name = alias.FullName + "<" + args.ToString () + ">";
2629 name = alias.FullName;
2632 public override string Name {
2633 get { return alias.FullName; }
2636 public override string FullName {
2637 get { return name; }
2640 protected override TypeExpr DoResolveAsTypeStep (EmitContext ec)
2642 texpr = alias.ResolveAsTypeTerminal (ec);
2646 Type type = texpr.Type;
2647 int num_args = TypeManager.GetNumberOfTypeArguments (type);
2650 if (num_args == 0) {
2651 Report.Error (308, loc,
2652 "The non-generic type `{0}' cannot " +
2653 "be used with type arguments.",
2654 TypeManager.CSharpName (type));
2658 ConstructedType ctype = new ConstructedType (type, args, loc);
2659 return ctype.ResolveAsTypeTerminal (ec);
2660 } else if (num_args > 0) {
2661 Report.Error (305, loc,
2662 "Using the generic type `{0}' " +
2663 "requires {1} type arguments",
2664 TypeManager.GetFullName (type), num_args);
2668 return new TypeExpression (type, loc);
2671 public override bool CheckAccessLevel (DeclSpace ds)
2673 return texpr.CheckAccessLevel (ds);
2676 public override bool AsAccessible (DeclSpace ds, int flags)
2678 return texpr.AsAccessible (ds, flags);
2681 public override bool IsClass {
2682 get { return texpr.IsClass; }
2685 public override bool IsValueType {
2686 get { return texpr.IsValueType; }
2689 public override bool IsInterface {
2690 get { return texpr.IsInterface; }
2693 public override bool IsSealed {
2694 get { return texpr.IsSealed; }
2699 /// This class denotes an expression which evaluates to a member
2700 /// of a struct or a class.
2702 public abstract class MemberExpr : Expression
2705 /// The name of this member.
2707 public abstract string Name {
2712 /// Whether this is an instance member.
2714 public abstract bool IsInstance {
2719 /// Whether this is a static member.
2721 public abstract bool IsStatic {
2726 /// The type which declares this member.
2728 public abstract Type DeclaringType {
2733 /// The instance expression associated with this member, if it's a
2734 /// non-static member.
2736 public Expression InstanceExpression;
2738 public static void error176 (Location loc, string name)
2740 Report.Error (176, loc, "Static member `{0}' cannot be accessed " +
2741 "with an instance reference, qualify it with a type name instead", name);
2745 // TODO: possible optimalization
2746 // Cache resolved constant result in FieldBuilder <-> expression map
2747 public virtual Expression ResolveMemberAccess (EmitContext ec, Expression left, Location loc,
2748 SimpleName original)
2752 // original == null || original.Resolve (...) ==> left
2755 if (left is TypeExpr) {
2757 SimpleName.Error_ObjectRefRequired (ec, loc, Name);
2765 if (original != null && original.IdenticalNameAndTypeName (ec, left, loc))
2768 error176 (loc, GetSignatureForError ());
2772 InstanceExpression = left;
2777 protected void EmitInstance (EmitContext ec, bool prepare_for_load)
2782 if (InstanceExpression == EmptyExpression.Null) {
2783 SimpleName.Error_ObjectRefRequired (ec, loc, Name);
2787 if (InstanceExpression.Type.IsValueType) {
2788 if (InstanceExpression is IMemoryLocation) {
2789 ((IMemoryLocation) InstanceExpression).AddressOf (ec, AddressOp.LoadStore);
2791 LocalTemporary t = new LocalTemporary (ec, InstanceExpression.Type);
2792 InstanceExpression.Emit (ec);
2794 t.AddressOf (ec, AddressOp.Store);
2797 InstanceExpression.Emit (ec);
2799 if (prepare_for_load)
2800 ec.ig.Emit (OpCodes.Dup);
2805 /// MethodGroup Expression.
2807 /// This is a fully resolved expression that evaluates to a type
2809 public class MethodGroupExpr : MemberExpr {
2810 public MethodBase [] Methods;
2811 bool has_type_arguments = false;
2812 bool identical_type_name = false;
2815 public MethodGroupExpr (MemberInfo [] mi, Location l)
2817 Methods = new MethodBase [mi.Length];
2818 mi.CopyTo (Methods, 0);
2819 eclass = ExprClass.MethodGroup;
2820 type = TypeManager.object_type;
2824 public MethodGroupExpr (ArrayList list, Location l)
2826 Methods = new MethodBase [list.Count];
2829 list.CopyTo (Methods, 0);
2831 foreach (MemberInfo m in list){
2832 if (!(m is MethodBase)){
2833 Console.WriteLine ("Name " + m.Name);
2834 Console.WriteLine ("Found a: " + m.GetType ().FullName);
2841 eclass = ExprClass.MethodGroup;
2842 type = TypeManager.object_type;
2845 public override Type DeclaringType {
2848 // We assume that the top-level type is in the end
2850 return Methods [Methods.Length - 1].DeclaringType;
2851 //return Methods [0].DeclaringType;
2855 public bool HasTypeArguments {
2857 return has_type_arguments;
2861 has_type_arguments = value;
2865 public bool IdenticalTypeName {
2867 return identical_type_name;
2871 identical_type_name = value;
2875 public bool IsBase {
2884 public override string GetSignatureForError ()
2886 return TypeManager.CSharpSignature (Methods [0]);
2889 public override string Name {
2891 return Methods [0].Name;
2895 public override bool IsInstance {
2897 foreach (MethodBase mb in Methods)
2905 public override bool IsStatic {
2907 foreach (MethodBase mb in Methods)
2915 public override Expression ResolveMemberAccess (EmitContext ec, Expression left, Location loc,
2916 SimpleName original)
2918 if (!(left is TypeExpr) &&
2919 original != null && original.IdenticalNameAndTypeName (ec, left, loc))
2920 IdenticalTypeName = true;
2922 return base.ResolveMemberAccess (ec, left, loc, original);
2925 override public Expression DoResolve (EmitContext ec)
2928 InstanceExpression = null;
2930 if (InstanceExpression != null) {
2931 InstanceExpression = InstanceExpression.DoResolve (ec);
2932 if (InstanceExpression == null)
2939 public void ReportUsageError ()
2941 Report.Error (654, loc, "Method `" + DeclaringType + "." +
2942 Name + "()' is referenced without parentheses");
2945 override public void Emit (EmitContext ec)
2947 ReportUsageError ();
2950 bool RemoveMethods (bool keep_static)
2952 ArrayList smethods = new ArrayList ();
2954 foreach (MethodBase mb in Methods){
2955 if (mb.IsStatic == keep_static)
2959 if (smethods.Count == 0)
2962 Methods = new MethodBase [smethods.Count];
2963 smethods.CopyTo (Methods, 0);
2969 /// Removes any instance methods from the MethodGroup, returns
2970 /// false if the resulting set is empty.
2972 public bool RemoveInstanceMethods ()
2974 return RemoveMethods (true);
2978 /// Removes any static methods from the MethodGroup, returns
2979 /// false if the resulting set is empty.
2981 public bool RemoveStaticMethods ()
2983 return RemoveMethods (false);
2986 public Expression ResolveGeneric (EmitContext ec, TypeArguments args)
2988 if (args.Resolve (ec) == false)
2991 Type[] atypes = args.Arguments;
2993 int first_count = 0;
2994 MethodInfo first = null;
2996 ArrayList list = new ArrayList ();
2997 foreach (MethodBase mb in Methods) {
2998 MethodInfo mi = mb as MethodInfo;
2999 if ((mi == null) || !mi.HasGenericParameters)
3002 Type[] gen_params = mi.GetGenericArguments ();
3004 if (first == null) {
3006 first_count = gen_params.Length;
3009 if (gen_params.Length != atypes.Length)
3012 list.Add (mi.BindGenericParameters (atypes));
3015 if (list.Count > 0) {
3016 MethodGroupExpr new_mg = new MethodGroupExpr (list, Location);
3017 new_mg.InstanceExpression = InstanceExpression;
3018 new_mg.HasTypeArguments = true;
3024 305, loc, "Using the generic method `{0}' " +
3025 "requires {1} type arguments", Name,
3029 308, loc, "The non-generic method `{0}' " +
3030 "cannot be used with type arguments", Name);
3037 /// Fully resolved expression that evaluates to a Field
3039 public class FieldExpr : MemberExpr, IAssignMethod, IMemoryLocation, IVariable {
3040 public readonly FieldInfo FieldInfo;
3041 VariableInfo variable_info;
3043 LocalTemporary temp;
3045 bool in_initializer;
3047 public FieldExpr (FieldInfo fi, Location l, bool in_initializer):
3050 this.in_initializer = in_initializer;
3053 public FieldExpr (FieldInfo fi, Location l)
3056 eclass = ExprClass.Variable;
3057 type = TypeManager.TypeToCoreType (fi.FieldType);
3061 public override string Name {
3063 return FieldInfo.Name;
3067 public override bool IsInstance {
3069 return !FieldInfo.IsStatic;
3073 public override bool IsStatic {
3075 return FieldInfo.IsStatic;
3079 public override Type DeclaringType {
3081 return FieldInfo.DeclaringType;
3085 public override string GetSignatureForError ()
3087 return TypeManager.GetFullNameSignature (FieldInfo);
3090 public VariableInfo VariableInfo {
3092 return variable_info;
3096 public override Expression ResolveMemberAccess (EmitContext ec, Expression left, Location loc,
3097 SimpleName original)
3099 bool left_is_type = left is TypeExpr;
3101 FieldInfo fi = FieldInfo.Mono_GetGenericFieldDefinition ();
3103 Type decl_type = fi.DeclaringType;
3105 bool is_emitted = fi is FieldBuilder;
3106 Type t = fi.FieldType;
3109 Const c = TypeManager.LookupConstant ((FieldBuilder) fi);
3113 if (!c.LookupConstantValue (out o))
3116 c.SetMemberIsUsed ();
3117 object real_value = ((Constant) c.Expr).GetValue ();
3119 Expression exp = Constantify (real_value, t);
3121 if (!left_is_type &&
3122 (original == null || !original.IdenticalNameAndTypeName (ec, left, loc))) {
3123 Report.SymbolRelatedToPreviousError (c);
3124 error176 (loc, c.GetSignatureForError ());
3133 // Decimal constants cannot be encoded in the constant blob, and thus are marked
3134 // as IsInitOnly ('readonly' in C# parlance). We get its value from the
3135 // DecimalConstantAttribute metadata.
3137 if (fi.IsInitOnly && !is_emitted && t == TypeManager.decimal_type) {
3138 object[] attrs = fi.GetCustomAttributes (TypeManager.decimal_constant_attribute_type, false);
3139 if (attrs.Length == 1)
3140 return new DecimalConstant (((System.Runtime.CompilerServices.DecimalConstantAttribute) attrs [0]).Value);
3147 o = TypeManager.GetValue ((FieldBuilder) fi);
3149 o = fi.GetValue (fi);
3151 if (decl_type.IsSubclassOf (TypeManager.enum_type)) {
3152 if (!left_is_type &&
3153 (original == null || !original.IdenticalNameAndTypeName (ec, left, loc))) {
3154 error176 (loc, TypeManager.GetFullNameSignature (FieldInfo));
3158 Expression enum_member = MemberLookup (
3159 ec, decl_type, "value__", MemberTypes.Field,
3160 AllBindingFlags | BindingFlags.NonPublic, loc);
3162 Enum en = TypeManager.LookupEnum (decl_type);
3166 c = Constantify (o, en.UnderlyingType);
3168 c = Constantify (o, enum_member.Type);
3170 return new EnumConstant (c, decl_type);
3173 Expression exp = Constantify (o, t);
3175 if (!left_is_type) {
3176 error176 (loc, TypeManager.GetFullNameSignature (FieldInfo));
3183 if (t.IsPointer && !ec.InUnsafe) {
3188 return base.ResolveMemberAccess (ec, left, loc, original);
3191 override public Expression DoResolve (EmitContext ec)
3193 if (ec.InRefOutArgumentResolving && FieldInfo.IsInitOnly && !ec.IsConstructor && FieldInfo.FieldType.IsValueType) {
3194 if (FieldInfo.FieldType is TypeBuilder) {
3195 if (FieldInfo.IsStatic)
3196 Report.Error (1651, loc, "Fields of static readonly field `{0}' cannot be passed ref or out (except in a static constructor)",
3197 GetSignatureForError ());
3199 Report.Error (1649, loc, "Members of readonly field `{0}.{1}' cannot be passed ref or out (except in a constructor)",
3200 TypeManager.CSharpName (DeclaringType), Name);
3202 if (FieldInfo.IsStatic)
3203 Report.Error (199, loc, "A static readonly field `{0}' cannot be passed ref or out (except in a static constructor)",
3206 Report.Error (192, loc, "A readonly field `{0}' cannot be passed ref or out (except in a constructor)",
3212 if (!FieldInfo.IsStatic){
3213 if (InstanceExpression == null){
3215 // This can happen when referencing an instance field using
3216 // a fully qualified type expression: TypeName.InstanceField = xxx
3218 SimpleName.Error_ObjectRefRequired (ec, loc, FieldInfo.Name);
3222 // Resolve the field's instance expression while flow analysis is turned
3223 // off: when accessing a field "a.b", we must check whether the field
3224 // "a.b" is initialized, not whether the whole struct "a" is initialized.
3225 InstanceExpression = InstanceExpression.Resolve (
3226 ec, ResolveFlags.VariableOrValue | ResolveFlags.DisableFlowAnalysis);
3227 if (InstanceExpression == null)
3231 if (!in_initializer) {
3232 ObsoleteAttribute oa;
3233 FieldBase f = TypeManager.GetField (FieldInfo);
3235 oa = f.GetObsoleteAttribute (f.Parent);
3237 AttributeTester.Report_ObsoleteMessage (oa, f.GetSignatureForError (), loc);
3238 // To be sure that type is external because we do not register generated fields
3239 } else if (!(FieldInfo.DeclaringType is TypeBuilder)) {
3240 oa = AttributeTester.GetMemberObsoleteAttribute (FieldInfo);
3242 AttributeTester.Report_ObsoleteMessage (oa, TypeManager.GetFullNameSignature (FieldInfo), loc);
3246 AnonymousContainer am = ec.CurrentAnonymousMethod;
3248 if (!FieldInfo.IsStatic){
3249 if (!am.IsIterator && (ec.TypeContainer is Struct)){
3250 Report.Error (1673, loc,
3251 "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",
3255 if ((am.ContainerAnonymousMethod == null) && (InstanceExpression is This))
3256 ec.CaptureField (this);
3260 // If the instance expression is a local variable or parameter.
3261 IVariable var = InstanceExpression as IVariable;
3262 if ((var == null) || (var.VariableInfo == null))
3265 VariableInfo vi = var.VariableInfo;
3266 if (!vi.IsFieldAssigned (ec, FieldInfo.Name, loc))
3269 variable_info = vi.GetSubStruct (FieldInfo.Name);
3273 void Report_AssignToReadonly (bool is_instance)
3278 msg = "A readonly field cannot be assigned to (except in a constructor or a variable initializer)";
3280 msg = "A static readonly field cannot be assigned to (except in a static constructor or a variable initializer)";
3282 Report.Error (is_instance ? 191 : 198, loc, msg);
3285 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
3287 IVariable var = InstanceExpression as IVariable;
3288 if ((var != null) && (var.VariableInfo != null))
3289 var.VariableInfo.SetFieldAssigned (ec, FieldInfo.Name);
3291 Expression e = DoResolve (ec);
3296 if (!FieldInfo.IsStatic && (InstanceExpression.Type.IsValueType && !(InstanceExpression is IMemoryLocation))) {
3297 Report.Error (1612, loc, "Cannot modify the return value of `{0}' because it is not a variable",
3298 InstanceExpression.GetSignatureForError ());
3302 FieldBase fb = TypeManager.GetField (FieldInfo);
3306 if (!FieldInfo.IsInitOnly)
3310 // InitOnly fields can only be assigned in constructors
3313 if (ec.IsConstructor){
3314 if (IsStatic && !ec.IsStatic)
3315 Report_AssignToReadonly (false);
3318 if (ec.TypeContainer.CurrentType != null)
3319 ctype = ec.TypeContainer.CurrentType;
3321 ctype = ec.ContainerType;
3323 if (TypeManager.IsEqual (ctype, FieldInfo.DeclaringType))
3327 Report_AssignToReadonly (!IsStatic);
3332 public override void CheckMarshallByRefAccess (Type container)
3334 if (!IsStatic && Type.IsValueType && !container.IsSubclassOf (TypeManager.mbr_type) && DeclaringType.IsSubclassOf (TypeManager.mbr_type)) {
3335 Report.SymbolRelatedToPreviousError (DeclaringType);
3336 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",
3337 GetSignatureForError ());
3341 public bool VerifyFixed ()
3343 IVariable variable = InstanceExpression as IVariable;
3344 // A variable of the form V.I is fixed when V is a fixed variable of a struct type.
3345 // We defer the InstanceExpression check after the variable check to avoid a
3346 // separate null check on InstanceExpression.
3347 return variable != null && InstanceExpression.Type.IsValueType && variable.VerifyFixed ();
3350 public override int GetHashCode()
3352 return FieldInfo.GetHashCode ();
3355 public override bool Equals (object obj)
3357 FieldExpr fe = obj as FieldExpr;
3361 if (FieldInfo != fe.FieldInfo)
3364 if (InstanceExpression == null || fe.InstanceExpression == null)
3367 return InstanceExpression.Equals (fe.InstanceExpression);
3370 public void Emit (EmitContext ec, bool leave_copy)
3372 ILGenerator ig = ec.ig;
3373 bool is_volatile = false;
3375 FieldInfo the_fi = FieldInfo.Mono_GetGenericFieldDefinition ();
3376 if (the_fi is FieldBuilder){
3377 FieldBase f = TypeManager.GetField (the_fi);
3379 if ((f.ModFlags & Modifiers.VOLATILE) != 0)
3382 f.SetMemberIsUsed ();
3386 if (FieldInfo.IsStatic){
3388 ig.Emit (OpCodes.Volatile);
3390 ig.Emit (OpCodes.Ldsfld, FieldInfo);
3393 EmitInstance (ec, false);
3396 ig.Emit (OpCodes.Volatile);
3398 IFixedBuffer ff = AttributeTester.GetFixedBuffer (FieldInfo);
3401 ig.Emit (OpCodes.Ldflda, FieldInfo);
3402 ig.Emit (OpCodes.Ldflda, ff.Element);
3405 ig.Emit (OpCodes.Ldfld, FieldInfo);
3410 ec.ig.Emit (OpCodes.Dup);
3411 if (!FieldInfo.IsStatic) {
3412 temp = new LocalTemporary (ec, this.Type);
3418 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
3420 FieldAttributes fa = FieldInfo.Attributes;
3421 bool is_static = (fa & FieldAttributes.Static) != 0;
3422 bool is_readonly = (fa & FieldAttributes.InitOnly) != 0;
3423 ILGenerator ig = ec.ig;
3424 prepared = prepare_for_load;
3426 if (is_readonly && !ec.IsConstructor){
3427 Report_AssignToReadonly (!is_static);
3431 EmitInstance (ec, prepare_for_load);
3435 ec.ig.Emit (OpCodes.Dup);
3436 if (!FieldInfo.IsStatic) {
3437 temp = new LocalTemporary (ec, this.Type);
3442 if (FieldInfo is FieldBuilder){
3443 FieldBase f = TypeManager.GetField (FieldInfo);
3445 if ((f.ModFlags & Modifiers.VOLATILE) != 0)
3446 ig.Emit (OpCodes.Volatile);
3453 ig.Emit (OpCodes.Stsfld, FieldInfo);
3455 ig.Emit (OpCodes.Stfld, FieldInfo);
3461 public override void Emit (EmitContext ec)
3466 public void AddressOf (EmitContext ec, AddressOp mode)
3468 ILGenerator ig = ec.ig;
3470 if (FieldInfo is FieldBuilder){
3471 FieldBase f = TypeManager.GetField (FieldInfo);
3473 if ((f.ModFlags & Modifiers.VOLATILE) != 0){
3474 Report.Warning (420, 1, loc, "`{0}': A volatile fields cannot be passed using a ref or out parameter",
3475 f.GetSignatureForError ());
3479 if ((mode & AddressOp.Store) != 0)
3481 if ((mode & AddressOp.Load) != 0)
3482 f.SetMemberIsUsed ();
3487 // Handle initonly fields specially: make a copy and then
3488 // get the address of the copy.
3491 if (FieldInfo.IsInitOnly){
3493 if (ec.IsConstructor){
3494 if (FieldInfo.IsStatic){
3506 local = ig.DeclareLocal (type);
3507 ig.Emit (OpCodes.Stloc, local);
3508 ig.Emit (OpCodes.Ldloca, local);
3513 if (FieldInfo.IsStatic){
3514 ig.Emit (OpCodes.Ldsflda, FieldInfo);
3516 EmitInstance (ec, false);
3517 ig.Emit (OpCodes.Ldflda, FieldInfo);
3523 // A FieldExpr whose address can not be taken
3525 public class FieldExprNoAddress : FieldExpr, IMemoryLocation {
3526 public FieldExprNoAddress (FieldInfo fi, Location loc) : base (fi, loc)
3530 public new void AddressOf (EmitContext ec, AddressOp mode)
3532 Report.Error (-215, "Report this: Taking the address of a remapped parameter not supported");
3537 /// Expression that evaluates to a Property. The Assign class
3538 /// might set the `Value' expression if we are in an assignment.
3540 /// This is not an LValue because we need to re-write the expression, we
3541 /// can not take data from the stack and store it.
3543 public class PropertyExpr : MemberExpr, IAssignMethod {
3544 public readonly PropertyInfo PropertyInfo;
3547 // This is set externally by the `BaseAccess' class
3550 MethodInfo getter, setter;
3555 LocalTemporary temp;
3558 internal static PtrHashtable AccessorTable = new PtrHashtable ();
3560 public PropertyExpr (EmitContext ec, PropertyInfo pi, Location l)
3563 eclass = ExprClass.PropertyAccess;
3567 type = TypeManager.TypeToCoreType (pi.PropertyType);
3569 ResolveAccessors (ec);
3572 public override string Name {
3574 return PropertyInfo.Name;
3578 public override bool IsInstance {
3584 public override bool IsStatic {
3590 public override Type DeclaringType {
3592 return PropertyInfo.DeclaringType;
3596 public override string GetSignatureForError ()
3598 return TypeManager.GetFullNameSignature (PropertyInfo);
3601 void FindAccessors (Type invocation_type)
3603 BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic |
3604 BindingFlags.Static | BindingFlags.Instance |
3605 BindingFlags.DeclaredOnly;
3607 Type current = PropertyInfo.DeclaringType;
3608 for (; current != null; current = current.BaseType) {
3609 MemberInfo[] group = TypeManager.MemberLookup (
3610 invocation_type, invocation_type, current,
3611 MemberTypes.Property, flags, PropertyInfo.Name, null);
3616 if (group.Length != 1)
3617 // Oooops, can this ever happen ?
3620 PropertyInfo pi = (PropertyInfo) group [0];
3623 getter = pi.GetGetMethod (true);
3626 setter = pi.GetSetMethod (true);
3628 MethodInfo accessor = getter != null ? getter : setter;
3630 if (!accessor.IsVirtual)
3636 // We also perform the permission checking here, as the PropertyInfo does not
3637 // hold the information for the accessibility of its setter/getter
3639 void ResolveAccessors (EmitContext ec)
3641 FindAccessors (ec.ContainerType);
3643 if (getter != null) {
3644 IMethodData md = TypeManager.GetMethod (getter);
3646 md.SetMemberIsUsed ();
3648 AccessorTable [getter] = PropertyInfo;
3649 is_static = getter.IsStatic;
3652 if (setter != null) {
3653 IMethodData md = TypeManager.GetMethod (setter);
3655 md.SetMemberIsUsed ();
3657 AccessorTable [setter] = PropertyInfo;
3658 is_static = setter.IsStatic;
3662 bool InstanceResolve (EmitContext ec, bool must_do_cs1540_check)
3665 InstanceExpression = null;
3669 if (InstanceExpression == null) {
3670 SimpleName.Error_ObjectRefRequired (ec, loc, PropertyInfo.Name);
3674 InstanceExpression = InstanceExpression.DoResolve (ec);
3675 if (InstanceExpression == null)
3678 InstanceExpression.CheckMarshallByRefAccess (ec.ContainerType);
3680 if (must_do_cs1540_check && InstanceExpression != EmptyExpression.Null) {
3681 if ((InstanceExpression.Type != ec.ContainerType) &&
3682 ec.ContainerType.IsSubclassOf (InstanceExpression.Type)) {
3683 Report.Error (1540, loc, "Cannot access protected member `" +
3684 PropertyInfo.DeclaringType + "." + PropertyInfo.Name +
3685 "' via a qualifier of type `" +
3686 TypeManager.CSharpName (InstanceExpression.Type) +
3687 "'; the qualifier must be of type `" +
3688 TypeManager.CSharpName (ec.ContainerType) +
3689 "' (or derived from it)");
3697 override public Expression DoResolve (EmitContext ec)
3702 if (getter != null){
3703 if (TypeManager.GetArgumentTypes (getter).Length != 0){
3705 117, loc, "`{0}' does not contain a " +
3706 "definition for `{1}'.", getter.DeclaringType,
3712 if (getter == null){
3714 // The following condition happens if the PropertyExpr was
3715 // created, but is invalid (ie, the property is inaccessible),
3716 // and we did not want to embed the knowledge about this in
3717 // the caller routine. This only avoids double error reporting.
3722 if (InstanceExpression != EmptyExpression.Null) {
3723 Report.Error (154, loc, "The property or indexer `{0}' cannot be used in this context because it lacks the `get' accessor",
3724 TypeManager.GetFullNameSignature (PropertyInfo));
3729 bool must_do_cs1540_check = false;
3730 if (getter != null &&
3731 !IsAccessorAccessible (ec.ContainerType, getter, out must_do_cs1540_check)) {
3732 PropertyBase.PropertyMethod pm = TypeManager.GetMethod (getter) as PropertyBase.PropertyMethod;
3733 if (pm != null && pm.HasCustomAccessModifier) {
3734 Report.SymbolRelatedToPreviousError (pm);
3735 Report.Error (271, loc, "The property or indexer `{0}' cannot be used in this context because the get accessor is inaccessible",
3736 TypeManager.CSharpSignature (getter));
3739 ErrorIsInaccesible (loc, TypeManager.CSharpSignature (getter));
3743 if (!InstanceResolve (ec, must_do_cs1540_check))
3747 // Only base will allow this invocation to happen.
3749 if (IsBase && getter.IsAbstract) {
3750 Error_CannotCallAbstractBase (TypeManager.GetFullNameSignature (PropertyInfo));
3754 if (PropertyInfo.PropertyType.IsPointer && !ec.InUnsafe){
3764 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
3766 if (setter == null){
3768 // The following condition happens if the PropertyExpr was
3769 // created, but is invalid (ie, the property is inaccessible),
3770 // and we did not want to embed the knowledge about this in
3771 // the caller routine. This only avoids double error reporting.
3776 Report.Error (200, loc, " Property or indexer `{0}' cannot be assigned to (it is read only)",
3777 TypeManager.GetFullNameSignature (PropertyInfo));
3781 if (TypeManager.GetArgumentTypes (setter).Length != 1){
3783 117, loc, "`{0}' does not contain a " +
3784 "definition for `{1}'.", getter.DeclaringType,
3789 bool must_do_cs1540_check;
3790 if (!IsAccessorAccessible (ec.ContainerType, setter, out must_do_cs1540_check)) {
3791 PropertyBase.PropertyMethod pm = TypeManager.GetMethod (setter) as PropertyBase.PropertyMethod;
3792 if (pm != null && pm.HasCustomAccessModifier) {
3793 Report.SymbolRelatedToPreviousError (pm);
3794 Report.Error (272, loc, "The property or indexer `{0}' cannot be used in this context because the set accessor is inaccessible",
3795 TypeManager.CSharpSignature (setter));
3798 ErrorIsInaccesible (loc, TypeManager.CSharpSignature (setter));
3802 if (!InstanceResolve (ec, must_do_cs1540_check))
3806 // Only base will allow this invocation to happen.
3808 if (IsBase && setter.IsAbstract){
3809 Error_CannotCallAbstractBase (TypeManager.GetFullNameSignature (PropertyInfo));
3814 // Check that we are not making changes to a temporary memory location
3816 if (InstanceExpression != null && InstanceExpression.Type.IsValueType && !(InstanceExpression is IMemoryLocation)) {
3817 Report.Error (1612, loc, "Cannot modify the return value of `{0}' because it is not a variable",
3818 InstanceExpression.GetSignatureForError ());
3825 public override void Emit (EmitContext ec)
3830 public void Emit (EmitContext ec, bool leave_copy)
3833 EmitInstance (ec, false);
3836 // Special case: length of single dimension array property is turned into ldlen
3838 if ((getter == TypeManager.system_int_array_get_length) ||
3839 (getter == TypeManager.int_array_get_length)){
3840 Type iet = InstanceExpression.Type;
3843 // System.Array.Length can be called, but the Type does not
3844 // support invoking GetArrayRank, so test for that case first
3846 if (iet != TypeManager.array_type && (iet.GetArrayRank () == 1)) {
3847 ec.ig.Emit (OpCodes.Ldlen);
3848 ec.ig.Emit (OpCodes.Conv_I4);
3853 Invocation.EmitCall (ec, IsBase, IsStatic, new EmptyAddressOf (), getter, null, loc);
3858 ec.ig.Emit (OpCodes.Dup);
3860 temp = new LocalTemporary (ec, this.Type);
3866 // Implements the IAssignMethod interface for assignments
3868 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
3870 prepared = prepare_for_load;
3872 EmitInstance (ec, prepare_for_load);
3876 ec.ig.Emit (OpCodes.Dup);
3878 temp = new LocalTemporary (ec, this.Type);
3883 ArrayList args = new ArrayList (1);
3884 args.Add (new Argument (new EmptyAddressOf (), Argument.AType.Expression));
3886 Invocation.EmitCall (ec, IsBase, IsStatic, new EmptyAddressOf (), setter, args, loc);
3894 /// Fully resolved expression that evaluates to an Event
3896 public class EventExpr : MemberExpr {
3897 public readonly EventInfo EventInfo;
3900 MethodInfo add_accessor, remove_accessor;
3902 public EventExpr (EventInfo ei, Location loc)
3906 eclass = ExprClass.EventAccess;
3908 add_accessor = TypeManager.GetAddMethod (ei);
3909 remove_accessor = TypeManager.GetRemoveMethod (ei);
3911 if (add_accessor.IsStatic || remove_accessor.IsStatic)
3914 if (EventInfo is MyEventBuilder){
3915 MyEventBuilder eb = (MyEventBuilder) EventInfo;
3916 type = eb.EventType;
3919 type = EventInfo.EventHandlerType;
3922 public override string Name {
3924 return EventInfo.Name;
3928 public override bool IsInstance {
3934 public override bool IsStatic {
3940 public override Type DeclaringType {
3942 return EventInfo.DeclaringType;
3946 public override Expression ResolveMemberAccess (EmitContext ec, Expression left, Location loc,
3947 SimpleName original)
3950 // If the event is local to this class, we transform ourselves into a FieldExpr
3953 if (EventInfo.DeclaringType == ec.ContainerType ||
3954 TypeManager.IsNestedChildOf(ec.ContainerType, EventInfo.DeclaringType)) {
3955 MemberInfo mi = TypeManager.GetPrivateFieldOfEvent (EventInfo);
3958 MemberExpr ml = (MemberExpr) ExprClassFromMemberInfo (ec, mi, loc);
3961 Report.Error (-200, loc, "Internal error!!");
3965 InstanceExpression = null;
3967 return ml.ResolveMemberAccess (ec, left, loc, original);
3971 return base.ResolveMemberAccess (ec, left, loc, original);
3975 bool InstanceResolve (EmitContext ec, bool must_do_cs1540_check)
3978 InstanceExpression = null;
3982 if (InstanceExpression == null) {
3983 SimpleName.Error_ObjectRefRequired (ec, loc, EventInfo.Name);
3987 InstanceExpression = InstanceExpression.DoResolve (ec);
3988 if (InstanceExpression == null)
3992 // This is using the same mechanism as the CS1540 check in PropertyExpr.
3993 // However, in the Event case, we reported a CS0122 instead.
3995 if (must_do_cs1540_check && InstanceExpression != EmptyExpression.Null) {
3996 if ((InstanceExpression.Type != ec.ContainerType) &&
3997 ec.ContainerType.IsSubclassOf (InstanceExpression.Type)) {
3998 ErrorIsInaccesible (loc, TypeManager.CSharpSignature (EventInfo));
4006 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
4008 return DoResolve (ec);
4011 public override Expression DoResolve (EmitContext ec)
4013 bool must_do_cs1540_check;
4014 if (!(IsAccessorAccessible (ec.ContainerType, add_accessor, out must_do_cs1540_check) &&
4015 IsAccessorAccessible (ec.ContainerType, remove_accessor, out must_do_cs1540_check))) {
4016 ErrorIsInaccesible (loc, TypeManager.CSharpSignature (EventInfo));
4020 if (!InstanceResolve (ec, must_do_cs1540_check))
4026 public override void Emit (EmitContext ec)
4028 if (InstanceExpression is This)
4029 Report.Error (79, loc, "The event `{0}' can only appear on the left hand side of += or -=", GetSignatureForError ());
4031 Report.Error (70, loc, "The event `{0}' can only appear on the left hand side of += or -= "+
4032 "(except on the defining type)", Name);
4035 public override string GetSignatureForError ()
4037 return TypeManager.CSharpSignature (EventInfo);
4040 public void EmitAddOrRemove (EmitContext ec, Expression source)
4042 BinaryDelegate source_del = (BinaryDelegate) source;
4043 Expression handler = source_del.Right;
4045 Argument arg = new Argument (handler, Argument.AType.Expression);
4046 ArrayList args = new ArrayList ();
4050 if (source_del.IsAddition)
4051 Invocation.EmitCall (
4052 ec, false, IsStatic, InstanceExpression, add_accessor, args, loc);
4054 Invocation.EmitCall (
4055 ec, false, IsStatic, InstanceExpression, remove_accessor, args, loc);