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) && !ec.ResolvingTypeTree && !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 if (ec.ResolvingTypeTree)
624 return MemberLookup (ec, ec.ContainerType, qualifier_type,
625 queried_type, name, MemberTypes.NestedType,
626 AllBindingFlags, loc);
628 return MemberLookup (ec, ec.ContainerType, qualifier_type,
629 queried_type, name, AllMemberTypes,
630 AllBindingFlags, loc);
633 public static Expression MethodLookup (EmitContext ec, Type queried_type,
634 string name, Location loc)
636 return MemberLookup (ec, ec.ContainerType, null, queried_type, name,
637 MemberTypes.Method, AllBindingFlags, loc);
641 /// This is a wrapper for MemberLookup that is not used to "probe", but
642 /// to find a final definition. If the final definition is not found, we
643 /// look for private members and display a useful debugging message if we
646 public static Expression MemberLookupFinal (EmitContext ec, Type qualifier_type,
647 Type queried_type, string name,
650 return MemberLookupFinal (ec, qualifier_type, queried_type, name,
651 AllMemberTypes, AllBindingFlags, loc);
654 public static Expression MemberLookupFinal (EmitContext ec, Type qualifier_type,
655 Type queried_type, string name,
656 MemberTypes mt, BindingFlags bf,
661 int errors = Report.Errors;
663 e = MemberLookup (ec, ec.ContainerType, qualifier_type, queried_type,
666 if (e == null && errors == Report.Errors)
667 // No errors were reported by MemberLookup, but there was an error.
668 MemberLookupFailed (ec, qualifier_type, queried_type, name, null, true, loc);
673 public static void MemberLookupFailed (EmitContext ec, Type qualifier_type,
674 Type queried_type, string name,
675 string class_name, bool complain_if_none_found,
678 if (almostMatchedMembers.Count != 0) {
679 if (qualifier_type == null) {
680 foreach (MemberInfo m in almostMatchedMembers)
681 Report.Error (38, loc,
682 "Cannot access non-static member `{0}' via nested type `{1}'",
683 TypeManager.GetFullNameSignature (m),
684 TypeManager.CSharpName (ec.ContainerType));
689 if (qualifier_type != ec.ContainerType) {
690 // Although a derived class can access protected members of
691 // its base class it cannot do so through an instance of the
692 // base class (CS1540). If the qualifier_type is a base of the
693 // ec.ContainerType and the lookup succeeds with the latter one,
694 // then we are in this situation.
695 for (int i = 0; i < almostMatchedMembers.Count; ++i) {
696 MemberInfo m = (MemberInfo) almostMatchedMembers [i];
697 for (int j = 0; j < i; ++j) {
698 if (m == almostMatchedMembers [j]) {
706 Report.SymbolRelatedToPreviousError (m);
707 Report.Error (1540, loc,
708 "Cannot access protected member `{0}' via a qualifier of type `{1}';"
709 + " the qualifier must be of type `{2}' (or derived from it)",
710 TypeManager.GetFullNameSignature (m),
711 TypeManager.CSharpName (qualifier_type),
712 TypeManager.CSharpName (ec.ContainerType));
716 almostMatchedMembers.Clear ();
719 MemberInfo[] mi = TypeManager.MemberLookup (queried_type, null, queried_type,
720 AllMemberTypes, AllBindingFlags |
721 BindingFlags.NonPublic, name, null);
724 if (!complain_if_none_found)
727 if (class_name != null)
728 Report.Error (103, loc, "The name `" + name + "' could not be " +
729 "found in `" + class_name + "'");
732 117, loc, "`" + queried_type + "' does not contain a " +
733 "definition for `" + name + "'");
737 if (TypeManager.MemberLookup (queried_type, null, queried_type,
738 AllMemberTypes, AllBindingFlags |
739 BindingFlags.NonPublic, name, null) == null) {
740 if ((mi.Length == 1) && (mi [0] is Type)) {
741 Type t = (Type) mi [0];
743 Report.Error (305, loc,
744 "Using the generic type `{0}' " +
745 "requires {1} type arguments",
746 TypeManager.GetFullName (t),
747 TypeManager.GetNumberOfTypeArguments (t));
752 if (name == ".ctor" && TypeManager.FindMembers (qualifier_type, MemberTypes.Constructor,
753 BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly, null, null).Count == 0)
755 Report.Error (143, loc, String.Format ("The type '{0}' has no constructors defined", TypeManager.CSharpName (queried_type)));
759 if (qualifier_type != null) {
760 Report.Error (122, loc, "'{0}' is inaccessible due to its protection level", TypeManager.CSharpName (qualifier_type) + "." + name);
762 Report.Error (122, loc, "'{0}' is inaccessible due to its protection level", name);
767 /// Returns an expression that can be used to invoke operator true
768 /// on the expression if it exists.
770 static public Expression GetOperatorTrue (EmitContext ec, Expression e, Location loc)
772 return GetOperatorTrueOrFalse (ec, e, true, loc);
776 /// Returns an expression that can be used to invoke operator false
777 /// on the expression if it exists.
779 static public Expression GetOperatorFalse (EmitContext ec, Expression e, Location loc)
781 return GetOperatorTrueOrFalse (ec, e, false, loc);
784 static Expression GetOperatorTrueOrFalse (EmitContext ec, Expression e, bool is_true, Location loc)
787 Expression operator_group;
789 if (TypeManager.IsNullableType (e.Type))
790 return new Nullable.OperatorTrueOrFalse (e, is_true, loc).Resolve (ec);
792 operator_group = MethodLookup (ec, e.Type, is_true ? "op_True" : "op_False", loc);
793 if (operator_group == null)
796 ArrayList arguments = new ArrayList ();
797 arguments.Add (new Argument (e, Argument.AType.Expression));
798 method = Invocation.OverloadResolve (
799 ec, (MethodGroupExpr) operator_group, arguments, false, loc);
804 return new StaticCallExpr ((MethodInfo) method, arguments, loc);
808 /// Resolves the expression `e' into a boolean expression: either through
809 /// an implicit conversion, or through an `operator true' invocation
811 public static Expression ResolveBoolean (EmitContext ec, Expression e, Location loc)
817 if (e.Type == TypeManager.bool_type)
820 Expression converted = Convert.ImplicitConversion (ec, e, TypeManager.bool_type, Location.Null);
822 if (converted != null)
826 // If no implicit conversion to bool exists, try using `operator true'
828 Expression operator_true = Expression.GetOperatorTrue (ec, e, loc);
829 if (operator_true == null){
830 Report.Error (31, loc, "Can not convert the expression to a boolean");
833 return operator_true;
836 public string ExprClassName ()
839 case ExprClass.Invalid:
841 case ExprClass.Value:
843 case ExprClass.Variable:
845 case ExprClass.Namespace:
849 case ExprClass.MethodGroup:
850 return "method group";
851 case ExprClass.PropertyAccess:
852 return "property access";
853 case ExprClass.EventAccess:
854 return "event access";
855 case ExprClass.IndexerAccess:
856 return "indexer access";
857 case ExprClass.Nothing:
860 throw new Exception ("Should not happen");
864 /// Reports that we were expecting `expr' to be of class `expected'
866 public void Error_UnexpectedKind (string expected, Location loc)
868 Report.Error (118, loc, "Expression denotes a `" + ExprClassName () +
869 "' where a `" + expected + "' was expected");
872 public void Error_UnexpectedKind (ResolveFlags flags, Location loc)
874 ArrayList valid = new ArrayList (10);
876 if ((flags & ResolveFlags.VariableOrValue) != 0) {
877 valid.Add ("variable");
881 if ((flags & ResolveFlags.Type) != 0)
884 if ((flags & ResolveFlags.MethodGroup) != 0)
885 valid.Add ("method group");
887 if (valid.Count == 0)
888 valid.Add ("unknown");
890 StringBuilder sb = new StringBuilder ();
891 for (int i = 0; i < valid.Count; i++) {
894 else if (i == valid.Count)
896 sb.Append (valid [i]);
899 Report.Error (119, loc, "Expression denotes a `" + ExprClassName () + "' where " +
900 "a `" + sb.ToString () + "' was expected");
903 static public void Error_ConstantValueCannotBeConverted (Location l, string val, Type t)
905 Report.Error (31, l, "Constant value `" + val + "' cannot be converted to " +
906 TypeManager.CSharpName (t));
909 public static void UnsafeError (Location loc)
911 Report.Error (214, loc, "Pointers may only be used in an unsafe context");
915 /// Converts the IntConstant, UIntConstant, LongConstant or
916 /// ULongConstant into the integral target_type. Notice
917 /// that we do not return an `Expression' we do return
918 /// a boxed integral type.
920 /// FIXME: Since I added the new constants, we need to
921 /// also support conversions from CharConstant, ByteConstant,
922 /// SByteConstant, UShortConstant, ShortConstant
924 /// This is used by the switch statement, so the domain
925 /// of work is restricted to the literals above, and the
926 /// targets are int32, uint32, char, byte, sbyte, ushort,
927 /// short, uint64 and int64
929 public static object ConvertIntLiteral (Constant c, Type target_type, Location loc)
931 if (!Convert.ImplicitStandardConversionExists (Convert.ConstantEC, c, target_type)){
932 Convert.Error_CannotImplicitConversion (loc, c.Type, target_type);
938 if (c.Type == target_type)
939 return ((Constant) c).GetValue ();
942 // Make into one of the literals we handle, we dont really care
943 // about this value as we will just return a few limited types
945 if (c is EnumConstant)
946 c = ((EnumConstant)c).WidenToCompilerConstant ();
948 if (c is IntConstant){
949 int v = ((IntConstant) c).Value;
951 if (target_type == TypeManager.uint32_type){
954 } else if (target_type == TypeManager.char_type){
955 if (v >= Char.MinValue && v <= Char.MaxValue)
957 } else if (target_type == TypeManager.byte_type){
958 if (v >= Byte.MinValue && v <= Byte.MaxValue)
960 } else if (target_type == TypeManager.sbyte_type){
961 if (v >= SByte.MinValue && v <= SByte.MaxValue)
963 } else if (target_type == TypeManager.short_type){
964 if (v >= Int16.MinValue && v <= UInt16.MaxValue)
966 } else if (target_type == TypeManager.ushort_type){
967 if (v >= UInt16.MinValue && v <= UInt16.MaxValue)
969 } else if (target_type == TypeManager.int64_type)
971 else if (target_type == TypeManager.uint64_type){
977 } else if (c is UIntConstant){
978 uint v = ((UIntConstant) c).Value;
980 if (target_type == TypeManager.int32_type){
981 if (v <= Int32.MaxValue)
983 } else if (target_type == TypeManager.char_type){
984 if (v >= Char.MinValue && v <= Char.MaxValue)
986 } else if (target_type == TypeManager.byte_type){
987 if (v <= Byte.MaxValue)
989 } else if (target_type == TypeManager.sbyte_type){
990 if (v <= SByte.MaxValue)
992 } else if (target_type == TypeManager.short_type){
993 if (v <= UInt16.MaxValue)
995 } else if (target_type == TypeManager.ushort_type){
996 if (v <= UInt16.MaxValue)
998 } else if (target_type == TypeManager.int64_type)
1000 else if (target_type == TypeManager.uint64_type)
1003 } else if (c is LongConstant){
1004 long v = ((LongConstant) c).Value;
1006 if (target_type == TypeManager.int32_type){
1007 if (v >= UInt32.MinValue && v <= UInt32.MaxValue)
1009 } else if (target_type == TypeManager.uint32_type){
1010 if (v >= 0 && v <= UInt32.MaxValue)
1012 } else if (target_type == TypeManager.char_type){
1013 if (v >= Char.MinValue && v <= Char.MaxValue)
1015 } else if (target_type == TypeManager.byte_type){
1016 if (v >= Byte.MinValue && v <= Byte.MaxValue)
1018 } else if (target_type == TypeManager.sbyte_type){
1019 if (v >= SByte.MinValue && v <= SByte.MaxValue)
1021 } else if (target_type == TypeManager.short_type){
1022 if (v >= Int16.MinValue && v <= UInt16.MaxValue)
1024 } else if (target_type == TypeManager.ushort_type){
1025 if (v >= UInt16.MinValue && v <= UInt16.MaxValue)
1027 } else if (target_type == TypeManager.uint64_type){
1032 } else if (c is ULongConstant){
1033 ulong v = ((ULongConstant) c).Value;
1035 if (target_type == TypeManager.int32_type){
1036 if (v <= Int32.MaxValue)
1038 } else if (target_type == TypeManager.uint32_type){
1039 if (v <= UInt32.MaxValue)
1041 } else if (target_type == TypeManager.char_type){
1042 if (v >= Char.MinValue && v <= Char.MaxValue)
1044 } else if (target_type == TypeManager.byte_type){
1045 if (v >= Byte.MinValue && v <= Byte.MaxValue)
1047 } else if (target_type == TypeManager.sbyte_type){
1048 if (v <= (int) SByte.MaxValue)
1050 } else if (target_type == TypeManager.short_type){
1051 if (v <= UInt16.MaxValue)
1053 } else if (target_type == TypeManager.ushort_type){
1054 if (v <= UInt16.MaxValue)
1056 } else if (target_type == TypeManager.int64_type){
1057 if (v <= Int64.MaxValue)
1061 } else if (c is ByteConstant){
1062 byte v = ((ByteConstant) c).Value;
1064 if (target_type == TypeManager.int32_type)
1066 else if (target_type == TypeManager.uint32_type)
1068 else if (target_type == TypeManager.char_type)
1070 else if (target_type == TypeManager.sbyte_type){
1071 if (v <= SByte.MaxValue)
1073 } else if (target_type == TypeManager.short_type)
1075 else if (target_type == TypeManager.ushort_type)
1077 else if (target_type == TypeManager.int64_type)
1079 else if (target_type == TypeManager.uint64_type)
1082 } else if (c is SByteConstant){
1083 sbyte v = ((SByteConstant) c).Value;
1085 if (target_type == TypeManager.int32_type)
1087 else if (target_type == TypeManager.uint32_type){
1090 } else if (target_type == TypeManager.char_type){
1093 } else if (target_type == TypeManager.byte_type){
1096 } else if (target_type == TypeManager.short_type)
1098 else if (target_type == TypeManager.ushort_type){
1101 } else if (target_type == TypeManager.int64_type)
1103 else if (target_type == TypeManager.uint64_type){
1108 } else if (c is ShortConstant){
1109 short v = ((ShortConstant) c).Value;
1111 if (target_type == TypeManager.int32_type){
1113 } else if (target_type == TypeManager.uint32_type){
1116 } else if (target_type == TypeManager.char_type){
1119 } else if (target_type == TypeManager.byte_type){
1120 if (v >= Byte.MinValue && v <= Byte.MaxValue)
1122 } else if (target_type == TypeManager.sbyte_type){
1123 if (v >= SByte.MinValue && v <= SByte.MaxValue)
1125 } else if (target_type == TypeManager.ushort_type){
1128 } else if (target_type == TypeManager.int64_type)
1130 else if (target_type == TypeManager.uint64_type)
1134 } else if (c is UShortConstant){
1135 ushort v = ((UShortConstant) c).Value;
1137 if (target_type == TypeManager.int32_type)
1139 else if (target_type == TypeManager.uint32_type)
1141 else if (target_type == TypeManager.char_type){
1142 if (v >= Char.MinValue && v <= Char.MaxValue)
1144 } else if (target_type == TypeManager.byte_type){
1145 if (v >= Byte.MinValue && v <= Byte.MaxValue)
1147 } else if (target_type == TypeManager.sbyte_type){
1148 if (v <= SByte.MaxValue)
1150 } else if (target_type == TypeManager.short_type){
1151 if (v <= Int16.MaxValue)
1153 } else if (target_type == TypeManager.int64_type)
1155 else if (target_type == TypeManager.uint64_type)
1159 } else if (c is CharConstant){
1160 char v = ((CharConstant) c).Value;
1162 if (target_type == TypeManager.int32_type)
1164 else if (target_type == TypeManager.uint32_type)
1166 else if (target_type == TypeManager.byte_type){
1167 if (v >= Byte.MinValue && v <= Byte.MaxValue)
1169 } else if (target_type == TypeManager.sbyte_type){
1170 if (v <= SByte.MaxValue)
1172 } else if (target_type == TypeManager.short_type){
1173 if (v <= Int16.MaxValue)
1175 } else if (target_type == TypeManager.ushort_type)
1177 else if (target_type == TypeManager.int64_type)
1179 else if (target_type == TypeManager.uint64_type)
1184 Error_ConstantValueCannotBeConverted (loc, s, target_type);
1189 // Load the object from the pointer.
1191 public static void LoadFromPtr (ILGenerator ig, Type t)
1193 if (t == TypeManager.int32_type)
1194 ig.Emit (OpCodes.Ldind_I4);
1195 else if (t == TypeManager.uint32_type)
1196 ig.Emit (OpCodes.Ldind_U4);
1197 else if (t == TypeManager.short_type)
1198 ig.Emit (OpCodes.Ldind_I2);
1199 else if (t == TypeManager.ushort_type)
1200 ig.Emit (OpCodes.Ldind_U2);
1201 else if (t == TypeManager.char_type)
1202 ig.Emit (OpCodes.Ldind_U2);
1203 else if (t == TypeManager.byte_type)
1204 ig.Emit (OpCodes.Ldind_U1);
1205 else if (t == TypeManager.sbyte_type)
1206 ig.Emit (OpCodes.Ldind_I1);
1207 else if (t == TypeManager.uint64_type)
1208 ig.Emit (OpCodes.Ldind_I8);
1209 else if (t == TypeManager.int64_type)
1210 ig.Emit (OpCodes.Ldind_I8);
1211 else if (t == TypeManager.float_type)
1212 ig.Emit (OpCodes.Ldind_R4);
1213 else if (t == TypeManager.double_type)
1214 ig.Emit (OpCodes.Ldind_R8);
1215 else if (t == TypeManager.bool_type)
1216 ig.Emit (OpCodes.Ldind_I1);
1217 else if (t == TypeManager.intptr_type)
1218 ig.Emit (OpCodes.Ldind_I);
1219 else if (TypeManager.IsEnumType (t)) {
1220 if (t == TypeManager.enum_type)
1221 ig.Emit (OpCodes.Ldind_Ref);
1223 LoadFromPtr (ig, TypeManager.EnumToUnderlying (t));
1224 } else if (t.IsValueType || t.IsGenericParameter)
1225 ig.Emit (OpCodes.Ldobj, t);
1226 else if (t.IsPointer)
1227 ig.Emit (OpCodes.Ldind_I);
1229 ig.Emit (OpCodes.Ldind_Ref);
1233 // The stack contains the pointer and the value of type `type'
1235 public static void StoreFromPtr (ILGenerator ig, Type type)
1237 if (TypeManager.IsEnumType (type))
1238 type = TypeManager.EnumToUnderlying (type);
1239 if (type == TypeManager.int32_type || type == TypeManager.uint32_type)
1240 ig.Emit (OpCodes.Stind_I4);
1241 else if (type == TypeManager.int64_type || type == TypeManager.uint64_type)
1242 ig.Emit (OpCodes.Stind_I8);
1243 else if (type == TypeManager.char_type || type == TypeManager.short_type ||
1244 type == TypeManager.ushort_type)
1245 ig.Emit (OpCodes.Stind_I2);
1246 else if (type == TypeManager.float_type)
1247 ig.Emit (OpCodes.Stind_R4);
1248 else if (type == TypeManager.double_type)
1249 ig.Emit (OpCodes.Stind_R8);
1250 else if (type == TypeManager.byte_type || type == TypeManager.sbyte_type ||
1251 type == TypeManager.bool_type)
1252 ig.Emit (OpCodes.Stind_I1);
1253 else if (type == TypeManager.intptr_type)
1254 ig.Emit (OpCodes.Stind_I);
1255 else if (type.IsValueType || type.IsGenericParameter)
1256 ig.Emit (OpCodes.Stobj, type);
1258 ig.Emit (OpCodes.Stind_Ref);
1262 // Returns the size of type `t' if known, otherwise, 0
1264 public static int GetTypeSize (Type t)
1266 t = TypeManager.TypeToCoreType (t);
1267 if (t == TypeManager.int32_type ||
1268 t == TypeManager.uint32_type ||
1269 t == TypeManager.float_type)
1271 else if (t == TypeManager.int64_type ||
1272 t == TypeManager.uint64_type ||
1273 t == TypeManager.double_type)
1275 else if (t == TypeManager.byte_type ||
1276 t == TypeManager.sbyte_type ||
1277 t == TypeManager.bool_type)
1279 else if (t == TypeManager.short_type ||
1280 t == TypeManager.char_type ||
1281 t == TypeManager.ushort_type)
1283 else if (t == TypeManager.decimal_type)
1289 public static void Error_NegativeArrayIndex (Location loc)
1291 Report.Error (248, loc, "Cannot create an array with a negative size");
1295 // Converts `source' to an int, uint, long or ulong.
1297 public Expression ExpressionToArrayArgument (EmitContext ec, Expression source, Location loc)
1301 bool old_checked = ec.CheckState;
1302 ec.CheckState = true;
1304 target = Convert.ImplicitConversion (ec, source, TypeManager.int32_type, loc);
1305 if (target == null){
1306 target = Convert.ImplicitConversion (ec, source, TypeManager.uint32_type, loc);
1307 if (target == null){
1308 target = Convert.ImplicitConversion (ec, source, TypeManager.int64_type, loc);
1309 if (target == null){
1310 target = Convert.ImplicitConversion (ec, source, TypeManager.uint64_type, loc);
1312 Convert.Error_CannotImplicitConversion (loc, source.Type, TypeManager.int32_type);
1316 ec.CheckState = old_checked;
1319 // Only positive constants are allowed at compile time
1321 if (target is Constant){
1322 if (target is IntConstant){
1323 if (((IntConstant) target).Value < 0){
1324 Error_NegativeArrayIndex (loc);
1329 if (target is LongConstant){
1330 if (((LongConstant) target).Value < 0){
1331 Error_NegativeArrayIndex (loc);
1344 /// This is just a base class for expressions that can
1345 /// appear on statements (invocations, object creation,
1346 /// assignments, post/pre increment and decrement). The idea
1347 /// being that they would support an extra Emition interface that
1348 /// does not leave a result on the stack.
1350 public abstract class ExpressionStatement : Expression {
1352 public virtual ExpressionStatement ResolveStatement (EmitContext ec)
1354 Expression e = Resolve (ec);
1358 ExpressionStatement es = e as ExpressionStatement;
1360 Error (201, "Only assignment, call, increment, decrement and new object " +
1361 "expressions can be used as a statement");
1367 /// Requests the expression to be emitted in a `statement'
1368 /// context. This means that no new value is left on the
1369 /// stack after invoking this method (constrasted with
1370 /// Emit that will always leave a value on the stack).
1372 public abstract void EmitStatement (EmitContext ec);
1376 /// This kind of cast is used to encapsulate the child
1377 /// whose type is child.Type into an expression that is
1378 /// reported to return "return_type". This is used to encapsulate
1379 /// expressions which have compatible types, but need to be dealt
1380 /// at higher levels with.
1382 /// For example, a "byte" expression could be encapsulated in one
1383 /// of these as an "unsigned int". The type for the expression
1384 /// would be "unsigned int".
1387 public class EmptyCast : Expression {
1388 protected Expression child;
1390 public Expression Child {
1396 public EmptyCast (Expression child, Type return_type)
1398 eclass = child.eclass;
1399 loc = child.Location;
1404 public override Expression DoResolve (EmitContext ec)
1406 // This should never be invoked, we are born in fully
1407 // initialized state.
1412 public override void Emit (EmitContext ec)
1419 // We need to special case this since an empty cast of
1420 // a NullLiteral is still a Constant
1422 public class NullCast : Constant {
1423 protected Expression child;
1425 public NullCast (Expression child, Type return_type)
1427 eclass = child.eclass;
1432 override public string AsString ()
1437 public override object GetValue ()
1442 public override Expression DoResolve (EmitContext ec)
1444 // This should never be invoked, we are born in fully
1445 // initialized state.
1450 public override void Emit (EmitContext ec)
1455 public override bool IsDefaultValue {
1457 throw new NotImplementedException ();
1461 public override bool IsNegative {
1470 /// This class is used to wrap literals which belong inside Enums
1472 public class EnumConstant : Constant {
1473 public Constant Child;
1475 public EnumConstant (Constant child, Type enum_type)
1477 eclass = child.eclass;
1482 public override Expression DoResolve (EmitContext ec)
1484 // This should never be invoked, we are born in fully
1485 // initialized state.
1490 public override void Emit (EmitContext ec)
1495 public override object GetValue ()
1497 return Child.GetValue ();
1500 public object GetValueAsEnumType ()
1502 return System.Enum.ToObject (type, Child.GetValue ());
1506 // Converts from one of the valid underlying types for an enumeration
1507 // (int32, uint32, int64, uint64, short, ushort, byte, sbyte) to
1508 // one of the internal compiler literals: Int/UInt/Long/ULong Literals.
1510 public Constant WidenToCompilerConstant ()
1512 Type t = TypeManager.EnumToUnderlying (Child.Type);
1513 object v = ((Constant) Child).GetValue ();;
1515 if (t == TypeManager.int32_type)
1516 return new IntConstant ((int) v);
1517 if (t == TypeManager.uint32_type)
1518 return new UIntConstant ((uint) v);
1519 if (t == TypeManager.int64_type)
1520 return new LongConstant ((long) v);
1521 if (t == TypeManager.uint64_type)
1522 return new ULongConstant ((ulong) v);
1523 if (t == TypeManager.short_type)
1524 return new ShortConstant ((short) v);
1525 if (t == TypeManager.ushort_type)
1526 return new UShortConstant ((ushort) v);
1527 if (t == TypeManager.byte_type)
1528 return new ByteConstant ((byte) v);
1529 if (t == TypeManager.sbyte_type)
1530 return new SByteConstant ((sbyte) v);
1532 throw new Exception ("Invalid enumeration underlying type: " + t);
1536 // Extracts the value in the enumeration on its native representation
1538 public object GetPlainValue ()
1540 Type t = TypeManager.EnumToUnderlying (Child.Type);
1541 object v = ((Constant) Child).GetValue ();;
1543 if (t == TypeManager.int32_type)
1545 if (t == TypeManager.uint32_type)
1547 if (t == TypeManager.int64_type)
1549 if (t == TypeManager.uint64_type)
1551 if (t == TypeManager.short_type)
1553 if (t == TypeManager.ushort_type)
1555 if (t == TypeManager.byte_type)
1557 if (t == TypeManager.sbyte_type)
1563 public override string AsString ()
1565 return Child.AsString ();
1568 public override DoubleConstant ConvertToDouble ()
1570 return Child.ConvertToDouble ();
1573 public override FloatConstant ConvertToFloat ()
1575 return Child.ConvertToFloat ();
1578 public override ULongConstant ConvertToULong ()
1580 return Child.ConvertToULong ();
1583 public override LongConstant ConvertToLong ()
1585 return Child.ConvertToLong ();
1588 public override UIntConstant ConvertToUInt ()
1590 return Child.ConvertToUInt ();
1593 public override IntConstant ConvertToInt ()
1595 return Child.ConvertToInt ();
1598 public override bool IsDefaultValue {
1600 return Child.IsDefaultValue;
1604 public override bool IsZeroInteger {
1605 get { return Child.IsZeroInteger; }
1608 public override bool IsNegative {
1610 return Child.IsNegative;
1616 /// This kind of cast is used to encapsulate Value Types in objects.
1618 /// The effect of it is to box the value type emitted by the previous
1621 public class BoxedCast : EmptyCast {
1623 public BoxedCast (Expression expr)
1624 : base (expr, TypeManager.object_type)
1626 eclass = ExprClass.Value;
1629 public BoxedCast (Expression expr, Type target_type)
1630 : base (expr, target_type)
1632 eclass = ExprClass.Value;
1635 public override Expression DoResolve (EmitContext ec)
1637 // This should never be invoked, we are born in fully
1638 // initialized state.
1643 public override void Emit (EmitContext ec)
1647 ec.ig.Emit (OpCodes.Box, child.Type);
1651 public class UnboxCast : EmptyCast {
1652 public UnboxCast (Expression expr, Type return_type)
1653 : base (expr, return_type)
1657 public override Expression DoResolve (EmitContext ec)
1659 // This should never be invoked, we are born in fully
1660 // initialized state.
1665 public override void Emit (EmitContext ec)
1668 ILGenerator ig = ec.ig;
1671 if (t.IsGenericParameter)
1672 ig.Emit (OpCodes.Unbox_Any, t);
1674 ig.Emit (OpCodes.Unbox, t);
1676 LoadFromPtr (ig, t);
1682 /// This is used to perform explicit numeric conversions.
1684 /// Explicit numeric conversions might trigger exceptions in a checked
1685 /// context, so they should generate the conv.ovf opcodes instead of
1688 public class ConvCast : EmptyCast {
1689 public enum Mode : byte {
1690 I1_U1, I1_U2, I1_U4, I1_U8, I1_CH,
1692 I2_I1, I2_U1, I2_U2, I2_U4, I2_U8, I2_CH,
1693 U2_I1, U2_U1, U2_I2, U2_CH,
1694 I4_I1, I4_U1, I4_I2, I4_U2, I4_U4, I4_U8, I4_CH,
1695 U4_I1, U4_U1, U4_I2, U4_U2, U4_I4, U4_CH,
1696 I8_I1, I8_U1, I8_I2, I8_U2, I8_I4, I8_U4, I8_U8, I8_CH,
1697 U8_I1, U8_U1, U8_I2, U8_U2, U8_I4, U8_U4, U8_I8, U8_CH,
1698 CH_I1, CH_U1, CH_I2,
1699 R4_I1, R4_U1, R4_I2, R4_U2, R4_I4, R4_U4, R4_I8, R4_U8, R4_CH,
1700 R8_I1, R8_U1, R8_I2, R8_U2, R8_I4, R8_U4, R8_I8, R8_U8, R8_CH, R8_R4
1706 public ConvCast (EmitContext ec, Expression child, Type return_type, Mode m)
1707 : base (child, return_type)
1709 checked_state = ec.CheckState;
1713 public override Expression DoResolve (EmitContext ec)
1715 // This should never be invoked, we are born in fully
1716 // initialized state.
1721 public override string ToString ()
1723 return String.Format ("ConvCast ({0}, {1})", mode, child);
1726 public override void Emit (EmitContext ec)
1728 ILGenerator ig = ec.ig;
1734 case Mode.I1_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1735 case Mode.I1_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1736 case Mode.I1_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1737 case Mode.I1_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1738 case Mode.I1_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1740 case Mode.U1_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1741 case Mode.U1_CH: /* nothing */ break;
1743 case Mode.I2_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1744 case Mode.I2_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1745 case Mode.I2_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1746 case Mode.I2_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1747 case Mode.I2_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1748 case Mode.I2_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1750 case Mode.U2_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1751 case Mode.U2_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
1752 case Mode.U2_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
1753 case Mode.U2_CH: /* nothing */ break;
1755 case Mode.I4_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1756 case Mode.I4_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1757 case Mode.I4_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
1758 case Mode.I4_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1759 case Mode.I4_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1760 case Mode.I4_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1761 case Mode.I4_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1763 case Mode.U4_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1764 case Mode.U4_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
1765 case Mode.U4_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
1766 case Mode.U4_U2: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
1767 case Mode.U4_I4: ig.Emit (OpCodes.Conv_Ovf_I4_Un); break;
1768 case Mode.U4_CH: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
1770 case Mode.I8_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1771 case Mode.I8_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1772 case Mode.I8_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
1773 case Mode.I8_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1774 case Mode.I8_I4: ig.Emit (OpCodes.Conv_Ovf_I4); break;
1775 case Mode.I8_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1776 case Mode.I8_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1777 case Mode.I8_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1779 case Mode.U8_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1780 case Mode.U8_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
1781 case Mode.U8_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
1782 case Mode.U8_U2: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
1783 case Mode.U8_I4: ig.Emit (OpCodes.Conv_Ovf_I4_Un); break;
1784 case Mode.U8_U4: ig.Emit (OpCodes.Conv_Ovf_U4_Un); break;
1785 case Mode.U8_I8: ig.Emit (OpCodes.Conv_Ovf_I8_Un); break;
1786 case Mode.U8_CH: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
1788 case Mode.CH_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1789 case Mode.CH_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
1790 case Mode.CH_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
1792 case Mode.R4_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1793 case Mode.R4_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1794 case Mode.R4_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
1795 case Mode.R4_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1796 case Mode.R4_I4: ig.Emit (OpCodes.Conv_Ovf_I4); break;
1797 case Mode.R4_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1798 case Mode.R4_I8: ig.Emit (OpCodes.Conv_Ovf_I8); break;
1799 case Mode.R4_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1800 case Mode.R4_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1802 case Mode.R8_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1803 case Mode.R8_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1804 case Mode.R8_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
1805 case Mode.R8_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1806 case Mode.R8_I4: ig.Emit (OpCodes.Conv_Ovf_I4); break;
1807 case Mode.R8_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1808 case Mode.R8_I8: ig.Emit (OpCodes.Conv_Ovf_I8); break;
1809 case Mode.R8_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1810 case Mode.R8_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1811 case Mode.R8_R4: ig.Emit (OpCodes.Conv_R4); break;
1815 case Mode.I1_U1: ig.Emit (OpCodes.Conv_U1); break;
1816 case Mode.I1_U2: ig.Emit (OpCodes.Conv_U2); break;
1817 case Mode.I1_U4: ig.Emit (OpCodes.Conv_U4); break;
1818 case Mode.I1_U8: ig.Emit (OpCodes.Conv_I8); break;
1819 case Mode.I1_CH: ig.Emit (OpCodes.Conv_U2); break;
1821 case Mode.U1_I1: ig.Emit (OpCodes.Conv_I1); break;
1822 case Mode.U1_CH: ig.Emit (OpCodes.Conv_U2); break;
1824 case Mode.I2_I1: ig.Emit (OpCodes.Conv_I1); break;
1825 case Mode.I2_U1: ig.Emit (OpCodes.Conv_U1); break;
1826 case Mode.I2_U2: ig.Emit (OpCodes.Conv_U2); break;
1827 case Mode.I2_U4: ig.Emit (OpCodes.Conv_U4); break;
1828 case Mode.I2_U8: ig.Emit (OpCodes.Conv_I8); break;
1829 case Mode.I2_CH: ig.Emit (OpCodes.Conv_U2); break;
1831 case Mode.U2_I1: ig.Emit (OpCodes.Conv_I1); break;
1832 case Mode.U2_U1: ig.Emit (OpCodes.Conv_U1); break;
1833 case Mode.U2_I2: ig.Emit (OpCodes.Conv_I2); break;
1834 case Mode.U2_CH: /* nothing */ break;
1836 case Mode.I4_I1: ig.Emit (OpCodes.Conv_I1); break;
1837 case Mode.I4_U1: ig.Emit (OpCodes.Conv_U1); break;
1838 case Mode.I4_I2: ig.Emit (OpCodes.Conv_I2); break;
1839 case Mode.I4_U4: /* nothing */ break;
1840 case Mode.I4_U2: ig.Emit (OpCodes.Conv_U2); break;
1841 case Mode.I4_U8: ig.Emit (OpCodes.Conv_I8); break;
1842 case Mode.I4_CH: ig.Emit (OpCodes.Conv_U2); break;
1844 case Mode.U4_I1: ig.Emit (OpCodes.Conv_I1); break;
1845 case Mode.U4_U1: ig.Emit (OpCodes.Conv_U1); break;
1846 case Mode.U4_I2: ig.Emit (OpCodes.Conv_I2); break;
1847 case Mode.U4_U2: ig.Emit (OpCodes.Conv_U2); break;
1848 case Mode.U4_I4: /* nothing */ break;
1849 case Mode.U4_CH: ig.Emit (OpCodes.Conv_U2); break;
1851 case Mode.I8_I1: ig.Emit (OpCodes.Conv_I1); break;
1852 case Mode.I8_U1: ig.Emit (OpCodes.Conv_U1); break;
1853 case Mode.I8_I2: ig.Emit (OpCodes.Conv_I2); break;
1854 case Mode.I8_U2: ig.Emit (OpCodes.Conv_U2); break;
1855 case Mode.I8_I4: ig.Emit (OpCodes.Conv_I4); break;
1856 case Mode.I8_U4: ig.Emit (OpCodes.Conv_U4); break;
1857 case Mode.I8_U8: /* nothing */ break;
1858 case Mode.I8_CH: ig.Emit (OpCodes.Conv_U2); break;
1860 case Mode.U8_I1: ig.Emit (OpCodes.Conv_I1); break;
1861 case Mode.U8_U1: ig.Emit (OpCodes.Conv_U1); break;
1862 case Mode.U8_I2: ig.Emit (OpCodes.Conv_I2); break;
1863 case Mode.U8_U2: ig.Emit (OpCodes.Conv_U2); break;
1864 case Mode.U8_I4: ig.Emit (OpCodes.Conv_I4); break;
1865 case Mode.U8_U4: ig.Emit (OpCodes.Conv_U4); break;
1866 case Mode.U8_I8: /* nothing */ break;
1867 case Mode.U8_CH: ig.Emit (OpCodes.Conv_U2); break;
1869 case Mode.CH_I1: ig.Emit (OpCodes.Conv_I1); break;
1870 case Mode.CH_U1: ig.Emit (OpCodes.Conv_U1); break;
1871 case Mode.CH_I2: ig.Emit (OpCodes.Conv_I2); break;
1873 case Mode.R4_I1: ig.Emit (OpCodes.Conv_I1); break;
1874 case Mode.R4_U1: ig.Emit (OpCodes.Conv_U1); break;
1875 case Mode.R4_I2: ig.Emit (OpCodes.Conv_I2); break;
1876 case Mode.R4_U2: ig.Emit (OpCodes.Conv_U2); break;
1877 case Mode.R4_I4: ig.Emit (OpCodes.Conv_I4); break;
1878 case Mode.R4_U4: ig.Emit (OpCodes.Conv_U4); break;
1879 case Mode.R4_I8: ig.Emit (OpCodes.Conv_I8); break;
1880 case Mode.R4_U8: ig.Emit (OpCodes.Conv_U8); break;
1881 case Mode.R4_CH: ig.Emit (OpCodes.Conv_U2); break;
1883 case Mode.R8_I1: ig.Emit (OpCodes.Conv_I1); break;
1884 case Mode.R8_U1: ig.Emit (OpCodes.Conv_U1); break;
1885 case Mode.R8_I2: ig.Emit (OpCodes.Conv_I2); break;
1886 case Mode.R8_U2: ig.Emit (OpCodes.Conv_U2); break;
1887 case Mode.R8_I4: ig.Emit (OpCodes.Conv_I4); break;
1888 case Mode.R8_U4: ig.Emit (OpCodes.Conv_U4); break;
1889 case Mode.R8_I8: ig.Emit (OpCodes.Conv_I8); break;
1890 case Mode.R8_U8: ig.Emit (OpCodes.Conv_U8); break;
1891 case Mode.R8_CH: ig.Emit (OpCodes.Conv_U2); break;
1892 case Mode.R8_R4: ig.Emit (OpCodes.Conv_R4); break;
1898 public class OpcodeCast : EmptyCast {
1902 public OpcodeCast (Expression child, Type return_type, OpCode op)
1903 : base (child, return_type)
1907 second_valid = false;
1910 public OpcodeCast (Expression child, Type return_type, OpCode op, OpCode op2)
1911 : base (child, return_type)
1916 second_valid = true;
1919 public override Expression DoResolve (EmitContext ec)
1921 // This should never be invoked, we are born in fully
1922 // initialized state.
1927 public override void Emit (EmitContext ec)
1938 /// This kind of cast is used to encapsulate a child and cast it
1939 /// to the class requested
1941 public class ClassCast : EmptyCast {
1942 public ClassCast (Expression child, Type return_type)
1943 : base (child, return_type)
1948 public override Expression DoResolve (EmitContext ec)
1950 // This should never be invoked, we are born in fully
1951 // initialized state.
1956 public override void Emit (EmitContext ec)
1960 if (child.Type.IsGenericParameter)
1961 ec.ig.Emit (OpCodes.Box, child.Type);
1963 if (type.IsGenericParameter)
1964 ec.ig.Emit (OpCodes.Unbox_Any, type);
1966 ec.ig.Emit (OpCodes.Castclass, type);
1971 /// SimpleName expressions are formed of a single word and only happen at the beginning
1972 /// of a dotted-name.
1974 public class SimpleName : Expression {
1976 public readonly TypeArguments Arguments;
1979 public SimpleName (string name, Location l)
1985 public SimpleName (string name, TypeArguments args, Location l)
1992 public SimpleName (string name, TypeParameter[] type_params, Location l)
1997 Arguments = new TypeArguments (l);
1998 foreach (TypeParameter type_param in type_params)
1999 Arguments.Add (new TypeParameterExpr (type_param, l));
2002 public static string RemoveGenericArity (string name)
2005 StringBuilder sb = new StringBuilder ();
2006 while (start < name.Length) {
2007 int pos = name.IndexOf ('`', start);
2009 sb.Append (name.Substring (start));
2013 sb.Append (name.Substring (start, pos-start));
2016 while ((pos < name.Length) && Char.IsNumber (name [pos]))
2022 return sb.ToString ();
2025 public SimpleName GetMethodGroup ()
2027 return new SimpleName (RemoveGenericArity (Name), Arguments, loc);
2030 public static void Error_ObjectRefRequired (EmitContext ec, Location l, string name)
2032 if (ec.IsFieldInitializer)
2035 "A field initializer cannot reference the non-static field, " +
2036 "method or property `"+name+"'");
2040 "An object reference is required " +
2041 "for the non-static field `"+name+"'");
2044 public bool IdenticalNameAndTypeName (EmitContext ec, Expression resolved_to, Location loc)
2046 return resolved_to != null && resolved_to.Type != null &&
2047 resolved_to.Type.Name == Name &&
2048 (ec.DeclSpace.LookupType (Name, loc, /* ignore_cs0104 = */ true) != null);
2051 public override Expression DoResolve (EmitContext ec)
2053 return SimpleNameResolve (ec, null, false);
2056 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
2058 return SimpleNameResolve (ec, right_side, false);
2062 public Expression DoResolve (EmitContext ec, bool intermediate)
2064 return SimpleNameResolve (ec, null, intermediate);
2067 private bool IsNestedChild (Type t, Type parent)
2072 while (parent != null) {
2073 if (parent.IsGenericInstance)
2074 parent = parent.GetGenericTypeDefinition ();
2076 if (TypeManager.IsNestedChildOf (t, parent))
2079 parent = parent.BaseType;
2085 FullNamedExpression ResolveNested (EmitContext ec, Type t)
2087 if (!t.IsGenericTypeDefinition)
2090 DeclSpace ds = ec.DeclSpace;
2091 while (ds != null) {
2092 if (IsNestedChild (t, ds.TypeBuilder))
2101 Type[] gen_params = t.GetGenericArguments ();
2103 int arg_count = Arguments != null ? Arguments.Count : 0;
2105 for (; (ds != null) && ds.IsGeneric; ds = ds.Parent) {
2106 if (arg_count + ds.CountTypeParameters == gen_params.Length) {
2107 TypeArguments new_args = new TypeArguments (loc);
2108 foreach (TypeParameter param in ds.TypeParameters)
2109 new_args.Add (new TypeParameterExpr (param, loc));
2111 if (Arguments != null)
2112 new_args.Add (Arguments);
2114 return new ConstructedType (t, new_args, loc);
2121 public override FullNamedExpression ResolveAsTypeStep (EmitContext ec)
2123 FullNamedExpression dt = ec.DeclSpace.LookupGeneric (Name, loc);
2125 return dt.ResolveAsTypeStep (ec);
2127 int errors = Report.Errors;
2128 dt = ec.DeclSpace.LookupType (Name, loc, /*ignore_cs0104=*/ false);
2129 if (Report.Errors != errors)
2132 if ((dt == null) || (dt.Type == null))
2135 FullNamedExpression nested = ResolveNested (ec, dt.Type);
2137 return nested.ResolveAsTypeStep (ec);
2139 if (Arguments != null) {
2140 ConstructedType ct = new ConstructedType (dt, Arguments, loc);
2141 return ct.ResolveAsTypeStep (ec);
2147 Expression SimpleNameResolve (EmitContext ec, Expression right_side, bool intermediate)
2153 Expression e = DoSimpleNameResolve (ec, right_side, intermediate);
2157 if (ec.CurrentBlock == null || ec.CurrentBlock.CheckInvariantMeaningInBlock (Name, e, Location))
2164 /// 7.5.2: Simple Names.
2166 /// Local Variables and Parameters are handled at
2167 /// parse time, so they never occur as SimpleNames.
2169 /// The `intermediate' flag is used by MemberAccess only
2170 /// and it is used to inform us that it is ok for us to
2171 /// avoid the static check, because MemberAccess might end
2172 /// up resolving the Name as a Type name and the access as
2173 /// a static type access.
2175 /// ie: Type Type; .... { Type.GetType (""); }
2177 /// Type is both an instance variable and a Type; Type.GetType
2178 /// is the static method not an instance method of type.
2180 Expression DoSimpleNameResolve (EmitContext ec, Expression right_side, bool intermediate)
2182 Expression e = null;
2185 // Stage 1: Performed by the parser (binding to locals or parameters).
2187 Block current_block = ec.CurrentBlock;
2188 if (current_block != null){
2189 LocalInfo vi = current_block.GetLocalInfo (Name);
2193 var = new LocalVariableReference (ec.CurrentBlock, Name, loc);
2195 if (right_side != null)
2196 return var.ResolveLValue (ec, right_side);
2198 return var.Resolve (ec);
2201 ParameterReference pref = current_block.GetParameterReference (Name, loc);
2203 if (right_side != null)
2204 return pref.ResolveLValue (ec, right_side);
2206 return pref.Resolve (ec);
2211 // Stage 2: Lookup members
2214 DeclSpace lookup_ds = ec.DeclSpace;
2215 Type almost_matched_type = null;
2216 ArrayList almost_matched = null;
2218 if (lookup_ds.TypeBuilder == null)
2221 e = MemberLookup (ec, lookup_ds.TypeBuilder, Name, loc);
2225 if (almost_matched == null && almostMatchedMembers.Count > 0) {
2226 almost_matched_type = lookup_ds.TypeBuilder;
2227 almost_matched = (ArrayList) almostMatchedMembers.Clone ();
2230 lookup_ds =lookup_ds.Parent;
2231 } while (lookup_ds != null);
2233 if (e == null && ec.ContainerType != null)
2234 e = MemberLookup (ec, ec.ContainerType, Name, loc);
2237 if (almost_matched == null && almostMatchedMembers.Count > 0) {
2238 almost_matched_type = ec.ContainerType;
2239 almost_matched = (ArrayList) almostMatchedMembers.Clone ();
2241 e = ResolveAsTypeStep (ec);
2245 if (almost_matched != null)
2246 almostMatchedMembers = almost_matched;
2247 if (almost_matched_type == null)
2248 almost_matched_type = ec.ContainerType;
2249 MemberLookupFailed (ec, null, almost_matched_type, ((SimpleName) this).Name, ec.DeclSpace.Name, true, loc);
2256 if (e is MemberExpr) {
2257 MemberExpr me = (MemberExpr) e;
2260 if (me.IsInstance) {
2261 if (ec.IsStatic || ec.IsFieldInitializer) {
2263 // Note that an MemberExpr can be both IsInstance and IsStatic.
2264 // An unresolved MethodGroupExpr can contain both kinds of methods
2265 // and each predicate is true if the MethodGroupExpr contains
2266 // at least one of that kind of method.
2270 (!intermediate || !IdenticalNameAndTypeName (ec, me, loc))) {
2271 Error_ObjectRefRequired (ec, loc, Name);
2276 // Pass the buck to MemberAccess and Invocation.
2278 left = EmptyExpression.Null;
2280 left = ec.GetThis (loc);
2283 left = new TypeExpression (ec.ContainerType, loc);
2286 e = me.ResolveMemberAccess (ec, left, loc, null);
2290 me = e as MemberExpr;
2294 if (Arguments != null) {
2295 MethodGroupExpr mg = me as MethodGroupExpr;
2299 return mg.ResolveGeneric (ec, Arguments);
2303 TypeManager.IsNestedFamilyAccessible (me.InstanceExpression.Type, me.DeclaringType) &&
2304 me.InstanceExpression.Type != me.DeclaringType &&
2305 !TypeManager.IsFamilyAccessible (me.InstanceExpression.Type, me.DeclaringType) &&
2306 (!intermediate || !IdenticalNameAndTypeName (ec, e, loc))) {
2307 Error (38, "Cannot access nonstatic member `" + me.Name + "' of " +
2308 "outer type `" + me.DeclaringType + "' via nested type `" +
2309 me.InstanceExpression.Type + "'");
2313 return (right_side != null)
2314 ? me.DoResolveLValue (ec, right_side)
2315 : me.DoResolve (ec);
2321 public override void Emit (EmitContext ec)
2324 // If this is ever reached, then we failed to
2325 // find the name as a namespace
2328 Error (103, "The name `" + Name +
2329 "' does not exist in the class `" +
2330 ec.DeclSpace.Name + "'");
2333 public override string ToString ()
2340 /// Represents a namespace or a type. The name of the class was inspired by
2341 /// section 10.8.1 (Fully Qualified Names).
2343 public abstract class FullNamedExpression : Expression {
2344 public override FullNamedExpression ResolveAsTypeStep (EmitContext ec)
2349 public abstract string FullName {
2355 /// Fully resolved expression that evaluates to a type
2357 public abstract class TypeExpr : FullNamedExpression {
2358 override public FullNamedExpression ResolveAsTypeStep (EmitContext ec)
2360 TypeExpr t = DoResolveAsTypeStep (ec);
2364 eclass = ExprClass.Type;
2368 override public Expression DoResolve (EmitContext ec)
2370 return ResolveAsTypeTerminal (ec);
2373 override public void Emit (EmitContext ec)
2375 throw new Exception ("Should never be called");
2378 public virtual bool CheckAccessLevel (DeclSpace ds)
2380 return ds.CheckAccessLevel (Type);
2383 public virtual bool AsAccessible (DeclSpace ds, int flags)
2385 return ds.AsAccessible (Type, flags);
2388 public virtual bool IsClass {
2389 get { return Type.IsClass; }
2392 public virtual bool IsValueType {
2393 get { return Type.IsValueType; }
2396 public virtual bool IsInterface {
2397 get { return Type.IsInterface; }
2400 public virtual bool IsSealed {
2401 get { return Type.IsSealed; }
2404 public virtual bool CanInheritFrom ()
2406 if (Type == TypeManager.enum_type ||
2407 (Type == TypeManager.value_type && RootContext.StdLib) ||
2408 Type == TypeManager.multicast_delegate_type ||
2409 Type == TypeManager.delegate_type ||
2410 Type == TypeManager.array_type)
2416 protected abstract TypeExpr DoResolveAsTypeStep (EmitContext ec);
2418 public virtual Type ResolveType (EmitContext ec)
2420 TypeExpr t = ResolveAsTypeTerminal (ec);
2427 public abstract string Name {
2431 public override bool Equals (object obj)
2433 TypeExpr tobj = obj as TypeExpr;
2437 return Type == tobj.Type;
2440 public override int GetHashCode ()
2442 return Type.GetHashCode ();
2445 public override string ToString ()
2451 public class TypeExpression : TypeExpr {
2452 public TypeExpression (Type t, Location l)
2455 eclass = ExprClass.Type;
2459 protected override TypeExpr DoResolveAsTypeStep (EmitContext ec)
2464 public override string Name {
2466 return Type.ToString ();
2470 public override string FullName {
2472 return Type.FullName != null ? Type.FullName : Type.Name;
2478 /// Used to create types from a fully qualified name. These are just used
2479 /// by the parser to setup the core types. A TypeLookupExpression is always
2480 /// classified as a type.
2482 public class TypeLookupExpression : TypeExpr {
2485 public TypeLookupExpression (string name)
2490 protected override TypeExpr DoResolveAsTypeStep (EmitContext ec)
2493 FullNamedExpression t = ec.DeclSpace.LookupType (name, Location.Null, /*ignore_cs0104=*/ false);
2495 Report.Error (246, loc, "Cannot find type `" + name + "'");
2498 if (!(t is TypeExpr)) {
2499 Report.Error (118, Location, "'{0}' denotes a '{1}', where a type was expected",
2500 t.FullName, t.ExprClassName ());
2504 type = ((TypeExpr) t).ResolveType (ec);
2510 public override string Name {
2516 public override string FullName {
2524 /// Represents an "unbound generic type", ie. typeof (Foo<>).
2527 public class UnboundTypeExpression : TypeLookupExpression {
2528 public UnboundTypeExpression (string name)
2533 public class TypeAliasExpression : TypeExpr {
2534 FullNamedExpression alias;
2539 public TypeAliasExpression (FullNamedExpression alias, TypeArguments args, Location l)
2545 eclass = ExprClass.Type;
2547 name = alias.FullName + "<" + args.ToString () + ">";
2549 name = alias.FullName;
2552 public override string Name {
2553 get { return alias.FullName; }
2556 public override string FullName {
2557 get { return name; }
2560 protected override TypeExpr DoResolveAsTypeStep (EmitContext ec)
2562 texpr = alias.ResolveAsTypeTerminal (ec);
2566 Type type = texpr.Type;
2567 int num_args = TypeManager.GetNumberOfTypeArguments (type);
2570 if (num_args == 0) {
2571 Report.Error (308, loc,
2572 "The non-generic type `{0}' cannot " +
2573 "be used with type arguments.",
2574 TypeManager.CSharpName (type));
2578 ConstructedType ctype = new ConstructedType (type, args, loc);
2579 return ctype.ResolveAsTypeTerminal (ec);
2580 } else if (num_args > 0) {
2581 Report.Error (305, loc,
2582 "Using the generic type `{0}' " +
2583 "requires {1} type arguments",
2584 TypeManager.GetFullName (type), num_args);
2588 return new TypeExpression (type, loc);
2591 public override bool CheckAccessLevel (DeclSpace ds)
2593 return texpr.CheckAccessLevel (ds);
2596 public override bool AsAccessible (DeclSpace ds, int flags)
2598 return texpr.AsAccessible (ds, flags);
2601 public override bool IsClass {
2602 get { return texpr.IsClass; }
2605 public override bool IsValueType {
2606 get { return texpr.IsValueType; }
2609 public override bool IsInterface {
2610 get { return texpr.IsInterface; }
2613 public override bool IsSealed {
2614 get { return texpr.IsSealed; }
2619 /// This class denotes an expression which evaluates to a member
2620 /// of a struct or a class.
2622 public abstract class MemberExpr : Expression
2625 /// The name of this member.
2627 public abstract string Name {
2632 /// Whether this is an instance member.
2634 public abstract bool IsInstance {
2639 /// Whether this is a static member.
2641 public abstract bool IsStatic {
2646 /// The type which declares this member.
2648 public abstract Type DeclaringType {
2653 /// The instance expression associated with this member, if it's a
2654 /// non-static member.
2656 public Expression InstanceExpression;
2658 public static void error176 (Location loc, string name)
2660 Report.Error (176, loc, "Static member `" + name + "' cannot be accessed " +
2661 "with an instance reference, qualify with a type name instead");
2665 // TODO: possible optimalization
2666 // Cache resolved constant result in FieldBuilder <-> expression map
2667 public virtual Expression ResolveMemberAccess (EmitContext ec, Expression left, Location loc,
2668 SimpleName original)
2672 // original == null || original.Resolve (...) ==> left
2675 if (left is TypeExpr) {
2677 SimpleName.Error_ObjectRefRequired (ec, loc, Name);
2685 if (original != null && original.IdenticalNameAndTypeName (ec, left, loc))
2688 error176 (loc, Name);
2692 InstanceExpression = left;
2699 /// MethodGroup Expression.
2701 /// This is a fully resolved expression that evaluates to a type
2703 public class MethodGroupExpr : MemberExpr {
2704 public MethodBase [] Methods;
2705 bool has_type_arguments = false;
2706 bool identical_type_name = false;
2709 public MethodGroupExpr (MemberInfo [] mi, Location l)
2711 Methods = new MethodBase [mi.Length];
2712 mi.CopyTo (Methods, 0);
2713 eclass = ExprClass.MethodGroup;
2714 type = TypeManager.object_type;
2718 public MethodGroupExpr (ArrayList list, Location l)
2720 Methods = new MethodBase [list.Count];
2723 list.CopyTo (Methods, 0);
2725 foreach (MemberInfo m in list){
2726 if (!(m is MethodBase)){
2727 Console.WriteLine ("Name " + m.Name);
2728 Console.WriteLine ("Found a: " + m.GetType ().FullName);
2735 eclass = ExprClass.MethodGroup;
2736 type = TypeManager.object_type;
2739 public override Type DeclaringType {
2742 // We assume that the top-level type is in the end
2744 return Methods [Methods.Length - 1].DeclaringType;
2745 //return Methods [0].DeclaringType;
2749 public bool HasTypeArguments {
2751 return has_type_arguments;
2755 has_type_arguments = value;
2759 public bool IdenticalTypeName {
2761 return identical_type_name;
2765 identical_type_name = value;
2769 public bool IsBase {
2778 public override string Name {
2780 //return Methods [0].Name;
2781 return Methods [Methods.Length - 1].Name;
2785 public override bool IsInstance {
2787 foreach (MethodBase mb in Methods)
2795 public override bool IsStatic {
2797 foreach (MethodBase mb in Methods)
2805 public override Expression ResolveMemberAccess (EmitContext ec, Expression left, Location loc,
2806 SimpleName original)
2808 if (!(left is TypeExpr) &&
2809 original != null && original.IdenticalNameAndTypeName (ec, left, loc))
2810 IdenticalTypeName = true;
2812 return base.ResolveMemberAccess (ec, left, loc, original);
2815 override public Expression DoResolve (EmitContext ec)
2818 InstanceExpression = null;
2820 if (InstanceExpression != null) {
2821 InstanceExpression = InstanceExpression.DoResolve (ec);
2822 if (InstanceExpression == null)
2829 public void ReportUsageError ()
2831 Report.Error (654, loc, "Method `" + DeclaringType + "." +
2832 Name + "()' is referenced without parentheses");
2835 override public void Emit (EmitContext ec)
2837 ReportUsageError ();
2840 bool RemoveMethods (bool keep_static)
2842 ArrayList smethods = new ArrayList ();
2844 foreach (MethodBase mb in Methods){
2845 if (mb.IsStatic == keep_static)
2849 if (smethods.Count == 0)
2852 Methods = new MethodBase [smethods.Count];
2853 smethods.CopyTo (Methods, 0);
2859 /// Removes any instance methods from the MethodGroup, returns
2860 /// false if the resulting set is empty.
2862 public bool RemoveInstanceMethods ()
2864 return RemoveMethods (true);
2868 /// Removes any static methods from the MethodGroup, returns
2869 /// false if the resulting set is empty.
2871 public bool RemoveStaticMethods ()
2873 return RemoveMethods (false);
2876 public Expression ResolveGeneric (EmitContext ec, TypeArguments args)
2878 if (args.Resolve (ec) == false)
2881 Type[] atypes = args.Arguments;
2883 int first_count = 0;
2884 MethodInfo first = null;
2886 ArrayList list = new ArrayList ();
2887 foreach (MethodBase mb in Methods) {
2888 MethodInfo mi = mb as MethodInfo;
2889 if ((mi == null) || !mi.HasGenericParameters)
2892 Type[] gen_params = mi.GetGenericArguments ();
2894 if (first == null) {
2896 first_count = gen_params.Length;
2899 if (gen_params.Length != atypes.Length)
2902 list.Add (mi.BindGenericParameters (atypes));
2905 if (list.Count > 0) {
2906 MethodGroupExpr new_mg = new MethodGroupExpr (list, Location);
2907 new_mg.InstanceExpression = InstanceExpression;
2908 new_mg.HasTypeArguments = true;
2914 305, loc, "Using the generic method `{0}' " +
2915 "requires {1} type arguments", Name,
2919 308, loc, "The non-generic method `{0}' " +
2920 "cannot be used with type arguments", Name);
2927 /// Fully resolved expression that evaluates to a Field
2929 public class FieldExpr : MemberExpr, IAssignMethod, IMemoryLocation, IVariable {
2930 public readonly FieldInfo FieldInfo;
2931 VariableInfo variable_info;
2933 LocalTemporary temp;
2935 bool in_initializer;
2937 public FieldExpr (FieldInfo fi, Location l, bool in_initializer):
2940 this.in_initializer = in_initializer;
2943 public FieldExpr (FieldInfo fi, Location l)
2946 eclass = ExprClass.Variable;
2947 type = TypeManager.TypeToCoreType (fi.FieldType);
2951 public override string Name {
2953 return FieldInfo.Name;
2957 public override bool IsInstance {
2959 return !FieldInfo.IsStatic;
2963 public override bool IsStatic {
2965 return FieldInfo.IsStatic;
2969 public override Type DeclaringType {
2971 return FieldInfo.DeclaringType;
2975 public VariableInfo VariableInfo {
2977 return variable_info;
2981 public override Expression ResolveMemberAccess (EmitContext ec, Expression left, Location loc,
2982 SimpleName original)
2984 bool left_is_type = left is TypeExpr;
2986 FieldInfo fi = FieldInfo.Mono_GetGenericFieldDefinition ();
2988 Type decl_type = fi.DeclaringType;
2990 bool is_emitted = fi is FieldBuilder;
2991 Type t = fi.FieldType;
2994 Const c = TypeManager.LookupConstant ((FieldBuilder) fi);
2998 if (!c.LookupConstantValue (out o))
3001 c.SetMemberIsUsed ();
3002 object real_value = ((Constant) c.Expr).GetValue ();
3004 Expression exp = Constantify (real_value, t);
3006 if (!left_is_type &&
3007 (original == null || !original.IdenticalNameAndTypeName (ec, left, loc))) {
3008 Report.SymbolRelatedToPreviousError (c);
3009 error176 (loc, c.GetSignatureForError ());
3018 // Decimal constants cannot be encoded in the constant blob, and thus are marked
3019 // as IsInitOnly ('readonly' in C# parlance). We get its value from the
3020 // DecimalConstantAttribute metadata.
3022 if (fi.IsInitOnly && !is_emitted && t == TypeManager.decimal_type) {
3023 object[] attrs = fi.GetCustomAttributes (TypeManager.decimal_constant_attribute_type, false);
3024 if (attrs.Length == 1)
3025 return new DecimalConstant (((System.Runtime.CompilerServices.DecimalConstantAttribute) attrs [0]).Value);
3032 o = TypeManager.GetValue ((FieldBuilder) fi);
3034 o = fi.GetValue (fi);
3036 if (decl_type.IsSubclassOf (TypeManager.enum_type)) {
3037 if (!left_is_type &&
3038 (original == null || !original.IdenticalNameAndTypeName (ec, left, loc))) {
3039 error176 (loc, fi.Name);
3043 Expression enum_member = MemberLookup (
3044 ec, decl_type, "value__", MemberTypes.Field,
3045 AllBindingFlags | BindingFlags.NonPublic, loc);
3047 Enum en = TypeManager.LookupEnum (decl_type);
3051 c = Constantify (o, en.UnderlyingType);
3053 c = Constantify (o, enum_member.Type);
3055 return new EnumConstant (c, decl_type);
3058 Expression exp = Constantify (o, t);
3060 if (!left_is_type) {
3061 error176 (loc, fi.Name);
3068 if (t.IsPointer && !ec.InUnsafe) {
3073 return base.ResolveMemberAccess (ec, left, loc, original);
3076 override public Expression DoResolve (EmitContext ec)
3078 if (ec.InRefOutArgumentResolving && FieldInfo.IsInitOnly && !ec.IsConstructor && FieldInfo.FieldType.IsValueType) {
3079 if (FieldInfo.FieldType is TypeBuilder) {
3080 if (FieldInfo.IsStatic)
3081 Report.Error (1651, loc, "Members of readonly static field '{0}.{1}' cannot be passed ref or out (except in a constructor)",
3082 TypeManager.CSharpName (DeclaringType), Name);
3084 Report.Error (1649, loc, "Members of readonly field '{0}.{1}' cannot be passed ref or out (except in a constructor)",
3085 TypeManager.CSharpName (DeclaringType), Name);
3087 if (FieldInfo.IsStatic)
3088 Report.Error (199, loc, "A static readonly field '{0}' cannot be passed ref or out (except in a static constructor)",
3091 Report.Error (192, loc, "A readonly field '{0}' cannot be passed ref or out (except in a constructor)",
3097 if (!FieldInfo.IsStatic){
3098 if (InstanceExpression == null){
3100 // This can happen when referencing an instance field using
3101 // a fully qualified type expression: TypeName.InstanceField = xxx
3103 SimpleName.Error_ObjectRefRequired (ec, loc, FieldInfo.Name);
3107 // Resolve the field's instance expression while flow analysis is turned
3108 // off: when accessing a field "a.b", we must check whether the field
3109 // "a.b" is initialized, not whether the whole struct "a" is initialized.
3110 InstanceExpression = InstanceExpression.Resolve (ec, ResolveFlags.VariableOrValue |
3111 ResolveFlags.DisableFlowAnalysis);
3112 if (InstanceExpression == null)
3116 if (!in_initializer) {
3117 ObsoleteAttribute oa;
3118 FieldBase f = TypeManager.GetField (FieldInfo);
3120 oa = f.GetObsoleteAttribute (f.Parent);
3122 AttributeTester.Report_ObsoleteMessage (oa, f.GetSignatureForError (), loc);
3123 // To be sure that type is external because we do not register generated fields
3124 } else if (!(FieldInfo.DeclaringType is TypeBuilder)) {
3125 oa = AttributeTester.GetMemberObsoleteAttribute (FieldInfo);
3127 AttributeTester.Report_ObsoleteMessage (oa, TypeManager.GetFullNameSignature (FieldInfo), loc);
3131 if (ec.CurrentAnonymousMethod != null){
3132 if (!FieldInfo.IsStatic){
3133 if (ec.TypeContainer is Struct){
3134 Report.Error (1673, loc, "Can not reference instance variables in anonymous methods hosted in structs");
3137 ec.CaptureField (this);
3141 // If the instance expression is a local variable or parameter.
3142 IVariable var = InstanceExpression as IVariable;
3143 if ((var == null) || (var.VariableInfo == null))
3146 VariableInfo vi = var.VariableInfo;
3147 if (!vi.IsFieldAssigned (ec, FieldInfo.Name, loc))
3150 variable_info = vi.GetSubStruct (FieldInfo.Name);
3154 void Report_AssignToReadonly (bool is_instance)
3159 msg = "Readonly field can not be assigned outside " +
3160 "of constructor or variable initializer";
3162 msg = "A static readonly field can only be assigned in " +
3163 "a static constructor";
3165 Report.Error (is_instance ? 191 : 198, loc, msg);
3168 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
3170 IVariable var = InstanceExpression as IVariable;
3171 if ((var != null) && (var.VariableInfo != null))
3172 var.VariableInfo.SetFieldAssigned (ec, FieldInfo.Name);
3174 Expression e = DoResolve (ec);
3179 if (!FieldInfo.IsStatic && (InstanceExpression.Type.IsValueType && !(InstanceExpression is IMemoryLocation))) {
3180 // FIXME: Provide better error reporting.
3181 Error (1612, "Cannot modify expression because it is not a variable.");
3185 FieldBase fb = TypeManager.GetField (FieldInfo);
3189 if (!FieldInfo.IsInitOnly)
3193 // InitOnly fields can only be assigned in constructors
3196 if (ec.IsConstructor){
3197 if (IsStatic && !ec.IsStatic)
3198 Report_AssignToReadonly (false);
3201 if (ec.TypeContainer.CurrentType != null)
3202 ctype = ec.TypeContainer.CurrentType;
3204 ctype = ec.ContainerType;
3206 if (TypeManager.IsEqual (ctype, FieldInfo.DeclaringType))
3210 Report_AssignToReadonly (!IsStatic);
3215 public override void CheckMarshallByRefAccess (Type container)
3217 if (!IsStatic && Type.IsValueType && !container.IsSubclassOf (TypeManager.mbr_type) && DeclaringType.IsSubclassOf (TypeManager.mbr_type)) {
3218 Report.SymbolRelatedToPreviousError (DeclaringType);
3219 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);
3223 public bool VerifyFixed (bool is_expression)
3225 IVariable variable = InstanceExpression as IVariable;
3226 if ((variable == null) || !variable.VerifyFixed (true))
3232 public override int GetHashCode()
3234 return FieldInfo.GetHashCode ();
3237 public override bool Equals (object obj)
3239 FieldExpr fe = obj as FieldExpr;
3243 if (FieldInfo != fe.FieldInfo)
3246 if (InstanceExpression == null || fe.InstanceExpression == null)
3249 return InstanceExpression.Equals (fe.InstanceExpression);
3252 public void Emit (EmitContext ec, bool leave_copy)
3254 ILGenerator ig = ec.ig;
3255 bool is_volatile = false;
3257 if (FieldInfo is FieldBuilder){
3258 FieldBase f = TypeManager.GetField (FieldInfo);
3260 if ((f.ModFlags & Modifiers.VOLATILE) != 0)
3263 f.SetMemberIsUsed ();
3267 if (FieldInfo.IsStatic){
3269 ig.Emit (OpCodes.Volatile);
3271 ig.Emit (OpCodes.Ldsfld, FieldInfo);
3277 ig.Emit (OpCodes.Volatile);
3279 IFixedBuffer ff = AttributeTester.GetFixedBuffer (FieldInfo);
3282 ig.Emit (OpCodes.Ldflda, FieldInfo);
3283 ig.Emit (OpCodes.Ldflda, ff.Element);
3286 ig.Emit (OpCodes.Ldfld, FieldInfo);
3291 ec.ig.Emit (OpCodes.Dup);
3292 if (!FieldInfo.IsStatic) {
3293 temp = new LocalTemporary (ec, this.Type);
3299 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
3301 FieldAttributes fa = FieldInfo.Attributes;
3302 bool is_static = (fa & FieldAttributes.Static) != 0;
3303 bool is_readonly = (fa & FieldAttributes.InitOnly) != 0;
3304 ILGenerator ig = ec.ig;
3305 prepared = prepare_for_load;
3307 if (is_readonly && !ec.IsConstructor){
3308 Report_AssignToReadonly (!is_static);
3314 if (prepare_for_load)
3315 ig.Emit (OpCodes.Dup);
3320 ec.ig.Emit (OpCodes.Dup);
3321 if (!FieldInfo.IsStatic) {
3322 temp = new LocalTemporary (ec, this.Type);
3327 if (FieldInfo is FieldBuilder){
3328 FieldBase f = TypeManager.GetField (FieldInfo);
3330 if ((f.ModFlags & Modifiers.VOLATILE) != 0)
3331 ig.Emit (OpCodes.Volatile);
3333 f.status |= Field.Status.ASSIGNED;
3338 ig.Emit (OpCodes.Stsfld, FieldInfo);
3340 ig.Emit (OpCodes.Stfld, FieldInfo);
3346 void EmitInstance (EmitContext ec)
3348 if (InstanceExpression.Type.IsValueType) {
3349 if (InstanceExpression is IMemoryLocation) {
3350 ((IMemoryLocation) InstanceExpression).AddressOf (ec, AddressOp.LoadStore);
3352 LocalTemporary t = new LocalTemporary (ec, InstanceExpression.Type);
3353 InstanceExpression.Emit (ec);
3355 t.AddressOf (ec, AddressOp.Store);
3358 InstanceExpression.Emit (ec);
3361 public override void Emit (EmitContext ec)
3366 public void AddressOf (EmitContext ec, AddressOp mode)
3368 ILGenerator ig = ec.ig;
3370 if (FieldInfo is FieldBuilder){
3371 FieldBase f = TypeManager.GetField (FieldInfo);
3373 if ((f.ModFlags & Modifiers.VOLATILE) != 0){
3374 Error (676, "volatile variable: can not take its address, or pass as ref/out parameter");
3378 if ((mode & AddressOp.Store) != 0)
3379 f.status |= Field.Status.ASSIGNED;
3380 if ((mode & AddressOp.Load) != 0)
3381 f.SetMemberIsUsed ();
3386 // Handle initonly fields specially: make a copy and then
3387 // get the address of the copy.
3390 if (FieldInfo.IsInitOnly){
3392 if (ec.IsConstructor){
3393 if (FieldInfo.IsStatic){
3405 local = ig.DeclareLocal (type);
3406 ig.Emit (OpCodes.Stloc, local);
3407 ig.Emit (OpCodes.Ldloca, local);
3412 if (FieldInfo.IsStatic){
3413 ig.Emit (OpCodes.Ldsflda, FieldInfo);
3416 ig.Emit (OpCodes.Ldflda, FieldInfo);
3422 // A FieldExpr whose address can not be taken
3424 public class FieldExprNoAddress : FieldExpr, IMemoryLocation {
3425 public FieldExprNoAddress (FieldInfo fi, Location loc) : base (fi, loc)
3429 public new void AddressOf (EmitContext ec, AddressOp mode)
3431 Report.Error (-215, "Report this: Taking the address of a remapped parameter not supported");
3436 /// Expression that evaluates to a Property. The Assign class
3437 /// might set the `Value' expression if we are in an assignment.
3439 /// This is not an LValue because we need to re-write the expression, we
3440 /// can not take data from the stack and store it.
3442 public class PropertyExpr : MemberExpr, IAssignMethod {
3443 public readonly PropertyInfo PropertyInfo;
3446 // This is set externally by the `BaseAccess' class
3449 MethodInfo getter, setter;
3454 LocalTemporary temp;
3457 internal static PtrHashtable AccessorTable = new PtrHashtable ();
3459 public PropertyExpr (EmitContext ec, PropertyInfo pi, Location l)
3462 eclass = ExprClass.PropertyAccess;
3466 type = TypeManager.TypeToCoreType (pi.PropertyType);
3468 ResolveAccessors (ec);
3471 public override string Name {
3473 return PropertyInfo.Name;
3477 public override bool IsInstance {
3483 public override bool IsStatic {
3489 public override Type DeclaringType {
3491 return PropertyInfo.DeclaringType;
3495 public bool VerifyAssignable ()
3497 if (setter == null) {
3498 Report.Error (200, loc,
3499 "The property `" + PropertyInfo.Name +
3500 "' can not be assigned to, as it has not set accessor");
3507 void FindAccessors (Type invocation_type)
3509 BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic |
3510 BindingFlags.Static | BindingFlags.Instance |
3511 BindingFlags.DeclaredOnly;
3513 Type current = PropertyInfo.DeclaringType;
3514 for (; current != null; current = current.BaseType) {
3515 MemberInfo[] group = TypeManager.MemberLookup (
3516 invocation_type, invocation_type, current,
3517 MemberTypes.Property, flags, PropertyInfo.Name, null);
3522 if (group.Length != 1)
3523 // Oooops, can this ever happen ?
3526 PropertyInfo pi = (PropertyInfo) group [0];
3529 getter = pi.GetGetMethod (true);
3532 setter = pi.GetSetMethod (true);
3534 MethodInfo accessor = getter != null ? getter : setter;
3536 if (!accessor.IsVirtual)
3542 // We also perform the permission checking here, as the PropertyInfo does not
3543 // hold the information for the accessibility of its setter/getter
3545 void ResolveAccessors (EmitContext ec)
3547 FindAccessors (ec.ContainerType);
3549 if (getter != null) {
3550 IMethodData md = TypeManager.GetMethod (getter);
3552 md.SetMemberIsUsed ();
3554 AccessorTable [getter] = PropertyInfo;
3555 is_static = getter.IsStatic;
3558 if (setter != null) {
3559 IMethodData md = TypeManager.GetMethod (setter);
3561 md.SetMemberIsUsed ();
3563 AccessorTable [setter] = PropertyInfo;
3564 is_static = setter.IsStatic;
3568 bool InstanceResolve (EmitContext ec, bool must_do_cs1540_check)
3570 if ((InstanceExpression == null) && ec.IsStatic && !is_static) {
3571 SimpleName.Error_ObjectRefRequired (ec, loc, PropertyInfo.Name);
3575 if (!IsInstance || InstanceExpression == EmptyExpression.Null)
3576 InstanceExpression = null;
3578 if (InstanceExpression != null) {
3579 InstanceExpression = InstanceExpression.DoResolve (ec);
3580 if (InstanceExpression == null)
3583 InstanceExpression.CheckMarshallByRefAccess (ec.ContainerType);
3586 if (must_do_cs1540_check && (InstanceExpression != null)) {
3587 if ((InstanceExpression.Type != ec.ContainerType) &&
3588 ec.ContainerType.IsSubclassOf (InstanceExpression.Type)) {
3589 Report.Error (1540, loc, "Cannot access protected member `" +
3590 PropertyInfo.DeclaringType + "." + PropertyInfo.Name +
3591 "' via a qualifier of type `" +
3592 TypeManager.CSharpName (InstanceExpression.Type) +
3593 "'; the qualifier must be of type `" +
3594 TypeManager.CSharpName (ec.ContainerType) +
3595 "' (or derived from it)");
3603 override public Expression DoResolve (EmitContext ec)
3606 Report.Debug ("Double resolve of " + Name);
3610 if (getter != null){
3611 if (TypeManager.GetArgumentTypes (getter).Length != 0){
3613 117, loc, "`{0}' does not contain a " +
3614 "definition for `{1}'.", getter.DeclaringType,
3620 if (getter == null){
3622 // The following condition happens if the PropertyExpr was
3623 // created, but is invalid (ie, the property is inaccessible),
3624 // and we did not want to embed the knowledge about this in
3625 // the caller routine. This only avoids double error reporting.
3630 if (InstanceExpression != EmptyExpression.Null) {
3631 Report.Error (154, loc,
3632 "The property `" + PropertyInfo.Name +
3633 "' can not be used in " +
3634 "this context because it lacks a get accessor");
3639 bool must_do_cs1540_check = false;
3640 if (getter != null &&
3641 !IsAccessorAccessible (ec.ContainerType, getter, out must_do_cs1540_check)) {
3642 PropertyBase.PropertyMethod pm = TypeManager.GetMethod (getter) as PropertyBase.PropertyMethod;
3643 if (pm != null && pm.HasCustomAccessModifier) {
3644 Report.SymbolRelatedToPreviousError (pm);
3645 Report.Error (271, loc, "The property or indexer '{0}' cannot be used in this context because the get accessor is inaccessible",
3646 TypeManager.CSharpSignature (getter));
3649 Report.Error (122, loc, "'{0}' is inaccessible due to its protection level",
3650 TypeManager.CSharpSignature (getter));
3654 if (!InstanceResolve (ec, must_do_cs1540_check))
3658 // Only base will allow this invocation to happen.
3660 if (IsBase && getter.IsAbstract){
3661 Report.Error (205, loc, "Cannot call an abstract base property: " +
3662 PropertyInfo.DeclaringType + "." +PropertyInfo.Name);
3666 if (PropertyInfo.PropertyType.IsPointer && !ec.InUnsafe){
3676 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
3678 if (setter == null){
3680 // The following condition happens if the PropertyExpr was
3681 // created, but is invalid (ie, the property is inaccessible),
3682 // and we did not want to embed the knowledge about this in
3683 // the caller routine. This only avoids double error reporting.
3688 // TODO: Print better property name
3689 Report.Error (200, loc, "Property or indexer '{0}' cannot be assigned to -- it is read only",
3694 if (TypeManager.GetArgumentTypes (setter).Length != 1){
3696 117, loc, "`{0}' does not contain a " +
3697 "definition for `{1}'.", getter.DeclaringType,
3702 bool must_do_cs1540_check;
3703 if (!IsAccessorAccessible (ec.ContainerType, setter, out must_do_cs1540_check)) {
3704 PropertyBase.PropertyMethod pm = TypeManager.GetMethod (setter) as PropertyBase.PropertyMethod;
3705 if (pm != null && pm.HasCustomAccessModifier) {
3706 Report.SymbolRelatedToPreviousError (pm);
3707 Report.Error (272, loc, "The property or indexer '{0}' cannot be used in this context because the set accessor is inaccessible",
3708 TypeManager.CSharpSignature (setter));
3711 Report.Error (122, loc, "'{0}' is inaccessible due to its protection level",
3712 TypeManager.CSharpSignature (setter));
3716 if (!InstanceResolve (ec, must_do_cs1540_check))
3720 // Only base will allow this invocation to happen.
3722 if (IsBase && setter.IsAbstract){
3723 Report.Error (205, loc, "Cannot call an abstract base property: " +
3724 PropertyInfo.DeclaringType + "." +PropertyInfo.Name);
3729 // Check that we are not making changes to a temporary memory location
3731 if (InstanceExpression != null && InstanceExpression.Type.IsValueType && !(InstanceExpression is IMemoryLocation)) {
3732 // FIXME: Provide better error reporting.
3733 Error (1612, "Cannot modify expression because it is not a variable.");
3742 public override void Emit (EmitContext ec)
3747 void EmitInstance (EmitContext ec)
3752 if (InstanceExpression.Type.IsValueType) {
3753 if (InstanceExpression is IMemoryLocation) {
3754 ((IMemoryLocation) InstanceExpression).AddressOf (ec, AddressOp.LoadStore);
3756 LocalTemporary t = new LocalTemporary (ec, InstanceExpression.Type);
3757 InstanceExpression.Emit (ec);
3759 t.AddressOf (ec, AddressOp.Store);
3762 InstanceExpression.Emit (ec);
3765 ec.ig.Emit (OpCodes.Dup);
3769 public void Emit (EmitContext ec, bool leave_copy)
3775 // Special case: length of single dimension array property is turned into ldlen
3777 if ((getter == TypeManager.system_int_array_get_length) ||
3778 (getter == TypeManager.int_array_get_length)){
3779 Type iet = InstanceExpression.Type;
3782 // System.Array.Length can be called, but the Type does not
3783 // support invoking GetArrayRank, so test for that case first
3785 if (iet != TypeManager.array_type && (iet.GetArrayRank () == 1)) {
3786 ec.ig.Emit (OpCodes.Ldlen);
3787 ec.ig.Emit (OpCodes.Conv_I4);
3792 Invocation.EmitCall (ec, IsBase, IsStatic, new EmptyAddressOf (), getter, null, loc);
3797 ec.ig.Emit (OpCodes.Dup);
3799 temp = new LocalTemporary (ec, this.Type);
3805 // Implements the IAssignMethod interface for assignments
3807 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
3809 prepared = prepare_for_load;
3815 ec.ig.Emit (OpCodes.Dup);
3817 temp = new LocalTemporary (ec, this.Type);
3822 ArrayList args = new ArrayList (1);
3823 args.Add (new Argument (new EmptyAddressOf (), Argument.AType.Expression));
3825 Invocation.EmitCall (ec, IsBase, IsStatic, new EmptyAddressOf (), setter, args, loc);
3833 /// Fully resolved expression that evaluates to an Event
3835 public class EventExpr : MemberExpr {
3836 public readonly EventInfo EventInfo;
3839 MethodInfo add_accessor, remove_accessor;
3841 public EventExpr (EventInfo ei, Location loc)
3845 eclass = ExprClass.EventAccess;
3847 add_accessor = TypeManager.GetAddMethod (ei);
3848 remove_accessor = TypeManager.GetRemoveMethod (ei);
3850 if (add_accessor.IsStatic || remove_accessor.IsStatic)
3853 if (EventInfo is MyEventBuilder){
3854 MyEventBuilder eb = (MyEventBuilder) EventInfo;
3855 type = eb.EventType;
3858 type = EventInfo.EventHandlerType;
3861 public override string Name {
3863 return EventInfo.Name;
3867 public override bool IsInstance {
3873 public override bool IsStatic {
3879 public override Type DeclaringType {
3881 return EventInfo.DeclaringType;
3885 public override Expression ResolveMemberAccess (EmitContext ec, Expression left, Location loc,
3886 SimpleName original)
3889 // If the event is local to this class, we transform ourselves into a FieldExpr
3892 if (EventInfo.DeclaringType == ec.ContainerType ||
3893 TypeManager.IsNestedChildOf(ec.ContainerType, EventInfo.DeclaringType)) {
3894 MemberInfo mi = TypeManager.GetPrivateFieldOfEvent (EventInfo);
3897 MemberExpr ml = (MemberExpr) ExprClassFromMemberInfo (ec, mi, loc);
3900 Report.Error (-200, loc, "Internal error!!");
3904 InstanceExpression = null;
3906 return ml.ResolveMemberAccess (ec, left, loc, original);
3910 return base.ResolveMemberAccess (ec, left, loc, original);
3914 bool InstanceResolve (EmitContext ec, bool must_do_cs1540_check)
3916 if ((InstanceExpression == null) && ec.IsStatic && !is_static) {
3917 SimpleName.Error_ObjectRefRequired (ec, loc, EventInfo.Name);
3921 if (!IsInstance || InstanceExpression == EmptyExpression.Null)
3922 InstanceExpression = null;
3924 if (InstanceExpression != null) {
3925 InstanceExpression = InstanceExpression.DoResolve (ec);
3926 if (InstanceExpression == null)
3931 // This is using the same mechanism as the CS1540 check in PropertyExpr.
3932 // However, in the Event case, we reported a CS0122 instead.
3934 if (must_do_cs1540_check && (InstanceExpression != null)) {
3935 if ((InstanceExpression.Type != ec.ContainerType) &&
3936 ec.ContainerType.IsSubclassOf (InstanceExpression.Type)) {
3937 Report.Error (122, loc, "'{0}' is inaccessible due to its protection level",
3938 DeclaringType.Name + "." + EventInfo.Name);
3947 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
3949 return DoResolve (ec);
3952 public override Expression DoResolve (EmitContext ec)
3955 InstanceExpression = null;
3957 if (InstanceExpression != null) {
3958 InstanceExpression = InstanceExpression.DoResolve (ec);
3959 if (InstanceExpression == null)
3963 bool must_do_cs1540_check;
3964 if (!(IsAccessorAccessible (ec.ContainerType, add_accessor, out must_do_cs1540_check) &&
3965 IsAccessorAccessible (ec.ContainerType, remove_accessor, out must_do_cs1540_check))) {
3967 Report.Error (122, loc, "'{0}' is inaccessible due to its protection level",
3968 DeclaringType.Name + "." + EventInfo.Name);
3972 if (!InstanceResolve (ec, must_do_cs1540_check))
3978 public override void Emit (EmitContext ec)
3980 if (InstanceExpression is This)
3981 Report.Error (79, loc, "The event `{0}' can only appear on the left hand side of += or -=, try calling the actual delegate", Name);
3983 Report.Error (70, loc, "The event `{0}' can only appear on the left hand side of += or -= "+
3984 "(except on the defining type)", Name);
3987 public void EmitAddOrRemove (EmitContext ec, Expression source)
3989 BinaryDelegate source_del = (BinaryDelegate) source;
3990 Expression handler = source_del.Right;
3992 Argument arg = new Argument (handler, Argument.AType.Expression);
3993 ArrayList args = new ArrayList ();
3997 if (source_del.IsAddition)
3998 Invocation.EmitCall (
3999 ec, false, IsStatic, InstanceExpression, add_accessor, args, loc);
4001 Invocation.EmitCall (
4002 ec, false, IsStatic, InstanceExpression, remove_accessor, args, loc);