2 // ecore.cs: Core of the Expression representation for the intermediate tree.
5 // Miguel de Icaza (miguel@ximian.com)
7 // (C) 2001, 2002, 2003 Ximian, Inc.
11 namespace Mono.CSharp {
13 using System.Collections;
14 using System.Diagnostics;
15 using System.Reflection;
16 using System.Reflection.Emit;
20 /// The ExprClass class contains the is used to pass the
21 /// classification of an expression (value, variable, namespace,
22 /// type, method group, property access, event access, indexer access,
25 public enum ExprClass : byte {
40 /// This is used to tell Resolve in which types of expressions we're
44 public enum ResolveFlags {
45 // Returns Value, Variable, PropertyAccess, EventAccess or IndexerAccess.
48 // Returns a type expression.
51 // Returns a method group.
54 // Mask of all the expression class flags.
57 // Disable control flow analysis while resolving the expression.
58 // This is used when resolving the instance expression of a field expression.
59 DisableFlowAnalysis = 8,
61 // Set if this is resolving the first part of a MemberAccess.
66 // This is just as a hint to AddressOf of what will be done with the
69 public enum AddressOp {
76 /// This interface is implemented by variables
78 public interface IMemoryLocation {
80 /// The AddressOf method should generate code that loads
81 /// the address of the object and leaves it on the stack.
83 /// The `mode' argument is used to notify the expression
84 /// of whether this will be used to read from the address or
85 /// write to the address.
87 /// This is just a hint that can be used to provide good error
88 /// reporting, and should have no other side effects.
90 void AddressOf (EmitContext ec, AddressOp mode);
94 /// We are either a namespace or a type.
95 /// If we're a type, `IsType' is true and we may use `Type' to get
96 /// a TypeExpr representing that type.
98 public interface IAlias {
107 TypeExpr ResolveAsType (EmitContext ec);
111 /// This interface is implemented by variables
113 public interface IVariable {
114 VariableInfo VariableInfo {
118 bool VerifyFixed (bool is_expression);
122 /// Base class for expressions
124 public abstract class Expression {
125 public ExprClass eclass;
127 protected Location loc;
139 public Location Location {
146 /// Utility wrapper routine for Error, just to beautify the code
148 public void Error (int error, string s)
150 if (!Location.IsNull (loc))
151 Report.Error (error, loc, s);
153 Report.Error (error, s);
157 /// Utility wrapper routine for Warning, just to beautify the code
159 public void Warning (int code, string format, params object[] args)
161 Report.Warning (code, loc, format, args);
164 // Not nice but we have broken hierarchy
165 public virtual void CheckMarshallByRefAccess (Type container) {}
168 /// Tests presence of ObsoleteAttribute and report proper error
170 protected void CheckObsoleteAttribute (Type type)
172 ObsoleteAttribute obsolete_attr = AttributeTester.GetObsoleteAttribute (type);
173 if (obsolete_attr == null)
176 AttributeTester.Report_ObsoleteMessage (obsolete_attr, type.FullName, loc);
179 public static bool IsAccessorAccessible (Type invocation_type, MethodInfo mi, out bool must_do_cs1540_check)
181 MethodAttributes ma = mi.Attributes & MethodAttributes.MemberAccessMask;
183 must_do_cs1540_check = false; // by default we do not check for this
186 // If only accessible to the current class or children
188 if (ma == MethodAttributes.Private) {
189 Type declaring_type = mi.DeclaringType;
191 if (invocation_type != declaring_type)
192 return TypeManager.IsNestedChildOf (invocation_type, declaring_type);
197 // FamAndAssem requires that we not only derivate, but we are on the
200 if (ma == MethodAttributes.FamANDAssem){
201 return (mi.DeclaringType.Assembly != invocation_type.Assembly);
204 // Assembly and FamORAssem succeed if we're in the same assembly.
205 if ((ma == MethodAttributes.Assembly) || (ma == MethodAttributes.FamORAssem)){
206 if (mi.DeclaringType.Assembly == invocation_type.Assembly)
210 // We already know that we aren't in the same assembly.
211 if (ma == MethodAttributes.Assembly)
214 // Family and FamANDAssem require that we derive.
215 if ((ma == MethodAttributes.Family) || (ma == MethodAttributes.FamANDAssem) || (ma == MethodAttributes.FamORAssem)){
216 if (!TypeManager.IsNestedFamilyAccessible (invocation_type, mi.DeclaringType))
219 if (!TypeManager.IsNestedChildOf (invocation_type, mi.DeclaringType))
220 must_do_cs1540_check = true;
229 /// Performs semantic analysis on the Expression
233 /// The Resolve method is invoked to perform the semantic analysis
236 /// The return value is an expression (it can be the
237 /// same expression in some cases) or a new
238 /// expression that better represents this node.
240 /// For example, optimizations of Unary (LiteralInt)
241 /// would return a new LiteralInt with a negated
244 /// If there is an error during semantic analysis,
245 /// then an error should be reported (using Report)
246 /// and a null value should be returned.
248 /// There are two side effects expected from calling
249 /// Resolve(): the the field variable "eclass" should
250 /// be set to any value of the enumeration
251 /// `ExprClass' and the type variable should be set
252 /// to a valid type (this is the type of the
255 public abstract Expression DoResolve (EmitContext ec);
257 public virtual Expression DoResolveLValue (EmitContext ec, Expression right_side)
263 // This is used if the expression should be resolved as a type or namespace name.
264 // the default implementation fails.
266 public virtual FullNamedExpression ResolveAsTypeStep (EmitContext ec)
272 // This is used to resolve the expression as a type, a null
273 // value will be returned if the expression is not a type
276 public virtual TypeExpr ResolveAsTypeTerminal (EmitContext ec)
278 int errors = Report.Errors;
280 FullNamedExpression fne = ResolveAsTypeStep (ec);
283 if (errors == Report.Errors)
284 Report.Error (246, Location, "Cannot find type '{0}'", ToString ());
288 if (fne.eclass != ExprClass.Type) {
289 if (errors == Report.Errors)
290 Report.Error (118, Location, "'{0}' denotes a '{1}', where a type was expected",
291 fne.FullName, fne.ExprClassName ());
295 TypeExpr te = fne as TypeExpr;
297 if (!te.CheckAccessLevel (ec.DeclSpace)) {
298 Report.Error (122, Location, "'{0}' is inaccessible due to its protection level", te.Name);
306 /// Resolves an expression and performs semantic analysis on it.
310 /// Currently Resolve wraps DoResolve to perform sanity
311 /// checking and assertion checking on what we expect from Resolve.
313 public Expression Resolve (EmitContext ec, ResolveFlags flags)
315 if ((flags & ResolveFlags.MaskExprClass) == ResolveFlags.Type)
316 return ResolveAsTypeStep (ec);
318 bool old_do_flow_analysis = ec.DoFlowAnalysis;
319 if ((flags & ResolveFlags.DisableFlowAnalysis) != 0)
320 ec.DoFlowAnalysis = false;
323 bool intermediate = (flags & ResolveFlags.Intermediate) == ResolveFlags.Intermediate;
324 if (this is SimpleName)
325 e = ((SimpleName) this).DoResolve (ec, intermediate);
330 ec.DoFlowAnalysis = old_do_flow_analysis;
335 if ((e is TypeExpr) || (e is ComposedCast) || (e is Namespace)) {
336 if ((flags & ResolveFlags.Type) == 0) {
337 e.Error_UnexpectedKind (flags, loc);
346 case ExprClass.Namespace:
347 if ((flags & ResolveFlags.VariableOrValue) == 0) {
348 e.Error_UnexpectedKind (flags, loc);
353 case ExprClass.MethodGroup:
354 if (RootContext.Version == LanguageVersion.ISO_1){
355 if ((flags & ResolveFlags.MethodGroup) == 0) {
356 ((MethodGroupExpr) e).ReportUsageError ();
362 case ExprClass.Value:
363 case ExprClass.Variable:
364 case ExprClass.PropertyAccess:
365 case ExprClass.EventAccess:
366 case ExprClass.IndexerAccess:
367 if ((flags & ResolveFlags.VariableOrValue) == 0) {
368 Console.WriteLine ("I got: {0} and {1}", e.GetType (), e);
369 Console.WriteLine ("I am {0} and {1}", this.GetType (), this);
370 FieldInfo fi = ((FieldExpr) e).FieldInfo;
372 Console.WriteLine ("{0} and {1}", fi.DeclaringType, fi.Name);
373 e.Error_UnexpectedKind (flags, loc);
379 throw new Exception ("Expression " + e.GetType () +
380 " ExprClass is Invalid after resolve");
383 if (e.type == null && !(e is Namespace)) {
384 throw new Exception (
385 "Expression " + e.GetType () +
386 " did not set its type after Resolve\n" +
387 "called from: " + this.GetType ());
394 /// Resolves an expression and performs semantic analysis on it.
396 public Expression Resolve (EmitContext ec)
398 return Resolve (ec, ResolveFlags.VariableOrValue);
402 /// Resolves an expression for LValue assignment
406 /// Currently ResolveLValue wraps DoResolveLValue to perform sanity
407 /// checking and assertion checking on what we expect from Resolve
409 public Expression ResolveLValue (EmitContext ec, Expression right_side)
411 int errors = Report.Errors;
412 Expression e = DoResolveLValue (ec, right_side);
415 if (errors == Report.Errors)
416 Report.Error (131, Location, "The left-hand side of an assignment or mutating operation must be a variable, property or indexer");
421 if (e.eclass == ExprClass.Invalid)
422 throw new Exception ("Expression " + e +
423 " ExprClass is Invalid after resolve");
425 if (e.eclass == ExprClass.MethodGroup) {
426 ((MethodGroupExpr) e).ReportUsageError ();
430 if ((e.type == null) && !(e is ConstructedType))
431 throw new Exception ("Expression " + e +
432 " did not set its type after Resolve");
439 /// Emits the code for the expression
443 /// The Emit method is invoked to generate the code
444 /// for the expression.
446 public abstract void Emit (EmitContext ec);
448 public virtual void EmitBranchable (EmitContext ec, Label target, bool onTrue)
451 ec.ig.Emit (onTrue ? OpCodes.Brtrue : OpCodes.Brfalse, target);
455 /// Protected constructor. Only derivate types should
456 /// be able to be created
459 protected Expression ()
461 eclass = ExprClass.Invalid;
466 /// Returns a literalized version of a literal FieldInfo
470 /// The possible return values are:
471 /// IntConstant, UIntConstant
472 /// LongLiteral, ULongConstant
473 /// FloatConstant, DoubleConstant
476 /// The value returned is already resolved.
478 public static Constant Constantify (object v, Type t)
480 if (t == TypeManager.int32_type)
481 return new IntConstant ((int) v);
482 else if (t == TypeManager.uint32_type)
483 return new UIntConstant ((uint) v);
484 else if (t == TypeManager.int64_type)
485 return new LongConstant ((long) v);
486 else if (t == TypeManager.uint64_type)
487 return new ULongConstant ((ulong) v);
488 else if (t == TypeManager.float_type)
489 return new FloatConstant ((float) v);
490 else if (t == TypeManager.double_type)
491 return new DoubleConstant ((double) v);
492 else if (t == TypeManager.string_type)
493 return new StringConstant ((string) v);
494 else if (t == TypeManager.short_type)
495 return new ShortConstant ((short)v);
496 else if (t == TypeManager.ushort_type)
497 return new UShortConstant ((ushort)v);
498 else if (t == TypeManager.sbyte_type)
499 return new SByteConstant (((sbyte)v));
500 else if (t == TypeManager.byte_type)
501 return new ByteConstant ((byte)v);
502 else if (t == TypeManager.char_type)
503 return new CharConstant ((char)v);
504 else if (t == TypeManager.bool_type)
505 return new BoolConstant ((bool) v);
506 else if (t == TypeManager.decimal_type)
507 return new DecimalConstant ((decimal) v);
508 else if (TypeManager.IsEnumType (t)){
509 Type real_type = TypeManager.TypeToCoreType (v.GetType ());
511 real_type = System.Enum.GetUnderlyingType (real_type);
513 Constant e = Constantify (v, real_type);
515 return new EnumConstant (e, t);
516 } else if (v == null && !TypeManager.IsValueType (t))
517 return NullLiteral.Null;
519 throw new Exception ("Unknown type for constant (" + t +
524 /// Returns a fully formed expression after a MemberLookup
526 public static Expression ExprClassFromMemberInfo (EmitContext ec, MemberInfo mi, Location loc)
529 return new EventExpr ((EventInfo) mi, loc);
530 else if (mi is FieldInfo)
531 return new FieldExpr ((FieldInfo) mi, loc);
532 else if (mi is PropertyInfo)
533 return new PropertyExpr (ec, (PropertyInfo) mi, loc);
534 else if (mi is Type){
535 return new TypeExpression ((System.Type) mi, loc);
541 protected static ArrayList almostMatchedMembers = new ArrayList (4);
544 // FIXME: Probably implement a cache for (t,name,current_access_set)?
546 // This code could use some optimizations, but we need to do some
547 // measurements. For example, we could use a delegate to `flag' when
548 // something can not any longer be a method-group (because it is something
552 // If the return value is an Array, then it is an array of
555 // If the return value is an MemberInfo, it is anything, but a Method
559 // FIXME: When calling MemberLookup inside an `Invocation', we should pass
560 // the arguments here and have MemberLookup return only the methods that
561 // match the argument count/type, unlike we are doing now (we delay this
564 // This is so we can catch correctly attempts to invoke instance methods
565 // from a static body (scan for error 120 in ResolveSimpleName).
568 // FIXME: Potential optimization, have a static ArrayList
571 public static Expression MemberLookup (EmitContext ec, Type queried_type, string name,
572 MemberTypes mt, BindingFlags bf, Location loc)
574 return MemberLookup (ec, ec.ContainerType, null, queried_type, name, mt, bf, loc);
578 // Lookup type `queried_type' for code in class `container_type' with a qualifier of
579 // `qualifier_type' or null to lookup members in the current class.
582 public static Expression MemberLookup (EmitContext ec, Type container_type,
583 Type qualifier_type, Type queried_type,
584 string name, MemberTypes mt,
585 BindingFlags bf, Location loc)
587 almostMatchedMembers.Clear ();
589 MemberInfo [] mi = TypeManager.MemberLookup (
590 container_type, qualifier_type,queried_type, mt, bf, name,
591 almostMatchedMembers);
596 int count = mi.Length;
598 if (mi [0] is MethodBase)
599 return new MethodGroupExpr (mi, loc);
604 return ExprClassFromMemberInfo (ec, mi [0], loc);
607 public const MemberTypes AllMemberTypes =
608 MemberTypes.Constructor |
612 MemberTypes.NestedType |
613 MemberTypes.Property;
615 public const BindingFlags AllBindingFlags =
616 BindingFlags.Public |
617 BindingFlags.Static |
618 BindingFlags.Instance;
620 public static Expression MemberLookup (EmitContext ec, Type queried_type,
621 string name, Location loc)
623 return MemberLookup (ec, ec.ContainerType, null, queried_type, name,
624 AllMemberTypes, AllBindingFlags, loc);
627 public static Expression MemberLookup (EmitContext ec, Type qualifier_type,
628 Type queried_type, string name, Location loc)
630 return MemberLookup (ec, ec.ContainerType, qualifier_type, queried_type,
631 name, AllMemberTypes, AllBindingFlags, loc);
634 public static Expression MethodLookup (EmitContext ec, Type queried_type,
635 string name, Location loc)
637 return MemberLookup (ec, ec.ContainerType, null, queried_type, name,
638 MemberTypes.Method, AllBindingFlags, loc);
642 /// This is a wrapper for MemberLookup that is not used to "probe", but
643 /// to find a final definition. If the final definition is not found, we
644 /// look for private members and display a useful debugging message if we
647 public static Expression MemberLookupFinal (EmitContext ec, Type qualifier_type,
648 Type queried_type, string name,
651 return MemberLookupFinal (ec, qualifier_type, queried_type, name,
652 AllMemberTypes, AllBindingFlags, loc);
655 public static Expression MemberLookupFinal (EmitContext ec, Type qualifier_type,
656 Type queried_type, string name,
657 MemberTypes mt, BindingFlags bf,
662 int errors = Report.Errors;
664 e = MemberLookup (ec, ec.ContainerType, qualifier_type, queried_type,
667 if (e == null && errors == Report.Errors)
668 // No errors were reported by MemberLookup, but there was an error.
669 MemberLookupFailed (ec, qualifier_type, queried_type, name, null, true, loc);
674 public static void MemberLookupFailed (EmitContext ec, Type qualifier_type,
675 Type queried_type, string name,
676 string class_name, bool complain_if_none_found,
679 if (almostMatchedMembers.Count != 0) {
680 if (qualifier_type == null) {
681 foreach (MemberInfo m in almostMatchedMembers)
682 Report.Error (38, loc,
683 "Cannot access non-static member `{0}' via nested type `{1}'",
684 TypeManager.GetFullNameSignature (m),
685 TypeManager.CSharpName (ec.ContainerType));
690 if (qualifier_type != ec.ContainerType) {
691 // Although a derived class can access protected members of
692 // its base class it cannot do so through an instance of the
693 // base class (CS1540). If the qualifier_type is a base of the
694 // ec.ContainerType and the lookup succeeds with the latter one,
695 // then we are in this situation.
696 for (int i = 0; i < almostMatchedMembers.Count; ++i) {
697 MemberInfo m = (MemberInfo) almostMatchedMembers [i];
698 for (int j = 0; j < i; ++j) {
699 if (m == almostMatchedMembers [j]) {
707 Report.SymbolRelatedToPreviousError (m);
708 Report.Error (1540, loc,
709 "Cannot access protected member `{0}' via a qualifier of type `{1}';"
710 + " the qualifier must be of type `{2}' (or derived from it)",
711 TypeManager.GetFullNameSignature (m),
712 TypeManager.CSharpName (qualifier_type),
713 TypeManager.CSharpName (ec.ContainerType));
717 almostMatchedMembers.Clear ();
720 MemberInfo[] mi = TypeManager.MemberLookup (queried_type, null, queried_type,
721 AllMemberTypes, AllBindingFlags |
722 BindingFlags.NonPublic, name, null);
725 if (!complain_if_none_found)
728 if (class_name != null)
729 Report.Error (103, loc, "The name `" + name + "' could not be " +
730 "found in `" + class_name + "'");
733 117, loc, "`" + queried_type + "' does not contain a " +
734 "definition for `" + name + "'");
738 if (TypeManager.MemberLookup (queried_type, null, queried_type,
739 AllMemberTypes, AllBindingFlags |
740 BindingFlags.NonPublic, name, null) == null) {
741 if ((mi.Length == 1) && (mi [0] is Type)) {
742 Type t = (Type) mi [0];
744 Report.Error (305, loc,
745 "Using the generic type `{0}' " +
746 "requires {1} type arguments",
747 TypeManager.GetFullName (t),
748 TypeManager.GetNumberOfTypeArguments (t));
753 if (name == ".ctor" && TypeManager.FindMembers (qualifier_type, MemberTypes.Constructor,
754 BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly, null, null).Count == 0)
756 Report.Error (143, loc, String.Format ("The type '{0}' has no constructors defined", TypeManager.CSharpName (queried_type)));
760 if (qualifier_type != null) {
761 Report.Error (122, loc, "'{0}' is inaccessible due to its protection level", TypeManager.CSharpName (qualifier_type) + "." + name);
763 Report.Error (122, loc, "'{0}' is inaccessible due to its protection level", name);
768 /// Returns an expression that can be used to invoke operator true
769 /// on the expression if it exists.
771 static public Expression GetOperatorTrue (EmitContext ec, Expression e, Location loc)
773 return GetOperatorTrueOrFalse (ec, e, true, loc);
777 /// Returns an expression that can be used to invoke operator false
778 /// on the expression if it exists.
780 static public Expression GetOperatorFalse (EmitContext ec, Expression e, Location loc)
782 return GetOperatorTrueOrFalse (ec, e, false, loc);
785 static Expression GetOperatorTrueOrFalse (EmitContext ec, Expression e, bool is_true, Location loc)
788 Expression operator_group;
790 if (TypeManager.IsNullableType (e.Type))
791 return new Nullable.OperatorTrueOrFalse (e, is_true, loc).Resolve (ec);
793 operator_group = MethodLookup (ec, e.Type, is_true ? "op_True" : "op_False", loc);
794 if (operator_group == null)
797 ArrayList arguments = new ArrayList ();
798 arguments.Add (new Argument (e, Argument.AType.Expression));
799 method = Invocation.OverloadResolve (
800 ec, (MethodGroupExpr) operator_group, arguments, false, loc);
805 return new StaticCallExpr ((MethodInfo) method, arguments, loc);
809 /// Resolves the expression `e' into a boolean expression: either through
810 /// an implicit conversion, or through an `operator true' invocation
812 public static Expression ResolveBoolean (EmitContext ec, Expression e, Location loc)
818 if (e.Type == TypeManager.bool_type)
821 Expression converted = Convert.ImplicitConversion (ec, e, TypeManager.bool_type, Location.Null);
823 if (converted != null)
827 // If no implicit conversion to bool exists, try using `operator true'
829 Expression operator_true = Expression.GetOperatorTrue (ec, e, loc);
830 if (operator_true == null){
831 Report.Error (31, loc, "Can not convert the expression to a boolean");
834 return operator_true;
837 public string ExprClassName ()
840 case ExprClass.Invalid:
842 case ExprClass.Value:
844 case ExprClass.Variable:
846 case ExprClass.Namespace:
850 case ExprClass.MethodGroup:
851 return "method group";
852 case ExprClass.PropertyAccess:
853 return "property access";
854 case ExprClass.EventAccess:
855 return "event access";
856 case ExprClass.IndexerAccess:
857 return "indexer access";
858 case ExprClass.Nothing:
861 throw new Exception ("Should not happen");
865 /// Reports that we were expecting `expr' to be of class `expected'
867 public void Error_UnexpectedKind (string expected, Location loc)
869 Report.Error (118, loc, "Expression denotes a `" + ExprClassName () +
870 "' where a `" + expected + "' was expected");
873 public void Error_UnexpectedKind (ResolveFlags flags, Location loc)
875 ArrayList valid = new ArrayList (10);
877 if ((flags & ResolveFlags.VariableOrValue) != 0) {
878 valid.Add ("variable");
882 if ((flags & ResolveFlags.Type) != 0)
885 if ((flags & ResolveFlags.MethodGroup) != 0)
886 valid.Add ("method group");
888 if (valid.Count == 0)
889 valid.Add ("unknown");
891 StringBuilder sb = new StringBuilder ();
892 for (int i = 0; i < valid.Count; i++) {
895 else if (i == valid.Count)
897 sb.Append (valid [i]);
900 Report.Error (119, loc, "Expression denotes a `" + ExprClassName () + "' where " +
901 "a `" + sb.ToString () + "' was expected");
904 static public void Error_ConstantValueCannotBeConverted (Location l, string val, Type t)
906 Report.Error (31, l, "Constant value `" + val + "' cannot be converted to " +
907 TypeManager.CSharpName (t));
910 public static void UnsafeError (Location loc)
912 Report.Error (214, loc, "Pointers may only be used in an unsafe context");
916 /// Converts the IntConstant, UIntConstant, LongConstant or
917 /// ULongConstant into the integral target_type. Notice
918 /// that we do not return an `Expression' we do return
919 /// a boxed integral type.
921 /// FIXME: Since I added the new constants, we need to
922 /// also support conversions from CharConstant, ByteConstant,
923 /// SByteConstant, UShortConstant, ShortConstant
925 /// This is used by the switch statement, so the domain
926 /// of work is restricted to the literals above, and the
927 /// targets are int32, uint32, char, byte, sbyte, ushort,
928 /// short, uint64 and int64
930 public static object ConvertIntLiteral (Constant c, Type target_type, Location loc)
932 if (!Convert.ImplicitStandardConversionExists (Convert.ConstantEC, c, target_type)){
933 Convert.Error_CannotImplicitConversion (loc, c.Type, target_type);
939 if (c.Type == target_type)
940 return ((Constant) c).GetValue ();
943 // Make into one of the literals we handle, we dont really care
944 // about this value as we will just return a few limited types
946 if (c is EnumConstant)
947 c = ((EnumConstant)c).WidenToCompilerConstant ();
949 if (c is IntConstant){
950 int v = ((IntConstant) c).Value;
952 if (target_type == TypeManager.uint32_type){
955 } else if (target_type == TypeManager.char_type){
956 if (v >= Char.MinValue && v <= Char.MaxValue)
958 } else if (target_type == TypeManager.byte_type){
959 if (v >= Byte.MinValue && v <= Byte.MaxValue)
961 } else if (target_type == TypeManager.sbyte_type){
962 if (v >= SByte.MinValue && v <= SByte.MaxValue)
964 } else if (target_type == TypeManager.short_type){
965 if (v >= Int16.MinValue && v <= UInt16.MaxValue)
967 } else if (target_type == TypeManager.ushort_type){
968 if (v >= UInt16.MinValue && v <= UInt16.MaxValue)
970 } else if (target_type == TypeManager.int64_type)
972 else if (target_type == TypeManager.uint64_type){
978 } else if (c is UIntConstant){
979 uint v = ((UIntConstant) c).Value;
981 if (target_type == TypeManager.int32_type){
982 if (v <= Int32.MaxValue)
984 } else if (target_type == TypeManager.char_type){
985 if (v >= Char.MinValue && v <= Char.MaxValue)
987 } else if (target_type == TypeManager.byte_type){
988 if (v <= Byte.MaxValue)
990 } else if (target_type == TypeManager.sbyte_type){
991 if (v <= SByte.MaxValue)
993 } else if (target_type == TypeManager.short_type){
994 if (v <= UInt16.MaxValue)
996 } else if (target_type == TypeManager.ushort_type){
997 if (v <= UInt16.MaxValue)
999 } else if (target_type == TypeManager.int64_type)
1001 else if (target_type == TypeManager.uint64_type)
1004 } else if (c is LongConstant){
1005 long v = ((LongConstant) c).Value;
1007 if (target_type == TypeManager.int32_type){
1008 if (v >= UInt32.MinValue && v <= UInt32.MaxValue)
1010 } else if (target_type == TypeManager.uint32_type){
1011 if (v >= 0 && v <= UInt32.MaxValue)
1013 } else if (target_type == TypeManager.char_type){
1014 if (v >= Char.MinValue && v <= Char.MaxValue)
1016 } else if (target_type == TypeManager.byte_type){
1017 if (v >= Byte.MinValue && v <= Byte.MaxValue)
1019 } else if (target_type == TypeManager.sbyte_type){
1020 if (v >= SByte.MinValue && v <= SByte.MaxValue)
1022 } else if (target_type == TypeManager.short_type){
1023 if (v >= Int16.MinValue && v <= UInt16.MaxValue)
1025 } else if (target_type == TypeManager.ushort_type){
1026 if (v >= UInt16.MinValue && v <= UInt16.MaxValue)
1028 } else if (target_type == TypeManager.uint64_type){
1033 } else if (c is ULongConstant){
1034 ulong v = ((ULongConstant) c).Value;
1036 if (target_type == TypeManager.int32_type){
1037 if (v <= Int32.MaxValue)
1039 } else if (target_type == TypeManager.uint32_type){
1040 if (v <= UInt32.MaxValue)
1042 } else if (target_type == TypeManager.char_type){
1043 if (v >= Char.MinValue && v <= Char.MaxValue)
1045 } else if (target_type == TypeManager.byte_type){
1046 if (v >= Byte.MinValue && v <= Byte.MaxValue)
1048 } else if (target_type == TypeManager.sbyte_type){
1049 if (v <= (int) SByte.MaxValue)
1051 } else if (target_type == TypeManager.short_type){
1052 if (v <= UInt16.MaxValue)
1054 } else if (target_type == TypeManager.ushort_type){
1055 if (v <= UInt16.MaxValue)
1057 } else if (target_type == TypeManager.int64_type){
1058 if (v <= Int64.MaxValue)
1062 } else if (c is ByteConstant){
1063 byte v = ((ByteConstant) c).Value;
1065 if (target_type == TypeManager.int32_type)
1067 else if (target_type == TypeManager.uint32_type)
1069 else if (target_type == TypeManager.char_type)
1071 else if (target_type == TypeManager.sbyte_type){
1072 if (v <= SByte.MaxValue)
1074 } else if (target_type == TypeManager.short_type)
1076 else if (target_type == TypeManager.ushort_type)
1078 else if (target_type == TypeManager.int64_type)
1080 else if (target_type == TypeManager.uint64_type)
1083 } else if (c is SByteConstant){
1084 sbyte v = ((SByteConstant) c).Value;
1086 if (target_type == TypeManager.int32_type)
1088 else if (target_type == TypeManager.uint32_type){
1091 } else if (target_type == TypeManager.char_type){
1094 } else if (target_type == TypeManager.byte_type){
1097 } else if (target_type == TypeManager.short_type)
1099 else if (target_type == TypeManager.ushort_type){
1102 } else if (target_type == TypeManager.int64_type)
1104 else if (target_type == TypeManager.uint64_type){
1109 } else if (c is ShortConstant){
1110 short v = ((ShortConstant) c).Value;
1112 if (target_type == TypeManager.int32_type){
1114 } else if (target_type == TypeManager.uint32_type){
1117 } else if (target_type == TypeManager.char_type){
1120 } else if (target_type == TypeManager.byte_type){
1121 if (v >= Byte.MinValue && v <= Byte.MaxValue)
1123 } else if (target_type == TypeManager.sbyte_type){
1124 if (v >= SByte.MinValue && v <= SByte.MaxValue)
1126 } else if (target_type == TypeManager.ushort_type){
1129 } else if (target_type == TypeManager.int64_type)
1131 else if (target_type == TypeManager.uint64_type)
1135 } else if (c is UShortConstant){
1136 ushort v = ((UShortConstant) c).Value;
1138 if (target_type == TypeManager.int32_type)
1140 else if (target_type == TypeManager.uint32_type)
1142 else if (target_type == TypeManager.char_type){
1143 if (v >= Char.MinValue && v <= Char.MaxValue)
1145 } else if (target_type == TypeManager.byte_type){
1146 if (v >= Byte.MinValue && v <= Byte.MaxValue)
1148 } else if (target_type == TypeManager.sbyte_type){
1149 if (v <= SByte.MaxValue)
1151 } else if (target_type == TypeManager.short_type){
1152 if (v <= Int16.MaxValue)
1154 } else if (target_type == TypeManager.int64_type)
1156 else if (target_type == TypeManager.uint64_type)
1160 } else if (c is CharConstant){
1161 char v = ((CharConstant) c).Value;
1163 if (target_type == TypeManager.int32_type)
1165 else if (target_type == TypeManager.uint32_type)
1167 else if (target_type == TypeManager.byte_type){
1168 if (v >= Byte.MinValue && v <= Byte.MaxValue)
1170 } else if (target_type == TypeManager.sbyte_type){
1171 if (v <= SByte.MaxValue)
1173 } else if (target_type == TypeManager.short_type){
1174 if (v <= Int16.MaxValue)
1176 } else if (target_type == TypeManager.ushort_type)
1178 else if (target_type == TypeManager.int64_type)
1180 else if (target_type == TypeManager.uint64_type)
1185 Error_ConstantValueCannotBeConverted (loc, s, target_type);
1190 // Load the object from the pointer.
1192 public static void LoadFromPtr (ILGenerator ig, Type t)
1194 if (t == TypeManager.int32_type)
1195 ig.Emit (OpCodes.Ldind_I4);
1196 else if (t == TypeManager.uint32_type)
1197 ig.Emit (OpCodes.Ldind_U4);
1198 else if (t == TypeManager.short_type)
1199 ig.Emit (OpCodes.Ldind_I2);
1200 else if (t == TypeManager.ushort_type)
1201 ig.Emit (OpCodes.Ldind_U2);
1202 else if (t == TypeManager.char_type)
1203 ig.Emit (OpCodes.Ldind_U2);
1204 else if (t == TypeManager.byte_type)
1205 ig.Emit (OpCodes.Ldind_U1);
1206 else if (t == TypeManager.sbyte_type)
1207 ig.Emit (OpCodes.Ldind_I1);
1208 else if (t == TypeManager.uint64_type)
1209 ig.Emit (OpCodes.Ldind_I8);
1210 else if (t == TypeManager.int64_type)
1211 ig.Emit (OpCodes.Ldind_I8);
1212 else if (t == TypeManager.float_type)
1213 ig.Emit (OpCodes.Ldind_R4);
1214 else if (t == TypeManager.double_type)
1215 ig.Emit (OpCodes.Ldind_R8);
1216 else if (t == TypeManager.bool_type)
1217 ig.Emit (OpCodes.Ldind_I1);
1218 else if (t == TypeManager.intptr_type)
1219 ig.Emit (OpCodes.Ldind_I);
1220 else if (TypeManager.IsEnumType (t)) {
1221 if (t == TypeManager.enum_type)
1222 ig.Emit (OpCodes.Ldind_Ref);
1224 LoadFromPtr (ig, TypeManager.EnumToUnderlying (t));
1225 } else if (t.IsValueType || t.IsGenericParameter)
1226 ig.Emit (OpCodes.Ldobj, t);
1227 else if (t.IsPointer)
1228 ig.Emit (OpCodes.Ldind_I);
1230 ig.Emit (OpCodes.Ldind_Ref);
1234 // The stack contains the pointer and the value of type `type'
1236 public static void StoreFromPtr (ILGenerator ig, Type type)
1238 if (TypeManager.IsEnumType (type))
1239 type = TypeManager.EnumToUnderlying (type);
1240 if (type == TypeManager.int32_type || type == TypeManager.uint32_type)
1241 ig.Emit (OpCodes.Stind_I4);
1242 else if (type == TypeManager.int64_type || type == TypeManager.uint64_type)
1243 ig.Emit (OpCodes.Stind_I8);
1244 else if (type == TypeManager.char_type || type == TypeManager.short_type ||
1245 type == TypeManager.ushort_type)
1246 ig.Emit (OpCodes.Stind_I2);
1247 else if (type == TypeManager.float_type)
1248 ig.Emit (OpCodes.Stind_R4);
1249 else if (type == TypeManager.double_type)
1250 ig.Emit (OpCodes.Stind_R8);
1251 else if (type == TypeManager.byte_type || type == TypeManager.sbyte_type ||
1252 type == TypeManager.bool_type)
1253 ig.Emit (OpCodes.Stind_I1);
1254 else if (type == TypeManager.intptr_type)
1255 ig.Emit (OpCodes.Stind_I);
1256 else if (type.IsValueType || type.IsGenericParameter)
1257 ig.Emit (OpCodes.Stobj, type);
1259 ig.Emit (OpCodes.Stind_Ref);
1263 // Returns the size of type `t' if known, otherwise, 0
1265 public static int GetTypeSize (Type t)
1267 t = TypeManager.TypeToCoreType (t);
1268 if (t == TypeManager.int32_type ||
1269 t == TypeManager.uint32_type ||
1270 t == TypeManager.float_type)
1272 else if (t == TypeManager.int64_type ||
1273 t == TypeManager.uint64_type ||
1274 t == TypeManager.double_type)
1276 else if (t == TypeManager.byte_type ||
1277 t == TypeManager.sbyte_type ||
1278 t == TypeManager.bool_type)
1280 else if (t == TypeManager.short_type ||
1281 t == TypeManager.char_type ||
1282 t == TypeManager.ushort_type)
1284 else if (t == TypeManager.decimal_type)
1290 public static void Error_NegativeArrayIndex (Location loc)
1292 Report.Error (248, loc, "Cannot create an array with a negative size");
1296 // Converts `source' to an int, uint, long or ulong.
1298 public Expression ExpressionToArrayArgument (EmitContext ec, Expression source, Location loc)
1302 bool old_checked = ec.CheckState;
1303 ec.CheckState = true;
1305 target = Convert.ImplicitConversion (ec, source, TypeManager.int32_type, loc);
1306 if (target == null){
1307 target = Convert.ImplicitConversion (ec, source, TypeManager.uint32_type, loc);
1308 if (target == null){
1309 target = Convert.ImplicitConversion (ec, source, TypeManager.int64_type, loc);
1310 if (target == null){
1311 target = Convert.ImplicitConversion (ec, source, TypeManager.uint64_type, loc);
1313 Convert.Error_CannotImplicitConversion (loc, source.Type, TypeManager.int32_type);
1317 ec.CheckState = old_checked;
1320 // Only positive constants are allowed at compile time
1322 if (target is Constant){
1323 if (target is IntConstant){
1324 if (((IntConstant) target).Value < 0){
1325 Error_NegativeArrayIndex (loc);
1330 if (target is LongConstant){
1331 if (((LongConstant) target).Value < 0){
1332 Error_NegativeArrayIndex (loc);
1345 /// This is just a base class for expressions that can
1346 /// appear on statements (invocations, object creation,
1347 /// assignments, post/pre increment and decrement). The idea
1348 /// being that they would support an extra Emition interface that
1349 /// does not leave a result on the stack.
1351 public abstract class ExpressionStatement : Expression {
1353 public virtual ExpressionStatement ResolveStatement (EmitContext ec)
1355 Expression e = Resolve (ec);
1359 ExpressionStatement es = e as ExpressionStatement;
1361 Error (201, "Only assignment, call, increment, decrement and new object " +
1362 "expressions can be used as a statement");
1368 /// Requests the expression to be emitted in a `statement'
1369 /// context. This means that no new value is left on the
1370 /// stack after invoking this method (constrasted with
1371 /// Emit that will always leave a value on the stack).
1373 public abstract void EmitStatement (EmitContext ec);
1377 /// This kind of cast is used to encapsulate the child
1378 /// whose type is child.Type into an expression that is
1379 /// reported to return "return_type". This is used to encapsulate
1380 /// expressions which have compatible types, but need to be dealt
1381 /// at higher levels with.
1383 /// For example, a "byte" expression could be encapsulated in one
1384 /// of these as an "unsigned int". The type for the expression
1385 /// would be "unsigned int".
1388 public class EmptyCast : Expression {
1389 protected Expression child;
1391 public Expression Child {
1397 public EmptyCast (Expression child, Type return_type)
1399 eclass = child.eclass;
1400 loc = child.Location;
1405 public override Expression DoResolve (EmitContext ec)
1407 // This should never be invoked, we are born in fully
1408 // initialized state.
1413 public override void Emit (EmitContext ec)
1420 // We need to special case this since an empty cast of
1421 // a NullLiteral is still a Constant
1423 public class NullCast : Constant {
1424 protected Expression child;
1426 public NullCast (Expression child, Type return_type)
1428 eclass = child.eclass;
1433 override public string AsString ()
1438 public override object GetValue ()
1443 public override Expression DoResolve (EmitContext ec)
1445 // This should never be invoked, we are born in fully
1446 // initialized state.
1451 public override void Emit (EmitContext ec)
1456 public override bool IsDefaultValue {
1458 throw new NotImplementedException ();
1462 public override bool IsNegative {
1471 /// This class is used to wrap literals which belong inside Enums
1473 public class EnumConstant : Constant {
1474 public Constant Child;
1476 public EnumConstant (Constant child, Type enum_type)
1478 eclass = child.eclass;
1483 public override Expression DoResolve (EmitContext ec)
1485 // This should never be invoked, we are born in fully
1486 // initialized state.
1491 public override void Emit (EmitContext ec)
1496 public override object GetValue ()
1498 return Child.GetValue ();
1501 public object GetValueAsEnumType ()
1503 return System.Enum.ToObject (type, Child.GetValue ());
1507 // Converts from one of the valid underlying types for an enumeration
1508 // (int32, uint32, int64, uint64, short, ushort, byte, sbyte) to
1509 // one of the internal compiler literals: Int/UInt/Long/ULong Literals.
1511 public Constant WidenToCompilerConstant ()
1513 Type t = TypeManager.EnumToUnderlying (Child.Type);
1514 object v = ((Constant) Child).GetValue ();;
1516 if (t == TypeManager.int32_type)
1517 return new IntConstant ((int) v);
1518 if (t == TypeManager.uint32_type)
1519 return new UIntConstant ((uint) v);
1520 if (t == TypeManager.int64_type)
1521 return new LongConstant ((long) v);
1522 if (t == TypeManager.uint64_type)
1523 return new ULongConstant ((ulong) v);
1524 if (t == TypeManager.short_type)
1525 return new ShortConstant ((short) v);
1526 if (t == TypeManager.ushort_type)
1527 return new UShortConstant ((ushort) v);
1528 if (t == TypeManager.byte_type)
1529 return new ByteConstant ((byte) v);
1530 if (t == TypeManager.sbyte_type)
1531 return new SByteConstant ((sbyte) v);
1533 throw new Exception ("Invalid enumeration underlying type: " + t);
1537 // Extracts the value in the enumeration on its native representation
1539 public object GetPlainValue ()
1541 Type t = TypeManager.EnumToUnderlying (Child.Type);
1542 object v = ((Constant) Child).GetValue ();;
1544 if (t == TypeManager.int32_type)
1546 if (t == TypeManager.uint32_type)
1548 if (t == TypeManager.int64_type)
1550 if (t == TypeManager.uint64_type)
1552 if (t == TypeManager.short_type)
1554 if (t == TypeManager.ushort_type)
1556 if (t == TypeManager.byte_type)
1558 if (t == TypeManager.sbyte_type)
1564 public override string AsString ()
1566 return Child.AsString ();
1569 public override DoubleConstant ConvertToDouble ()
1571 return Child.ConvertToDouble ();
1574 public override FloatConstant ConvertToFloat ()
1576 return Child.ConvertToFloat ();
1579 public override ULongConstant ConvertToULong ()
1581 return Child.ConvertToULong ();
1584 public override LongConstant ConvertToLong ()
1586 return Child.ConvertToLong ();
1589 public override UIntConstant ConvertToUInt ()
1591 return Child.ConvertToUInt ();
1594 public override IntConstant ConvertToInt ()
1596 return Child.ConvertToInt ();
1599 public override bool IsDefaultValue {
1601 return Child.IsDefaultValue;
1605 public override bool IsZeroInteger {
1606 get { return Child.IsZeroInteger; }
1609 public override bool IsNegative {
1611 return Child.IsNegative;
1617 /// This kind of cast is used to encapsulate Value Types in objects.
1619 /// The effect of it is to box the value type emitted by the previous
1622 public class BoxedCast : EmptyCast {
1624 public BoxedCast (Expression expr)
1625 : base (expr, TypeManager.object_type)
1627 eclass = ExprClass.Value;
1630 public BoxedCast (Expression expr, Type target_type)
1631 : base (expr, target_type)
1633 eclass = ExprClass.Value;
1636 public override Expression DoResolve (EmitContext ec)
1638 // This should never be invoked, we are born in fully
1639 // initialized state.
1644 public override void Emit (EmitContext ec)
1648 ec.ig.Emit (OpCodes.Box, child.Type);
1652 public class UnboxCast : EmptyCast {
1653 public UnboxCast (Expression expr, Type return_type)
1654 : base (expr, return_type)
1658 public override Expression DoResolve (EmitContext ec)
1660 // This should never be invoked, we are born in fully
1661 // initialized state.
1666 public override void Emit (EmitContext ec)
1669 ILGenerator ig = ec.ig;
1672 if (t.IsGenericParameter)
1673 ig.Emit (OpCodes.Unbox_Any, t);
1675 ig.Emit (OpCodes.Unbox, t);
1677 LoadFromPtr (ig, t);
1683 /// This is used to perform explicit numeric conversions.
1685 /// Explicit numeric conversions might trigger exceptions in a checked
1686 /// context, so they should generate the conv.ovf opcodes instead of
1689 public class ConvCast : EmptyCast {
1690 public enum Mode : byte {
1691 I1_U1, I1_U2, I1_U4, I1_U8, I1_CH,
1693 I2_I1, I2_U1, I2_U2, I2_U4, I2_U8, I2_CH,
1694 U2_I1, U2_U1, U2_I2, U2_CH,
1695 I4_I1, I4_U1, I4_I2, I4_U2, I4_U4, I4_U8, I4_CH,
1696 U4_I1, U4_U1, U4_I2, U4_U2, U4_I4, U4_CH,
1697 I8_I1, I8_U1, I8_I2, I8_U2, I8_I4, I8_U4, I8_U8, I8_CH,
1698 U8_I1, U8_U1, U8_I2, U8_U2, U8_I4, U8_U4, U8_I8, U8_CH,
1699 CH_I1, CH_U1, CH_I2,
1700 R4_I1, R4_U1, R4_I2, R4_U2, R4_I4, R4_U4, R4_I8, R4_U8, R4_CH,
1701 R8_I1, R8_U1, R8_I2, R8_U2, R8_I4, R8_U4, R8_I8, R8_U8, R8_CH, R8_R4
1707 public ConvCast (EmitContext ec, Expression child, Type return_type, Mode m)
1708 : base (child, return_type)
1710 checked_state = ec.CheckState;
1714 public override Expression DoResolve (EmitContext ec)
1716 // This should never be invoked, we are born in fully
1717 // initialized state.
1722 public override string ToString ()
1724 return String.Format ("ConvCast ({0}, {1})", mode, child);
1727 public override void Emit (EmitContext ec)
1729 ILGenerator ig = ec.ig;
1735 case Mode.I1_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1736 case Mode.I1_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1737 case Mode.I1_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1738 case Mode.I1_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1739 case Mode.I1_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1741 case Mode.U1_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1742 case Mode.U1_CH: /* nothing */ break;
1744 case Mode.I2_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1745 case Mode.I2_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1746 case Mode.I2_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1747 case Mode.I2_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1748 case Mode.I2_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1749 case Mode.I2_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1751 case Mode.U2_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1752 case Mode.U2_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
1753 case Mode.U2_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
1754 case Mode.U2_CH: /* nothing */ break;
1756 case Mode.I4_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1757 case Mode.I4_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1758 case Mode.I4_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
1759 case Mode.I4_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1760 case Mode.I4_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1761 case Mode.I4_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1762 case Mode.I4_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1764 case Mode.U4_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1765 case Mode.U4_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
1766 case Mode.U4_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
1767 case Mode.U4_U2: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
1768 case Mode.U4_I4: ig.Emit (OpCodes.Conv_Ovf_I4_Un); break;
1769 case Mode.U4_CH: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
1771 case Mode.I8_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1772 case Mode.I8_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1773 case Mode.I8_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
1774 case Mode.I8_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1775 case Mode.I8_I4: ig.Emit (OpCodes.Conv_Ovf_I4); break;
1776 case Mode.I8_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1777 case Mode.I8_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1778 case Mode.I8_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1780 case Mode.U8_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1781 case Mode.U8_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
1782 case Mode.U8_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
1783 case Mode.U8_U2: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
1784 case Mode.U8_I4: ig.Emit (OpCodes.Conv_Ovf_I4_Un); break;
1785 case Mode.U8_U4: ig.Emit (OpCodes.Conv_Ovf_U4_Un); break;
1786 case Mode.U8_I8: ig.Emit (OpCodes.Conv_Ovf_I8_Un); break;
1787 case Mode.U8_CH: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
1789 case Mode.CH_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1790 case Mode.CH_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
1791 case Mode.CH_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
1793 case Mode.R4_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1794 case Mode.R4_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1795 case Mode.R4_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
1796 case Mode.R4_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1797 case Mode.R4_I4: ig.Emit (OpCodes.Conv_Ovf_I4); break;
1798 case Mode.R4_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1799 case Mode.R4_I8: ig.Emit (OpCodes.Conv_Ovf_I8); break;
1800 case Mode.R4_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1801 case Mode.R4_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1803 case Mode.R8_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1804 case Mode.R8_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1805 case Mode.R8_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
1806 case Mode.R8_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1807 case Mode.R8_I4: ig.Emit (OpCodes.Conv_Ovf_I4); break;
1808 case Mode.R8_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1809 case Mode.R8_I8: ig.Emit (OpCodes.Conv_Ovf_I8); break;
1810 case Mode.R8_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1811 case Mode.R8_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1812 case Mode.R8_R4: ig.Emit (OpCodes.Conv_R4); break;
1816 case Mode.I1_U1: ig.Emit (OpCodes.Conv_U1); break;
1817 case Mode.I1_U2: ig.Emit (OpCodes.Conv_U2); break;
1818 case Mode.I1_U4: ig.Emit (OpCodes.Conv_U4); break;
1819 case Mode.I1_U8: ig.Emit (OpCodes.Conv_I8); break;
1820 case Mode.I1_CH: ig.Emit (OpCodes.Conv_U2); break;
1822 case Mode.U1_I1: ig.Emit (OpCodes.Conv_I1); break;
1823 case Mode.U1_CH: ig.Emit (OpCodes.Conv_U2); break;
1825 case Mode.I2_I1: ig.Emit (OpCodes.Conv_I1); break;
1826 case Mode.I2_U1: ig.Emit (OpCodes.Conv_U1); break;
1827 case Mode.I2_U2: ig.Emit (OpCodes.Conv_U2); break;
1828 case Mode.I2_U4: ig.Emit (OpCodes.Conv_U4); break;
1829 case Mode.I2_U8: ig.Emit (OpCodes.Conv_I8); break;
1830 case Mode.I2_CH: ig.Emit (OpCodes.Conv_U2); break;
1832 case Mode.U2_I1: ig.Emit (OpCodes.Conv_I1); break;
1833 case Mode.U2_U1: ig.Emit (OpCodes.Conv_U1); break;
1834 case Mode.U2_I2: ig.Emit (OpCodes.Conv_I2); break;
1835 case Mode.U2_CH: /* nothing */ break;
1837 case Mode.I4_I1: ig.Emit (OpCodes.Conv_I1); break;
1838 case Mode.I4_U1: ig.Emit (OpCodes.Conv_U1); break;
1839 case Mode.I4_I2: ig.Emit (OpCodes.Conv_I2); break;
1840 case Mode.I4_U4: /* nothing */ break;
1841 case Mode.I4_U2: ig.Emit (OpCodes.Conv_U2); break;
1842 case Mode.I4_U8: ig.Emit (OpCodes.Conv_I8); break;
1843 case Mode.I4_CH: ig.Emit (OpCodes.Conv_U2); break;
1845 case Mode.U4_I1: ig.Emit (OpCodes.Conv_I1); break;
1846 case Mode.U4_U1: ig.Emit (OpCodes.Conv_U1); break;
1847 case Mode.U4_I2: ig.Emit (OpCodes.Conv_I2); break;
1848 case Mode.U4_U2: ig.Emit (OpCodes.Conv_U2); break;
1849 case Mode.U4_I4: /* nothing */ break;
1850 case Mode.U4_CH: ig.Emit (OpCodes.Conv_U2); break;
1852 case Mode.I8_I1: ig.Emit (OpCodes.Conv_I1); break;
1853 case Mode.I8_U1: ig.Emit (OpCodes.Conv_U1); break;
1854 case Mode.I8_I2: ig.Emit (OpCodes.Conv_I2); break;
1855 case Mode.I8_U2: ig.Emit (OpCodes.Conv_U2); break;
1856 case Mode.I8_I4: ig.Emit (OpCodes.Conv_I4); break;
1857 case Mode.I8_U4: ig.Emit (OpCodes.Conv_U4); break;
1858 case Mode.I8_U8: /* nothing */ break;
1859 case Mode.I8_CH: ig.Emit (OpCodes.Conv_U2); break;
1861 case Mode.U8_I1: ig.Emit (OpCodes.Conv_I1); break;
1862 case Mode.U8_U1: ig.Emit (OpCodes.Conv_U1); break;
1863 case Mode.U8_I2: ig.Emit (OpCodes.Conv_I2); break;
1864 case Mode.U8_U2: ig.Emit (OpCodes.Conv_U2); break;
1865 case Mode.U8_I4: ig.Emit (OpCodes.Conv_I4); break;
1866 case Mode.U8_U4: ig.Emit (OpCodes.Conv_U4); break;
1867 case Mode.U8_I8: /* nothing */ break;
1868 case Mode.U8_CH: ig.Emit (OpCodes.Conv_U2); break;
1870 case Mode.CH_I1: ig.Emit (OpCodes.Conv_I1); break;
1871 case Mode.CH_U1: ig.Emit (OpCodes.Conv_U1); break;
1872 case Mode.CH_I2: ig.Emit (OpCodes.Conv_I2); break;
1874 case Mode.R4_I1: ig.Emit (OpCodes.Conv_I1); break;
1875 case Mode.R4_U1: ig.Emit (OpCodes.Conv_U1); break;
1876 case Mode.R4_I2: ig.Emit (OpCodes.Conv_I2); break;
1877 case Mode.R4_U2: ig.Emit (OpCodes.Conv_U2); break;
1878 case Mode.R4_I4: ig.Emit (OpCodes.Conv_I4); break;
1879 case Mode.R4_U4: ig.Emit (OpCodes.Conv_U4); break;
1880 case Mode.R4_I8: ig.Emit (OpCodes.Conv_I8); break;
1881 case Mode.R4_U8: ig.Emit (OpCodes.Conv_U8); break;
1882 case Mode.R4_CH: ig.Emit (OpCodes.Conv_U2); break;
1884 case Mode.R8_I1: ig.Emit (OpCodes.Conv_I1); break;
1885 case Mode.R8_U1: ig.Emit (OpCodes.Conv_U1); break;
1886 case Mode.R8_I2: ig.Emit (OpCodes.Conv_I2); break;
1887 case Mode.R8_U2: ig.Emit (OpCodes.Conv_U2); break;
1888 case Mode.R8_I4: ig.Emit (OpCodes.Conv_I4); break;
1889 case Mode.R8_U4: ig.Emit (OpCodes.Conv_U4); break;
1890 case Mode.R8_I8: ig.Emit (OpCodes.Conv_I8); break;
1891 case Mode.R8_U8: ig.Emit (OpCodes.Conv_U8); break;
1892 case Mode.R8_CH: ig.Emit (OpCodes.Conv_U2); break;
1893 case Mode.R8_R4: ig.Emit (OpCodes.Conv_R4); break;
1899 public class OpcodeCast : EmptyCast {
1903 public OpcodeCast (Expression child, Type return_type, OpCode op)
1904 : base (child, return_type)
1908 second_valid = false;
1911 public OpcodeCast (Expression child, Type return_type, OpCode op, OpCode op2)
1912 : base (child, return_type)
1917 second_valid = true;
1920 public override Expression DoResolve (EmitContext ec)
1922 // This should never be invoked, we are born in fully
1923 // initialized state.
1928 public override void Emit (EmitContext ec)
1939 /// This kind of cast is used to encapsulate a child and cast it
1940 /// to the class requested
1942 public class ClassCast : EmptyCast {
1943 public ClassCast (Expression child, Type return_type)
1944 : base (child, return_type)
1949 public override Expression DoResolve (EmitContext ec)
1951 // This should never be invoked, we are born in fully
1952 // initialized state.
1957 public override void Emit (EmitContext ec)
1961 if (child.Type.IsGenericParameter)
1962 ec.ig.Emit (OpCodes.Box, child.Type);
1964 if (type.IsGenericParameter)
1965 ec.ig.Emit (OpCodes.Unbox_Any, type);
1967 ec.ig.Emit (OpCodes.Castclass, type);
1972 /// SimpleName expressions are formed of a single word and only happen at the beginning
1973 /// of a dotted-name.
1975 public class SimpleName : Expression {
1977 public readonly TypeArguments Arguments;
1979 public SimpleName (string name, Location l)
1985 public SimpleName (string name, TypeArguments args, Location l)
1992 public SimpleName (string name, TypeParameter[] type_params, Location l)
1997 Arguments = new TypeArguments (l);
1998 foreach (TypeParameter type_param in type_params)
1999 Arguments.Add (new TypeParameterExpr (type_param, l));
2002 public static string RemoveGenericArity (string name)
2005 StringBuilder sb = new StringBuilder ();
2006 while (start < name.Length) {
2007 int pos = name.IndexOf ('`', start);
2009 sb.Append (name.Substring (start));
2013 sb.Append (name.Substring (start, pos-start));
2016 while ((pos < name.Length) && Char.IsNumber (name [pos]))
2022 return sb.ToString ();
2025 public SimpleName GetMethodGroup ()
2027 return new SimpleName (RemoveGenericArity (Name), Arguments, loc);
2030 public static void Error_ObjectRefRequired (EmitContext ec, Location l, string name)
2032 if (ec.IsFieldInitializer)
2035 "A field initializer cannot reference the non-static field, " +
2036 "method or property `"+name+"'");
2040 "An object reference is required " +
2041 "for the non-static field `"+name+"'");
2044 public bool IdenticalNameAndTypeName (EmitContext ec, Expression resolved_to, Location loc)
2046 return resolved_to != null && resolved_to.Type != null &&
2047 resolved_to.Type.Name == Name &&
2048 (ec.DeclSpace.LookupType (Name, loc, /* ignore_cs0104 = */ true) != null);
2051 public override Expression DoResolve (EmitContext ec)
2053 return SimpleNameResolve (ec, null, false);
2056 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
2058 return SimpleNameResolve (ec, right_side, false);
2062 public Expression DoResolve (EmitContext ec, bool intermediate)
2064 return SimpleNameResolve (ec, null, intermediate);
2067 private bool IsNestedChild (Type t, Type parent)
2072 while (parent != null) {
2073 if (parent.IsGenericInstance)
2074 parent = parent.GetGenericTypeDefinition ();
2076 if (TypeManager.IsNestedChildOf (t, parent))
2079 parent = parent.BaseType;
2085 FullNamedExpression ResolveNested (EmitContext ec, Type t)
2087 if (!t.IsGenericTypeDefinition)
2090 DeclSpace ds = ec.DeclSpace;
2091 while (ds != null) {
2092 if (IsNestedChild (t, ds.TypeBuilder))
2101 Type[] gen_params = t.GetGenericArguments ();
2103 int arg_count = Arguments != null ? Arguments.Count : 0;
2105 for (; (ds != null) && ds.IsGeneric; ds = ds.Parent) {
2106 if (arg_count + ds.CountTypeParameters == gen_params.Length) {
2107 TypeArguments new_args = new TypeArguments (loc);
2108 foreach (TypeParameter param in ds.TypeParameters)
2109 new_args.Add (new TypeParameterExpr (param, loc));
2111 if (Arguments != null)
2112 new_args.Add (Arguments);
2114 return new ConstructedType (t, new_args, loc);
2121 public override FullNamedExpression ResolveAsTypeStep (EmitContext ec)
2123 FullNamedExpression dt = ec.DeclSpace.LookupGeneric (Name, loc);
2125 return dt.ResolveAsTypeStep (ec);
2127 int errors = Report.Errors;
2128 dt = ec.DeclSpace.LookupType (Name, loc, /*ignore_cs0104=*/ false);
2129 if (Report.Errors != errors)
2132 if ((dt == null) || (dt.Type == null))
2135 FullNamedExpression nested = ResolveNested (ec, dt.Type);
2137 return nested.ResolveAsTypeStep (ec);
2139 if (Arguments != null) {
2140 ConstructedType ct = new ConstructedType (dt, Arguments, loc);
2141 return ct.ResolveAsTypeStep (ec);
2147 Expression SimpleNameResolve (EmitContext ec, Expression right_side, bool intermediate)
2149 Expression e = DoSimpleNameResolve (ec, right_side, intermediate);
2153 Block current_block = ec.CurrentBlock;
2154 if (current_block != null){
2155 if (current_block.IsVariableNameUsedInChildBlock (Name)) {
2156 Report.Error (135, Location,
2157 "'{0}' has a different meaning in a child block", Name);
2161 if (!(e is LocalVariableReference) && current_block.IsVariableNameUsedInBlock (Name)) {
2162 // Catch some false positives, e.g., when a local variable resolves to a constant.
2163 LocalInfo vi = current_block.GetLocalInfo (Name);
2165 Report.Error (136, Location, "'{0}' has a different meaning later in the block", Name);
2171 if (e.Type != null && e.Type.IsPointer && !ec.InUnsafe) {
2180 /// 7.5.2: Simple Names.
2182 /// Local Variables and Parameters are handled at
2183 /// parse time, so they never occur as SimpleNames.
2185 /// The `intermediate' flag is used by MemberAccess only
2186 /// and it is used to inform us that it is ok for us to
2187 /// avoid the static check, because MemberAccess might end
2188 /// up resolving the Name as a Type name and the access as
2189 /// a static type access.
2191 /// ie: Type Type; .... { Type.GetType (""); }
2193 /// Type is both an instance variable and a Type; Type.GetType
2194 /// is the static method not an instance method of type.
2196 Expression DoSimpleNameResolve (EmitContext ec, Expression right_side, bool intermediate)
2198 Expression e = null;
2201 // Stage 1: Performed by the parser (binding to locals or parameters).
2203 Block current_block = ec.CurrentBlock;
2204 if (current_block != null){
2205 LocalInfo vi = current_block.GetLocalInfo (Name);
2209 var = new LocalVariableReference (ec.CurrentBlock, Name, loc);
2211 if (right_side != null)
2212 return var.ResolveLValue (ec, right_side);
2214 return var.Resolve (ec);
2217 ParameterReference pref = current_block.GetParameterReference (Name, loc);
2219 if (right_side != null)
2220 return pref.ResolveLValue (ec, right_side);
2222 return pref.Resolve (ec);
2227 // Stage 2: Lookup members
2230 DeclSpace lookup_ds = ec.DeclSpace;
2231 Type almost_matched_type = null;
2232 ArrayList almost_matched = null;
2234 if (lookup_ds.TypeBuilder == null)
2237 e = MemberLookup (ec, lookup_ds.TypeBuilder, Name, loc);
2241 if (almost_matched == null && almostMatchedMembers.Count > 0) {
2242 almost_matched_type = lookup_ds.TypeBuilder;
2243 almost_matched = (ArrayList) almostMatchedMembers.Clone ();
2246 lookup_ds =lookup_ds.Parent;
2247 } while (lookup_ds != null);
2249 if (e == null && ec.ContainerType != null)
2250 e = MemberLookup (ec, ec.ContainerType, Name, loc);
2253 if (almost_matched == null && almostMatchedMembers.Count > 0) {
2254 almost_matched_type = ec.ContainerType;
2255 almost_matched = (ArrayList) almostMatchedMembers.Clone ();
2257 e = ResolveAsTypeStep (ec);
2261 if (almost_matched != null)
2262 almostMatchedMembers = almost_matched;
2263 if (almost_matched_type == null)
2264 almost_matched_type = ec.ContainerType;
2265 MemberLookupFailed (ec, null, almost_matched_type, ((SimpleName) this).Name, ec.DeclSpace.Name, true, loc);
2272 if (e is MemberExpr) {
2273 MemberExpr me = (MemberExpr) e;
2274 Expression left = (ec.IsStatic || ec.IsFieldInitializer)
2275 ? (Expression) new TypeExpression (ec.ContainerType, loc)
2276 : (Expression) ec.GetThis (loc);
2278 e = me.ResolveMemberAccess (ec, left, loc, (intermediate ? this : null), true);
2282 me = e as MemberExpr;
2286 if (Arguments != null) {
2287 MethodGroupExpr mg = me as MethodGroupExpr;
2291 return mg.ResolveGeneric (ec, Arguments);
2294 // This fails if ResolveMemberAccess() was unable to decide whether
2295 // it's a field or a type of the same name.
2296 if (!me.IsStatic && me.InstanceExpression == null &&
2297 (intermediate && IdenticalNameAndTypeName (ec, e, loc)))
2301 TypeManager.IsNestedFamilyAccessible (me.InstanceExpression.Type, me.DeclaringType) &&
2302 me.InstanceExpression.Type != me.DeclaringType &&
2303 !TypeManager.IsFamilyAccessible (me.InstanceExpression.Type, me.DeclaringType) &&
2304 (!intermediate || !IdenticalNameAndTypeName (ec, e, loc))) {
2305 Error (38, "Cannot access nonstatic member `" + me.Name + "' of " +
2306 "outer type `" + me.DeclaringType + "' via nested type `" +
2307 me.InstanceExpression.Type + "'");
2311 return (right_side != null)
2312 ? me.DoResolveLValue (ec, right_side)
2313 : me.DoResolve (ec);
2319 public override void Emit (EmitContext ec)
2322 // If this is ever reached, then we failed to
2323 // find the name as a namespace
2326 Error (103, "The name `" + Name +
2327 "' does not exist in the class `" +
2328 ec.DeclSpace.Name + "'");
2331 public override string ToString ()
2338 /// Represents a namespace or a type. The name of the class was inspired by
2339 /// section 10.8.1 (Fully Qualified Names).
2341 public abstract class FullNamedExpression : Expression {
2342 public override FullNamedExpression ResolveAsTypeStep (EmitContext ec)
2347 public abstract string FullName {
2353 /// Fully resolved expression that evaluates to a type
2355 public abstract class TypeExpr : FullNamedExpression {
2356 override public FullNamedExpression ResolveAsTypeStep (EmitContext ec)
2358 TypeExpr t = DoResolveAsTypeStep (ec);
2362 eclass = ExprClass.Type;
2366 override public Expression DoResolve (EmitContext ec)
2368 return ResolveAsTypeTerminal (ec);
2371 override public void Emit (EmitContext ec)
2373 throw new Exception ("Should never be called");
2376 public virtual bool CheckAccessLevel (DeclSpace ds)
2378 return ds.CheckAccessLevel (Type);
2381 public virtual bool AsAccessible (DeclSpace ds, int flags)
2383 return ds.AsAccessible (Type, flags);
2386 public virtual bool IsClass {
2387 get { return Type.IsClass; }
2390 public virtual bool IsValueType {
2391 get { return Type.IsValueType; }
2394 public virtual bool IsInterface {
2395 get { return Type.IsInterface; }
2398 public virtual bool IsSealed {
2399 get { return Type.IsSealed; }
2402 public virtual bool CanInheritFrom ()
2404 if (Type == TypeManager.enum_type ||
2405 (Type == TypeManager.value_type && RootContext.StdLib) ||
2406 Type == TypeManager.multicast_delegate_type ||
2407 Type == TypeManager.delegate_type ||
2408 Type == TypeManager.array_type)
2414 protected abstract TypeExpr DoResolveAsTypeStep (EmitContext ec);
2416 public virtual Type ResolveType (EmitContext ec)
2418 TypeExpr t = ResolveAsTypeTerminal (ec);
2425 public abstract string Name {
2429 public override bool Equals (object obj)
2431 TypeExpr tobj = obj as TypeExpr;
2435 return Type == tobj.Type;
2438 public override int GetHashCode ()
2440 return Type.GetHashCode ();
2443 public override string ToString ()
2449 public class TypeExpression : TypeExpr {
2450 public TypeExpression (Type t, Location l)
2453 eclass = ExprClass.Type;
2457 protected override TypeExpr DoResolveAsTypeStep (EmitContext ec)
2462 public override string Name {
2464 return Type.ToString ();
2468 public override string FullName {
2470 return Type.FullName != null ? Type.FullName : Type.Name;
2476 /// Used to create types from a fully qualified name. These are just used
2477 /// by the parser to setup the core types. A TypeLookupExpression is always
2478 /// classified as a type.
2480 public class TypeLookupExpression : TypeExpr {
2483 public TypeLookupExpression (string name)
2488 protected override TypeExpr DoResolveAsTypeStep (EmitContext ec)
2491 FullNamedExpression t = ec.DeclSpace.LookupType (name, Location.Null, /*ignore_cs0104=*/ false);
2493 Report.Error (246, loc, "Cannot find type `" + name + "'");
2496 if (!(t is TypeExpr)) {
2497 Report.Error (118, Location, "'{0}' denotes a '{1}', where a type was expected",
2498 t.FullName, t.ExprClassName ());
2502 type = ((TypeExpr) t).ResolveType (ec);
2508 public override string Name {
2514 public override string FullName {
2522 /// Represents an "unbound generic type", ie. typeof (Foo<>).
2525 public class UnboundTypeExpression : TypeLookupExpression {
2526 public UnboundTypeExpression (string name)
2531 public class TypeAliasExpression : TypeExpr {
2532 FullNamedExpression alias;
2537 public TypeAliasExpression (FullNamedExpression alias, TypeArguments args, Location l)
2543 eclass = ExprClass.Type;
2545 name = alias.FullName + "<" + args.ToString () + ">";
2547 name = alias.FullName;
2550 public override string Name {
2551 get { return alias.FullName; }
2554 public override string FullName {
2555 get { return name; }
2558 protected override TypeExpr DoResolveAsTypeStep (EmitContext ec)
2560 texpr = alias.ResolveAsTypeTerminal (ec);
2564 Type type = texpr.Type;
2565 int num_args = TypeManager.GetNumberOfTypeArguments (type);
2568 if (num_args == 0) {
2569 Report.Error (308, loc,
2570 "The non-generic type `{0}' cannot " +
2571 "be used with type arguments.",
2572 TypeManager.CSharpName (type));
2576 ConstructedType ctype = new ConstructedType (type, args, loc);
2577 return ctype.ResolveAsTypeTerminal (ec);
2578 } else if (num_args > 0) {
2579 Report.Error (305, loc,
2580 "Using the generic type `{0}' " +
2581 "requires {1} type arguments",
2582 TypeManager.GetFullName (type), num_args);
2586 return new TypeExpression (type, loc);
2589 public override bool CheckAccessLevel (DeclSpace ds)
2591 return texpr.CheckAccessLevel (ds);
2594 public override bool AsAccessible (DeclSpace ds, int flags)
2596 return texpr.AsAccessible (ds, flags);
2599 public override bool IsClass {
2600 get { return texpr.IsClass; }
2603 public override bool IsValueType {
2604 get { return texpr.IsValueType; }
2607 public override bool IsInterface {
2608 get { return texpr.IsInterface; }
2611 public override bool IsSealed {
2612 get { return texpr.IsSealed; }
2617 /// This class denotes an expression which evaluates to a member
2618 /// of a struct or a class.
2620 public abstract class MemberExpr : Expression
2623 /// The name of this member.
2625 public abstract string Name {
2630 /// Whether this is an instance member.
2632 public abstract bool IsInstance {
2637 /// Whether this is a static member.
2639 public abstract bool IsStatic {
2644 /// The type which declares this member.
2646 public abstract Type DeclaringType {
2651 /// The instance expression associated with this member, if it's a
2652 /// non-static member.
2654 public Expression InstanceExpression;
2656 public static void error176 (Location loc, string name)
2658 Report.Error (176, loc, "Static member `" + name + "' cannot be accessed " +
2659 "with an instance reference, qualify with a type name instead");
2663 // TODO: possible optimalization
2664 // Cache resolved constant result in FieldBuilder <-> expression map
2665 public virtual Expression ResolveMemberAccess (EmitContext ec, Expression left, Location loc,
2666 SimpleName original, bool left_is_inferred)
2670 // original == null || original.Resolve (...) === (left_is_inferred ? this : left)
2673 if (left is TypeExpr) {
2675 if ((ec.IsFieldInitializer || ec.IsStatic) && left_is_inferred &&
2676 original != null && original.IdenticalNameAndTypeName (ec, this, loc))
2679 SimpleName.Error_ObjectRefRequired (ec, loc, Name);
2687 if (left_is_inferred ||
2688 (original != null && original.IdenticalNameAndTypeName (ec, left, loc)))
2691 error176 (loc, Name);
2695 InstanceExpression = left;
2702 /// MethodGroup Expression.
2704 /// This is a fully resolved expression that evaluates to a type
2706 public class MethodGroupExpr : MemberExpr {
2707 public MethodBase [] Methods;
2708 bool has_type_arguments = false;
2709 bool identical_type_name = false;
2712 public MethodGroupExpr (MemberInfo [] mi, Location l)
2714 Methods = new MethodBase [mi.Length];
2715 mi.CopyTo (Methods, 0);
2716 eclass = ExprClass.MethodGroup;
2717 type = TypeManager.object_type;
2721 public MethodGroupExpr (ArrayList list, Location l)
2723 Methods = new MethodBase [list.Count];
2726 list.CopyTo (Methods, 0);
2728 foreach (MemberInfo m in list){
2729 if (!(m is MethodBase)){
2730 Console.WriteLine ("Name " + m.Name);
2731 Console.WriteLine ("Found a: " + m.GetType ().FullName);
2738 eclass = ExprClass.MethodGroup;
2739 type = TypeManager.object_type;
2742 public override Type DeclaringType {
2745 // We assume that the top-level type is in the end
2747 return Methods [Methods.Length - 1].DeclaringType;
2748 //return Methods [0].DeclaringType;
2752 public bool HasTypeArguments {
2754 return has_type_arguments;
2758 has_type_arguments = value;
2762 public bool IdenticalTypeName {
2764 return identical_type_name;
2768 identical_type_name = value;
2772 public bool IsBase {
2781 public override string Name {
2783 //return Methods [0].Name;
2784 return Methods [Methods.Length - 1].Name;
2788 public override bool IsInstance {
2790 foreach (MethodBase mb in Methods)
2798 public override bool IsStatic {
2800 foreach (MethodBase mb in Methods)
2808 public override Expression ResolveMemberAccess (EmitContext ec, Expression left, Location loc,
2809 SimpleName original, bool left_is_inferred)
2811 if (!left_is_inferred &&
2812 !(left is TypeExpr) &&
2813 original != null && original.IdenticalNameAndTypeName (ec, left, loc))
2814 IdenticalTypeName = true;
2816 return base.ResolveMemberAccess (ec, left, loc, original, left_is_inferred);
2819 override public Expression DoResolve (EmitContext ec)
2822 InstanceExpression = null;
2824 if (InstanceExpression != null) {
2825 InstanceExpression = InstanceExpression.DoResolve (ec);
2826 if (InstanceExpression == null)
2833 public void ReportUsageError ()
2835 Report.Error (654, loc, "Method `" + DeclaringType + "." +
2836 Name + "()' is referenced without parentheses");
2839 override public void Emit (EmitContext ec)
2841 ReportUsageError ();
2844 bool RemoveMethods (bool keep_static)
2846 ArrayList smethods = new ArrayList ();
2848 foreach (MethodBase mb in Methods){
2849 if (mb.IsStatic == keep_static)
2853 if (smethods.Count == 0)
2856 Methods = new MethodBase [smethods.Count];
2857 smethods.CopyTo (Methods, 0);
2863 /// Removes any instance methods from the MethodGroup, returns
2864 /// false if the resulting set is empty.
2866 public bool RemoveInstanceMethods ()
2868 return RemoveMethods (true);
2872 /// Removes any static methods from the MethodGroup, returns
2873 /// false if the resulting set is empty.
2875 public bool RemoveStaticMethods ()
2877 return RemoveMethods (false);
2880 public Expression ResolveGeneric (EmitContext ec, TypeArguments args)
2882 if (args.Resolve (ec) == false)
2885 Type[] atypes = args.Arguments;
2887 int first_count = 0;
2888 MethodInfo first = null;
2890 ArrayList list = new ArrayList ();
2891 foreach (MethodBase mb in Methods) {
2892 MethodInfo mi = mb as MethodInfo;
2893 if ((mi == null) || !mi.HasGenericParameters)
2896 Type[] gen_params = mi.GetGenericArguments ();
2898 if (first == null) {
2900 first_count = gen_params.Length;
2903 if (gen_params.Length != atypes.Length)
2906 list.Add (mi.BindGenericParameters (atypes));
2909 if (list.Count > 0) {
2910 MethodGroupExpr new_mg = new MethodGroupExpr (list, Location);
2911 new_mg.InstanceExpression = InstanceExpression;
2912 new_mg.HasTypeArguments = true;
2918 305, loc, "Using the generic method `{0}' " +
2919 "requires {1} type arguments", Name,
2923 308, loc, "The non-generic method `{0}' " +
2924 "cannot be used with type arguments", Name);
2931 /// Fully resolved expression that evaluates to a Field
2933 public class FieldExpr : MemberExpr, IAssignMethod, IMemoryLocation, IVariable {
2934 public readonly FieldInfo FieldInfo;
2935 VariableInfo variable_info;
2937 LocalTemporary temp;
2939 bool is_field_initializer;
2941 public FieldExpr (FieldInfo fi, Location l)
2944 eclass = ExprClass.Variable;
2945 type = TypeManager.TypeToCoreType (fi.FieldType);
2949 public override string Name {
2951 return FieldInfo.Name;
2955 public override bool IsInstance {
2957 return !FieldInfo.IsStatic;
2961 public override bool IsStatic {
2963 return FieldInfo.IsStatic;
2967 public override Type DeclaringType {
2969 return FieldInfo.DeclaringType;
2973 public VariableInfo VariableInfo {
2975 return variable_info;
2979 public override Expression ResolveMemberAccess (EmitContext ec, Expression left, Location loc,
2980 SimpleName original, bool left_is_inferred)
2982 bool left_is_type = left is TypeExpr;
2984 FieldInfo fi = FieldInfo.Mono_GetGenericFieldDefinition ();
2986 Type decl_type = fi.DeclaringType;
2988 bool is_emitted = fi is FieldBuilder;
2989 Type t = fi.FieldType;
2992 Const c = TypeManager.LookupConstant ((FieldBuilder) fi);
2996 if (!c.LookupConstantValue (out o))
2999 object real_value = ((Constant) c.Expr).GetValue ();
3001 Expression exp = Constantify (real_value, t);
3003 if (!left_is_inferred && !left_is_type &&
3004 (original == null || !original.IdenticalNameAndTypeName (ec, left, loc))) {
3005 Report.SymbolRelatedToPreviousError (c);
3006 error176 (loc, c.GetSignatureForError ());
3014 // IsInitOnly is because of MS compatibility, I don't know why but they emit decimal constant as InitOnly
3015 if (fi.IsInitOnly && !is_emitted && t == TypeManager.decimal_type) {
3016 object[] attrs = fi.GetCustomAttributes (TypeManager.decimal_constant_attribute_type, false);
3017 if (attrs.Length == 1)
3018 return new DecimalConstant (((System.Runtime.CompilerServices.DecimalConstantAttribute) attrs [0]).Value);
3025 o = TypeManager.GetValue ((FieldBuilder) fi);
3027 o = fi.GetValue (fi);
3029 if (decl_type.IsSubclassOf (TypeManager.enum_type)) {
3030 if (!left_is_inferred && !left_is_type &&
3031 (original == null || !original.IdenticalNameAndTypeName (ec, left, loc))) {
3032 error176 (loc, fi.Name);
3036 Expression enum_member = MemberLookup (
3037 ec, decl_type, "value__", MemberTypes.Field,
3038 AllBindingFlags | BindingFlags.NonPublic, loc);
3040 Enum en = TypeManager.LookupEnum (decl_type);
3044 c = Constantify (o, en.UnderlyingType);
3046 c = Constantify (o, enum_member.Type);
3048 return new EnumConstant (c, decl_type);
3051 Expression exp = Constantify (o, t);
3053 if (!left_is_inferred && !left_is_type) {
3054 error176 (loc, fi.Name);
3061 if (t.IsPointer && !ec.InUnsafe) {
3066 return base.ResolveMemberAccess (ec, left, loc, original, left_is_inferred);
3069 override public Expression DoResolve (EmitContext ec)
3071 if (!FieldInfo.IsStatic){
3072 if (InstanceExpression == null){
3074 // This can happen when referencing an instance field using
3075 // a fully qualified type expression: TypeName.InstanceField = xxx
3077 SimpleName.Error_ObjectRefRequired (ec, loc, FieldInfo.Name);
3081 // Resolve the field's instance expression while flow analysis is turned
3082 // off: when accessing a field "a.b", we must check whether the field
3083 // "a.b" is initialized, not whether the whole struct "a" is initialized.
3084 InstanceExpression = InstanceExpression.Resolve (ec, ResolveFlags.VariableOrValue |
3085 ResolveFlags.DisableFlowAnalysis);
3086 if (InstanceExpression == null)
3090 ObsoleteAttribute oa;
3091 FieldBase f = TypeManager.GetField (FieldInfo);
3093 oa = f.GetObsoleteAttribute (f.Parent);
3095 AttributeTester.Report_ObsoleteMessage (oa, f.GetSignatureForError (), loc);
3096 // To be sure that type is external because we do not register generated fields
3097 } else if (!(FieldInfo.DeclaringType is TypeBuilder)) {
3098 oa = AttributeTester.GetMemberObsoleteAttribute (FieldInfo);
3100 AttributeTester.Report_ObsoleteMessage (oa, TypeManager.GetFullNameSignature (FieldInfo), loc);
3103 if (ec.CurrentAnonymousMethod != null){
3104 if (!FieldInfo.IsStatic){
3105 if (ec.TypeContainer is Struct){
3106 Report.Error (1673, loc, "Can not reference instance variables in anonymous methods hosted in structs");
3109 ec.CaptureField (this);
3113 // If the instance expression is a local variable or parameter.
3114 IVariable var = InstanceExpression as IVariable;
3115 if ((var == null) || (var.VariableInfo == null))
3118 VariableInfo vi = var.VariableInfo;
3119 if (!vi.IsFieldAssigned (ec, FieldInfo.Name, loc))
3122 variable_info = vi.GetSubStruct (FieldInfo.Name);
3126 void Report_AssignToReadonly (bool is_instance)
3131 msg = "Readonly field can not be assigned outside " +
3132 "of constructor or variable initializer";
3134 msg = "A static readonly field can only be assigned in " +
3135 "a static constructor";
3137 Report.Error (is_instance ? 191 : 198, loc, msg);
3140 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
3142 IVariable var = InstanceExpression as IVariable;
3143 if ((var != null) && (var.VariableInfo != null))
3144 var.VariableInfo.SetFieldAssigned (ec, FieldInfo.Name);
3146 Expression e = DoResolve (ec);
3151 if (!FieldInfo.IsStatic && (InstanceExpression.Type.IsValueType && !(InstanceExpression is IMemoryLocation))) {
3152 // FIXME: Provide better error reporting.
3153 Error (1612, "Cannot modify expression because it is not a variable.");
3157 if (!FieldInfo.IsInitOnly)
3160 FieldBase fb = TypeManager.GetField (FieldInfo);
3165 // InitOnly fields can only be assigned in constructors
3168 if (ec.IsConstructor){
3169 if (IsStatic && !ec.IsStatic)
3170 Report_AssignToReadonly (false);
3173 if (!is_field_initializer &&
3174 (ec.TypeContainer.CurrentType != null))
3175 ctype = ec.TypeContainer.CurrentType;
3177 ctype = ec.ContainerType;
3179 if (TypeManager.IsEqual (ctype, FieldInfo.DeclaringType))
3183 Report_AssignToReadonly (!IsStatic);
3188 public override void CheckMarshallByRefAccess (Type container)
3190 if (!IsStatic && Type.IsValueType && !container.IsSubclassOf (TypeManager.mbr_type) && DeclaringType.IsSubclassOf (TypeManager.mbr_type)) {
3191 Report.SymbolRelatedToPreviousError (DeclaringType);
3192 Report.Error (1690, loc, "Cannot call '{0}' method, property, or indexer because it is a value type member of a marshal-by-reference class", Name);
3196 public bool VerifyFixed (bool is_expression)
3198 IVariable variable = InstanceExpression as IVariable;
3199 if ((variable == null) || !variable.VerifyFixed (true))
3205 public override int GetHashCode()
3207 return FieldInfo.GetHashCode ();
3210 public override bool Equals (object obj)
3212 FieldExpr fe = obj as FieldExpr;
3216 if (FieldInfo != fe.FieldInfo)
3219 if (InstanceExpression == null || fe.InstanceExpression == null)
3222 return InstanceExpression.Equals (fe.InstanceExpression);
3225 public void Emit (EmitContext ec, bool leave_copy)
3227 ILGenerator ig = ec.ig;
3228 bool is_volatile = false;
3230 if (FieldInfo is FieldBuilder){
3231 FieldBase f = TypeManager.GetField (FieldInfo);
3233 if ((f.ModFlags & Modifiers.VOLATILE) != 0)
3236 f.status |= Field.Status.USED;
3240 if (FieldInfo.IsStatic){
3242 ig.Emit (OpCodes.Volatile);
3244 ig.Emit (OpCodes.Ldsfld, FieldInfo);
3250 ig.Emit (OpCodes.Volatile);
3252 IFixedBuffer ff = AttributeTester.GetFixedBuffer (FieldInfo);
3255 ig.Emit (OpCodes.Ldflda, FieldInfo);
3256 ig.Emit (OpCodes.Ldflda, ff.Element);
3259 ig.Emit (OpCodes.Ldfld, FieldInfo);
3264 ec.ig.Emit (OpCodes.Dup);
3265 if (!FieldInfo.IsStatic) {
3266 temp = new LocalTemporary (ec, this.Type);
3272 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
3274 FieldAttributes fa = FieldInfo.Attributes;
3275 bool is_static = (fa & FieldAttributes.Static) != 0;
3276 bool is_readonly = (fa & FieldAttributes.InitOnly) != 0;
3277 ILGenerator ig = ec.ig;
3278 prepared = prepare_for_load;
3280 if (is_readonly && !ec.IsConstructor){
3281 Report_AssignToReadonly (!is_static);
3287 if (prepare_for_load)
3288 ig.Emit (OpCodes.Dup);
3293 ec.ig.Emit (OpCodes.Dup);
3294 if (!FieldInfo.IsStatic) {
3295 temp = new LocalTemporary (ec, this.Type);
3300 if (FieldInfo is FieldBuilder){
3301 FieldBase f = TypeManager.GetField (FieldInfo);
3303 if ((f.ModFlags & Modifiers.VOLATILE) != 0)
3304 ig.Emit (OpCodes.Volatile);
3306 f.status |= Field.Status.ASSIGNED;
3311 ig.Emit (OpCodes.Stsfld, FieldInfo);
3313 ig.Emit (OpCodes.Stfld, FieldInfo);
3319 void EmitInstance (EmitContext ec)
3322 // In case it escapes StaticMemberCheck due to IdenticalTypeAndName.
3323 // This happens in cases like 'string String', 'int Int32', etc.
3324 // where the "IdenticalTypeAndName" mechanism is fooled.
3326 if (InstanceExpression == null) {
3327 SimpleName.Error_ObjectRefRequired (ec, loc, FieldInfo.Name);
3331 if (InstanceExpression.Type.IsValueType) {
3332 if (InstanceExpression is IMemoryLocation) {
3333 ((IMemoryLocation) InstanceExpression).AddressOf (ec, AddressOp.LoadStore);
3335 LocalTemporary t = new LocalTemporary (ec, InstanceExpression.Type);
3336 InstanceExpression.Emit (ec);
3338 t.AddressOf (ec, AddressOp.Store);
3341 InstanceExpression.Emit (ec);
3344 public override void Emit (EmitContext ec)
3349 public void AddressOf (EmitContext ec, AddressOp mode)
3351 ILGenerator ig = ec.ig;
3353 if (FieldInfo is FieldBuilder){
3354 FieldBase f = TypeManager.GetField (FieldInfo);
3356 if ((f.ModFlags & Modifiers.VOLATILE) != 0){
3357 Error (676, "volatile variable: can not take its address, or pass as ref/out parameter");
3361 if ((mode & AddressOp.Store) != 0)
3362 f.status |= Field.Status.ASSIGNED;
3363 if ((mode & AddressOp.Load) != 0)
3364 f.status |= Field.Status.USED;
3369 // Handle initonly fields specially: make a copy and then
3370 // get the address of the copy.
3373 if (FieldInfo.IsInitOnly){
3375 if (ec.IsConstructor){
3376 if (FieldInfo.IsStatic){
3388 local = ig.DeclareLocal (type);
3389 ig.Emit (OpCodes.Stloc, local);
3390 ig.Emit (OpCodes.Ldloca, local);
3395 if (FieldInfo.IsStatic){
3396 ig.Emit (OpCodes.Ldsflda, FieldInfo);
3399 ig.Emit (OpCodes.Ldflda, FieldInfo);
3405 // A FieldExpr whose address can not be taken
3407 public class FieldExprNoAddress : FieldExpr, IMemoryLocation {
3408 public FieldExprNoAddress (FieldInfo fi, Location loc) : base (fi, loc)
3412 public new void AddressOf (EmitContext ec, AddressOp mode)
3414 Report.Error (-215, "Report this: Taking the address of a remapped parameter not supported");
3419 /// Expression that evaluates to a Property. The Assign class
3420 /// might set the `Value' expression if we are in an assignment.
3422 /// This is not an LValue because we need to re-write the expression, we
3423 /// can not take data from the stack and store it.
3425 public class PropertyExpr : MemberExpr, IAssignMethod {
3426 public readonly PropertyInfo PropertyInfo;
3429 // This is set externally by the `BaseAccess' class
3432 MethodInfo getter, setter;
3435 LocalTemporary temp;
3438 internal static PtrHashtable AccessorTable = new PtrHashtable ();
3440 public PropertyExpr (EmitContext ec, PropertyInfo pi, Location l)
3443 eclass = ExprClass.PropertyAccess;
3447 type = TypeManager.TypeToCoreType (pi.PropertyType);
3449 ResolveAccessors (ec);
3452 public override string Name {
3454 return PropertyInfo.Name;
3458 public override bool IsInstance {
3464 public override bool IsStatic {
3470 public override Type DeclaringType {
3472 return PropertyInfo.DeclaringType;
3476 public bool VerifyAssignable ()
3478 if (setter == null) {
3479 Report.Error (200, loc,
3480 "The property `" + PropertyInfo.Name +
3481 "' can not be assigned to, as it has not set accessor");
3488 void FindAccessors (Type invocation_type)
3490 BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic |
3491 BindingFlags.Static | BindingFlags.Instance |
3492 BindingFlags.DeclaredOnly;
3494 Type current = PropertyInfo.DeclaringType;
3495 for (; current != null; current = current.BaseType) {
3496 MemberInfo[] group = TypeManager.MemberLookup (
3497 invocation_type, invocation_type, current,
3498 MemberTypes.Property, flags, PropertyInfo.Name, null);
3503 if (group.Length != 1)
3504 // Oooops, can this ever happen ?
3507 PropertyInfo pi = (PropertyInfo) group [0];
3510 getter = pi.GetGetMethod (true);
3513 setter = pi.GetSetMethod (true);
3515 MethodInfo accessor = getter != null ? getter : setter;
3517 if (!accessor.IsVirtual)
3523 // We also perform the permission checking here, as the PropertyInfo does not
3524 // hold the information for the accessibility of its setter/getter
3526 void ResolveAccessors (EmitContext ec)
3528 FindAccessors (ec.ContainerType);
3530 if (getter != null) {
3531 AccessorTable [getter] = PropertyInfo;
3532 is_static = getter.IsStatic;
3535 if (setter != null) {
3536 AccessorTable [setter] = PropertyInfo;
3537 is_static = setter.IsStatic;
3541 bool InstanceResolve (EmitContext ec, bool must_do_cs1540_check)
3543 if ((InstanceExpression == null) && ec.IsStatic && !is_static) {
3544 SimpleName.Error_ObjectRefRequired (ec, loc, PropertyInfo.Name);
3548 if (InstanceExpression != null) {
3549 InstanceExpression = InstanceExpression.DoResolve (ec);
3550 if (InstanceExpression == null)
3553 InstanceExpression.CheckMarshallByRefAccess (ec.ContainerType);
3556 if (must_do_cs1540_check && (InstanceExpression != null)) {
3557 if ((InstanceExpression.Type != ec.ContainerType) &&
3558 ec.ContainerType.IsSubclassOf (InstanceExpression.Type)) {
3559 Report.Error (1540, loc, "Cannot access protected member `" +
3560 PropertyInfo.DeclaringType + "." + PropertyInfo.Name +
3561 "' via a qualifier of type `" +
3562 TypeManager.CSharpName (InstanceExpression.Type) +
3563 "'; the qualifier must be of type `" +
3564 TypeManager.CSharpName (ec.ContainerType) +
3565 "' (or derived from it)");
3573 override public Expression DoResolve (EmitContext ec)
3575 if (getter != null){
3576 if (TypeManager.GetArgumentTypes (getter).Length != 0){
3578 117, loc, "`{0}' does not contain a " +
3579 "definition for `{1}'.", getter.DeclaringType,
3585 if (getter == null){
3587 // The following condition happens if the PropertyExpr was
3588 // created, but is invalid (ie, the property is inaccessible),
3589 // and we did not want to embed the knowledge about this in
3590 // the caller routine. This only avoids double error reporting.
3595 Report.Error (154, loc,
3596 "The property `" + PropertyInfo.Name +
3597 "' can not be used in " +
3598 "this context because it lacks a get accessor");
3602 bool must_do_cs1540_check;
3603 if (!IsAccessorAccessible (ec.ContainerType, getter, out must_do_cs1540_check)) {
3604 PropertyBase.PropertyMethod pm = TypeManager.GetMethod (getter) as PropertyBase.PropertyMethod;
3605 if (pm != null && pm.HasCustomAccessModifier) {
3606 Report.SymbolRelatedToPreviousError (pm);
3607 Report.Error (271, loc, "The property or indexer '{0}' cannot be used in this context because the get accessor is inaccessible",
3608 TypeManager.CSharpSignature (getter));
3611 Report.Error (122, loc, "'{0}' is inaccessible due to its protection level",
3612 TypeManager.CSharpSignature (getter));
3616 if (!InstanceResolve (ec, must_do_cs1540_check))
3620 // Only base will allow this invocation to happen.
3622 if (IsBase && getter.IsAbstract){
3623 Report.Error (205, loc, "Cannot call an abstract base property: " +
3624 PropertyInfo.DeclaringType + "." +PropertyInfo.Name);
3628 if (PropertyInfo.PropertyType.IsPointer && !ec.InUnsafe){
3636 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
3638 if (setter == null){
3640 // The following condition happens if the PropertyExpr was
3641 // created, but is invalid (ie, the property is inaccessible),
3642 // and we did not want to embed the knowledge about this in
3643 // the caller routine. This only avoids double error reporting.
3648 // TODO: Print better property name
3649 Report.Error (200, loc, "Property or indexer '{0}' cannot be assigned to -- it is read only",
3654 if (TypeManager.GetArgumentTypes (setter).Length != 1){
3656 117, loc, "`{0}' does not contain a " +
3657 "definition for `{1}'.", getter.DeclaringType,
3662 bool must_do_cs1540_check;
3663 if (!IsAccessorAccessible (ec.ContainerType, setter, out must_do_cs1540_check)) {
3664 PropertyBase.PropertyMethod pm = TypeManager.GetMethod (setter) as PropertyBase.PropertyMethod;
3665 if (pm != null && pm.HasCustomAccessModifier) {
3666 Report.SymbolRelatedToPreviousError (pm);
3667 Report.Error (272, loc, "The property or indexer '{0}' cannot be used in this context because the set accessor is inaccessible",
3668 TypeManager.CSharpSignature (setter));
3671 Report.Error (122, loc, "'{0}' is inaccessible due to its protection level",
3672 TypeManager.CSharpSignature (setter));
3676 if (!InstanceResolve (ec, must_do_cs1540_check))
3680 // Only base will allow this invocation to happen.
3682 if (IsBase && setter.IsAbstract){
3683 Report.Error (205, loc, "Cannot call an abstract base property: " +
3684 PropertyInfo.DeclaringType + "." +PropertyInfo.Name);
3689 // Check that we are not making changes to a temporary memory location
3691 if (InstanceExpression != null && InstanceExpression.Type.IsValueType && !(InstanceExpression is IMemoryLocation)) {
3692 // FIXME: Provide better error reporting.
3693 Error (1612, "Cannot modify expression because it is not a variable.");
3702 public override void Emit (EmitContext ec)
3707 void EmitInstance (EmitContext ec)
3713 // In case it escapes StaticMemberCheck due to IdenticalTypeAndName.
3714 // This happens in cases like 'string String', 'int Int32', etc.
3715 // where the "IdenticalTypeAndName" mechanism is fooled.
3717 if (InstanceExpression == null) {
3718 SimpleName.Error_ObjectRefRequired (ec, loc, PropertyInfo.Name);
3722 if (InstanceExpression.Type.IsValueType) {
3723 if (InstanceExpression is IMemoryLocation) {
3724 ((IMemoryLocation) InstanceExpression).AddressOf (ec, AddressOp.LoadStore);
3726 LocalTemporary t = new LocalTemporary (ec, InstanceExpression.Type);
3727 InstanceExpression.Emit (ec);
3729 t.AddressOf (ec, AddressOp.Store);
3732 InstanceExpression.Emit (ec);
3735 ec.ig.Emit (OpCodes.Dup);
3739 public void Emit (EmitContext ec, bool leave_copy)
3745 // Special case: length of single dimension array property is turned into ldlen
3747 if ((getter == TypeManager.system_int_array_get_length) ||
3748 (getter == TypeManager.int_array_get_length)){
3749 Type iet = InstanceExpression.Type;
3752 // System.Array.Length can be called, but the Type does not
3753 // support invoking GetArrayRank, so test for that case first
3755 if (iet != TypeManager.array_type && (iet.GetArrayRank () == 1)) {
3756 ec.ig.Emit (OpCodes.Ldlen);
3757 ec.ig.Emit (OpCodes.Conv_I4);
3762 Invocation.EmitCall (ec, IsBase, IsStatic, new EmptyAddressOf (), getter, null, loc);
3767 ec.ig.Emit (OpCodes.Dup);
3769 temp = new LocalTemporary (ec, this.Type);
3775 // Implements the IAssignMethod interface for assignments
3777 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
3779 prepared = prepare_for_load;
3785 ec.ig.Emit (OpCodes.Dup);
3787 temp = new LocalTemporary (ec, this.Type);
3792 ArrayList args = new ArrayList (1);
3793 args.Add (new Argument (new EmptyAddressOf (), Argument.AType.Expression));
3795 Invocation.EmitCall (ec, IsBase, IsStatic, new EmptyAddressOf (), setter, args, loc);
3803 /// Fully resolved expression that evaluates to an Event
3805 public class EventExpr : MemberExpr {
3806 public readonly EventInfo EventInfo;
3809 MethodInfo add_accessor, remove_accessor;
3811 public EventExpr (EventInfo ei, Location loc)
3815 eclass = ExprClass.EventAccess;
3817 add_accessor = TypeManager.GetAddMethod (ei);
3818 remove_accessor = TypeManager.GetRemoveMethod (ei);
3820 if (add_accessor.IsStatic || remove_accessor.IsStatic)
3823 if (EventInfo is MyEventBuilder){
3824 MyEventBuilder eb = (MyEventBuilder) EventInfo;
3825 type = eb.EventType;
3828 type = EventInfo.EventHandlerType;
3831 public override string Name {
3833 return EventInfo.Name;
3837 public override bool IsInstance {
3843 public override bool IsStatic {
3849 public override Type DeclaringType {
3851 return EventInfo.DeclaringType;
3855 public override Expression ResolveMemberAccess (EmitContext ec, Expression left, Location loc,
3856 SimpleName original, bool left_is_inferred)
3859 // If the event is local to this class, we transform ourselves into a FieldExpr
3862 if (EventInfo.DeclaringType == ec.ContainerType ||
3863 TypeManager.IsNestedChildOf(ec.ContainerType, EventInfo.DeclaringType)) {
3864 MemberInfo mi = TypeManager.GetPrivateFieldOfEvent (EventInfo);
3867 MemberExpr ml = (MemberExpr) ExprClassFromMemberInfo (ec, mi, loc);
3870 Report.Error (-200, loc, "Internal error!!");
3874 InstanceExpression = left_is_inferred ? null : left;
3876 return ml.ResolveMemberAccess (ec, left, loc, original, left_is_inferred);
3880 return base.ResolveMemberAccess (ec, left, loc, original, left_is_inferred);
3884 bool InstanceResolve (EmitContext ec, bool must_do_cs1540_check)
3886 if ((InstanceExpression == null) && ec.IsStatic && !is_static) {
3887 SimpleName.Error_ObjectRefRequired (ec, loc, EventInfo.Name);
3891 if (InstanceExpression != null) {
3892 InstanceExpression = InstanceExpression.DoResolve (ec);
3893 if (InstanceExpression == null)
3898 // This is using the same mechanism as the CS1540 check in PropertyExpr.
3899 // However, in the Event case, we reported a CS0122 instead.
3901 if (must_do_cs1540_check && (InstanceExpression != null)) {
3902 if ((InstanceExpression.Type != ec.ContainerType) &&
3903 ec.ContainerType.IsSubclassOf (InstanceExpression.Type)) {
3904 Report.Error (122, loc, "'{0}' is inaccessible due to its protection level",
3905 DeclaringType.Name + "." + EventInfo.Name);
3914 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
3916 return DoResolve (ec);
3919 public override Expression DoResolve (EmitContext ec)
3921 if (InstanceExpression != null) {
3922 InstanceExpression = InstanceExpression.DoResolve (ec);
3923 if (InstanceExpression == null)
3927 bool must_do_cs1540_check;
3928 if (!(IsAccessorAccessible (ec.ContainerType, add_accessor, out must_do_cs1540_check)
3929 && IsAccessorAccessible (ec.ContainerType, remove_accessor, out must_do_cs1540_check))) {
3931 Report.Error (122, loc, "'{0}' is inaccessible due to its protection level",
3932 DeclaringType.Name + "." + EventInfo.Name);
3936 if (!InstanceResolve (ec, must_do_cs1540_check))
3942 public override void Emit (EmitContext ec)
3944 if (InstanceExpression is This)
3945 Report.Error (79, loc, "The event `{0}' can only appear on the left hand side of += or -=, try calling the actual delegate", Name);
3947 Report.Error (70, loc, "The event `{0}' can only appear on the left hand side of += or -= "+
3948 "(except on the defining type)", Name);
3951 public void EmitAddOrRemove (EmitContext ec, Expression source)
3953 BinaryDelegate source_del = (BinaryDelegate) source;
3954 Expression handler = source_del.Right;
3956 Argument arg = new Argument (handler, Argument.AType.Expression);
3957 ArrayList args = new ArrayList ();
3961 if (source_del.IsAddition)
3962 Invocation.EmitCall (
3963 ec, false, IsStatic, InstanceExpression, add_accessor, args, loc);
3965 Invocation.EmitCall (
3966 ec, false, IsStatic, InstanceExpression, remove_accessor, args, loc);