2 // ecore.cs: Core of the Expression representation for the intermediate tree.
5 // Miguel de Icaza (miguel@ximian.com)
7 // (C) 2001, 2002, 2003 Ximian, Inc.
11 namespace Mono.CSharp {
13 using System.Collections;
14 using System.Diagnostics;
15 using System.Reflection;
16 using System.Reflection.Emit;
20 /// The ExprClass class contains the is used to pass the
21 /// classification of an expression (value, variable, namespace,
22 /// type, method group, property access, event access, indexer access,
25 public enum ExprClass : byte {
40 /// This is used to tell Resolve in which types of expressions we're
44 public enum ResolveFlags {
45 // Returns Value, Variable, PropertyAccess, EventAccess or IndexerAccess.
48 // Returns a type expression.
51 // Returns a method group.
54 // Mask of all the expression class flags.
57 // Disable control flow analysis while resolving the expression.
58 // This is used when resolving the instance expression of a field expression.
59 DisableFlowAnalysis = 8,
61 // Set if this is resolving the first part of a MemberAccess.
66 // This is just as a hint to AddressOf of what will be done with the
69 public enum AddressOp {
76 /// This interface is implemented by variables
78 public interface IMemoryLocation {
80 /// The AddressOf method should generate code that loads
81 /// the address of the object and leaves it on the stack.
83 /// The `mode' argument is used to notify the expression
84 /// of whether this will be used to read from the address or
85 /// write to the address.
87 /// This is just a hint that can be used to provide good error
88 /// reporting, and should have no other side effects.
90 void AddressOf (EmitContext ec, AddressOp mode);
94 /// We are either a namespace or a type.
95 /// If we're a type, `IsType' is true and we may use `Type' to get
96 /// a TypeExpr representing that type.
98 public interface IAlias {
107 TypeExpr ResolveAsType (EmitContext ec);
111 /// This interface is implemented by variables
113 public interface IVariable {
114 VariableInfo VariableInfo {
118 bool VerifyFixed (bool is_expression);
122 /// Base class for expressions
124 public abstract class Expression {
125 public ExprClass eclass;
127 protected Location loc;
139 public Location Location {
146 /// Utility wrapper routine for Error, just to beautify the code
148 public void Error (int error, string s)
150 if (!Location.IsNull (loc))
151 Report.Error (error, loc, s);
153 Report.Error (error, s);
157 /// Utility wrapper routine for Warning, just to beautify the code
159 public void Warning (int code, string format, params object[] args)
161 Report.Warning (code, loc, format, args);
164 // Not nice but we have broken hierarchy
165 public virtual void CheckMarshallByRefAccess (Type container) {}
168 /// Tests presence of ObsoleteAttribute and report proper error
170 protected void CheckObsoleteAttribute (Type type)
172 ObsoleteAttribute obsolete_attr = AttributeTester.GetObsoleteAttribute (type);
173 if (obsolete_attr == null)
176 AttributeTester.Report_ObsoleteMessage (obsolete_attr, type.FullName, loc);
179 public static bool IsAccessorAccessible (Type invocation_type, MethodInfo mi, out bool must_do_cs1540_check)
181 MethodAttributes ma = mi.Attributes & MethodAttributes.MemberAccessMask;
183 must_do_cs1540_check = false; // by default we do not check for this
186 // If only accessible to the current class or children
188 if (ma == MethodAttributes.Private)
189 return invocation_type == mi.DeclaringType ||
190 TypeManager.IsNestedChildOf (invocation_type, mi.DeclaringType);
192 if (mi.DeclaringType.Assembly == invocation_type.Assembly) {
193 if (ma == MethodAttributes.Assembly || ma == MethodAttributes.FamORAssem)
196 if (ma == MethodAttributes.Assembly || ma == MethodAttributes.FamANDAssem)
200 // Family and FamANDAssem require that we derive.
201 // FamORAssem requires that we derive if in different assemblies.
202 if (ma == MethodAttributes.Family ||
203 ma == MethodAttributes.FamANDAssem ||
204 ma == MethodAttributes.FamORAssem) {
205 if (!TypeManager.IsNestedFamilyAccessible (invocation_type, mi.DeclaringType))
208 if (!TypeManager.IsNestedChildOf (invocation_type, mi.DeclaringType))
209 must_do_cs1540_check = true;
218 /// Performs semantic analysis on the Expression
222 /// The Resolve method is invoked to perform the semantic analysis
225 /// The return value is an expression (it can be the
226 /// same expression in some cases) or a new
227 /// expression that better represents this node.
229 /// For example, optimizations of Unary (LiteralInt)
230 /// would return a new LiteralInt with a negated
233 /// If there is an error during semantic analysis,
234 /// then an error should be reported (using Report)
235 /// and a null value should be returned.
237 /// There are two side effects expected from calling
238 /// Resolve(): the the field variable "eclass" should
239 /// be set to any value of the enumeration
240 /// `ExprClass' and the type variable should be set
241 /// to a valid type (this is the type of the
244 public abstract Expression DoResolve (EmitContext ec);
246 public virtual Expression DoResolveLValue (EmitContext ec, Expression right_side)
252 // This is used if the expression should be resolved as a type or namespace name.
253 // the default implementation fails.
255 public virtual FullNamedExpression ResolveAsTypeStep (EmitContext ec)
261 // This is used to resolve the expression as a type, a null
262 // value will be returned if the expression is not a type
265 public virtual TypeExpr ResolveAsTypeTerminal (EmitContext ec)
267 int errors = Report.Errors;
269 FullNamedExpression fne = ResolveAsTypeStep (ec);
272 if (errors == Report.Errors)
273 Report.Error (246, Location, "Cannot find type '{0}'", ToString ());
277 if (fne.eclass != ExprClass.Type) {
278 if (errors == Report.Errors)
279 Report.Error (118, Location, "'{0}' denotes a '{1}', where a type was expected",
280 fne.FullName, fne.ExprClassName ());
284 TypeExpr te = fne as TypeExpr;
286 if (!te.CheckAccessLevel (ec.DeclSpace)) {
287 Report.Error (122, Location, "'{0}' is inaccessible due to its protection level", te.Name);
291 ConstructedType ct = te as ConstructedType;
292 if ((ct != null) && !ct.CheckConstraints (ec))
299 /// Resolves an expression and performs semantic analysis on it.
303 /// Currently Resolve wraps DoResolve to perform sanity
304 /// checking and assertion checking on what we expect from Resolve.
306 public Expression Resolve (EmitContext ec, ResolveFlags flags)
308 if ((flags & ResolveFlags.MaskExprClass) == ResolveFlags.Type)
309 return ResolveAsTypeStep (ec);
311 bool old_do_flow_analysis = ec.DoFlowAnalysis;
312 if ((flags & ResolveFlags.DisableFlowAnalysis) != 0)
313 ec.DoFlowAnalysis = false;
316 bool intermediate = (flags & ResolveFlags.Intermediate) == ResolveFlags.Intermediate;
317 if (this is SimpleName)
318 e = ((SimpleName) this).DoResolve (ec, intermediate);
323 ec.DoFlowAnalysis = old_do_flow_analysis;
328 if ((e is TypeExpr) || (e is ComposedCast) || (e is Namespace)) {
329 if ((flags & ResolveFlags.Type) == 0) {
330 e.Error_UnexpectedKind (flags, loc);
339 case ExprClass.Namespace:
340 if ((flags & ResolveFlags.VariableOrValue) == 0) {
341 e.Error_UnexpectedKind (flags, loc);
346 case ExprClass.MethodGroup:
347 if (RootContext.Version == LanguageVersion.ISO_1){
348 if ((flags & ResolveFlags.MethodGroup) == 0) {
349 ((MethodGroupExpr) e).ReportUsageError ();
355 case ExprClass.Value:
356 case ExprClass.Variable:
357 case ExprClass.PropertyAccess:
358 case ExprClass.EventAccess:
359 case ExprClass.IndexerAccess:
360 if ((flags & ResolveFlags.VariableOrValue) == 0) {
361 Console.WriteLine ("I got: {0} and {1}", e.GetType (), e);
362 Console.WriteLine ("I am {0} and {1}", this.GetType (), this);
363 FieldInfo fi = ((FieldExpr) e).FieldInfo;
365 Console.WriteLine ("{0} and {1}", fi.DeclaringType, fi.Name);
366 e.Error_UnexpectedKind (flags, loc);
372 throw new Exception ("Expression " + e.GetType () +
373 " ExprClass is Invalid after resolve");
376 if (e.type == null && !(e is Namespace)) {
377 throw new Exception (
378 "Expression " + e.GetType () +
379 " did not set its type after Resolve\n" +
380 "called from: " + this.GetType ());
387 /// Resolves an expression and performs semantic analysis on it.
389 public Expression Resolve (EmitContext ec)
391 return Resolve (ec, ResolveFlags.VariableOrValue);
395 /// Resolves an expression for LValue assignment
399 /// Currently ResolveLValue wraps DoResolveLValue to perform sanity
400 /// checking and assertion checking on what we expect from Resolve
402 public Expression ResolveLValue (EmitContext ec, Expression right_side)
404 int errors = Report.Errors;
405 Expression e = DoResolveLValue (ec, right_side);
408 if (errors == Report.Errors)
409 Report.Error (131, Location, "The left-hand side of an assignment or mutating operation must be a variable, property or indexer");
414 if (e.eclass == ExprClass.Invalid)
415 throw new Exception ("Expression " + e +
416 " ExprClass is Invalid after resolve");
418 if (e.eclass == ExprClass.MethodGroup) {
419 ((MethodGroupExpr) e).ReportUsageError ();
423 if ((e.type == null) && !(e is ConstructedType))
424 throw new Exception ("Expression " + e +
425 " did not set its type after Resolve");
432 /// Emits the code for the expression
436 /// The Emit method is invoked to generate the code
437 /// for the expression.
439 public abstract void Emit (EmitContext ec);
441 public virtual void EmitBranchable (EmitContext ec, Label target, bool onTrue)
444 ec.ig.Emit (onTrue ? OpCodes.Brtrue : OpCodes.Brfalse, target);
448 /// Protected constructor. Only derivate types should
449 /// be able to be created
452 protected Expression ()
454 eclass = ExprClass.Invalid;
459 /// Returns a literalized version of a literal FieldInfo
463 /// The possible return values are:
464 /// IntConstant, UIntConstant
465 /// LongLiteral, ULongConstant
466 /// FloatConstant, DoubleConstant
469 /// The value returned is already resolved.
471 public static Constant Constantify (object v, Type t)
473 if (t == TypeManager.int32_type)
474 return new IntConstant ((int) v);
475 else if (t == TypeManager.uint32_type)
476 return new UIntConstant ((uint) v);
477 else if (t == TypeManager.int64_type)
478 return new LongConstant ((long) v);
479 else if (t == TypeManager.uint64_type)
480 return new ULongConstant ((ulong) v);
481 else if (t == TypeManager.float_type)
482 return new FloatConstant ((float) v);
483 else if (t == TypeManager.double_type)
484 return new DoubleConstant ((double) v);
485 else if (t == TypeManager.string_type)
486 return new StringConstant ((string) v);
487 else if (t == TypeManager.short_type)
488 return new ShortConstant ((short)v);
489 else if (t == TypeManager.ushort_type)
490 return new UShortConstant ((ushort)v);
491 else if (t == TypeManager.sbyte_type)
492 return new SByteConstant (((sbyte)v));
493 else if (t == TypeManager.byte_type)
494 return new ByteConstant ((byte)v);
495 else if (t == TypeManager.char_type)
496 return new CharConstant ((char)v);
497 else if (t == TypeManager.bool_type)
498 return new BoolConstant ((bool) v);
499 else if (t == TypeManager.decimal_type)
500 return new DecimalConstant ((decimal) v);
501 else if (TypeManager.IsEnumType (t)){
502 Type real_type = TypeManager.TypeToCoreType (v.GetType ());
504 real_type = System.Enum.GetUnderlyingType (real_type);
506 Constant e = Constantify (v, real_type);
508 return new EnumConstant (e, t);
509 } else if (v == null && !TypeManager.IsValueType (t))
510 return NullLiteral.Null;
512 throw new Exception ("Unknown type for constant (" + t +
517 /// Returns a fully formed expression after a MemberLookup
519 public static Expression ExprClassFromMemberInfo (EmitContext ec, MemberInfo mi, Location loc)
522 return new EventExpr ((EventInfo) mi, loc);
523 else if (mi is FieldInfo)
524 return new FieldExpr ((FieldInfo) mi, loc);
525 else if (mi is PropertyInfo)
526 return new PropertyExpr (ec, (PropertyInfo) mi, loc);
527 else if (mi is Type){
528 return new TypeExpression ((System.Type) mi, loc);
534 protected static ArrayList almostMatchedMembers = new ArrayList (4);
537 // FIXME: Probably implement a cache for (t,name,current_access_set)?
539 // This code could use some optimizations, but we need to do some
540 // measurements. For example, we could use a delegate to `flag' when
541 // something can not any longer be a method-group (because it is something
545 // If the return value is an Array, then it is an array of
548 // If the return value is an MemberInfo, it is anything, but a Method
552 // FIXME: When calling MemberLookup inside an `Invocation', we should pass
553 // the arguments here and have MemberLookup return only the methods that
554 // match the argument count/type, unlike we are doing now (we delay this
557 // This is so we can catch correctly attempts to invoke instance methods
558 // from a static body (scan for error 120 in ResolveSimpleName).
561 // FIXME: Potential optimization, have a static ArrayList
564 public static Expression MemberLookup (EmitContext ec, Type queried_type, string name,
565 MemberTypes mt, BindingFlags bf, Location loc)
567 return MemberLookup (ec, ec.ContainerType, null, queried_type, name, mt, bf, loc);
571 // Lookup type `queried_type' for code in class `container_type' with a qualifier of
572 // `qualifier_type' or null to lookup members in the current class.
575 public static Expression MemberLookup (EmitContext ec, Type container_type,
576 Type qualifier_type, Type queried_type,
577 string name, MemberTypes mt,
578 BindingFlags bf, Location loc)
580 almostMatchedMembers.Clear ();
582 MemberInfo [] mi = TypeManager.MemberLookup (
583 container_type, qualifier_type,queried_type, mt, bf, name,
584 almostMatchedMembers);
589 int count = mi.Length;
591 if (mi [0] is MethodBase)
592 return new MethodGroupExpr (mi, loc);
597 return ExprClassFromMemberInfo (ec, mi [0], loc);
600 public const MemberTypes AllMemberTypes =
601 MemberTypes.Constructor |
605 MemberTypes.NestedType |
606 MemberTypes.Property;
608 public const BindingFlags AllBindingFlags =
609 BindingFlags.Public |
610 BindingFlags.Static |
611 BindingFlags.Instance;
613 public static Expression MemberLookup (EmitContext ec, Type queried_type,
614 string name, Location loc)
616 return MemberLookup (ec, ec.ContainerType, null, queried_type, name,
617 AllMemberTypes, AllBindingFlags, loc);
620 public static Expression MemberLookup (EmitContext ec, Type qualifier_type,
621 Type queried_type, string name, Location loc)
623 return MemberLookup (ec, ec.ContainerType, qualifier_type, queried_type,
624 name, AllMemberTypes, AllBindingFlags, loc);
627 public static Expression MethodLookup (EmitContext ec, Type queried_type,
628 string name, Location loc)
630 return MemberLookup (ec, ec.ContainerType, null, queried_type, name,
631 MemberTypes.Method, AllBindingFlags, loc);
635 /// This is a wrapper for MemberLookup that is not used to "probe", but
636 /// to find a final definition. If the final definition is not found, we
637 /// look for private members and display a useful debugging message if we
640 public static Expression MemberLookupFinal (EmitContext ec, Type qualifier_type,
641 Type queried_type, string name,
644 return MemberLookupFinal (ec, qualifier_type, queried_type, name,
645 AllMemberTypes, AllBindingFlags, loc);
648 public static Expression MemberLookupFinal (EmitContext ec, Type qualifier_type,
649 Type queried_type, string name,
650 MemberTypes mt, BindingFlags bf,
655 int errors = Report.Errors;
657 e = MemberLookup (ec, ec.ContainerType, qualifier_type, queried_type,
660 if (e == null && errors == Report.Errors)
661 // No errors were reported by MemberLookup, but there was an error.
662 MemberLookupFailed (ec, qualifier_type, queried_type, name, null, true, loc);
667 public static void MemberLookupFailed (EmitContext ec, Type qualifier_type,
668 Type queried_type, string name,
669 string class_name, bool complain_if_none_found,
672 if (almostMatchedMembers.Count != 0) {
673 if (qualifier_type == null) {
674 foreach (MemberInfo m in almostMatchedMembers)
675 Report.Error (38, loc,
676 "Cannot access non-static member `{0}' via nested type `{1}'",
677 TypeManager.GetFullNameSignature (m),
678 TypeManager.CSharpName (ec.ContainerType));
683 if (qualifier_type != ec.ContainerType) {
684 // Although a derived class can access protected members of
685 // its base class it cannot do so through an instance of the
686 // base class (CS1540). If the qualifier_type is a base of the
687 // ec.ContainerType and the lookup succeeds with the latter one,
688 // then we are in this situation.
689 for (int i = 0; i < almostMatchedMembers.Count; ++i) {
690 MemberInfo m = (MemberInfo) almostMatchedMembers [i];
691 for (int j = 0; j < i; ++j) {
692 if (m == almostMatchedMembers [j]) {
700 Report.SymbolRelatedToPreviousError (m);
701 Report.Error (1540, loc,
702 "Cannot access protected member `{0}' via a qualifier of type `{1}';"
703 + " the qualifier must be of type `{2}' (or derived from it)",
704 TypeManager.GetFullNameSignature (m),
705 TypeManager.CSharpName (qualifier_type),
706 TypeManager.CSharpName (ec.ContainerType));
710 almostMatchedMembers.Clear ();
713 MemberInfo[] mi = TypeManager.MemberLookup (queried_type, null, queried_type,
714 AllMemberTypes, AllBindingFlags |
715 BindingFlags.NonPublic, name, null);
718 if (!complain_if_none_found)
721 if (class_name != null)
722 Report.Error (103, loc, "The name `" + name + "' could not be " +
723 "found in `" + class_name + "'");
726 117, loc, "`" + queried_type + "' does not contain a " +
727 "definition for `" + name + "'");
731 if (TypeManager.MemberLookup (queried_type, null, queried_type,
732 AllMemberTypes, AllBindingFlags |
733 BindingFlags.NonPublic, name, null) == null) {
734 if ((mi.Length == 1) && (mi [0] is Type)) {
735 Type t = (Type) mi [0];
737 Report.Error (305, loc,
738 "Using the generic type `{0}' " +
739 "requires {1} type arguments",
740 TypeManager.GetFullName (t),
741 TypeManager.GetNumberOfTypeArguments (t));
746 if (name == ".ctor" && TypeManager.FindMembers (qualifier_type, MemberTypes.Constructor,
747 BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly, null, null).Count == 0)
749 Report.Error (143, loc, String.Format ("The type '{0}' has no constructors defined", TypeManager.CSharpName (queried_type)));
753 if (qualifier_type != null) {
754 Report.Error (122, loc, "'{0}' is inaccessible due to its protection level", TypeManager.CSharpName (qualifier_type) + "." + name);
756 Report.Error (122, loc, "'{0}' is inaccessible due to its protection level", name);
761 /// Returns an expression that can be used to invoke operator true
762 /// on the expression if it exists.
764 static public Expression GetOperatorTrue (EmitContext ec, Expression e, Location loc)
766 return GetOperatorTrueOrFalse (ec, e, true, loc);
770 /// Returns an expression that can be used to invoke operator false
771 /// on the expression if it exists.
773 static public Expression GetOperatorFalse (EmitContext ec, Expression e, Location loc)
775 return GetOperatorTrueOrFalse (ec, e, false, loc);
778 static Expression GetOperatorTrueOrFalse (EmitContext ec, Expression e, bool is_true, Location loc)
781 Expression operator_group;
783 if (TypeManager.IsNullableType (e.Type))
784 return new Nullable.OperatorTrueOrFalse (e, is_true, loc).Resolve (ec);
786 operator_group = MethodLookup (ec, e.Type, is_true ? "op_True" : "op_False", loc);
787 if (operator_group == null)
790 ArrayList arguments = new ArrayList ();
791 arguments.Add (new Argument (e, Argument.AType.Expression));
792 method = Invocation.OverloadResolve (
793 ec, (MethodGroupExpr) operator_group, arguments, false, loc);
798 return new StaticCallExpr ((MethodInfo) method, arguments, loc);
802 /// Resolves the expression `e' into a boolean expression: either through
803 /// an implicit conversion, or through an `operator true' invocation
805 public static Expression ResolveBoolean (EmitContext ec, Expression e, Location loc)
811 if (e.Type == TypeManager.bool_type)
814 Expression converted = Convert.ImplicitConversion (ec, e, TypeManager.bool_type, Location.Null);
816 if (converted != null)
820 // If no implicit conversion to bool exists, try using `operator true'
822 Expression operator_true = Expression.GetOperatorTrue (ec, e, loc);
823 if (operator_true == null){
824 Report.Error (31, loc, "Can not convert the expression to a boolean");
827 return operator_true;
830 public string ExprClassName ()
833 case ExprClass.Invalid:
835 case ExprClass.Value:
837 case ExprClass.Variable:
839 case ExprClass.Namespace:
843 case ExprClass.MethodGroup:
844 return "method group";
845 case ExprClass.PropertyAccess:
846 return "property access";
847 case ExprClass.EventAccess:
848 return "event access";
849 case ExprClass.IndexerAccess:
850 return "indexer access";
851 case ExprClass.Nothing:
854 throw new Exception ("Should not happen");
858 /// Reports that we were expecting `expr' to be of class `expected'
860 public void Error_UnexpectedKind (string expected, Location loc)
862 Report.Error (118, loc, "Expression denotes a `" + ExprClassName () +
863 "' where a `" + expected + "' was expected");
866 public void Error_UnexpectedKind (ResolveFlags flags, Location loc)
868 ArrayList valid = new ArrayList (10);
870 if ((flags & ResolveFlags.VariableOrValue) != 0) {
871 valid.Add ("variable");
875 if ((flags & ResolveFlags.Type) != 0)
878 if ((flags & ResolveFlags.MethodGroup) != 0)
879 valid.Add ("method group");
881 if (valid.Count == 0)
882 valid.Add ("unknown");
884 StringBuilder sb = new StringBuilder ();
885 for (int i = 0; i < valid.Count; i++) {
888 else if (i == valid.Count)
890 sb.Append (valid [i]);
893 Report.Error (119, loc, "Expression denotes a `" + ExprClassName () + "' where " +
894 "a `" + sb.ToString () + "' was expected");
897 static public void Error_ConstantValueCannotBeConverted (Location l, string val, Type t)
899 Report.Error (31, l, "Constant value `" + val + "' cannot be converted to " +
900 TypeManager.CSharpName (t));
903 public static void UnsafeError (Location loc)
905 Report.Error (214, loc, "Pointers may only be used in an unsafe context");
909 /// Converts the IntConstant, UIntConstant, LongConstant or
910 /// ULongConstant into the integral target_type. Notice
911 /// that we do not return an `Expression' we do return
912 /// a boxed integral type.
914 /// FIXME: Since I added the new constants, we need to
915 /// also support conversions from CharConstant, ByteConstant,
916 /// SByteConstant, UShortConstant, ShortConstant
918 /// This is used by the switch statement, so the domain
919 /// of work is restricted to the literals above, and the
920 /// targets are int32, uint32, char, byte, sbyte, ushort,
921 /// short, uint64 and int64
923 public static object ConvertIntLiteral (Constant c, Type target_type, Location loc)
925 if (!Convert.ImplicitStandardConversionExists (Convert.ConstantEC, c, target_type)){
926 Convert.Error_CannotImplicitConversion (loc, c.Type, target_type);
932 if (c.Type == target_type)
933 return ((Constant) c).GetValue ();
936 // Make into one of the literals we handle, we dont really care
937 // about this value as we will just return a few limited types
939 if (c is EnumConstant)
940 c = ((EnumConstant)c).WidenToCompilerConstant ();
942 if (c is IntConstant){
943 int v = ((IntConstant) c).Value;
945 if (target_type == TypeManager.uint32_type){
948 } else if (target_type == TypeManager.char_type){
949 if (v >= Char.MinValue && v <= Char.MaxValue)
951 } else if (target_type == TypeManager.byte_type){
952 if (v >= Byte.MinValue && v <= Byte.MaxValue)
954 } else if (target_type == TypeManager.sbyte_type){
955 if (v >= SByte.MinValue && v <= SByte.MaxValue)
957 } else if (target_type == TypeManager.short_type){
958 if (v >= Int16.MinValue && v <= UInt16.MaxValue)
960 } else if (target_type == TypeManager.ushort_type){
961 if (v >= UInt16.MinValue && v <= UInt16.MaxValue)
963 } else if (target_type == TypeManager.int64_type)
965 else if (target_type == TypeManager.uint64_type){
971 } else if (c is UIntConstant){
972 uint v = ((UIntConstant) c).Value;
974 if (target_type == TypeManager.int32_type){
975 if (v <= Int32.MaxValue)
977 } else if (target_type == TypeManager.char_type){
978 if (v >= Char.MinValue && v <= Char.MaxValue)
980 } else if (target_type == TypeManager.byte_type){
981 if (v <= Byte.MaxValue)
983 } else if (target_type == TypeManager.sbyte_type){
984 if (v <= SByte.MaxValue)
986 } else if (target_type == TypeManager.short_type){
987 if (v <= UInt16.MaxValue)
989 } else if (target_type == TypeManager.ushort_type){
990 if (v <= UInt16.MaxValue)
992 } else if (target_type == TypeManager.int64_type)
994 else if (target_type == TypeManager.uint64_type)
997 } else if (c is LongConstant){
998 long v = ((LongConstant) c).Value;
1000 if (target_type == TypeManager.int32_type){
1001 if (v >= UInt32.MinValue && v <= UInt32.MaxValue)
1003 } else if (target_type == TypeManager.uint32_type){
1004 if (v >= 0 && v <= UInt32.MaxValue)
1006 } else if (target_type == TypeManager.char_type){
1007 if (v >= Char.MinValue && v <= Char.MaxValue)
1009 } else if (target_type == TypeManager.byte_type){
1010 if (v >= Byte.MinValue && v <= Byte.MaxValue)
1012 } else if (target_type == TypeManager.sbyte_type){
1013 if (v >= SByte.MinValue && v <= SByte.MaxValue)
1015 } else if (target_type == TypeManager.short_type){
1016 if (v >= Int16.MinValue && v <= UInt16.MaxValue)
1018 } else if (target_type == TypeManager.ushort_type){
1019 if (v >= UInt16.MinValue && v <= UInt16.MaxValue)
1021 } else if (target_type == TypeManager.uint64_type){
1026 } else if (c is ULongConstant){
1027 ulong v = ((ULongConstant) c).Value;
1029 if (target_type == TypeManager.int32_type){
1030 if (v <= Int32.MaxValue)
1032 } else if (target_type == TypeManager.uint32_type){
1033 if (v <= UInt32.MaxValue)
1035 } else if (target_type == TypeManager.char_type){
1036 if (v >= Char.MinValue && v <= Char.MaxValue)
1038 } else if (target_type == TypeManager.byte_type){
1039 if (v >= Byte.MinValue && v <= Byte.MaxValue)
1041 } else if (target_type == TypeManager.sbyte_type){
1042 if (v <= (int) SByte.MaxValue)
1044 } else if (target_type == TypeManager.short_type){
1045 if (v <= UInt16.MaxValue)
1047 } else if (target_type == TypeManager.ushort_type){
1048 if (v <= UInt16.MaxValue)
1050 } else if (target_type == TypeManager.int64_type){
1051 if (v <= Int64.MaxValue)
1055 } else if (c is ByteConstant){
1056 byte v = ((ByteConstant) c).Value;
1058 if (target_type == TypeManager.int32_type)
1060 else if (target_type == TypeManager.uint32_type)
1062 else if (target_type == TypeManager.char_type)
1064 else if (target_type == TypeManager.sbyte_type){
1065 if (v <= SByte.MaxValue)
1067 } else if (target_type == TypeManager.short_type)
1069 else if (target_type == TypeManager.ushort_type)
1071 else if (target_type == TypeManager.int64_type)
1073 else if (target_type == TypeManager.uint64_type)
1076 } else if (c is SByteConstant){
1077 sbyte v = ((SByteConstant) c).Value;
1079 if (target_type == TypeManager.int32_type)
1081 else if (target_type == TypeManager.uint32_type){
1084 } else if (target_type == TypeManager.char_type){
1087 } else if (target_type == TypeManager.byte_type){
1090 } else if (target_type == TypeManager.short_type)
1092 else if (target_type == TypeManager.ushort_type){
1095 } else if (target_type == TypeManager.int64_type)
1097 else if (target_type == TypeManager.uint64_type){
1102 } else if (c is ShortConstant){
1103 short v = ((ShortConstant) c).Value;
1105 if (target_type == TypeManager.int32_type){
1107 } else if (target_type == TypeManager.uint32_type){
1110 } else if (target_type == TypeManager.char_type){
1113 } else if (target_type == TypeManager.byte_type){
1114 if (v >= Byte.MinValue && v <= Byte.MaxValue)
1116 } else if (target_type == TypeManager.sbyte_type){
1117 if (v >= SByte.MinValue && v <= SByte.MaxValue)
1119 } else if (target_type == TypeManager.ushort_type){
1122 } else if (target_type == TypeManager.int64_type)
1124 else if (target_type == TypeManager.uint64_type)
1128 } else if (c is UShortConstant){
1129 ushort v = ((UShortConstant) c).Value;
1131 if (target_type == TypeManager.int32_type)
1133 else if (target_type == TypeManager.uint32_type)
1135 else if (target_type == TypeManager.char_type){
1136 if (v >= Char.MinValue && v <= Char.MaxValue)
1138 } else if (target_type == TypeManager.byte_type){
1139 if (v >= Byte.MinValue && v <= Byte.MaxValue)
1141 } else if (target_type == TypeManager.sbyte_type){
1142 if (v <= SByte.MaxValue)
1144 } else if (target_type == TypeManager.short_type){
1145 if (v <= Int16.MaxValue)
1147 } else if (target_type == TypeManager.int64_type)
1149 else if (target_type == TypeManager.uint64_type)
1153 } else if (c is CharConstant){
1154 char v = ((CharConstant) c).Value;
1156 if (target_type == TypeManager.int32_type)
1158 else if (target_type == TypeManager.uint32_type)
1160 else if (target_type == TypeManager.byte_type){
1161 if (v >= Byte.MinValue && v <= Byte.MaxValue)
1163 } else if (target_type == TypeManager.sbyte_type){
1164 if (v <= SByte.MaxValue)
1166 } else if (target_type == TypeManager.short_type){
1167 if (v <= Int16.MaxValue)
1169 } else if (target_type == TypeManager.ushort_type)
1171 else if (target_type == TypeManager.int64_type)
1173 else if (target_type == TypeManager.uint64_type)
1178 Error_ConstantValueCannotBeConverted (loc, s, target_type);
1183 // Load the object from the pointer.
1185 public static void LoadFromPtr (ILGenerator ig, Type t)
1187 if (t == TypeManager.int32_type)
1188 ig.Emit (OpCodes.Ldind_I4);
1189 else if (t == TypeManager.uint32_type)
1190 ig.Emit (OpCodes.Ldind_U4);
1191 else if (t == TypeManager.short_type)
1192 ig.Emit (OpCodes.Ldind_I2);
1193 else if (t == TypeManager.ushort_type)
1194 ig.Emit (OpCodes.Ldind_U2);
1195 else if (t == TypeManager.char_type)
1196 ig.Emit (OpCodes.Ldind_U2);
1197 else if (t == TypeManager.byte_type)
1198 ig.Emit (OpCodes.Ldind_U1);
1199 else if (t == TypeManager.sbyte_type)
1200 ig.Emit (OpCodes.Ldind_I1);
1201 else if (t == TypeManager.uint64_type)
1202 ig.Emit (OpCodes.Ldind_I8);
1203 else if (t == TypeManager.int64_type)
1204 ig.Emit (OpCodes.Ldind_I8);
1205 else if (t == TypeManager.float_type)
1206 ig.Emit (OpCodes.Ldind_R4);
1207 else if (t == TypeManager.double_type)
1208 ig.Emit (OpCodes.Ldind_R8);
1209 else if (t == TypeManager.bool_type)
1210 ig.Emit (OpCodes.Ldind_I1);
1211 else if (t == TypeManager.intptr_type)
1212 ig.Emit (OpCodes.Ldind_I);
1213 else if (TypeManager.IsEnumType (t)) {
1214 if (t == TypeManager.enum_type)
1215 ig.Emit (OpCodes.Ldind_Ref);
1217 LoadFromPtr (ig, TypeManager.EnumToUnderlying (t));
1218 } else if (t.IsValueType || t.IsGenericParameter)
1219 ig.Emit (OpCodes.Ldobj, t);
1220 else if (t.IsPointer)
1221 ig.Emit (OpCodes.Ldind_I);
1223 ig.Emit (OpCodes.Ldind_Ref);
1227 // The stack contains the pointer and the value of type `type'
1229 public static void StoreFromPtr (ILGenerator ig, Type type)
1231 if (TypeManager.IsEnumType (type))
1232 type = TypeManager.EnumToUnderlying (type);
1233 if (type == TypeManager.int32_type || type == TypeManager.uint32_type)
1234 ig.Emit (OpCodes.Stind_I4);
1235 else if (type == TypeManager.int64_type || type == TypeManager.uint64_type)
1236 ig.Emit (OpCodes.Stind_I8);
1237 else if (type == TypeManager.char_type || type == TypeManager.short_type ||
1238 type == TypeManager.ushort_type)
1239 ig.Emit (OpCodes.Stind_I2);
1240 else if (type == TypeManager.float_type)
1241 ig.Emit (OpCodes.Stind_R4);
1242 else if (type == TypeManager.double_type)
1243 ig.Emit (OpCodes.Stind_R8);
1244 else if (type == TypeManager.byte_type || type == TypeManager.sbyte_type ||
1245 type == TypeManager.bool_type)
1246 ig.Emit (OpCodes.Stind_I1);
1247 else if (type == TypeManager.intptr_type)
1248 ig.Emit (OpCodes.Stind_I);
1249 else if (type.IsValueType || type.IsGenericParameter)
1250 ig.Emit (OpCodes.Stobj, type);
1252 ig.Emit (OpCodes.Stind_Ref);
1256 // Returns the size of type `t' if known, otherwise, 0
1258 public static int GetTypeSize (Type t)
1260 t = TypeManager.TypeToCoreType (t);
1261 if (t == TypeManager.int32_type ||
1262 t == TypeManager.uint32_type ||
1263 t == TypeManager.float_type)
1265 else if (t == TypeManager.int64_type ||
1266 t == TypeManager.uint64_type ||
1267 t == TypeManager.double_type)
1269 else if (t == TypeManager.byte_type ||
1270 t == TypeManager.sbyte_type ||
1271 t == TypeManager.bool_type)
1273 else if (t == TypeManager.short_type ||
1274 t == TypeManager.char_type ||
1275 t == TypeManager.ushort_type)
1277 else if (t == TypeManager.decimal_type)
1283 public static void Error_NegativeArrayIndex (Location loc)
1285 Report.Error (248, loc, "Cannot create an array with a negative size");
1289 // Converts `source' to an int, uint, long or ulong.
1291 public Expression ExpressionToArrayArgument (EmitContext ec, Expression source, Location loc)
1295 bool old_checked = ec.CheckState;
1296 ec.CheckState = true;
1298 target = Convert.ImplicitConversion (ec, source, TypeManager.int32_type, loc);
1299 if (target == null){
1300 target = Convert.ImplicitConversion (ec, source, TypeManager.uint32_type, loc);
1301 if (target == null){
1302 target = Convert.ImplicitConversion (ec, source, TypeManager.int64_type, loc);
1303 if (target == null){
1304 target = Convert.ImplicitConversion (ec, source, TypeManager.uint64_type, loc);
1306 Convert.Error_CannotImplicitConversion (loc, source.Type, TypeManager.int32_type);
1310 ec.CheckState = old_checked;
1313 // Only positive constants are allowed at compile time
1315 if (target is Constant){
1316 if (target is IntConstant){
1317 if (((IntConstant) target).Value < 0){
1318 Error_NegativeArrayIndex (loc);
1323 if (target is LongConstant){
1324 if (((LongConstant) target).Value < 0){
1325 Error_NegativeArrayIndex (loc);
1338 /// This is just a base class for expressions that can
1339 /// appear on statements (invocations, object creation,
1340 /// assignments, post/pre increment and decrement). The idea
1341 /// being that they would support an extra Emition interface that
1342 /// does not leave a result on the stack.
1344 public abstract class ExpressionStatement : Expression {
1346 public virtual ExpressionStatement ResolveStatement (EmitContext ec)
1348 Expression e = Resolve (ec);
1352 ExpressionStatement es = e as ExpressionStatement;
1354 Error (201, "Only assignment, call, increment, decrement and new object " +
1355 "expressions can be used as a statement");
1361 /// Requests the expression to be emitted in a `statement'
1362 /// context. This means that no new value is left on the
1363 /// stack after invoking this method (constrasted with
1364 /// Emit that will always leave a value on the stack).
1366 public abstract void EmitStatement (EmitContext ec);
1370 /// This kind of cast is used to encapsulate the child
1371 /// whose type is child.Type into an expression that is
1372 /// reported to return "return_type". This is used to encapsulate
1373 /// expressions which have compatible types, but need to be dealt
1374 /// at higher levels with.
1376 /// For example, a "byte" expression could be encapsulated in one
1377 /// of these as an "unsigned int". The type for the expression
1378 /// would be "unsigned int".
1381 public class EmptyCast : Expression {
1382 protected Expression child;
1384 public Expression Child {
1390 public EmptyCast (Expression child, Type return_type)
1392 eclass = child.eclass;
1393 loc = child.Location;
1398 public override Expression DoResolve (EmitContext ec)
1400 // This should never be invoked, we are born in fully
1401 // initialized state.
1406 public override void Emit (EmitContext ec)
1413 // We need to special case this since an empty cast of
1414 // a NullLiteral is still a Constant
1416 public class NullCast : Constant {
1417 protected Expression child;
1419 public NullCast (Expression child, Type return_type)
1421 eclass = child.eclass;
1426 override public string AsString ()
1431 public override object GetValue ()
1436 public override Expression DoResolve (EmitContext ec)
1438 // This should never be invoked, we are born in fully
1439 // initialized state.
1444 public override void Emit (EmitContext ec)
1449 public override bool IsDefaultValue {
1451 throw new NotImplementedException ();
1455 public override bool IsNegative {
1464 /// This class is used to wrap literals which belong inside Enums
1466 public class EnumConstant : Constant {
1467 public Constant Child;
1469 public EnumConstant (Constant child, Type enum_type)
1471 eclass = child.eclass;
1476 public override Expression DoResolve (EmitContext ec)
1478 // This should never be invoked, we are born in fully
1479 // initialized state.
1484 public override void Emit (EmitContext ec)
1489 public override object GetValue ()
1491 return Child.GetValue ();
1494 public object GetValueAsEnumType ()
1496 return System.Enum.ToObject (type, Child.GetValue ());
1500 // Converts from one of the valid underlying types for an enumeration
1501 // (int32, uint32, int64, uint64, short, ushort, byte, sbyte) to
1502 // one of the internal compiler literals: Int/UInt/Long/ULong Literals.
1504 public Constant WidenToCompilerConstant ()
1506 Type t = TypeManager.EnumToUnderlying (Child.Type);
1507 object v = ((Constant) Child).GetValue ();;
1509 if (t == TypeManager.int32_type)
1510 return new IntConstant ((int) v);
1511 if (t == TypeManager.uint32_type)
1512 return new UIntConstant ((uint) v);
1513 if (t == TypeManager.int64_type)
1514 return new LongConstant ((long) v);
1515 if (t == TypeManager.uint64_type)
1516 return new ULongConstant ((ulong) v);
1517 if (t == TypeManager.short_type)
1518 return new ShortConstant ((short) v);
1519 if (t == TypeManager.ushort_type)
1520 return new UShortConstant ((ushort) v);
1521 if (t == TypeManager.byte_type)
1522 return new ByteConstant ((byte) v);
1523 if (t == TypeManager.sbyte_type)
1524 return new SByteConstant ((sbyte) v);
1526 throw new Exception ("Invalid enumeration underlying type: " + t);
1530 // Extracts the value in the enumeration on its native representation
1532 public object GetPlainValue ()
1534 Type t = TypeManager.EnumToUnderlying (Child.Type);
1535 object v = ((Constant) Child).GetValue ();;
1537 if (t == TypeManager.int32_type)
1539 if (t == TypeManager.uint32_type)
1541 if (t == TypeManager.int64_type)
1543 if (t == TypeManager.uint64_type)
1545 if (t == TypeManager.short_type)
1547 if (t == TypeManager.ushort_type)
1549 if (t == TypeManager.byte_type)
1551 if (t == TypeManager.sbyte_type)
1557 public override string AsString ()
1559 return Child.AsString ();
1562 public override DoubleConstant ConvertToDouble ()
1564 return Child.ConvertToDouble ();
1567 public override FloatConstant ConvertToFloat ()
1569 return Child.ConvertToFloat ();
1572 public override ULongConstant ConvertToULong ()
1574 return Child.ConvertToULong ();
1577 public override LongConstant ConvertToLong ()
1579 return Child.ConvertToLong ();
1582 public override UIntConstant ConvertToUInt ()
1584 return Child.ConvertToUInt ();
1587 public override IntConstant ConvertToInt ()
1589 return Child.ConvertToInt ();
1592 public override bool IsDefaultValue {
1594 return Child.IsDefaultValue;
1598 public override bool IsZeroInteger {
1599 get { return Child.IsZeroInteger; }
1602 public override bool IsNegative {
1604 return Child.IsNegative;
1610 /// This kind of cast is used to encapsulate Value Types in objects.
1612 /// The effect of it is to box the value type emitted by the previous
1615 public class BoxedCast : EmptyCast {
1617 public BoxedCast (Expression expr)
1618 : base (expr, TypeManager.object_type)
1620 eclass = ExprClass.Value;
1623 public BoxedCast (Expression expr, Type target_type)
1624 : base (expr, target_type)
1626 eclass = ExprClass.Value;
1629 public override Expression DoResolve (EmitContext ec)
1631 // This should never be invoked, we are born in fully
1632 // initialized state.
1637 public override void Emit (EmitContext ec)
1641 ec.ig.Emit (OpCodes.Box, child.Type);
1645 public class UnboxCast : EmptyCast {
1646 public UnboxCast (Expression expr, Type return_type)
1647 : base (expr, return_type)
1651 public override Expression DoResolve (EmitContext ec)
1653 // This should never be invoked, we are born in fully
1654 // initialized state.
1659 public override void Emit (EmitContext ec)
1662 ILGenerator ig = ec.ig;
1665 if (t.IsGenericParameter)
1666 ig.Emit (OpCodes.Unbox_Any, t);
1668 ig.Emit (OpCodes.Unbox, t);
1670 LoadFromPtr (ig, t);
1676 /// This is used to perform explicit numeric conversions.
1678 /// Explicit numeric conversions might trigger exceptions in a checked
1679 /// context, so they should generate the conv.ovf opcodes instead of
1682 public class ConvCast : EmptyCast {
1683 public enum Mode : byte {
1684 I1_U1, I1_U2, I1_U4, I1_U8, I1_CH,
1686 I2_I1, I2_U1, I2_U2, I2_U4, I2_U8, I2_CH,
1687 U2_I1, U2_U1, U2_I2, U2_CH,
1688 I4_I1, I4_U1, I4_I2, I4_U2, I4_U4, I4_U8, I4_CH,
1689 U4_I1, U4_U1, U4_I2, U4_U2, U4_I4, U4_CH,
1690 I8_I1, I8_U1, I8_I2, I8_U2, I8_I4, I8_U4, I8_U8, I8_CH,
1691 U8_I1, U8_U1, U8_I2, U8_U2, U8_I4, U8_U4, U8_I8, U8_CH,
1692 CH_I1, CH_U1, CH_I2,
1693 R4_I1, R4_U1, R4_I2, R4_U2, R4_I4, R4_U4, R4_I8, R4_U8, R4_CH,
1694 R8_I1, R8_U1, R8_I2, R8_U2, R8_I4, R8_U4, R8_I8, R8_U8, R8_CH, R8_R4
1700 public ConvCast (EmitContext ec, Expression child, Type return_type, Mode m)
1701 : base (child, return_type)
1703 checked_state = ec.CheckState;
1707 public override Expression DoResolve (EmitContext ec)
1709 // This should never be invoked, we are born in fully
1710 // initialized state.
1715 public override string ToString ()
1717 return String.Format ("ConvCast ({0}, {1})", mode, child);
1720 public override void Emit (EmitContext ec)
1722 ILGenerator ig = ec.ig;
1728 case Mode.I1_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1729 case Mode.I1_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1730 case Mode.I1_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1731 case Mode.I1_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1732 case Mode.I1_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1734 case Mode.U1_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1735 case Mode.U1_CH: /* nothing */ break;
1737 case Mode.I2_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1738 case Mode.I2_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1739 case Mode.I2_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1740 case Mode.I2_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1741 case Mode.I2_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1742 case Mode.I2_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1744 case Mode.U2_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1745 case Mode.U2_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
1746 case Mode.U2_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
1747 case Mode.U2_CH: /* nothing */ break;
1749 case Mode.I4_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1750 case Mode.I4_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1751 case Mode.I4_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
1752 case Mode.I4_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1753 case Mode.I4_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1754 case Mode.I4_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1755 case Mode.I4_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1757 case Mode.U4_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1758 case Mode.U4_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
1759 case Mode.U4_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
1760 case Mode.U4_U2: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
1761 case Mode.U4_I4: ig.Emit (OpCodes.Conv_Ovf_I4_Un); break;
1762 case Mode.U4_CH: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
1764 case Mode.I8_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1765 case Mode.I8_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1766 case Mode.I8_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
1767 case Mode.I8_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1768 case Mode.I8_I4: ig.Emit (OpCodes.Conv_Ovf_I4); break;
1769 case Mode.I8_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1770 case Mode.I8_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1771 case Mode.I8_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1773 case Mode.U8_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1774 case Mode.U8_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
1775 case Mode.U8_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
1776 case Mode.U8_U2: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
1777 case Mode.U8_I4: ig.Emit (OpCodes.Conv_Ovf_I4_Un); break;
1778 case Mode.U8_U4: ig.Emit (OpCodes.Conv_Ovf_U4_Un); break;
1779 case Mode.U8_I8: ig.Emit (OpCodes.Conv_Ovf_I8_Un); break;
1780 case Mode.U8_CH: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
1782 case Mode.CH_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1783 case Mode.CH_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
1784 case Mode.CH_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
1786 case Mode.R4_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1787 case Mode.R4_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1788 case Mode.R4_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
1789 case Mode.R4_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1790 case Mode.R4_I4: ig.Emit (OpCodes.Conv_Ovf_I4); break;
1791 case Mode.R4_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1792 case Mode.R4_I8: ig.Emit (OpCodes.Conv_Ovf_I8); break;
1793 case Mode.R4_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1794 case Mode.R4_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1796 case Mode.R8_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1797 case Mode.R8_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1798 case Mode.R8_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
1799 case Mode.R8_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1800 case Mode.R8_I4: ig.Emit (OpCodes.Conv_Ovf_I4); break;
1801 case Mode.R8_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1802 case Mode.R8_I8: ig.Emit (OpCodes.Conv_Ovf_I8); break;
1803 case Mode.R8_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1804 case Mode.R8_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1805 case Mode.R8_R4: ig.Emit (OpCodes.Conv_R4); break;
1809 case Mode.I1_U1: ig.Emit (OpCodes.Conv_U1); break;
1810 case Mode.I1_U2: ig.Emit (OpCodes.Conv_U2); break;
1811 case Mode.I1_U4: ig.Emit (OpCodes.Conv_U4); break;
1812 case Mode.I1_U8: ig.Emit (OpCodes.Conv_I8); break;
1813 case Mode.I1_CH: ig.Emit (OpCodes.Conv_U2); break;
1815 case Mode.U1_I1: ig.Emit (OpCodes.Conv_I1); break;
1816 case Mode.U1_CH: ig.Emit (OpCodes.Conv_U2); break;
1818 case Mode.I2_I1: ig.Emit (OpCodes.Conv_I1); break;
1819 case Mode.I2_U1: ig.Emit (OpCodes.Conv_U1); break;
1820 case Mode.I2_U2: ig.Emit (OpCodes.Conv_U2); break;
1821 case Mode.I2_U4: ig.Emit (OpCodes.Conv_U4); break;
1822 case Mode.I2_U8: ig.Emit (OpCodes.Conv_I8); break;
1823 case Mode.I2_CH: ig.Emit (OpCodes.Conv_U2); break;
1825 case Mode.U2_I1: ig.Emit (OpCodes.Conv_I1); break;
1826 case Mode.U2_U1: ig.Emit (OpCodes.Conv_U1); break;
1827 case Mode.U2_I2: ig.Emit (OpCodes.Conv_I2); break;
1828 case Mode.U2_CH: /* nothing */ break;
1830 case Mode.I4_I1: ig.Emit (OpCodes.Conv_I1); break;
1831 case Mode.I4_U1: ig.Emit (OpCodes.Conv_U1); break;
1832 case Mode.I4_I2: ig.Emit (OpCodes.Conv_I2); break;
1833 case Mode.I4_U4: /* nothing */ break;
1834 case Mode.I4_U2: ig.Emit (OpCodes.Conv_U2); break;
1835 case Mode.I4_U8: ig.Emit (OpCodes.Conv_I8); break;
1836 case Mode.I4_CH: ig.Emit (OpCodes.Conv_U2); break;
1838 case Mode.U4_I1: ig.Emit (OpCodes.Conv_I1); break;
1839 case Mode.U4_U1: ig.Emit (OpCodes.Conv_U1); break;
1840 case Mode.U4_I2: ig.Emit (OpCodes.Conv_I2); break;
1841 case Mode.U4_U2: ig.Emit (OpCodes.Conv_U2); break;
1842 case Mode.U4_I4: /* nothing */ break;
1843 case Mode.U4_CH: ig.Emit (OpCodes.Conv_U2); break;
1845 case Mode.I8_I1: ig.Emit (OpCodes.Conv_I1); break;
1846 case Mode.I8_U1: ig.Emit (OpCodes.Conv_U1); break;
1847 case Mode.I8_I2: ig.Emit (OpCodes.Conv_I2); break;
1848 case Mode.I8_U2: ig.Emit (OpCodes.Conv_U2); break;
1849 case Mode.I8_I4: ig.Emit (OpCodes.Conv_I4); break;
1850 case Mode.I8_U4: ig.Emit (OpCodes.Conv_U4); break;
1851 case Mode.I8_U8: /* nothing */ break;
1852 case Mode.I8_CH: ig.Emit (OpCodes.Conv_U2); break;
1854 case Mode.U8_I1: ig.Emit (OpCodes.Conv_I1); break;
1855 case Mode.U8_U1: ig.Emit (OpCodes.Conv_U1); break;
1856 case Mode.U8_I2: ig.Emit (OpCodes.Conv_I2); break;
1857 case Mode.U8_U2: ig.Emit (OpCodes.Conv_U2); break;
1858 case Mode.U8_I4: ig.Emit (OpCodes.Conv_I4); break;
1859 case Mode.U8_U4: ig.Emit (OpCodes.Conv_U4); break;
1860 case Mode.U8_I8: /* nothing */ break;
1861 case Mode.U8_CH: ig.Emit (OpCodes.Conv_U2); break;
1863 case Mode.CH_I1: ig.Emit (OpCodes.Conv_I1); break;
1864 case Mode.CH_U1: ig.Emit (OpCodes.Conv_U1); break;
1865 case Mode.CH_I2: ig.Emit (OpCodes.Conv_I2); break;
1867 case Mode.R4_I1: ig.Emit (OpCodes.Conv_I1); break;
1868 case Mode.R4_U1: ig.Emit (OpCodes.Conv_U1); break;
1869 case Mode.R4_I2: ig.Emit (OpCodes.Conv_I2); break;
1870 case Mode.R4_U2: ig.Emit (OpCodes.Conv_U2); break;
1871 case Mode.R4_I4: ig.Emit (OpCodes.Conv_I4); break;
1872 case Mode.R4_U4: ig.Emit (OpCodes.Conv_U4); break;
1873 case Mode.R4_I8: ig.Emit (OpCodes.Conv_I8); break;
1874 case Mode.R4_U8: ig.Emit (OpCodes.Conv_U8); break;
1875 case Mode.R4_CH: ig.Emit (OpCodes.Conv_U2); break;
1877 case Mode.R8_I1: ig.Emit (OpCodes.Conv_I1); break;
1878 case Mode.R8_U1: ig.Emit (OpCodes.Conv_U1); break;
1879 case Mode.R8_I2: ig.Emit (OpCodes.Conv_I2); break;
1880 case Mode.R8_U2: ig.Emit (OpCodes.Conv_U2); break;
1881 case Mode.R8_I4: ig.Emit (OpCodes.Conv_I4); break;
1882 case Mode.R8_U4: ig.Emit (OpCodes.Conv_U4); break;
1883 case Mode.R8_I8: ig.Emit (OpCodes.Conv_I8); break;
1884 case Mode.R8_U8: ig.Emit (OpCodes.Conv_U8); break;
1885 case Mode.R8_CH: ig.Emit (OpCodes.Conv_U2); break;
1886 case Mode.R8_R4: ig.Emit (OpCodes.Conv_R4); break;
1892 public class OpcodeCast : EmptyCast {
1896 public OpcodeCast (Expression child, Type return_type, OpCode op)
1897 : base (child, return_type)
1901 second_valid = false;
1904 public OpcodeCast (Expression child, Type return_type, OpCode op, OpCode op2)
1905 : base (child, return_type)
1910 second_valid = true;
1913 public override Expression DoResolve (EmitContext ec)
1915 // This should never be invoked, we are born in fully
1916 // initialized state.
1921 public override void Emit (EmitContext ec)
1932 /// This kind of cast is used to encapsulate a child and cast it
1933 /// to the class requested
1935 public class ClassCast : EmptyCast {
1936 public ClassCast (Expression child, Type return_type)
1937 : base (child, return_type)
1942 public override Expression DoResolve (EmitContext ec)
1944 // This should never be invoked, we are born in fully
1945 // initialized state.
1950 public override void Emit (EmitContext ec)
1954 if (child.Type.IsGenericParameter)
1955 ec.ig.Emit (OpCodes.Box, child.Type);
1957 if (type.IsGenericParameter)
1958 ec.ig.Emit (OpCodes.Unbox_Any, type);
1960 ec.ig.Emit (OpCodes.Castclass, type);
1965 /// SimpleName expressions are formed of a single word and only happen at the beginning
1966 /// of a dotted-name.
1968 public class SimpleName : Expression {
1970 public readonly TypeArguments Arguments;
1972 public SimpleName (string name, Location l)
1978 public SimpleName (string name, TypeArguments args, Location l)
1985 public SimpleName (string name, TypeParameter[] type_params, Location l)
1990 Arguments = new TypeArguments (l);
1991 foreach (TypeParameter type_param in type_params)
1992 Arguments.Add (new TypeParameterExpr (type_param, l));
1995 public static string RemoveGenericArity (string name)
1998 StringBuilder sb = new StringBuilder ();
1999 while (start < name.Length) {
2000 int pos = name.IndexOf ('`', start);
2002 sb.Append (name.Substring (start));
2006 sb.Append (name.Substring (start, pos-start));
2009 while ((pos < name.Length) && Char.IsNumber (name [pos]))
2015 return sb.ToString ();
2018 public SimpleName GetMethodGroup ()
2020 return new SimpleName (RemoveGenericArity (Name), Arguments, loc);
2023 public static void Error_ObjectRefRequired (EmitContext ec, Location l, string name)
2025 if (ec.IsFieldInitializer)
2028 "A field initializer cannot reference the non-static field, " +
2029 "method or property `"+name+"'");
2033 "An object reference is required " +
2034 "for the non-static field `"+name+"'");
2037 public bool IdenticalNameAndTypeName (EmitContext ec, Expression resolved_to, Location loc)
2039 return resolved_to != null && resolved_to.Type != null &&
2040 resolved_to.Type.Name == Name &&
2041 (ec.DeclSpace.LookupType (Name, loc, /* ignore_cs0104 = */ true) != null);
2044 public override Expression DoResolve (EmitContext ec)
2046 return SimpleNameResolve (ec, null, false);
2049 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
2051 return SimpleNameResolve (ec, right_side, false);
2055 public Expression DoResolve (EmitContext ec, bool intermediate)
2057 return SimpleNameResolve (ec, null, intermediate);
2060 private bool IsNestedChild (Type t, Type parent)
2065 while (parent != null) {
2066 if (parent.IsGenericInstance)
2067 parent = parent.GetGenericTypeDefinition ();
2069 if (TypeManager.IsNestedChildOf (t, parent))
2072 parent = parent.BaseType;
2078 FullNamedExpression ResolveNested (EmitContext ec, Type t)
2080 if (!t.IsGenericTypeDefinition)
2083 DeclSpace ds = ec.DeclSpace;
2084 while (ds != null) {
2085 if (IsNestedChild (t, ds.TypeBuilder))
2094 Type[] gen_params = t.GetGenericArguments ();
2096 int arg_count = Arguments != null ? Arguments.Count : 0;
2098 for (; (ds != null) && ds.IsGeneric; ds = ds.Parent) {
2099 if (arg_count + ds.CountTypeParameters == gen_params.Length) {
2100 TypeArguments new_args = new TypeArguments (loc);
2101 foreach (TypeParameter param in ds.TypeParameters)
2102 new_args.Add (new TypeParameterExpr (param, loc));
2104 if (Arguments != null)
2105 new_args.Add (Arguments);
2107 return new ConstructedType (t, new_args, loc);
2114 public override FullNamedExpression ResolveAsTypeStep (EmitContext ec)
2116 FullNamedExpression dt = ec.DeclSpace.LookupGeneric (Name, loc);
2118 return dt.ResolveAsTypeStep (ec);
2120 int errors = Report.Errors;
2121 dt = ec.DeclSpace.LookupType (Name, loc, /*ignore_cs0104=*/ false);
2122 if (Report.Errors != errors)
2125 if ((dt == null) || (dt.Type == null))
2128 FullNamedExpression nested = ResolveNested (ec, dt.Type);
2130 return nested.ResolveAsTypeStep (ec);
2132 if (Arguments != null) {
2133 ConstructedType ct = new ConstructedType (dt, Arguments, loc);
2134 return ct.ResolveAsTypeStep (ec);
2140 Expression SimpleNameResolve (EmitContext ec, Expression right_side, bool intermediate)
2142 Expression e = DoSimpleNameResolve (ec, right_side, intermediate);
2146 if (ec.CurrentBlock == null || ec.CurrentBlock.CheckInvariantMeaningInBlock (Name, e, Location))
2153 /// 7.5.2: Simple Names.
2155 /// Local Variables and Parameters are handled at
2156 /// parse time, so they never occur as SimpleNames.
2158 /// The `intermediate' flag is used by MemberAccess only
2159 /// and it is used to inform us that it is ok for us to
2160 /// avoid the static check, because MemberAccess might end
2161 /// up resolving the Name as a Type name and the access as
2162 /// a static type access.
2164 /// ie: Type Type; .... { Type.GetType (""); }
2166 /// Type is both an instance variable and a Type; Type.GetType
2167 /// is the static method not an instance method of type.
2169 Expression DoSimpleNameResolve (EmitContext ec, Expression right_side, bool intermediate)
2171 Expression e = null;
2174 // Stage 1: Performed by the parser (binding to locals or parameters).
2176 Block current_block = ec.CurrentBlock;
2177 if (current_block != null){
2178 LocalInfo vi = current_block.GetLocalInfo (Name);
2182 var = new LocalVariableReference (ec.CurrentBlock, Name, loc);
2184 if (right_side != null)
2185 return var.ResolveLValue (ec, right_side);
2187 return var.Resolve (ec);
2190 ParameterReference pref = current_block.GetParameterReference (Name, loc);
2192 if (right_side != null)
2193 return pref.ResolveLValue (ec, right_side);
2195 return pref.Resolve (ec);
2200 // Stage 2: Lookup members
2203 DeclSpace lookup_ds = ec.DeclSpace;
2204 Type almost_matched_type = null;
2205 ArrayList almost_matched = null;
2207 if (lookup_ds.TypeBuilder == null)
2210 e = MemberLookup (ec, lookup_ds.TypeBuilder, Name, loc);
2214 if (almost_matched == null && almostMatchedMembers.Count > 0) {
2215 almost_matched_type = lookup_ds.TypeBuilder;
2216 almost_matched = (ArrayList) almostMatchedMembers.Clone ();
2219 lookup_ds =lookup_ds.Parent;
2220 } while (lookup_ds != null);
2222 if (e == null && ec.ContainerType != null)
2223 e = MemberLookup (ec, ec.ContainerType, Name, loc);
2226 if (almost_matched == null && almostMatchedMembers.Count > 0) {
2227 almost_matched_type = ec.ContainerType;
2228 almost_matched = (ArrayList) almostMatchedMembers.Clone ();
2230 e = ResolveAsTypeStep (ec);
2234 if (almost_matched != null)
2235 almostMatchedMembers = almost_matched;
2236 if (almost_matched_type == null)
2237 almost_matched_type = ec.ContainerType;
2238 MemberLookupFailed (ec, null, almost_matched_type, ((SimpleName) this).Name, ec.DeclSpace.Name, true, loc);
2245 if (e is MemberExpr) {
2246 MemberExpr me = (MemberExpr) e;
2249 if (me.IsInstance) {
2250 if (ec.IsStatic || ec.IsFieldInitializer) {
2252 // Note that an MemberExpr can be both IsInstance and IsStatic.
2253 // An unresolved MethodGroupExpr can contain both kinds of methods
2254 // and each predicate is true if the MethodGroupExpr contains
2255 // at least one of that kind of method.
2259 (!intermediate || !IdenticalNameAndTypeName (ec, me, loc))) {
2260 Error_ObjectRefRequired (ec, loc, Name);
2265 // Pass the buck to MemberAccess and Invocation.
2267 left = EmptyExpression.Null;
2269 left = ec.GetThis (loc);
2272 left = new TypeExpression (ec.ContainerType, loc);
2275 e = me.ResolveMemberAccess (ec, left, loc, null);
2279 me = e as MemberExpr;
2283 if (Arguments != null) {
2284 MethodGroupExpr mg = me as MethodGroupExpr;
2288 return mg.ResolveGeneric (ec, Arguments);
2292 TypeManager.IsNestedFamilyAccessible (me.InstanceExpression.Type, me.DeclaringType) &&
2293 me.InstanceExpression.Type != me.DeclaringType &&
2294 !TypeManager.IsFamilyAccessible (me.InstanceExpression.Type, me.DeclaringType) &&
2295 (!intermediate || !IdenticalNameAndTypeName (ec, e, loc))) {
2296 Error (38, "Cannot access nonstatic member `" + me.Name + "' of " +
2297 "outer type `" + me.DeclaringType + "' via nested type `" +
2298 me.InstanceExpression.Type + "'");
2302 return (right_side != null)
2303 ? me.DoResolveLValue (ec, right_side)
2304 : me.DoResolve (ec);
2310 public override void Emit (EmitContext ec)
2313 // If this is ever reached, then we failed to
2314 // find the name as a namespace
2317 Error (103, "The name `" + Name +
2318 "' does not exist in the class `" +
2319 ec.DeclSpace.Name + "'");
2322 public override string ToString ()
2329 /// Represents a namespace or a type. The name of the class was inspired by
2330 /// section 10.8.1 (Fully Qualified Names).
2332 public abstract class FullNamedExpression : Expression {
2333 public override FullNamedExpression ResolveAsTypeStep (EmitContext ec)
2338 public abstract string FullName {
2344 /// Fully resolved expression that evaluates to a type
2346 public abstract class TypeExpr : FullNamedExpression {
2347 override public FullNamedExpression ResolveAsTypeStep (EmitContext ec)
2349 TypeExpr t = DoResolveAsTypeStep (ec);
2353 eclass = ExprClass.Type;
2357 override public Expression DoResolve (EmitContext ec)
2359 return ResolveAsTypeTerminal (ec);
2362 override public void Emit (EmitContext ec)
2364 throw new Exception ("Should never be called");
2367 public virtual bool CheckAccessLevel (DeclSpace ds)
2369 return ds.CheckAccessLevel (Type);
2372 public virtual bool AsAccessible (DeclSpace ds, int flags)
2374 return ds.AsAccessible (Type, flags);
2377 public virtual bool IsClass {
2378 get { return Type.IsClass; }
2381 public virtual bool IsValueType {
2382 get { return Type.IsValueType; }
2385 public virtual bool IsInterface {
2386 get { return Type.IsInterface; }
2389 public virtual bool IsSealed {
2390 get { return Type.IsSealed; }
2393 public virtual bool CanInheritFrom ()
2395 if (Type == TypeManager.enum_type ||
2396 (Type == TypeManager.value_type && RootContext.StdLib) ||
2397 Type == TypeManager.multicast_delegate_type ||
2398 Type == TypeManager.delegate_type ||
2399 Type == TypeManager.array_type)
2405 protected abstract TypeExpr DoResolveAsTypeStep (EmitContext ec);
2407 public virtual Type ResolveType (EmitContext ec)
2409 TypeExpr t = ResolveAsTypeTerminal (ec);
2416 public abstract string Name {
2420 public override bool Equals (object obj)
2422 TypeExpr tobj = obj as TypeExpr;
2426 return Type == tobj.Type;
2429 public override int GetHashCode ()
2431 return Type.GetHashCode ();
2434 public override string ToString ()
2440 public class TypeExpression : TypeExpr {
2441 public TypeExpression (Type t, Location l)
2444 eclass = ExprClass.Type;
2448 protected override TypeExpr DoResolveAsTypeStep (EmitContext ec)
2453 public override string Name {
2455 return Type.ToString ();
2459 public override string FullName {
2461 return Type.FullName != null ? Type.FullName : Type.Name;
2467 /// Used to create types from a fully qualified name. These are just used
2468 /// by the parser to setup the core types. A TypeLookupExpression is always
2469 /// classified as a type.
2471 public class TypeLookupExpression : TypeExpr {
2474 public TypeLookupExpression (string name)
2479 protected override TypeExpr DoResolveAsTypeStep (EmitContext ec)
2482 FullNamedExpression t = ec.DeclSpace.LookupType (name, Location.Null, /*ignore_cs0104=*/ false);
2484 Report.Error (246, loc, "Cannot find type `" + name + "'");
2487 if (!(t is TypeExpr)) {
2488 Report.Error (118, Location, "'{0}' denotes a '{1}', where a type was expected",
2489 t.FullName, t.ExprClassName ());
2493 type = ((TypeExpr) t).ResolveType (ec);
2499 public override string Name {
2505 public override string FullName {
2513 /// Represents an "unbound generic type", ie. typeof (Foo<>).
2516 public class UnboundTypeExpression : TypeLookupExpression {
2517 public UnboundTypeExpression (string name)
2522 public class TypeAliasExpression : TypeExpr {
2523 FullNamedExpression alias;
2528 public TypeAliasExpression (FullNamedExpression alias, TypeArguments args, Location l)
2534 eclass = ExprClass.Type;
2536 name = alias.FullName + "<" + args.ToString () + ">";
2538 name = alias.FullName;
2541 public override string Name {
2542 get { return alias.FullName; }
2545 public override string FullName {
2546 get { return name; }
2549 protected override TypeExpr DoResolveAsTypeStep (EmitContext ec)
2551 texpr = alias.ResolveAsTypeTerminal (ec);
2555 Type type = texpr.Type;
2556 int num_args = TypeManager.GetNumberOfTypeArguments (type);
2559 if (num_args == 0) {
2560 Report.Error (308, loc,
2561 "The non-generic type `{0}' cannot " +
2562 "be used with type arguments.",
2563 TypeManager.CSharpName (type));
2567 ConstructedType ctype = new ConstructedType (type, args, loc);
2568 return ctype.ResolveAsTypeTerminal (ec);
2569 } else if (num_args > 0) {
2570 Report.Error (305, loc,
2571 "Using the generic type `{0}' " +
2572 "requires {1} type arguments",
2573 TypeManager.GetFullName (type), num_args);
2577 return new TypeExpression (type, loc);
2580 public override bool CheckAccessLevel (DeclSpace ds)
2582 return texpr.CheckAccessLevel (ds);
2585 public override bool AsAccessible (DeclSpace ds, int flags)
2587 return texpr.AsAccessible (ds, flags);
2590 public override bool IsClass {
2591 get { return texpr.IsClass; }
2594 public override bool IsValueType {
2595 get { return texpr.IsValueType; }
2598 public override bool IsInterface {
2599 get { return texpr.IsInterface; }
2602 public override bool IsSealed {
2603 get { return texpr.IsSealed; }
2608 /// This class denotes an expression which evaluates to a member
2609 /// of a struct or a class.
2611 public abstract class MemberExpr : Expression
2614 /// The name of this member.
2616 public abstract string Name {
2621 /// Whether this is an instance member.
2623 public abstract bool IsInstance {
2628 /// Whether this is a static member.
2630 public abstract bool IsStatic {
2635 /// The type which declares this member.
2637 public abstract Type DeclaringType {
2642 /// The instance expression associated with this member, if it's a
2643 /// non-static member.
2645 public Expression InstanceExpression;
2647 public static void error176 (Location loc, string name)
2649 Report.Error (176, loc, "Static member `" + name + "' cannot be accessed " +
2650 "with an instance reference, qualify with a type name instead");
2654 // TODO: possible optimalization
2655 // Cache resolved constant result in FieldBuilder <-> expression map
2656 public virtual Expression ResolveMemberAccess (EmitContext ec, Expression left, Location loc,
2657 SimpleName original)
2661 // original == null || original.Resolve (...) ==> left
2664 if (left is TypeExpr) {
2666 SimpleName.Error_ObjectRefRequired (ec, loc, Name);
2674 if (original != null && original.IdenticalNameAndTypeName (ec, left, loc))
2677 error176 (loc, Name);
2681 InstanceExpression = left;
2688 /// MethodGroup Expression.
2690 /// This is a fully resolved expression that evaluates to a type
2692 public class MethodGroupExpr : MemberExpr {
2693 public MethodBase [] Methods;
2694 bool has_type_arguments = false;
2695 bool identical_type_name = false;
2698 public MethodGroupExpr (MemberInfo [] mi, Location l)
2700 Methods = new MethodBase [mi.Length];
2701 mi.CopyTo (Methods, 0);
2702 eclass = ExprClass.MethodGroup;
2703 type = TypeManager.object_type;
2707 public MethodGroupExpr (ArrayList list, Location l)
2709 Methods = new MethodBase [list.Count];
2712 list.CopyTo (Methods, 0);
2714 foreach (MemberInfo m in list){
2715 if (!(m is MethodBase)){
2716 Console.WriteLine ("Name " + m.Name);
2717 Console.WriteLine ("Found a: " + m.GetType ().FullName);
2724 eclass = ExprClass.MethodGroup;
2725 type = TypeManager.object_type;
2728 public override Type DeclaringType {
2731 // We assume that the top-level type is in the end
2733 return Methods [Methods.Length - 1].DeclaringType;
2734 //return Methods [0].DeclaringType;
2738 public bool HasTypeArguments {
2740 return has_type_arguments;
2744 has_type_arguments = value;
2748 public bool IdenticalTypeName {
2750 return identical_type_name;
2754 identical_type_name = value;
2758 public bool IsBase {
2767 public override string Name {
2769 //return Methods [0].Name;
2770 return Methods [Methods.Length - 1].Name;
2774 public override bool IsInstance {
2776 foreach (MethodBase mb in Methods)
2784 public override bool IsStatic {
2786 foreach (MethodBase mb in Methods)
2794 public override Expression ResolveMemberAccess (EmitContext ec, Expression left, Location loc,
2795 SimpleName original)
2797 if (!(left is TypeExpr) &&
2798 original != null && original.IdenticalNameAndTypeName (ec, left, loc))
2799 IdenticalTypeName = true;
2801 return base.ResolveMemberAccess (ec, left, loc, original);
2804 override public Expression DoResolve (EmitContext ec)
2807 InstanceExpression = null;
2809 if (InstanceExpression != null) {
2810 InstanceExpression = InstanceExpression.DoResolve (ec);
2811 if (InstanceExpression == null)
2818 public void ReportUsageError ()
2820 Report.Error (654, loc, "Method `" + DeclaringType + "." +
2821 Name + "()' is referenced without parentheses");
2824 override public void Emit (EmitContext ec)
2826 ReportUsageError ();
2829 bool RemoveMethods (bool keep_static)
2831 ArrayList smethods = new ArrayList ();
2833 foreach (MethodBase mb in Methods){
2834 if (mb.IsStatic == keep_static)
2838 if (smethods.Count == 0)
2841 Methods = new MethodBase [smethods.Count];
2842 smethods.CopyTo (Methods, 0);
2848 /// Removes any instance methods from the MethodGroup, returns
2849 /// false if the resulting set is empty.
2851 public bool RemoveInstanceMethods ()
2853 return RemoveMethods (true);
2857 /// Removes any static methods from the MethodGroup, returns
2858 /// false if the resulting set is empty.
2860 public bool RemoveStaticMethods ()
2862 return RemoveMethods (false);
2865 public Expression ResolveGeneric (EmitContext ec, TypeArguments args)
2867 if (args.Resolve (ec) == false)
2870 Type[] atypes = args.Arguments;
2872 int first_count = 0;
2873 MethodInfo first = null;
2875 ArrayList list = new ArrayList ();
2876 foreach (MethodBase mb in Methods) {
2877 MethodInfo mi = mb as MethodInfo;
2878 if ((mi == null) || !mi.HasGenericParameters)
2881 Type[] gen_params = mi.GetGenericArguments ();
2883 if (first == null) {
2885 first_count = gen_params.Length;
2888 if (gen_params.Length != atypes.Length)
2891 list.Add (mi.BindGenericParameters (atypes));
2894 if (list.Count > 0) {
2895 MethodGroupExpr new_mg = new MethodGroupExpr (list, Location);
2896 new_mg.InstanceExpression = InstanceExpression;
2897 new_mg.HasTypeArguments = true;
2903 305, loc, "Using the generic method `{0}' " +
2904 "requires {1} type arguments", Name,
2908 308, loc, "The non-generic method `{0}' " +
2909 "cannot be used with type arguments", Name);
2916 /// Fully resolved expression that evaluates to a Field
2918 public class FieldExpr : MemberExpr, IAssignMethod, IMemoryLocation, IVariable {
2919 public readonly FieldInfo FieldInfo;
2920 VariableInfo variable_info;
2922 LocalTemporary temp;
2924 bool in_initializer;
2926 public FieldExpr (FieldInfo fi, Location l, bool in_initializer):
2929 this.in_initializer = in_initializer;
2932 public FieldExpr (FieldInfo fi, Location l)
2935 eclass = ExprClass.Variable;
2936 type = TypeManager.TypeToCoreType (fi.FieldType);
2940 public override string Name {
2942 return FieldInfo.Name;
2946 public override bool IsInstance {
2948 return !FieldInfo.IsStatic;
2952 public override bool IsStatic {
2954 return FieldInfo.IsStatic;
2958 public override Type DeclaringType {
2960 return FieldInfo.DeclaringType;
2964 public VariableInfo VariableInfo {
2966 return variable_info;
2970 public override Expression ResolveMemberAccess (EmitContext ec, Expression left, Location loc,
2971 SimpleName original)
2973 bool left_is_type = left is TypeExpr;
2975 FieldInfo fi = FieldInfo.Mono_GetGenericFieldDefinition ();
2977 Type decl_type = fi.DeclaringType;
2979 bool is_emitted = fi is FieldBuilder;
2980 Type t = fi.FieldType;
2983 Const c = TypeManager.LookupConstant ((FieldBuilder) fi);
2987 if (!c.LookupConstantValue (out o))
2990 c.SetMemberIsUsed ();
2991 object real_value = ((Constant) c.Expr).GetValue ();
2993 Expression exp = Constantify (real_value, t);
2995 if (!left_is_type &&
2996 (original == null || !original.IdenticalNameAndTypeName (ec, left, loc))) {
2997 Report.SymbolRelatedToPreviousError (c);
2998 error176 (loc, c.GetSignatureForError ());
3006 // IsInitOnly is because of MS compatibility, I don't know why but they emit decimal constant as InitOnly
3007 if (fi.IsInitOnly && !is_emitted && t == TypeManager.decimal_type) {
3008 object[] attrs = fi.GetCustomAttributes (TypeManager.decimal_constant_attribute_type, false);
3009 if (attrs.Length == 1)
3010 return new DecimalConstant (((System.Runtime.CompilerServices.DecimalConstantAttribute) attrs [0]).Value);
3017 o = TypeManager.GetValue ((FieldBuilder) fi);
3019 o = fi.GetValue (fi);
3021 if (decl_type.IsSubclassOf (TypeManager.enum_type)) {
3022 if (!left_is_type &&
3023 (original == null || !original.IdenticalNameAndTypeName (ec, left, loc))) {
3024 error176 (loc, fi.Name);
3028 Expression enum_member = MemberLookup (
3029 ec, decl_type, "value__", MemberTypes.Field,
3030 AllBindingFlags | BindingFlags.NonPublic, loc);
3032 Enum en = TypeManager.LookupEnum (decl_type);
3036 c = Constantify (o, en.UnderlyingType);
3038 c = Constantify (o, enum_member.Type);
3040 return new EnumConstant (c, decl_type);
3043 Expression exp = Constantify (o, t);
3045 if (!left_is_type) {
3046 error176 (loc, fi.Name);
3053 if (t.IsPointer && !ec.InUnsafe) {
3058 return base.ResolveMemberAccess (ec, left, loc, original);
3061 override public Expression DoResolve (EmitContext ec)
3063 if (ec.InRefOutArgumentResolving && FieldInfo.IsInitOnly && !ec.IsConstructor && FieldInfo.FieldType.IsValueType) {
3064 if (FieldInfo.FieldType is TypeBuilder) {
3065 if (FieldInfo.IsStatic)
3066 Report.Error (1651, loc, "Members of readonly static field '{0}.{1}' cannot be passed ref or out (except in a constructor)",
3067 TypeManager.CSharpName (DeclaringType), Name);
3069 Report.Error (1649, loc, "Members of readonly field '{0}.{1}' cannot be passed ref or out (except in a constructor)",
3070 TypeManager.CSharpName (DeclaringType), Name);
3072 if (FieldInfo.IsStatic)
3073 Report.Error (199, loc, "A static readonly field '{0}' cannot be passed ref or out (except in a static constructor)",
3076 Report.Error (192, loc, "A readonly field '{0}' cannot be passed ref or out (except in a constructor)",
3082 if (!FieldInfo.IsStatic){
3083 if (InstanceExpression == null){
3085 // This can happen when referencing an instance field using
3086 // a fully qualified type expression: TypeName.InstanceField = xxx
3088 SimpleName.Error_ObjectRefRequired (ec, loc, FieldInfo.Name);
3092 // Resolve the field's instance expression while flow analysis is turned
3093 // off: when accessing a field "a.b", we must check whether the field
3094 // "a.b" is initialized, not whether the whole struct "a" is initialized.
3095 InstanceExpression = InstanceExpression.Resolve (ec, ResolveFlags.VariableOrValue |
3096 ResolveFlags.DisableFlowAnalysis);
3097 if (InstanceExpression == null)
3101 if (!in_initializer) {
3102 ObsoleteAttribute oa;
3103 FieldBase f = TypeManager.GetField (FieldInfo);
3105 oa = f.GetObsoleteAttribute (f.Parent);
3107 AttributeTester.Report_ObsoleteMessage (oa, f.GetSignatureForError (), loc);
3108 // To be sure that type is external because we do not register generated fields
3109 } else if (!(FieldInfo.DeclaringType is TypeBuilder)) {
3110 oa = AttributeTester.GetMemberObsoleteAttribute (FieldInfo);
3112 AttributeTester.Report_ObsoleteMessage (oa, TypeManager.GetFullNameSignature (FieldInfo), loc);
3116 if (ec.CurrentAnonymousMethod != null){
3117 if (!FieldInfo.IsStatic){
3118 if (ec.TypeContainer is Struct){
3119 Report.Error (1673, loc, "Can not reference instance variables in anonymous methods hosted in structs");
3122 ec.CaptureField (this);
3126 // If the instance expression is a local variable or parameter.
3127 IVariable var = InstanceExpression as IVariable;
3128 if ((var == null) || (var.VariableInfo == null))
3131 VariableInfo vi = var.VariableInfo;
3132 if (!vi.IsFieldAssigned (ec, FieldInfo.Name, loc))
3135 variable_info = vi.GetSubStruct (FieldInfo.Name);
3139 void Report_AssignToReadonly (bool is_instance)
3144 msg = "Readonly field can not be assigned outside " +
3145 "of constructor or variable initializer";
3147 msg = "A static readonly field can only be assigned in " +
3148 "a static constructor";
3150 Report.Error (is_instance ? 191 : 198, loc, msg);
3153 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
3155 IVariable var = InstanceExpression as IVariable;
3156 if ((var != null) && (var.VariableInfo != null))
3157 var.VariableInfo.SetFieldAssigned (ec, FieldInfo.Name);
3159 Expression e = DoResolve (ec);
3164 if (!FieldInfo.IsStatic && (InstanceExpression.Type.IsValueType && !(InstanceExpression is IMemoryLocation))) {
3165 // FIXME: Provide better error reporting.
3166 Error (1612, "Cannot modify expression because it is not a variable.");
3170 FieldBase fb = TypeManager.GetField (FieldInfo);
3174 if (!FieldInfo.IsInitOnly)
3178 // InitOnly fields can only be assigned in constructors
3181 if (ec.IsConstructor){
3182 if (IsStatic && !ec.IsStatic)
3183 Report_AssignToReadonly (false);
3186 if (ec.TypeContainer.CurrentType != null)
3187 ctype = ec.TypeContainer.CurrentType;
3189 ctype = ec.ContainerType;
3191 if (TypeManager.IsEqual (ctype, FieldInfo.DeclaringType))
3195 Report_AssignToReadonly (!IsStatic);
3200 public override void CheckMarshallByRefAccess (Type container)
3202 if (!IsStatic && Type.IsValueType && !container.IsSubclassOf (TypeManager.mbr_type) && DeclaringType.IsSubclassOf (TypeManager.mbr_type)) {
3203 Report.SymbolRelatedToPreviousError (DeclaringType);
3204 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);
3208 public bool VerifyFixed (bool is_expression)
3210 IVariable variable = InstanceExpression as IVariable;
3211 if ((variable == null) || !variable.VerifyFixed (true))
3217 public override int GetHashCode()
3219 return FieldInfo.GetHashCode ();
3222 public override bool Equals (object obj)
3224 FieldExpr fe = obj as FieldExpr;
3228 if (FieldInfo != fe.FieldInfo)
3231 if (InstanceExpression == null || fe.InstanceExpression == null)
3234 return InstanceExpression.Equals (fe.InstanceExpression);
3237 public void Emit (EmitContext ec, bool leave_copy)
3239 ILGenerator ig = ec.ig;
3240 bool is_volatile = false;
3242 if (FieldInfo is FieldBuilder){
3243 FieldBase f = TypeManager.GetField (FieldInfo);
3245 if ((f.ModFlags & Modifiers.VOLATILE) != 0)
3248 f.SetMemberIsUsed ();
3252 if (FieldInfo.IsStatic){
3254 ig.Emit (OpCodes.Volatile);
3256 ig.Emit (OpCodes.Ldsfld, FieldInfo);
3262 ig.Emit (OpCodes.Volatile);
3264 IFixedBuffer ff = AttributeTester.GetFixedBuffer (FieldInfo);
3267 ig.Emit (OpCodes.Ldflda, FieldInfo);
3268 ig.Emit (OpCodes.Ldflda, ff.Element);
3271 ig.Emit (OpCodes.Ldfld, FieldInfo);
3276 ec.ig.Emit (OpCodes.Dup);
3277 if (!FieldInfo.IsStatic) {
3278 temp = new LocalTemporary (ec, this.Type);
3284 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
3286 FieldAttributes fa = FieldInfo.Attributes;
3287 bool is_static = (fa & FieldAttributes.Static) != 0;
3288 bool is_readonly = (fa & FieldAttributes.InitOnly) != 0;
3289 ILGenerator ig = ec.ig;
3290 prepared = prepare_for_load;
3292 if (is_readonly && !ec.IsConstructor){
3293 Report_AssignToReadonly (!is_static);
3299 if (prepare_for_load)
3300 ig.Emit (OpCodes.Dup);
3305 ec.ig.Emit (OpCodes.Dup);
3306 if (!FieldInfo.IsStatic) {
3307 temp = new LocalTemporary (ec, this.Type);
3312 if (FieldInfo is FieldBuilder){
3313 FieldBase f = TypeManager.GetField (FieldInfo);
3315 if ((f.ModFlags & Modifiers.VOLATILE) != 0)
3316 ig.Emit (OpCodes.Volatile);
3318 f.status |= Field.Status.ASSIGNED;
3323 ig.Emit (OpCodes.Stsfld, FieldInfo);
3325 ig.Emit (OpCodes.Stfld, FieldInfo);
3331 void EmitInstance (EmitContext ec)
3333 if (InstanceExpression.Type.IsValueType) {
3334 if (InstanceExpression is IMemoryLocation) {
3335 ((IMemoryLocation) InstanceExpression).AddressOf (ec, AddressOp.LoadStore);
3337 LocalTemporary t = new LocalTemporary (ec, InstanceExpression.Type);
3338 InstanceExpression.Emit (ec);
3340 t.AddressOf (ec, AddressOp.Store);
3343 InstanceExpression.Emit (ec);
3346 public override void Emit (EmitContext ec)
3351 public void AddressOf (EmitContext ec, AddressOp mode)
3353 ILGenerator ig = ec.ig;
3355 if (FieldInfo is FieldBuilder){
3356 FieldBase f = TypeManager.GetField (FieldInfo);
3358 if ((f.ModFlags & Modifiers.VOLATILE) != 0){
3359 Error (676, "volatile variable: can not take its address, or pass as ref/out parameter");
3363 if ((mode & AddressOp.Store) != 0)
3364 f.status |= Field.Status.ASSIGNED;
3365 if ((mode & AddressOp.Load) != 0)
3366 f.SetMemberIsUsed ();
3371 // Handle initonly fields specially: make a copy and then
3372 // get the address of the copy.
3375 if (FieldInfo.IsInitOnly){
3377 if (ec.IsConstructor){
3378 if (FieldInfo.IsStatic){
3390 local = ig.DeclareLocal (type);
3391 ig.Emit (OpCodes.Stloc, local);
3392 ig.Emit (OpCodes.Ldloca, local);
3397 if (FieldInfo.IsStatic){
3398 ig.Emit (OpCodes.Ldsflda, FieldInfo);
3401 ig.Emit (OpCodes.Ldflda, FieldInfo);
3407 // A FieldExpr whose address can not be taken
3409 public class FieldExprNoAddress : FieldExpr, IMemoryLocation {
3410 public FieldExprNoAddress (FieldInfo fi, Location loc) : base (fi, loc)
3414 public new void AddressOf (EmitContext ec, AddressOp mode)
3416 Report.Error (-215, "Report this: Taking the address of a remapped parameter not supported");
3421 /// Expression that evaluates to a Property. The Assign class
3422 /// might set the `Value' expression if we are in an assignment.
3424 /// This is not an LValue because we need to re-write the expression, we
3425 /// can not take data from the stack and store it.
3427 public class PropertyExpr : MemberExpr, IAssignMethod {
3428 public readonly PropertyInfo PropertyInfo;
3431 // This is set externally by the `BaseAccess' class
3434 MethodInfo getter, setter;
3439 LocalTemporary temp;
3442 internal static PtrHashtable AccessorTable = new PtrHashtable ();
3444 public PropertyExpr (EmitContext ec, PropertyInfo pi, Location l)
3447 eclass = ExprClass.PropertyAccess;
3451 type = TypeManager.TypeToCoreType (pi.PropertyType);
3453 ResolveAccessors (ec);
3456 public override string Name {
3458 return PropertyInfo.Name;
3462 public override bool IsInstance {
3468 public override bool IsStatic {
3474 public override Type DeclaringType {
3476 return PropertyInfo.DeclaringType;
3480 public bool VerifyAssignable ()
3482 if (setter == null) {
3483 Report.Error (200, loc,
3484 "The property `" + PropertyInfo.Name +
3485 "' can not be assigned to, as it has not set accessor");
3492 void FindAccessors (Type invocation_type)
3494 BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic |
3495 BindingFlags.Static | BindingFlags.Instance |
3496 BindingFlags.DeclaredOnly;
3498 Type current = PropertyInfo.DeclaringType;
3499 for (; current != null; current = current.BaseType) {
3500 MemberInfo[] group = TypeManager.MemberLookup (
3501 invocation_type, invocation_type, current,
3502 MemberTypes.Property, flags, PropertyInfo.Name, null);
3507 if (group.Length != 1)
3508 // Oooops, can this ever happen ?
3511 PropertyInfo pi = (PropertyInfo) group [0];
3514 getter = pi.GetGetMethod (true);
3517 setter = pi.GetSetMethod (true);
3519 MethodInfo accessor = getter != null ? getter : setter;
3521 if (!accessor.IsVirtual)
3527 // We also perform the permission checking here, as the PropertyInfo does not
3528 // hold the information for the accessibility of its setter/getter
3530 void ResolveAccessors (EmitContext ec)
3532 FindAccessors (ec.ContainerType);
3534 if (getter != null) {
3535 IMethodData md = TypeManager.GetMethod (getter);
3537 md.SetMemberIsUsed ();
3539 AccessorTable [getter] = PropertyInfo;
3540 is_static = getter.IsStatic;
3543 if (setter != null) {
3544 IMethodData md = TypeManager.GetMethod (setter);
3546 md.SetMemberIsUsed ();
3548 AccessorTable [setter] = PropertyInfo;
3549 is_static = setter.IsStatic;
3553 bool InstanceResolve (EmitContext ec, bool must_do_cs1540_check)
3555 if ((InstanceExpression == null) && ec.IsStatic && !is_static) {
3556 SimpleName.Error_ObjectRefRequired (ec, loc, PropertyInfo.Name);
3560 if (!IsInstance || InstanceExpression == EmptyExpression.Null)
3561 InstanceExpression = null;
3563 if (InstanceExpression != null) {
3564 InstanceExpression = InstanceExpression.DoResolve (ec);
3565 if (InstanceExpression == null)
3568 InstanceExpression.CheckMarshallByRefAccess (ec.ContainerType);
3571 if (must_do_cs1540_check && (InstanceExpression != null)) {
3572 if ((InstanceExpression.Type != ec.ContainerType) &&
3573 ec.ContainerType.IsSubclassOf (InstanceExpression.Type)) {
3574 Report.Error (1540, loc, "Cannot access protected member `" +
3575 PropertyInfo.DeclaringType + "." + PropertyInfo.Name +
3576 "' via a qualifier of type `" +
3577 TypeManager.CSharpName (InstanceExpression.Type) +
3578 "'; the qualifier must be of type `" +
3579 TypeManager.CSharpName (ec.ContainerType) +
3580 "' (or derived from it)");
3588 override public Expression DoResolve (EmitContext ec)
3591 Report.Debug ("Double resolve of " + Name);
3595 if (getter != null){
3596 if (TypeManager.GetArgumentTypes (getter).Length != 0){
3598 117, loc, "`{0}' does not contain a " +
3599 "definition for `{1}'.", getter.DeclaringType,
3605 if (getter == null){
3607 // The following condition happens if the PropertyExpr was
3608 // created, but is invalid (ie, the property is inaccessible),
3609 // and we did not want to embed the knowledge about this in
3610 // the caller routine. This only avoids double error reporting.
3615 if (InstanceExpression != EmptyExpression.Null) {
3616 Report.Error (154, loc,
3617 "The property `" + PropertyInfo.Name +
3618 "' can not be used in " +
3619 "this context because it lacks a get accessor");
3624 bool must_do_cs1540_check = false;
3625 if (getter != null &&
3626 !IsAccessorAccessible (ec.ContainerType, getter, out must_do_cs1540_check)) {
3627 PropertyBase.PropertyMethod pm = TypeManager.GetMethod (getter) as PropertyBase.PropertyMethod;
3628 if (pm != null && pm.HasCustomAccessModifier) {
3629 Report.SymbolRelatedToPreviousError (pm);
3630 Report.Error (271, loc, "The property or indexer '{0}' cannot be used in this context because the get accessor is inaccessible",
3631 TypeManager.CSharpSignature (getter));
3634 Report.Error (122, loc, "'{0}' is inaccessible due to its protection level",
3635 TypeManager.CSharpSignature (getter));
3639 if (!InstanceResolve (ec, must_do_cs1540_check))
3643 // Only base will allow this invocation to happen.
3645 if (IsBase && getter.IsAbstract){
3646 Report.Error (205, loc, "Cannot call an abstract base property: " +
3647 PropertyInfo.DeclaringType + "." +PropertyInfo.Name);
3651 if (PropertyInfo.PropertyType.IsPointer && !ec.InUnsafe){
3661 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
3663 if (setter == null){
3665 // The following condition happens if the PropertyExpr was
3666 // created, but is invalid (ie, the property is inaccessible),
3667 // and we did not want to embed the knowledge about this in
3668 // the caller routine. This only avoids double error reporting.
3673 // TODO: Print better property name
3674 Report.Error (200, loc, "Property or indexer '{0}' cannot be assigned to -- it is read only",
3679 if (TypeManager.GetArgumentTypes (setter).Length != 1){
3681 117, loc, "`{0}' does not contain a " +
3682 "definition for `{1}'.", getter.DeclaringType,
3687 bool must_do_cs1540_check;
3688 if (!IsAccessorAccessible (ec.ContainerType, setter, out must_do_cs1540_check)) {
3689 PropertyBase.PropertyMethod pm = TypeManager.GetMethod (setter) as PropertyBase.PropertyMethod;
3690 if (pm != null && pm.HasCustomAccessModifier) {
3691 Report.SymbolRelatedToPreviousError (pm);
3692 Report.Error (272, loc, "The property or indexer '{0}' cannot be used in this context because the set accessor is inaccessible",
3693 TypeManager.CSharpSignature (setter));
3696 Report.Error (122, loc, "'{0}' is inaccessible due to its protection level",
3697 TypeManager.CSharpSignature (setter));
3701 if (!InstanceResolve (ec, must_do_cs1540_check))
3705 // Only base will allow this invocation to happen.
3707 if (IsBase && setter.IsAbstract){
3708 Report.Error (205, loc, "Cannot call an abstract base property: " +
3709 PropertyInfo.DeclaringType + "." +PropertyInfo.Name);
3714 // Check that we are not making changes to a temporary memory location
3716 if (InstanceExpression != null && InstanceExpression.Type.IsValueType && !(InstanceExpression is IMemoryLocation)) {
3717 // FIXME: Provide better error reporting.
3718 Error (1612, "Cannot modify expression because it is not a variable.");
3727 public override void Emit (EmitContext ec)
3732 void EmitInstance (EmitContext ec)
3737 if (InstanceExpression.Type.IsValueType) {
3738 if (InstanceExpression is IMemoryLocation) {
3739 ((IMemoryLocation) InstanceExpression).AddressOf (ec, AddressOp.LoadStore);
3741 LocalTemporary t = new LocalTemporary (ec, InstanceExpression.Type);
3742 InstanceExpression.Emit (ec);
3744 t.AddressOf (ec, AddressOp.Store);
3747 InstanceExpression.Emit (ec);
3750 ec.ig.Emit (OpCodes.Dup);
3754 public void Emit (EmitContext ec, bool leave_copy)
3760 // Special case: length of single dimension array property is turned into ldlen
3762 if ((getter == TypeManager.system_int_array_get_length) ||
3763 (getter == TypeManager.int_array_get_length)){
3764 Type iet = InstanceExpression.Type;
3767 // System.Array.Length can be called, but the Type does not
3768 // support invoking GetArrayRank, so test for that case first
3770 if (iet != TypeManager.array_type && (iet.GetArrayRank () == 1)) {
3771 ec.ig.Emit (OpCodes.Ldlen);
3772 ec.ig.Emit (OpCodes.Conv_I4);
3777 Invocation.EmitCall (ec, IsBase, IsStatic, new EmptyAddressOf (), getter, null, loc);
3782 ec.ig.Emit (OpCodes.Dup);
3784 temp = new LocalTemporary (ec, this.Type);
3790 // Implements the IAssignMethod interface for assignments
3792 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
3794 prepared = prepare_for_load;
3800 ec.ig.Emit (OpCodes.Dup);
3802 temp = new LocalTemporary (ec, this.Type);
3807 ArrayList args = new ArrayList (1);
3808 args.Add (new Argument (new EmptyAddressOf (), Argument.AType.Expression));
3810 Invocation.EmitCall (ec, IsBase, IsStatic, new EmptyAddressOf (), setter, args, loc);
3818 /// Fully resolved expression that evaluates to an Event
3820 public class EventExpr : MemberExpr {
3821 public readonly EventInfo EventInfo;
3824 MethodInfo add_accessor, remove_accessor;
3826 public EventExpr (EventInfo ei, Location loc)
3830 eclass = ExprClass.EventAccess;
3832 add_accessor = TypeManager.GetAddMethod (ei);
3833 remove_accessor = TypeManager.GetRemoveMethod (ei);
3835 if (add_accessor.IsStatic || remove_accessor.IsStatic)
3838 if (EventInfo is MyEventBuilder){
3839 MyEventBuilder eb = (MyEventBuilder) EventInfo;
3840 type = eb.EventType;
3843 type = EventInfo.EventHandlerType;
3846 public override string Name {
3848 return EventInfo.Name;
3852 public override bool IsInstance {
3858 public override bool IsStatic {
3864 public override Type DeclaringType {
3866 return EventInfo.DeclaringType;
3870 public override Expression ResolveMemberAccess (EmitContext ec, Expression left, Location loc,
3871 SimpleName original)
3874 // If the event is local to this class, we transform ourselves into a FieldExpr
3877 if (EventInfo.DeclaringType == ec.ContainerType ||
3878 TypeManager.IsNestedChildOf(ec.ContainerType, EventInfo.DeclaringType)) {
3879 MemberInfo mi = TypeManager.GetPrivateFieldOfEvent (EventInfo);
3882 MemberExpr ml = (MemberExpr) ExprClassFromMemberInfo (ec, mi, loc);
3885 Report.Error (-200, loc, "Internal error!!");
3889 InstanceExpression = null;
3891 return ml.ResolveMemberAccess (ec, left, loc, original);
3895 return base.ResolveMemberAccess (ec, left, loc, original);
3899 bool InstanceResolve (EmitContext ec, bool must_do_cs1540_check)
3901 if ((InstanceExpression == null) && ec.IsStatic && !is_static) {
3902 SimpleName.Error_ObjectRefRequired (ec, loc, EventInfo.Name);
3906 if (!IsInstance || InstanceExpression == EmptyExpression.Null)
3907 InstanceExpression = null;
3909 if (InstanceExpression != null) {
3910 InstanceExpression = InstanceExpression.DoResolve (ec);
3911 if (InstanceExpression == null)
3916 // This is using the same mechanism as the CS1540 check in PropertyExpr.
3917 // However, in the Event case, we reported a CS0122 instead.
3919 if (must_do_cs1540_check && (InstanceExpression != null)) {
3920 if ((InstanceExpression.Type != ec.ContainerType) &&
3921 ec.ContainerType.IsSubclassOf (InstanceExpression.Type)) {
3922 Report.Error (122, loc, "'{0}' is inaccessible due to its protection level",
3923 DeclaringType.Name + "." + EventInfo.Name);
3932 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
3934 return DoResolve (ec);
3937 public override Expression DoResolve (EmitContext ec)
3940 InstanceExpression = null;
3942 if (InstanceExpression != null) {
3943 InstanceExpression = InstanceExpression.DoResolve (ec);
3944 if (InstanceExpression == null)
3948 bool must_do_cs1540_check;
3949 if (!(IsAccessorAccessible (ec.ContainerType, add_accessor, out must_do_cs1540_check) &&
3950 IsAccessorAccessible (ec.ContainerType, remove_accessor, out must_do_cs1540_check))) {
3952 Report.Error (122, loc, "'{0}' is inaccessible due to its protection level",
3953 DeclaringType.Name + "." + EventInfo.Name);
3957 if (!InstanceResolve (ec, must_do_cs1540_check))
3963 public override void Emit (EmitContext ec)
3965 if (InstanceExpression is This)
3966 Report.Error (79, loc, "The event `{0}' can only appear on the left hand side of += or -=, try calling the actual delegate", Name);
3968 Report.Error (70, loc, "The event `{0}' can only appear on the left hand side of += or -= "+
3969 "(except on the defining type)", Name);
3972 public void EmitAddOrRemove (EmitContext ec, Expression source)
3974 BinaryDelegate source_del = (BinaryDelegate) source;
3975 Expression handler = source_del.Right;
3977 Argument arg = new Argument (handler, Argument.AType.Expression);
3978 ArrayList args = new ArrayList ();
3982 if (source_del.IsAddition)
3983 Invocation.EmitCall (
3984 ec, false, IsStatic, InstanceExpression, add_accessor, args, loc);
3986 Invocation.EmitCall (
3987 ec, false, IsStatic, InstanceExpression, remove_accessor, args, loc);