2 // ecore.cs: Core of the Expression representation for the intermediate tree.
5 // Miguel de Icaza (miguel@ximian.com)
7 // (C) 2001, 2002, 2003 Ximian, Inc.
11 namespace Mono.CSharp {
13 using System.Collections;
14 using System.Diagnostics;
15 using System.Reflection;
16 using System.Reflection.Emit;
20 /// The ExprClass class contains the is used to pass the
21 /// classification of an expression (value, variable, namespace,
22 /// type, method group, property access, event access, indexer access,
25 public enum ExprClass : byte {
40 /// This is used to tell Resolve in which types of expressions we're
44 public enum ResolveFlags {
45 // Returns Value, Variable, PropertyAccess, EventAccess or IndexerAccess.
48 // Returns a type expression.
51 // Returns a method group.
54 // Mask of all the expression class flags.
57 // Disable control flow analysis while resolving the expression.
58 // This is used when resolving the instance expression of a field expression.
59 DisableFlowAnalysis = 8,
61 // Set if this is resolving the first part of a MemberAccess.
64 // Disable control flow analysis _of struct_ while resolving the expression.
65 // This is used when resolving the instance expression of a field expression.
66 DisableStructFlowAnalysis = 32,
71 // This is just as a hint to AddressOf of what will be done with the
74 public enum AddressOp {
81 /// This interface is implemented by variables
83 public interface IMemoryLocation {
85 /// The AddressOf method should generate code that loads
86 /// the address of the object and leaves it on the stack.
88 /// The `mode' argument is used to notify the expression
89 /// of whether this will be used to read from the address or
90 /// write to the address.
92 /// This is just a hint that can be used to provide good error
93 /// reporting, and should have no other side effects.
95 void AddressOf (EmitContext ec, AddressOp mode);
99 /// This interface is implemented by variables
101 public interface IVariable {
102 VariableInfo VariableInfo {
110 /// Base class for expressions
112 public abstract class Expression {
113 public ExprClass eclass;
115 protected Location loc;
119 set { type = value; }
122 public virtual Location Location {
127 /// Utility wrapper routine for Error, just to beautify the code
129 public void Error (int error, string s)
132 Report.Error (error, s);
134 Report.Error (error, loc, s);
138 /// Utility wrapper routine for Warning, just to beautify the code
140 public void Warning (int code, string format, params object[] args)
142 Report.Warning (code, loc, format, args);
145 // Not nice but we have broken hierarchy
146 public virtual void CheckMarshallByRefAccess (Type container) {}
149 /// Tests presence of ObsoleteAttribute and report proper error
151 protected void CheckObsoleteAttribute (Type type)
153 ObsoleteAttribute obsolete_attr = AttributeTester.GetObsoleteAttribute (type);
154 if (obsolete_attr == null)
157 AttributeTester.Report_ObsoleteMessage (obsolete_attr, type.FullName, loc);
160 public virtual string GetSignatureForError ()
162 return TypeManager.CSharpName (type);
165 public static bool IsAccessorAccessible (Type invocation_type, MethodInfo mi, out bool must_do_cs1540_check)
167 MethodAttributes ma = mi.Attributes & MethodAttributes.MemberAccessMask;
169 must_do_cs1540_check = false; // by default we do not check for this
172 // If only accessible to the current class or children
174 if (ma == MethodAttributes.Private)
175 return invocation_type == mi.DeclaringType ||
176 TypeManager.IsNestedChildOf (invocation_type, mi.DeclaringType);
178 if (mi.DeclaringType.Assembly == invocation_type.Assembly) {
179 if (ma == MethodAttributes.Assembly || ma == MethodAttributes.FamORAssem)
182 if (ma == MethodAttributes.Assembly || ma == MethodAttributes.FamANDAssem)
186 // Family and FamANDAssem require that we derive.
187 // FamORAssem requires that we derive if in different assemblies.
188 if (ma == MethodAttributes.Family ||
189 ma == MethodAttributes.FamANDAssem ||
190 ma == MethodAttributes.FamORAssem) {
191 if (!TypeManager.IsNestedFamilyAccessible (invocation_type, mi.DeclaringType))
194 if (!TypeManager.IsNestedChildOf (invocation_type, mi.DeclaringType))
195 must_do_cs1540_check = true;
204 /// Performs semantic analysis on the Expression
208 /// The Resolve method is invoked to perform the semantic analysis
211 /// The return value is an expression (it can be the
212 /// same expression in some cases) or a new
213 /// expression that better represents this node.
215 /// For example, optimizations of Unary (LiteralInt)
216 /// would return a new LiteralInt with a negated
219 /// If there is an error during semantic analysis,
220 /// then an error should be reported (using Report)
221 /// and a null value should be returned.
223 /// There are two side effects expected from calling
224 /// Resolve(): the the field variable "eclass" should
225 /// be set to any value of the enumeration
226 /// `ExprClass' and the type variable should be set
227 /// to a valid type (this is the type of the
230 public abstract Expression DoResolve (EmitContext ec);
232 public virtual Expression DoResolveLValue (EmitContext ec, Expression right_side)
238 // This is used if the expression should be resolved as a type or namespace name.
239 // the default implementation fails.
241 public virtual FullNamedExpression ResolveAsTypeStep (EmitContext ec, bool silent)
247 // This is used to resolve the expression as a type, a null
248 // value will be returned if the expression is not a type
251 public TypeExpr ResolveAsTypeTerminal (EmitContext ec, bool silent)
253 int errors = Report.Errors;
255 FullNamedExpression fne = ResolveAsTypeStep (ec, silent);
260 if (fne.eclass != ExprClass.Type) {
261 if (!silent && errors == Report.Errors)
262 fne.Error_UnexpectedKind (null, "type", loc);
266 TypeExpr te = fne as TypeExpr;
268 if (!te.CheckAccessLevel (ec.DeclSpace)) {
269 ErrorIsInaccesible (loc, TypeManager.CSharpName (te.Type));
276 public static void ErrorIsInaccesible (Location loc, string name)
278 Report.Error (122, loc, "`{0}' is inaccessible due to its protection level", name);
281 public virtual void Error_ValueCannotBeConverted (Location loc, Type t)
283 Convert.Error_CannotImplicitConversion (loc, Type, t);
286 protected static void Error_TypeDoesNotContainDefinition (Location loc, Type type, string name)
288 Report.Error (117, loc, "`{0}' does not contain a definition for `{1}'",
289 TypeManager.CSharpName (type), name);
292 ResolveFlags ExprClassToResolveFlags ()
296 case ExprClass.Namespace:
297 return ResolveFlags.Type;
299 case ExprClass.MethodGroup:
300 return ResolveFlags.MethodGroup;
302 case ExprClass.Value:
303 case ExprClass.Variable:
304 case ExprClass.PropertyAccess:
305 case ExprClass.EventAccess:
306 case ExprClass.IndexerAccess:
307 return ResolveFlags.VariableOrValue;
310 throw new Exception ("Expression " + GetType () +
311 " ExprClass is Invalid after resolve");
317 /// Resolves an expression and performs semantic analysis on it.
321 /// Currently Resolve wraps DoResolve to perform sanity
322 /// checking and assertion checking on what we expect from Resolve.
324 public Expression Resolve (EmitContext ec, ResolveFlags flags)
326 if ((flags & ResolveFlags.MaskExprClass) == ResolveFlags.Type)
327 return ResolveAsTypeStep (ec, false);
329 bool old_do_flow_analysis = ec.DoFlowAnalysis;
330 bool old_omit_struct_analysis = ec.OmitStructFlowAnalysis;
331 if ((flags & ResolveFlags.DisableFlowAnalysis) != 0)
332 ec.DoFlowAnalysis = false;
333 if ((flags & ResolveFlags.DisableStructFlowAnalysis) != 0)
334 ec.OmitStructFlowAnalysis = true;
337 bool intermediate = (flags & ResolveFlags.Intermediate) == ResolveFlags.Intermediate;
338 if (this is SimpleName)
339 e = ((SimpleName) this).DoResolve (ec, intermediate);
344 ec.DoFlowAnalysis = old_do_flow_analysis;
345 ec.OmitStructFlowAnalysis = old_omit_struct_analysis;
350 if ((flags & e.ExprClassToResolveFlags ()) == 0) {
351 e.Error_UnexpectedKind (flags, loc);
355 if (e.type == null && !(e is Namespace)) {
356 throw new Exception (
357 "Expression " + e.GetType () +
358 " did not set its type after Resolve\n" +
359 "called from: " + this.GetType ());
366 /// Resolves an expression and performs semantic analysis on it.
368 public Expression Resolve (EmitContext ec)
370 Expression e = Resolve (ec, ResolveFlags.VariableOrValue | ResolveFlags.MethodGroup);
372 if (e != null && e.eclass == ExprClass.MethodGroup && RootContext.Version == LanguageVersion.ISO_1) {
373 ((MethodGroupExpr) e).ReportUsageError ();
379 public Constant ResolveAsConstant (EmitContext ec, MemberCore mc)
381 Expression e = Resolve (ec);
383 Constant c = e as Constant;
387 EmptyCast empty = e as EmptyCast;
389 c = empty.Child as Constant;
391 // TODO: not sure about this maybe there is easier way how to use EmptyCast
400 Const.Error_ExpressionMustBeConstant (loc, mc.GetSignatureForError ());
405 /// Resolves an expression for LValue assignment
409 /// Currently ResolveLValue wraps DoResolveLValue to perform sanity
410 /// checking and assertion checking on what we expect from Resolve
412 public Expression ResolveLValue (EmitContext ec, Expression right_side, Location loc)
414 int errors = Report.Errors;
415 Expression e = DoResolveLValue (ec, right_side);
418 if (errors == Report.Errors)
419 Report.Error (131, loc, "The left-hand side of an assignment or mutating operation must be a variable, property or indexer");
424 if (e.eclass == ExprClass.Invalid)
425 throw new Exception ("Expression " + e +
426 " ExprClass is Invalid after resolve");
428 if (e.eclass == ExprClass.MethodGroup) {
429 ((MethodGroupExpr) e).ReportUsageError ();
434 throw new Exception ("Expression " + e +
435 " did not set its type after Resolve");
442 /// Emits the code for the expression
446 /// The Emit method is invoked to generate the code
447 /// for the expression.
449 public abstract void Emit (EmitContext ec);
451 public virtual void EmitBranchable (EmitContext ec, Label target, bool onTrue)
454 ec.ig.Emit (onTrue ? OpCodes.Brtrue : OpCodes.Brfalse, target);
458 /// Protected constructor. Only derivate types should
459 /// be able to be created
462 protected Expression ()
464 eclass = ExprClass.Invalid;
469 /// Returns a literalized version of a literal FieldInfo
473 /// The possible return values are:
474 /// IntConstant, UIntConstant
475 /// LongLiteral, ULongConstant
476 /// FloatConstant, DoubleConstant
479 /// The value returned is already resolved.
481 public static Constant Constantify (object v, Type t)
483 if (t == TypeManager.int32_type)
484 return new IntConstant ((int) v, Location.Null);
485 else if (t == TypeManager.uint32_type)
486 return new UIntConstant ((uint) v, Location.Null);
487 else if (t == TypeManager.int64_type)
488 return new LongConstant ((long) v, Location.Null);
489 else if (t == TypeManager.uint64_type)
490 return new ULongConstant ((ulong) v, Location.Null);
491 else if (t == TypeManager.float_type)
492 return new FloatConstant ((float) v, Location.Null);
493 else if (t == TypeManager.double_type)
494 return new DoubleConstant ((double) v, Location.Null);
495 else if (t == TypeManager.string_type)
496 return new StringConstant ((string) v, Location.Null);
497 else if (t == TypeManager.short_type)
498 return new ShortConstant ((short)v, Location.Null);
499 else if (t == TypeManager.ushort_type)
500 return new UShortConstant ((ushort)v, Location.Null);
501 else if (t == TypeManager.sbyte_type)
502 return new SByteConstant ((sbyte)v, Location.Null);
503 else if (t == TypeManager.byte_type)
504 return new ByteConstant ((byte)v, Location.Null);
505 else if (t == TypeManager.char_type)
506 return new CharConstant ((char)v, Location.Null);
507 else if (t == TypeManager.bool_type)
508 return new BoolConstant ((bool) v, Location.Null);
509 else if (t == TypeManager.decimal_type)
510 return new DecimalConstant ((decimal) v, Location.Null);
511 else if (TypeManager.IsEnumType (t)){
512 Type real_type = TypeManager.TypeToCoreType (v.GetType ());
514 real_type = System.Enum.GetUnderlyingType (real_type);
516 Constant e = Constantify (v, real_type);
518 return new EnumConstant (e, t);
519 } else if (v == null && !TypeManager.IsValueType (t))
520 return new NullLiteral (Location.Null);
522 throw new Exception ("Unknown type for constant (" + t +
527 /// Returns a fully formed expression after a MemberLookup
530 // TODO: This can be heavily cached
531 public static Expression ExprClassFromMemberInfo (EmitContext ec, MemberInfo mi, Location loc)
534 return new EventExpr ((EventInfo) mi, loc);
535 else if (mi is FieldInfo)
536 return new FieldExpr ((FieldInfo) mi, loc);
537 else if (mi is PropertyInfo)
538 return new PropertyExpr (ec, (PropertyInfo) mi, loc);
539 else if (mi is Type){
540 return new TypeExpression ((System.Type) mi, loc);
546 protected static ArrayList almostMatchedMembers = new ArrayList (4);
549 // FIXME: Probably implement a cache for (t,name,current_access_set)?
551 // This code could use some optimizations, but we need to do some
552 // measurements. For example, we could use a delegate to `flag' when
553 // something can not any longer be a method-group (because it is something
557 // If the return value is an Array, then it is an array of
560 // If the return value is an MemberInfo, it is anything, but a Method
564 // FIXME: When calling MemberLookup inside an `Invocation', we should pass
565 // the arguments here and have MemberLookup return only the methods that
566 // match the argument count/type, unlike we are doing now (we delay this
569 // This is so we can catch correctly attempts to invoke instance methods
570 // from a static body (scan for error 120 in ResolveSimpleName).
573 // FIXME: Potential optimization, have a static ArrayList
576 public static Expression MemberLookup (EmitContext ec, Type queried_type, string name,
577 MemberTypes mt, BindingFlags bf, Location loc)
579 return MemberLookup (ec, ec.ContainerType, null, queried_type, name, mt, bf, loc);
583 // Lookup type `queried_type' for code in class `container_type' with a qualifier of
584 // `qualifier_type' or null to lookup members in the current class.
587 public static Expression MemberLookup (EmitContext ec, Type container_type,
588 Type qualifier_type, Type queried_type,
589 string name, MemberTypes mt,
590 BindingFlags bf, Location loc)
592 almostMatchedMembers.Clear ();
594 MemberInfo [] mi = TypeManager.MemberLookup (container_type, qualifier_type,
595 queried_type, mt, bf, name, almostMatchedMembers);
600 int count = mi.Length;
602 if (mi [0] is MethodBase)
603 return new MethodGroupExpr (mi, loc);
608 return ExprClassFromMemberInfo (ec, mi [0], loc);
611 public const MemberTypes AllMemberTypes =
612 MemberTypes.Constructor |
616 MemberTypes.NestedType |
617 MemberTypes.Property;
619 public const BindingFlags AllBindingFlags =
620 BindingFlags.Public |
621 BindingFlags.Static |
622 BindingFlags.Instance;
624 public static Expression MemberLookup (EmitContext ec, Type queried_type,
625 string name, Location loc)
627 return MemberLookup (ec, ec.ContainerType, null, queried_type, name,
628 AllMemberTypes, AllBindingFlags, loc);
631 public static Expression MemberLookup (EmitContext ec, Type qualifier_type,
632 Type queried_type, string name, Location loc)
634 return MemberLookup (ec, ec.ContainerType, qualifier_type, queried_type,
635 name, AllMemberTypes, AllBindingFlags, loc);
638 public static Expression MethodLookup (EmitContext ec, Type queried_type,
639 string name, Location loc)
641 return MemberLookup (ec, ec.ContainerType, null, queried_type, name,
642 MemberTypes.Method, AllBindingFlags, loc);
646 /// This is a wrapper for MemberLookup that is not used to "probe", but
647 /// to find a final definition. If the final definition is not found, we
648 /// look for private members and display a useful debugging message if we
651 public static Expression MemberLookupFinal (EmitContext ec, Type qualifier_type,
652 Type queried_type, string name, Location loc)
654 return MemberLookupFinal (ec, qualifier_type, queried_type, name,
655 AllMemberTypes, AllBindingFlags, loc);
658 public static Expression MemberLookupFinal (EmitContext ec, Type qualifier_type,
659 Type queried_type, string name,
660 MemberTypes mt, BindingFlags bf,
665 int errors = Report.Errors;
667 e = MemberLookup (ec, ec.ContainerType, qualifier_type, queried_type, name, mt, bf, loc);
669 if (e == null && errors == Report.Errors)
670 // No errors were reported by MemberLookup, but there was an error.
671 MemberLookupFailed (ec, qualifier_type, queried_type, name, null, true, loc);
676 public static void MemberLookupFailed (EmitContext ec, Type qualifier_type,
677 Type queried_type, string name,
678 string class_name, bool complain_if_none_found,
681 if (almostMatchedMembers.Count != 0) {
682 for (int i = 0; i < almostMatchedMembers.Count; ++i) {
683 MemberInfo m = (MemberInfo) almostMatchedMembers [i];
684 for (int j = 0; j < i; ++j) {
685 if (m == almostMatchedMembers [j]) {
693 Type declaring_type = m.DeclaringType;
695 Report.SymbolRelatedToPreviousError (m);
696 if (qualifier_type == null) {
697 Report.Error (38, loc, "Cannot access a nonstatic member of outer type `{0}' via nested type `{1}'",
698 TypeManager.CSharpName (m.DeclaringType),
699 TypeManager.CSharpName (ec.ContainerType));
701 } else if (qualifier_type != ec.ContainerType &&
702 TypeManager.IsNestedFamilyAccessible (ec.ContainerType, declaring_type)) {
703 // Although a derived class can access protected members of
704 // its base class it cannot do so through an instance of the
705 // base class (CS1540). If the qualifier_type is a base of the
706 // ec.ContainerType and the lookup succeeds with the latter one,
707 // then we are in this situation.
708 Report.Error (1540, loc,
709 "Cannot access protected member `{0}' via a qualifier of type `{1}';"
710 + " the qualifier must be of type `{2}' (or derived from it)",
711 TypeManager.GetFullNameSignature (m),
712 TypeManager.CSharpName (qualifier_type),
713 TypeManager.CSharpName (ec.ContainerType));
715 ErrorIsInaccesible (loc, TypeManager.GetFullNameSignature (m));
718 almostMatchedMembers.Clear ();
722 MemberInfo[] lookup = TypeManager.MemberLookup (queried_type, null, queried_type,
723 AllMemberTypes, AllBindingFlags |
724 BindingFlags.NonPublic, name, null);
726 if (lookup == null) {
727 if (!complain_if_none_found)
730 if (class_name != null)
731 Report.Error (103, loc, "The name `{0}' does not exist in the context of `{1}'",
734 Error_TypeDoesNotContainDefinition (loc, queried_type, name);
738 MemberList ml = TypeManager.FindMembers (queried_type, MemberTypes.Constructor,
739 BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly, null, null);
740 if (name == ".ctor" && ml.Count == 0)
742 Report.Error (143, loc, String.Format ("The type `{0}' has no constructors defined", TypeManager.CSharpName (queried_type)));
746 ErrorIsInaccesible (loc, TypeManager.GetFullNameSignature (lookup [0]));
750 /// Returns an expression that can be used to invoke operator true
751 /// on the expression if it exists.
753 static public StaticCallExpr GetOperatorTrue (EmitContext ec, Expression e, Location loc)
755 return GetOperatorTrueOrFalse (ec, e, true, loc);
759 /// Returns an expression that can be used to invoke operator false
760 /// on the expression if it exists.
762 static public StaticCallExpr GetOperatorFalse (EmitContext ec, Expression e, Location loc)
764 return GetOperatorTrueOrFalse (ec, e, false, loc);
767 static StaticCallExpr GetOperatorTrueOrFalse (EmitContext ec, Expression e, bool is_true, Location loc)
770 Expression operator_group;
772 operator_group = MethodLookup (ec, e.Type, is_true ? "op_True" : "op_False", loc);
773 if (operator_group == null)
776 ArrayList arguments = new ArrayList ();
777 arguments.Add (new Argument (e, Argument.AType.Expression));
778 method = Invocation.OverloadResolve (
779 ec, (MethodGroupExpr) operator_group, arguments, false, loc);
784 return new StaticCallExpr ((MethodInfo) method, arguments, loc);
788 /// Resolves the expression `e' into a boolean expression: either through
789 /// an implicit conversion, or through an `operator true' invocation
791 public static Expression ResolveBoolean (EmitContext ec, Expression e, Location loc)
797 if (e.Type == TypeManager.bool_type)
800 Expression converted = Convert.ImplicitConversion (ec, e, TypeManager.bool_type, Location.Null);
802 if (converted != null)
806 // If no implicit conversion to bool exists, try using `operator true'
808 Expression operator_true = Expression.GetOperatorTrue (ec, e, loc);
809 if (operator_true == null){
810 Report.Error (31, loc, "Can not convert the expression to a boolean");
813 return operator_true;
816 string ExprClassName ()
819 case ExprClass.Invalid:
821 case ExprClass.Value:
823 case ExprClass.Variable:
825 case ExprClass.Namespace:
829 case ExprClass.MethodGroup:
830 return "method group";
831 case ExprClass.PropertyAccess:
832 return "property access";
833 case ExprClass.EventAccess:
834 return "event access";
835 case ExprClass.IndexerAccess:
836 return "indexer access";
837 case ExprClass.Nothing:
840 throw new Exception ("Should not happen");
844 /// Reports that we were expecting `expr' to be of class `expected'
846 public void Error_UnexpectedKind (EmitContext ec, string expected, Location loc)
848 Error_UnexpectedKind (ec, expected, ExprClassName (), loc);
851 public void Error_UnexpectedKind (EmitContext ec, string expected, string was, Location loc)
853 string name = GetSignatureForError ();
855 name = ec.DeclSpace.GetSignatureForError () + '.' + name;
857 Report.Error (118, loc, "`{0}' is a `{1}' but a `{2}' was expected",
858 name, was, expected);
861 public void Error_UnexpectedKind (ResolveFlags flags, Location loc)
863 string [] valid = new string [4];
866 if ((flags & ResolveFlags.VariableOrValue) != 0) {
867 valid [count++] = "variable";
868 valid [count++] = "value";
871 if ((flags & ResolveFlags.Type) != 0)
872 valid [count++] = "type";
874 if ((flags & ResolveFlags.MethodGroup) != 0)
875 valid [count++] = "method group";
878 valid [count++] = "unknown";
880 StringBuilder sb = new StringBuilder (valid [0]);
881 for (int i = 1; i < count - 1; i++) {
883 sb.Append (valid [i]);
886 sb.Append ("' or `");
887 sb.Append (valid [count - 1]);
890 Report.Error (119, loc,
891 "Expression denotes a `{0}', where a `{1}' was expected", ExprClassName (), sb);
894 public static void UnsafeError (Location loc)
896 Report.Error (214, loc, "Pointers and fixed size buffers may only be used in an unsafe context");
900 // Load the object from the pointer.
902 public static void LoadFromPtr (ILGenerator ig, Type t)
904 if (t == TypeManager.int32_type)
905 ig.Emit (OpCodes.Ldind_I4);
906 else if (t == TypeManager.uint32_type)
907 ig.Emit (OpCodes.Ldind_U4);
908 else if (t == TypeManager.short_type)
909 ig.Emit (OpCodes.Ldind_I2);
910 else if (t == TypeManager.ushort_type)
911 ig.Emit (OpCodes.Ldind_U2);
912 else if (t == TypeManager.char_type)
913 ig.Emit (OpCodes.Ldind_U2);
914 else if (t == TypeManager.byte_type)
915 ig.Emit (OpCodes.Ldind_U1);
916 else if (t == TypeManager.sbyte_type)
917 ig.Emit (OpCodes.Ldind_I1);
918 else if (t == TypeManager.uint64_type)
919 ig.Emit (OpCodes.Ldind_I8);
920 else if (t == TypeManager.int64_type)
921 ig.Emit (OpCodes.Ldind_I8);
922 else if (t == TypeManager.float_type)
923 ig.Emit (OpCodes.Ldind_R4);
924 else if (t == TypeManager.double_type)
925 ig.Emit (OpCodes.Ldind_R8);
926 else if (t == TypeManager.bool_type)
927 ig.Emit (OpCodes.Ldind_I1);
928 else if (t == TypeManager.intptr_type)
929 ig.Emit (OpCodes.Ldind_I);
930 else if (TypeManager.IsEnumType (t)) {
931 if (t == TypeManager.enum_type)
932 ig.Emit (OpCodes.Ldind_Ref);
934 LoadFromPtr (ig, TypeManager.EnumToUnderlying (t));
935 } else if (t.IsValueType)
936 ig.Emit (OpCodes.Ldobj, t);
937 else if (t.IsPointer)
938 ig.Emit (OpCodes.Ldind_I);
940 ig.Emit (OpCodes.Ldind_Ref);
944 // The stack contains the pointer and the value of type `type'
946 public static void StoreFromPtr (ILGenerator ig, Type type)
948 if (TypeManager.IsEnumType (type))
949 type = TypeManager.EnumToUnderlying (type);
950 if (type == TypeManager.int32_type || type == TypeManager.uint32_type)
951 ig.Emit (OpCodes.Stind_I4);
952 else if (type == TypeManager.int64_type || type == TypeManager.uint64_type)
953 ig.Emit (OpCodes.Stind_I8);
954 else if (type == TypeManager.char_type || type == TypeManager.short_type ||
955 type == TypeManager.ushort_type)
956 ig.Emit (OpCodes.Stind_I2);
957 else if (type == TypeManager.float_type)
958 ig.Emit (OpCodes.Stind_R4);
959 else if (type == TypeManager.double_type)
960 ig.Emit (OpCodes.Stind_R8);
961 else if (type == TypeManager.byte_type || type == TypeManager.sbyte_type ||
962 type == TypeManager.bool_type)
963 ig.Emit (OpCodes.Stind_I1);
964 else if (type == TypeManager.intptr_type)
965 ig.Emit (OpCodes.Stind_I);
966 else if (type.IsValueType)
967 ig.Emit (OpCodes.Stobj, type);
969 ig.Emit (OpCodes.Stind_Ref);
973 // Returns the size of type `t' if known, otherwise, 0
975 public static int GetTypeSize (Type t)
977 t = TypeManager.TypeToCoreType (t);
978 if (t == TypeManager.int32_type ||
979 t == TypeManager.uint32_type ||
980 t == TypeManager.float_type)
982 else if (t == TypeManager.int64_type ||
983 t == TypeManager.uint64_type ||
984 t == TypeManager.double_type)
986 else if (t == TypeManager.byte_type ||
987 t == TypeManager.sbyte_type ||
988 t == TypeManager.bool_type)
990 else if (t == TypeManager.short_type ||
991 t == TypeManager.char_type ||
992 t == TypeManager.ushort_type)
994 else if (t == TypeManager.decimal_type)
1000 public static void Error_NegativeArrayIndex (Location loc)
1002 Report.Error (248, loc, "Cannot create an array with a negative size");
1005 protected void Error_CannotCallAbstractBase (string name)
1007 Report.Error (205, loc, "Cannot call an abstract base member `{0}'", name);
1011 // Converts `source' to an int, uint, long or ulong.
1013 public Expression ExpressionToArrayArgument (EmitContext ec, Expression source, Location loc)
1017 bool old_checked = ec.CheckState;
1018 ec.CheckState = true;
1020 target = Convert.ImplicitConversion (ec, source, TypeManager.int32_type, loc);
1021 if (target == null){
1022 target = Convert.ImplicitConversion (ec, source, TypeManager.uint32_type, loc);
1023 if (target == null){
1024 target = Convert.ImplicitConversion (ec, source, TypeManager.int64_type, loc);
1025 if (target == null){
1026 target = Convert.ImplicitConversion (ec, source, TypeManager.uint64_type, loc);
1028 Convert.Error_CannotImplicitConversion (loc, source.Type, TypeManager.int32_type);
1032 ec.CheckState = old_checked;
1035 // Only positive constants are allowed at compile time
1037 if (target is Constant){
1038 if (target is IntConstant){
1039 if (((IntConstant) target).Value < 0){
1040 Error_NegativeArrayIndex (loc);
1045 if (target is LongConstant){
1046 if (((LongConstant) target).Value < 0){
1047 Error_NegativeArrayIndex (loc);
1060 /// This is just a base class for expressions that can
1061 /// appear on statements (invocations, object creation,
1062 /// assignments, post/pre increment and decrement). The idea
1063 /// being that they would support an extra Emition interface that
1064 /// does not leave a result on the stack.
1066 public abstract class ExpressionStatement : Expression {
1068 public virtual ExpressionStatement ResolveStatement (EmitContext ec)
1070 Expression e = Resolve (ec);
1074 ExpressionStatement es = e as ExpressionStatement;
1076 Error (201, "Only assignment, call, increment, decrement and new object " +
1077 "expressions can be used as a statement");
1083 /// Requests the expression to be emitted in a `statement'
1084 /// context. This means that no new value is left on the
1085 /// stack after invoking this method (constrasted with
1086 /// Emit that will always leave a value on the stack).
1088 public abstract void EmitStatement (EmitContext ec);
1092 /// This kind of cast is used to encapsulate the child
1093 /// whose type is child.Type into an expression that is
1094 /// reported to return "return_type". This is used to encapsulate
1095 /// expressions which have compatible types, but need to be dealt
1096 /// at higher levels with.
1098 /// For example, a "byte" expression could be encapsulated in one
1099 /// of these as an "unsigned int". The type for the expression
1100 /// would be "unsigned int".
1103 public class EmptyCast : Expression {
1104 protected Expression child;
1106 public Expression Child {
1112 public EmptyCast (Expression child, Type return_type)
1114 eclass = child.eclass;
1115 loc = child.Location;
1120 public override Expression DoResolve (EmitContext ec)
1122 // This should never be invoked, we are born in fully
1123 // initialized state.
1128 public override void Emit (EmitContext ec)
1134 /// This is a numeric cast to a Decimal
1136 public class CastToDecimal : EmptyCast {
1138 MethodInfo conversion_operator;
1140 public CastToDecimal (EmitContext ec, Expression child)
1141 : this (ec, child, false)
1145 public CastToDecimal (EmitContext ec, Expression child, bool find_explicit)
1146 : base (child, TypeManager.decimal_type)
1148 conversion_operator = GetConversionOperator (ec, find_explicit);
1150 if (conversion_operator == null)
1151 Convert.Error_CannotImplicitConversion (loc, child.Type, type);
1154 // Returns the implicit operator that converts from
1155 // 'child.Type' to System.Decimal.
1156 MethodInfo GetConversionOperator (EmitContext ec, bool find_explicit)
1158 string operator_name = "op_Implicit";
1161 operator_name = "op_Explicit";
1163 MethodGroupExpr opers = Expression.MethodLookup (
1164 ec, type, operator_name, loc) as MethodGroupExpr;
1167 Convert.Error_CannotImplicitConversion (loc, child.Type, type);
1169 foreach (MethodInfo oper in opers.Methods) {
1170 ParameterData pd = TypeManager.GetParameterData (oper);
1172 if (pd.ParameterType (0) == child.Type && oper.ReturnType == type)
1178 public override void Emit (EmitContext ec)
1180 ILGenerator ig = ec.ig;
1183 ig.Emit (OpCodes.Call, conversion_operator);
1187 /// This is an explicit numeric cast from a Decimal
1189 public class CastFromDecimal : EmptyCast
1191 MethodInfo conversion_operator;
1192 public CastFromDecimal (EmitContext ec, Expression child, Type return_type)
1193 : base (child, return_type)
1195 if (child.Type != TypeManager.decimal_type)
1196 throw new InternalErrorException (
1197 "The expected type is Decimal, instead it is " + child.Type.FullName);
1199 conversion_operator = GetConversionOperator (ec);
1200 if (conversion_operator == null)
1201 Convert.Error_CannotImplicitConversion (loc, child.Type, type);
1204 // Returns the explicit operator that converts from an
1205 // express of type System.Decimal to 'type'.
1206 MethodInfo GetConversionOperator (EmitContext ec)
1208 MethodGroupExpr opers = Expression.MethodLookup (
1209 ec, child.Type, "op_Explicit", loc) as MethodGroupExpr;
1212 Convert.Error_CannotImplicitConversion (loc, child.Type, type);
1214 foreach (MethodInfo oper in opers.Methods) {
1215 ParameterData pd = TypeManager.GetParameterData (oper);
1217 if (pd.ParameterType (0) == child.Type && oper.ReturnType == type)
1223 public override void Emit (EmitContext ec)
1225 ILGenerator ig = ec.ig;
1228 ig.Emit (OpCodes.Call, conversion_operator);
1233 // We need to special case this since an empty cast of
1234 // a NullLiteral is still a Constant
1236 public class NullCast : Constant {
1237 protected Expression child;
1239 public NullCast (Expression child, Type return_type):
1240 base (Location.Null)
1242 eclass = child.eclass;
1247 override public string AsString ()
1252 public override object GetValue ()
1257 public override Expression DoResolve (EmitContext ec)
1259 // This should never be invoked, we are born in fully
1260 // initialized state.
1265 public override void Emit (EmitContext ec)
1270 public override Constant Increment ()
1272 throw new NotSupportedException ();
1275 public override bool IsDefaultValue {
1277 throw new NotImplementedException ();
1281 public override bool IsNegative {
1290 /// This class is used to wrap literals which belong inside Enums
1292 public class EnumConstant : Constant {
1293 public Constant Child;
1295 public EnumConstant (Constant child, Type enum_type):
1296 base (child.Location)
1298 eclass = child.eclass;
1303 public override Expression DoResolve (EmitContext ec)
1305 // This should never be invoked, we are born in fully
1306 // initialized state.
1311 public override void Emit (EmitContext ec)
1316 public override object GetValue ()
1318 return Child.GetValue ();
1321 public override object GetTypedValue ()
1323 // FIXME: runtime is not ready to work with just emited enums
1324 if (!RootContext.StdLib) {
1325 return Child.GetValue ();
1328 return System.Enum.ToObject (type, Child.GetValue ());
1331 public override void Error_ValueCannotBeConverted (Location loc, Type t)
1333 Convert.Error_CannotImplicitConversion (loc, Type, t);
1336 public override string AsString ()
1338 return Child.AsString ();
1341 public override DoubleConstant ConvertToDouble ()
1343 return Child.ConvertToDouble ();
1346 public override FloatConstant ConvertToFloat ()
1348 return Child.ConvertToFloat ();
1351 public override ULongConstant ConvertToULong ()
1353 return Child.ConvertToULong ();
1356 public override LongConstant ConvertToLong ()
1358 return Child.ConvertToLong ();
1361 public override UIntConstant ConvertToUInt ()
1363 return Child.ConvertToUInt ();
1366 public override IntConstant ConvertToInt ()
1368 return Child.ConvertToInt ();
1371 public override Constant Increment()
1373 return new EnumConstant (Child.Increment (), type);
1376 public override bool IsDefaultValue {
1378 return Child.IsDefaultValue;
1382 public override bool IsZeroInteger {
1383 get { return Child.IsZeroInteger; }
1386 public override bool IsNegative {
1388 return Child.IsNegative;
1392 public override Constant ToType (Type type, Location loc)
1395 // This is workaround of mono bug. It can be removed when the latest corlib spreads enough
1396 if (TypeManager.IsEnumType (type.UnderlyingSystemType))
1399 if (type.UnderlyingSystemType != Child.Type)
1400 Child = Child.ToType (type.UnderlyingSystemType, loc);
1404 if (!Convert.ImplicitStandardConversionExists (Convert.ConstantEC, this, type)){
1405 Error_ValueCannotBeConverted (loc, type);
1409 return Child.ToType (type, loc);
1415 /// This kind of cast is used to encapsulate Value Types in objects.
1417 /// The effect of it is to box the value type emitted by the previous
1420 public class BoxedCast : EmptyCast {
1422 public BoxedCast (Expression expr, Type target_type)
1423 : base (expr, target_type)
1425 eclass = ExprClass.Value;
1428 public override Expression DoResolve (EmitContext ec)
1430 // This should never be invoked, we are born in fully
1431 // initialized state.
1436 public override void Emit (EmitContext ec)
1440 ec.ig.Emit (OpCodes.Box, child.Type);
1444 public class UnboxCast : EmptyCast {
1445 public UnboxCast (Expression expr, Type return_type)
1446 : base (expr, return_type)
1450 public override Expression DoResolve (EmitContext ec)
1452 // This should never be invoked, we are born in fully
1453 // initialized state.
1458 public override void Emit (EmitContext ec)
1461 ILGenerator ig = ec.ig;
1464 ig.Emit (OpCodes.Unbox, t);
1466 LoadFromPtr (ig, t);
1471 /// This is used to perform explicit numeric conversions.
1473 /// Explicit numeric conversions might trigger exceptions in a checked
1474 /// context, so they should generate the conv.ovf opcodes instead of
1477 public class ConvCast : EmptyCast {
1478 public enum Mode : byte {
1479 I1_U1, I1_U2, I1_U4, I1_U8, I1_CH,
1481 I2_I1, I2_U1, I2_U2, I2_U4, I2_U8, I2_CH,
1482 U2_I1, U2_U1, U2_I2, U2_CH,
1483 I4_I1, I4_U1, I4_I2, I4_U2, I4_U4, I4_U8, I4_CH,
1484 U4_I1, U4_U1, U4_I2, U4_U2, U4_I4, U4_CH,
1485 I8_I1, I8_U1, I8_I2, I8_U2, I8_I4, I8_U4, I8_U8, I8_CH,
1486 U8_I1, U8_U1, U8_I2, U8_U2, U8_I4, U8_U4, U8_I8, U8_CH,
1487 CH_I1, CH_U1, CH_I2,
1488 R4_I1, R4_U1, R4_I2, R4_U2, R4_I4, R4_U4, R4_I8, R4_U8, R4_CH,
1489 R8_I1, R8_U1, R8_I2, R8_U2, R8_I4, R8_U4, R8_I8, R8_U8, R8_CH, R8_R4
1495 public ConvCast (EmitContext ec, Expression child, Type return_type, Mode m)
1496 : base (child, return_type)
1498 checked_state = ec.CheckState;
1502 public override Expression DoResolve (EmitContext ec)
1504 // This should never be invoked, we are born in fully
1505 // initialized state.
1510 public override string ToString ()
1512 return String.Format ("ConvCast ({0}, {1})", mode, child);
1515 public override void Emit (EmitContext ec)
1517 ILGenerator ig = ec.ig;
1523 case Mode.I1_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1524 case Mode.I1_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1525 case Mode.I1_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1526 case Mode.I1_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1527 case Mode.I1_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1529 case Mode.U1_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1530 case Mode.U1_CH: /* nothing */ break;
1532 case Mode.I2_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1533 case Mode.I2_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1534 case Mode.I2_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1535 case Mode.I2_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1536 case Mode.I2_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1537 case Mode.I2_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1539 case Mode.U2_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1540 case Mode.U2_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
1541 case Mode.U2_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
1542 case Mode.U2_CH: /* nothing */ break;
1544 case Mode.I4_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1545 case Mode.I4_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1546 case Mode.I4_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
1547 case Mode.I4_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1548 case Mode.I4_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1549 case Mode.I4_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1550 case Mode.I4_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1552 case Mode.U4_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1553 case Mode.U4_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
1554 case Mode.U4_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
1555 case Mode.U4_U2: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
1556 case Mode.U4_I4: ig.Emit (OpCodes.Conv_Ovf_I4_Un); break;
1557 case Mode.U4_CH: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
1559 case Mode.I8_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1560 case Mode.I8_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1561 case Mode.I8_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
1562 case Mode.I8_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1563 case Mode.I8_I4: ig.Emit (OpCodes.Conv_Ovf_I4); break;
1564 case Mode.I8_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1565 case Mode.I8_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1566 case Mode.I8_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1568 case Mode.U8_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1569 case Mode.U8_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
1570 case Mode.U8_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
1571 case Mode.U8_U2: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
1572 case Mode.U8_I4: ig.Emit (OpCodes.Conv_Ovf_I4_Un); break;
1573 case Mode.U8_U4: ig.Emit (OpCodes.Conv_Ovf_U4_Un); break;
1574 case Mode.U8_I8: ig.Emit (OpCodes.Conv_Ovf_I8_Un); break;
1575 case Mode.U8_CH: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
1577 case Mode.CH_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1578 case Mode.CH_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
1579 case Mode.CH_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
1581 case Mode.R4_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1582 case Mode.R4_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1583 case Mode.R4_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
1584 case Mode.R4_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1585 case Mode.R4_I4: ig.Emit (OpCodes.Conv_Ovf_I4); break;
1586 case Mode.R4_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1587 case Mode.R4_I8: ig.Emit (OpCodes.Conv_Ovf_I8); break;
1588 case Mode.R4_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1589 case Mode.R4_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1591 case Mode.R8_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1592 case Mode.R8_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1593 case Mode.R8_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
1594 case Mode.R8_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1595 case Mode.R8_I4: ig.Emit (OpCodes.Conv_Ovf_I4); break;
1596 case Mode.R8_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1597 case Mode.R8_I8: ig.Emit (OpCodes.Conv_Ovf_I8); break;
1598 case Mode.R8_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1599 case Mode.R8_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1600 case Mode.R8_R4: ig.Emit (OpCodes.Conv_R4); break;
1604 case Mode.I1_U1: ig.Emit (OpCodes.Conv_U1); break;
1605 case Mode.I1_U2: ig.Emit (OpCodes.Conv_U2); break;
1606 case Mode.I1_U4: ig.Emit (OpCodes.Conv_U4); break;
1607 case Mode.I1_U8: ig.Emit (OpCodes.Conv_I8); break;
1608 case Mode.I1_CH: ig.Emit (OpCodes.Conv_U2); break;
1610 case Mode.U1_I1: ig.Emit (OpCodes.Conv_I1); break;
1611 case Mode.U1_CH: ig.Emit (OpCodes.Conv_U2); break;
1613 case Mode.I2_I1: ig.Emit (OpCodes.Conv_I1); break;
1614 case Mode.I2_U1: ig.Emit (OpCodes.Conv_U1); break;
1615 case Mode.I2_U2: ig.Emit (OpCodes.Conv_U2); break;
1616 case Mode.I2_U4: ig.Emit (OpCodes.Conv_U4); break;
1617 case Mode.I2_U8: ig.Emit (OpCodes.Conv_I8); break;
1618 case Mode.I2_CH: ig.Emit (OpCodes.Conv_U2); break;
1620 case Mode.U2_I1: ig.Emit (OpCodes.Conv_I1); break;
1621 case Mode.U2_U1: ig.Emit (OpCodes.Conv_U1); break;
1622 case Mode.U2_I2: ig.Emit (OpCodes.Conv_I2); break;
1623 case Mode.U2_CH: /* nothing */ break;
1625 case Mode.I4_I1: ig.Emit (OpCodes.Conv_I1); break;
1626 case Mode.I4_U1: ig.Emit (OpCodes.Conv_U1); break;
1627 case Mode.I4_I2: ig.Emit (OpCodes.Conv_I2); break;
1628 case Mode.I4_U4: /* nothing */ break;
1629 case Mode.I4_U2: ig.Emit (OpCodes.Conv_U2); break;
1630 case Mode.I4_U8: ig.Emit (OpCodes.Conv_I8); break;
1631 case Mode.I4_CH: ig.Emit (OpCodes.Conv_U2); break;
1633 case Mode.U4_I1: ig.Emit (OpCodes.Conv_I1); break;
1634 case Mode.U4_U1: ig.Emit (OpCodes.Conv_U1); break;
1635 case Mode.U4_I2: ig.Emit (OpCodes.Conv_I2); break;
1636 case Mode.U4_U2: ig.Emit (OpCodes.Conv_U2); break;
1637 case Mode.U4_I4: /* nothing */ break;
1638 case Mode.U4_CH: ig.Emit (OpCodes.Conv_U2); break;
1640 case Mode.I8_I1: ig.Emit (OpCodes.Conv_I1); break;
1641 case Mode.I8_U1: ig.Emit (OpCodes.Conv_U1); break;
1642 case Mode.I8_I2: ig.Emit (OpCodes.Conv_I2); break;
1643 case Mode.I8_U2: ig.Emit (OpCodes.Conv_U2); break;
1644 case Mode.I8_I4: ig.Emit (OpCodes.Conv_I4); break;
1645 case Mode.I8_U4: ig.Emit (OpCodes.Conv_U4); break;
1646 case Mode.I8_U8: /* nothing */ break;
1647 case Mode.I8_CH: ig.Emit (OpCodes.Conv_U2); break;
1649 case Mode.U8_I1: ig.Emit (OpCodes.Conv_I1); break;
1650 case Mode.U8_U1: ig.Emit (OpCodes.Conv_U1); break;
1651 case Mode.U8_I2: ig.Emit (OpCodes.Conv_I2); break;
1652 case Mode.U8_U2: ig.Emit (OpCodes.Conv_U2); break;
1653 case Mode.U8_I4: ig.Emit (OpCodes.Conv_I4); break;
1654 case Mode.U8_U4: ig.Emit (OpCodes.Conv_U4); break;
1655 case Mode.U8_I8: /* nothing */ break;
1656 case Mode.U8_CH: ig.Emit (OpCodes.Conv_U2); break;
1658 case Mode.CH_I1: ig.Emit (OpCodes.Conv_I1); break;
1659 case Mode.CH_U1: ig.Emit (OpCodes.Conv_U1); break;
1660 case Mode.CH_I2: ig.Emit (OpCodes.Conv_I2); break;
1662 case Mode.R4_I1: ig.Emit (OpCodes.Conv_I1); break;
1663 case Mode.R4_U1: ig.Emit (OpCodes.Conv_U1); break;
1664 case Mode.R4_I2: ig.Emit (OpCodes.Conv_I2); break;
1665 case Mode.R4_U2: ig.Emit (OpCodes.Conv_U2); break;
1666 case Mode.R4_I4: ig.Emit (OpCodes.Conv_I4); break;
1667 case Mode.R4_U4: ig.Emit (OpCodes.Conv_U4); break;
1668 case Mode.R4_I8: ig.Emit (OpCodes.Conv_I8); break;
1669 case Mode.R4_U8: ig.Emit (OpCodes.Conv_U8); break;
1670 case Mode.R4_CH: ig.Emit (OpCodes.Conv_U2); break;
1672 case Mode.R8_I1: ig.Emit (OpCodes.Conv_I1); break;
1673 case Mode.R8_U1: ig.Emit (OpCodes.Conv_U1); break;
1674 case Mode.R8_I2: ig.Emit (OpCodes.Conv_I2); break;
1675 case Mode.R8_U2: ig.Emit (OpCodes.Conv_U2); break;
1676 case Mode.R8_I4: ig.Emit (OpCodes.Conv_I4); break;
1677 case Mode.R8_U4: ig.Emit (OpCodes.Conv_U4); break;
1678 case Mode.R8_I8: ig.Emit (OpCodes.Conv_I8); break;
1679 case Mode.R8_U8: ig.Emit (OpCodes.Conv_U8); break;
1680 case Mode.R8_CH: ig.Emit (OpCodes.Conv_U2); break;
1681 case Mode.R8_R4: ig.Emit (OpCodes.Conv_R4); break;
1687 public class OpcodeCast : EmptyCast {
1691 public OpcodeCast (Expression child, Type return_type, OpCode op)
1692 : base (child, return_type)
1696 second_valid = false;
1699 public OpcodeCast (Expression child, Type return_type, OpCode op, OpCode op2)
1700 : base (child, return_type)
1705 second_valid = true;
1708 public override Expression DoResolve (EmitContext ec)
1710 // This should never be invoked, we are born in fully
1711 // initialized state.
1716 public override void Emit (EmitContext ec)
1727 /// This kind of cast is used to encapsulate a child and cast it
1728 /// to the class requested
1730 public class ClassCast : EmptyCast {
1731 public ClassCast (Expression child, Type return_type)
1732 : base (child, return_type)
1737 public override Expression DoResolve (EmitContext ec)
1739 // This should never be invoked, we are born in fully
1740 // initialized state.
1745 public override void Emit (EmitContext ec)
1749 ec.ig.Emit (OpCodes.Castclass, type);
1755 /// SimpleName expressions are formed of a single word and only happen at the beginning
1756 /// of a dotted-name.
1758 public class SimpleName : Expression {
1762 public SimpleName (string name, Location l)
1768 public static void Error_ObjectRefRequired (EmitContext ec, Location l, string name)
1770 if (ec.IsFieldInitializer)
1771 Report.Error (236, l,
1772 "A field initializer cannot reference the nonstatic field, method, or property `{0}'",
1775 if (name.LastIndexOf ('.') > 0)
1776 name = name.Substring (name.LastIndexOf ('.') + 1);
1779 120, l, "`{0}': An object reference is required for the nonstatic field, method or property",
1784 public bool IdenticalNameAndTypeName (EmitContext ec, Expression resolved_to, Location loc)
1786 return resolved_to != null && resolved_to.Type != null &&
1787 resolved_to.Type.Name == Name &&
1788 (ec.DeclSpace.LookupType (Name, loc, /* ignore_cs0104 = */ true) != null);
1791 public override Expression DoResolve (EmitContext ec)
1793 return SimpleNameResolve (ec, null, false);
1796 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
1798 return SimpleNameResolve (ec, right_side, false);
1802 public Expression DoResolve (EmitContext ec, bool intermediate)
1804 return SimpleNameResolve (ec, null, intermediate);
1807 public override FullNamedExpression ResolveAsTypeStep (EmitContext ec, bool silent)
1809 int errors = Report.Errors;
1810 FullNamedExpression fne = ec.DeclSpace.LookupType (Name, loc, /*ignore_cs0104=*/ false);
1814 if (silent || errors != Report.Errors)
1817 MemberCore mc = ec.DeclSpace.GetDefinition (Name);
1819 Error_UnexpectedKind (ec, "type", GetMemberType (mc), loc);
1821 NamespaceEntry.Error_NamespaceNotFound (loc, Name);
1827 // TODO: I am still not convinced about this. If someone else will need it
1828 // implement this as virtual property in MemberCore hierarchy
1829 string GetMemberType (MemberCore mc)
1831 if (mc is PropertyBase)
1835 if (mc is FieldBase)
1841 Expression SimpleNameResolve (EmitContext ec, Expression right_side, bool intermediate)
1847 Expression e = DoSimpleNameResolve (ec, right_side, intermediate);
1851 if (ec.CurrentBlock == null || ec.CurrentBlock.CheckInvariantMeaningInBlock (Name, e, Location))
1858 /// 7.5.2: Simple Names.
1860 /// Local Variables and Parameters are handled at
1861 /// parse time, so they never occur as SimpleNames.
1863 /// The `intermediate' flag is used by MemberAccess only
1864 /// and it is used to inform us that it is ok for us to
1865 /// avoid the static check, because MemberAccess might end
1866 /// up resolving the Name as a Type name and the access as
1867 /// a static type access.
1869 /// ie: Type Type; .... { Type.GetType (""); }
1871 /// Type is both an instance variable and a Type; Type.GetType
1872 /// is the static method not an instance method of type.
1874 Expression DoSimpleNameResolve (EmitContext ec, Expression right_side, bool intermediate)
1876 Expression e = null;
1879 // Stage 1: Performed by the parser (binding to locals or parameters).
1881 Block current_block = ec.CurrentBlock;
1882 if (current_block != null){
1883 LocalInfo vi = current_block.GetLocalInfo (Name);
1885 LocalVariableReference var = new LocalVariableReference (ec.CurrentBlock, Name, loc);
1886 if (right_side != null) {
1887 return var.ResolveLValue (ec, right_side, loc);
1889 ResolveFlags rf = ResolveFlags.VariableOrValue;
1891 rf |= ResolveFlags.DisableFlowAnalysis;
1892 return var.Resolve (ec, rf);
1896 ParameterReference pref = current_block.Toplevel.GetParameterReference (Name, loc);
1898 if (right_side != null)
1899 return pref.ResolveLValue (ec, right_side, loc);
1901 return pref.Resolve (ec);
1906 // Stage 2: Lookup members
1909 DeclSpace lookup_ds = ec.DeclSpace;
1910 Type almost_matched_type = null;
1911 ArrayList almost_matched = null;
1913 if (lookup_ds.TypeBuilder == null)
1916 e = MemberLookup (ec, lookup_ds.TypeBuilder, Name, loc);
1920 if (almost_matched == null && almostMatchedMembers.Count > 0) {
1921 almost_matched_type = lookup_ds.TypeBuilder;
1922 almost_matched = (ArrayList) almostMatchedMembers.Clone ();
1925 lookup_ds =lookup_ds.Parent;
1926 } while (lookup_ds != null);
1928 if (e == null && ec.ContainerType != null)
1929 e = MemberLookup (ec, ec.ContainerType, Name, loc);
1932 if (almost_matched == null && almostMatchedMembers.Count > 0) {
1933 almost_matched_type = ec.ContainerType;
1934 almost_matched = (ArrayList) almostMatchedMembers.Clone ();
1936 e = ResolveAsTypeStep (ec, false);
1940 if (almost_matched != null)
1941 almostMatchedMembers = almost_matched;
1942 if (almost_matched_type == null)
1943 almost_matched_type = ec.ContainerType;
1944 MemberLookupFailed (ec, null, almost_matched_type, ((SimpleName) this).Name, ec.DeclSpace.Name, true, loc);
1951 if (e is MemberExpr) {
1952 MemberExpr me = (MemberExpr) e;
1955 if (me.IsInstance) {
1956 if (ec.IsStatic || ec.IsFieldInitializer) {
1958 // Note that an MemberExpr can be both IsInstance and IsStatic.
1959 // An unresolved MethodGroupExpr can contain both kinds of methods
1960 // and each predicate is true if the MethodGroupExpr contains
1961 // at least one of that kind of method.
1965 (!intermediate || !IdenticalNameAndTypeName (ec, me, loc))) {
1966 Error_ObjectRefRequired (ec, loc, me.GetSignatureForError ());
1971 // Pass the buck to MemberAccess and Invocation.
1973 left = EmptyExpression.Null;
1975 left = ec.GetThis (loc);
1978 left = new TypeExpression (ec.ContainerType, loc);
1981 e = me.ResolveMemberAccess (ec, left, loc, null);
1985 me = e as MemberExpr;
1990 TypeManager.IsNestedFamilyAccessible (me.InstanceExpression.Type, me.DeclaringType) &&
1991 me.InstanceExpression.Type != me.DeclaringType &&
1992 !me.InstanceExpression.Type.IsSubclassOf (me.DeclaringType) &&
1993 (!intermediate || !IdenticalNameAndTypeName (ec, e, loc))) {
1994 Report.Error (38, loc, "Cannot access a nonstatic member of outer type `{0}' via nested type `{1}'",
1995 TypeManager.CSharpName (me.DeclaringType), TypeManager.CSharpName (me.InstanceExpression.Type));
1999 return (right_side != null)
2000 ? me.DoResolveLValue (ec, right_side)
2001 : me.DoResolve (ec);
2007 public override void Emit (EmitContext ec)
2010 // If this is ever reached, then we failed to
2011 // find the name as a namespace
2014 Error (103, "The name `" + Name +
2015 "' does not exist in the class `" +
2016 ec.DeclSpace.Name + "'");
2019 public override string ToString ()
2024 public override string GetSignatureForError ()
2031 /// Represents a namespace or a type. The name of the class was inspired by
2032 /// section 10.8.1 (Fully Qualified Names).
2034 public abstract class FullNamedExpression : Expression {
2035 public override FullNamedExpression ResolveAsTypeStep (EmitContext ec, bool silent)
2040 public abstract string FullName {
2046 /// Fully resolved expression that evaluates to a type
2048 public abstract class TypeExpr : FullNamedExpression {
2049 override public FullNamedExpression ResolveAsTypeStep (EmitContext ec, bool silent)
2051 TypeExpr t = DoResolveAsTypeStep (ec);
2055 eclass = ExprClass.Type;
2059 override public Expression DoResolve (EmitContext ec)
2061 return ResolveAsTypeTerminal (ec, false);
2064 override public void Emit (EmitContext ec)
2066 throw new Exception ("Should never be called");
2069 public virtual bool CheckAccessLevel (DeclSpace ds)
2071 return ds.CheckAccessLevel (Type);
2074 public virtual bool AsAccessible (DeclSpace ds, int flags)
2076 return ds.AsAccessible (Type, flags);
2079 public virtual bool IsClass {
2080 get { return Type.IsClass; }
2083 public virtual bool IsValueType {
2084 get { return Type.IsValueType; }
2087 public virtual bool IsInterface {
2088 get { return Type.IsInterface; }
2091 public virtual bool IsSealed {
2092 get { return Type.IsSealed; }
2095 public virtual bool CanInheritFrom ()
2097 if (Type == TypeManager.enum_type ||
2098 (Type == TypeManager.value_type && RootContext.StdLib) ||
2099 Type == TypeManager.multicast_delegate_type ||
2100 Type == TypeManager.delegate_type ||
2101 Type == TypeManager.array_type)
2107 public abstract TypeExpr DoResolveAsTypeStep (EmitContext ec);
2109 public virtual Type ResolveType (EmitContext ec)
2111 TypeExpr t = ResolveAsTypeTerminal (ec, false);
2118 public abstract string Name {
2122 public override bool Equals (object obj)
2124 TypeExpr tobj = obj as TypeExpr;
2128 return Type == tobj.Type;
2131 public override int GetHashCode ()
2133 return Type.GetHashCode ();
2136 public override string ToString ()
2142 public class TypeExpression : TypeExpr {
2143 public TypeExpression (Type t, Location l)
2146 eclass = ExprClass.Type;
2150 public override TypeExpr DoResolveAsTypeStep (EmitContext ec)
2155 public override string Name {
2156 get { return Type.ToString (); }
2159 public override string FullName {
2160 get { return Type.FullName; }
2165 /// Used to create types from a fully qualified name. These are just used
2166 /// by the parser to setup the core types. A TypeLookupExpression is always
2167 /// classified as a type.
2169 public class TypeLookupExpression : TypeExpr {
2172 public TypeLookupExpression (string name)
2177 static readonly char [] dot_array = { '.' };
2178 public override TypeExpr DoResolveAsTypeStep (EmitContext ec)
2183 // If name is of the form `N.I', first lookup `N', then search a member `I' in it.
2185 string lookup_name = name;
2186 int pos = name.IndexOf ('.');
2188 rest = name.Substring (pos + 1);
2189 lookup_name = name.Substring (0, pos);
2192 FullNamedExpression resolved = Namespace.Root.Lookup (ec.DeclSpace, lookup_name, Location.Null);
2194 if (resolved != null && rest != null) {
2195 // Now handle the rest of the the name.
2196 string [] elements = rest.Split (dot_array);
2198 int count = elements.Length;
2200 while (i < count && resolved != null && resolved is Namespace) {
2201 Namespace ns = resolved as Namespace;
2202 element = elements [i++];
2203 lookup_name += "." + element;
2204 resolved = ns.Lookup (ec.DeclSpace, element, Location.Null);
2207 if (resolved != null && resolved is TypeExpr) {
2208 Type t = ((TypeExpr) resolved).Type;
2210 if (!ec.DeclSpace.CheckAccessLevel (t)) {
2212 lookup_name = t.FullName;
2219 t = TypeManager.GetNestedType (t, elements [i++]);
2224 if (resolved == null) {
2225 NamespaceEntry.Error_NamespaceNotFound (loc, lookup_name);
2229 if (!(resolved is TypeExpr)) {
2230 resolved.Error_UnexpectedKind (ec, "type", loc);
2234 type = ((TypeExpr) resolved).ResolveType (ec);
2238 public override string Name {
2239 get { return name; }
2242 public override string FullName {
2243 get { return name; }
2247 public class TypeAliasExpression : TypeExpr {
2250 public TypeAliasExpression (TypeExpr texpr, Location l)
2253 loc = texpr.Location;
2255 eclass = ExprClass.Type;
2258 public override string Name {
2259 get { return texpr.Name; }
2262 public override string FullName {
2263 get { return texpr.FullName; }
2266 public override TypeExpr DoResolveAsTypeStep (EmitContext ec)
2268 Type type = texpr.ResolveType (ec);
2272 return new TypeExpression (type, loc);
2275 public override bool CheckAccessLevel (DeclSpace ds)
2277 return texpr.CheckAccessLevel (ds);
2280 public override bool AsAccessible (DeclSpace ds, int flags)
2282 return texpr.AsAccessible (ds, flags);
2285 public override bool IsClass {
2286 get { return texpr.IsClass; }
2289 public override bool IsValueType {
2290 get { return texpr.IsValueType; }
2293 public override bool IsInterface {
2294 get { return texpr.IsInterface; }
2297 public override bool IsSealed {
2298 get { return texpr.IsSealed; }
2303 /// This class denotes an expression which evaluates to a member
2304 /// of a struct or a class.
2306 public abstract class MemberExpr : Expression
2309 /// The name of this member.
2311 public abstract string Name {
2316 /// Whether this is an instance member.
2318 public abstract bool IsInstance {
2323 /// Whether this is a static member.
2325 public abstract bool IsStatic {
2330 /// The type which declares this member.
2332 public abstract Type DeclaringType {
2337 /// The instance expression associated with this member, if it's a
2338 /// non-static member.
2340 public Expression InstanceExpression;
2342 public static void error176 (Location loc, string name)
2344 Report.Error (176, loc, "Static member `{0}' cannot be accessed " +
2345 "with an instance reference, qualify it with a type name instead", name);
2349 // TODO: possible optimalization
2350 // Cache resolved constant result in FieldBuilder <-> expression map
2351 public virtual Expression ResolveMemberAccess (EmitContext ec, Expression left, Location loc,
2352 SimpleName original)
2356 // original == null || original.Resolve (...) ==> left
2359 if (left is TypeExpr) {
2361 SimpleName.Error_ObjectRefRequired (ec, loc, Name);
2369 if (original != null && original.IdenticalNameAndTypeName (ec, left, loc))
2372 error176 (loc, GetSignatureForError ());
2376 InstanceExpression = left;
2381 protected void EmitInstance (EmitContext ec, bool prepare_for_load)
2386 if (InstanceExpression == EmptyExpression.Null) {
2387 SimpleName.Error_ObjectRefRequired (ec, loc, Name);
2391 if (InstanceExpression.Type.IsValueType) {
2392 if (InstanceExpression is IMemoryLocation) {
2393 ((IMemoryLocation) InstanceExpression).AddressOf (ec, AddressOp.LoadStore);
2395 LocalTemporary t = new LocalTemporary (ec, InstanceExpression.Type);
2396 InstanceExpression.Emit (ec);
2398 t.AddressOf (ec, AddressOp.Store);
2401 InstanceExpression.Emit (ec);
2403 if (prepare_for_load)
2404 ec.ig.Emit (OpCodes.Dup);
2409 /// MethodGroup Expression.
2411 /// This is a fully resolved expression that evaluates to a type
2413 public class MethodGroupExpr : MemberExpr {
2414 public MethodBase [] Methods;
2415 bool identical_type_name = false;
2418 public MethodGroupExpr (MemberInfo [] mi, Location l)
2420 Methods = new MethodBase [mi.Length];
2421 mi.CopyTo (Methods, 0);
2422 eclass = ExprClass.MethodGroup;
2423 type = TypeManager.object_type;
2427 public MethodGroupExpr (ArrayList list, Location l)
2429 Methods = new MethodBase [list.Count];
2432 list.CopyTo (Methods, 0);
2434 foreach (MemberInfo m in list){
2435 if (!(m is MethodBase)){
2436 Console.WriteLine ("Name " + m.Name);
2437 Console.WriteLine ("Found a: " + m.GetType ().FullName);
2444 eclass = ExprClass.MethodGroup;
2445 type = TypeManager.object_type;
2448 public override Type DeclaringType {
2451 // The methods are arranged in this order:
2452 // derived type -> base type
2454 return Methods [0].DeclaringType;
2458 public bool IdenticalTypeName {
2460 return identical_type_name;
2464 identical_type_name = value;
2468 public bool IsBase {
2477 public override string GetSignatureForError ()
2479 return TypeManager.CSharpSignature (Methods [0]);
2482 public override string Name {
2484 return Methods [0].Name;
2488 public override bool IsInstance {
2490 foreach (MethodBase mb in Methods)
2498 public override bool IsStatic {
2500 foreach (MethodBase mb in Methods)
2508 public override Expression ResolveMemberAccess (EmitContext ec, Expression left, Location loc,
2509 SimpleName original)
2511 if (!(left is TypeExpr) &&
2512 original != null && original.IdenticalNameAndTypeName (ec, left, loc))
2513 IdenticalTypeName = true;
2515 return base.ResolveMemberAccess (ec, left, loc, original);
2518 override public Expression DoResolve (EmitContext ec)
2521 InstanceExpression = null;
2523 if (InstanceExpression != null) {
2524 InstanceExpression = InstanceExpression.DoResolve (ec);
2525 if (InstanceExpression == null)
2532 public void ReportUsageError ()
2534 Report.Error (654, loc, "Method `" + DeclaringType + "." +
2535 Name + "()' is referenced without parentheses");
2538 override public void Emit (EmitContext ec)
2540 ReportUsageError ();
2543 bool RemoveMethods (bool keep_static)
2545 ArrayList smethods = new ArrayList ();
2547 foreach (MethodBase mb in Methods){
2548 if (mb.IsStatic == keep_static)
2552 if (smethods.Count == 0)
2555 Methods = new MethodBase [smethods.Count];
2556 smethods.CopyTo (Methods, 0);
2562 /// Removes any instance methods from the MethodGroup, returns
2563 /// false if the resulting set is empty.
2565 public bool RemoveInstanceMethods ()
2567 return RemoveMethods (true);
2571 /// Removes any static methods from the MethodGroup, returns
2572 /// false if the resulting set is empty.
2574 public bool RemoveStaticMethods ()
2576 return RemoveMethods (false);
2581 /// Fully resolved expression that evaluates to a Field
2583 public class FieldExpr : MemberExpr, IAssignMethod, IMemoryLocation, IVariable {
2584 public readonly FieldInfo FieldInfo;
2585 VariableInfo variable_info;
2587 LocalTemporary temp;
2589 bool in_initializer;
2591 public FieldExpr (FieldInfo fi, Location l, bool in_initializer):
2594 this.in_initializer = in_initializer;
2597 public FieldExpr (FieldInfo fi, Location l)
2600 eclass = ExprClass.Variable;
2601 type = fi.FieldType;
2605 public override string Name {
2607 return FieldInfo.Name;
2611 public override bool IsInstance {
2613 return !FieldInfo.IsStatic;
2617 public override bool IsStatic {
2619 return FieldInfo.IsStatic;
2623 public override Type DeclaringType {
2625 return FieldInfo.DeclaringType;
2629 public override string GetSignatureForError ()
2631 return TypeManager.GetFullNameSignature (FieldInfo);
2634 public VariableInfo VariableInfo {
2636 return variable_info;
2640 public override Expression ResolveMemberAccess (EmitContext ec, Expression left, Location loc,
2641 SimpleName original)
2643 if (FieldInfo.IsLiteral) {
2644 IConstant ic = TypeManager.GetConstant (FieldInfo);
2646 ic = new ExternalConstant (FieldInfo);
2647 TypeManager.RegisterConstant (FieldInfo, ic);
2650 bool left_is_type = left is TypeExpr;
2651 if (!left_is_type && (original == null || !original.IdenticalNameAndTypeName (ec, left, loc))) {
2652 Report.SymbolRelatedToPreviousError (FieldInfo);
2653 error176 (loc, TypeManager.GetFullNameSignature (FieldInfo));
2657 if (ic.ResolveValue ())
2658 ic.CheckObsoleteness (loc);
2663 bool is_emitted = FieldInfo is FieldBuilder;
2664 Type t = FieldInfo.FieldType;
2667 // Decimal constants cannot be encoded in the constant blob, and thus are marked
2668 // as IsInitOnly ('readonly' in C# parlance). We get its value from the
2669 // DecimalConstantAttribute metadata.
2671 //TODO: incorporate in GetContant otherwise we miss all error checks + obsoleteness check
2672 if (FieldInfo.IsInitOnly && !is_emitted && t == TypeManager.decimal_type) {
2673 object[] attrs = FieldInfo.GetCustomAttributes (TypeManager.decimal_constant_attribute_type, false);
2674 if (attrs.Length == 1)
2675 return new DecimalConstant (((System.Runtime.CompilerServices.DecimalConstantAttribute) attrs [0]).Value, Location.Null);
2678 if (t.IsPointer && !ec.InUnsafe) {
2683 return base.ResolveMemberAccess (ec, left, loc, original);
2686 override public Expression DoResolve (EmitContext ec)
2688 if (ec.InRefOutArgumentResolving && FieldInfo.IsInitOnly && !ec.IsConstructor && FieldInfo.FieldType.IsValueType) {
2689 if (FieldInfo.FieldType is TypeBuilder) {
2690 if (FieldInfo.IsStatic)
2691 Report.Error (1651, loc, "Fields of static readonly field `{0}' cannot be passed ref or out (except in a static constructor)",
2692 GetSignatureForError ());
2694 Report.Error (1649, loc, "Members of readonly field `{0}.{1}' cannot be passed ref or out (except in a constructor)",
2695 TypeManager.CSharpName (DeclaringType), Name);
2697 if (FieldInfo.IsStatic)
2698 Report.Error (199, loc, "A static readonly field `{0}' cannot be passed ref or out (except in a static constructor)",
2701 Report.Error (192, loc, "A readonly field `{0}' cannot be passed ref or out (except in a constructor)",
2707 if (!FieldInfo.IsStatic){
2708 if (InstanceExpression == null){
2710 // This can happen when referencing an instance field using
2711 // a fully qualified type expression: TypeName.InstanceField = xxx
2713 SimpleName.Error_ObjectRefRequired (ec, loc, FieldInfo.Name);
2717 // Resolve the field's instance expression while flow analysis is turned
2718 // off: when accessing a field "a.b", we must check whether the field
2719 // "a.b" is initialized, not whether the whole struct "a" is initialized.
2720 InstanceExpression = InstanceExpression.Resolve (
2721 ec, ResolveFlags.VariableOrValue | ResolveFlags.DisableFlowAnalysis);
2722 if (InstanceExpression == null)
2726 if (!in_initializer) {
2727 ObsoleteAttribute oa;
2728 FieldBase f = TypeManager.GetField (FieldInfo);
2730 f.CheckObsoleteness (loc);
2732 // To be sure that type is external because we do not register generated fields
2733 } else if (!(FieldInfo.DeclaringType is TypeBuilder)) {
2734 oa = AttributeTester.GetMemberObsoleteAttribute (FieldInfo);
2736 AttributeTester.Report_ObsoleteMessage (oa, TypeManager.GetFullNameSignature (FieldInfo), loc);
2740 AnonymousContainer am = ec.CurrentAnonymousMethod;
2742 if (!FieldInfo.IsStatic){
2743 if (!am.IsIterator && (ec.TypeContainer is Struct)){
2744 Report.Error (1673, loc,
2745 "Anonymous methods inside structs cannot access instance members of `{0}'. Consider copying `{0}' to a local variable outside the anonymous method and using the local instead",
2749 if ((am.ContainerAnonymousMethod == null) && (InstanceExpression is This))
2750 ec.CaptureField (this);
2754 // If the instance expression is a local variable or parameter.
2755 IVariable var = InstanceExpression as IVariable;
2756 if ((var == null) || (var.VariableInfo == null))
2759 VariableInfo vi = var.VariableInfo;
2760 if (!vi.IsFieldAssigned (ec, FieldInfo.Name, loc))
2763 variable_info = vi.GetSubStruct (FieldInfo.Name);
2767 void Report_AssignToReadonly (bool is_instance)
2772 msg = "A readonly field cannot be assigned to (except in a constructor or a variable initializer)";
2774 msg = "A static readonly field cannot be assigned to (except in a static constructor or a variable initializer)";
2776 Report.Error (is_instance ? 191 : 198, loc, msg);
2779 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
2781 IVariable var = InstanceExpression as IVariable;
2782 if ((var != null) && (var.VariableInfo != null))
2783 var.VariableInfo.SetFieldAssigned (ec, FieldInfo.Name);
2785 Expression e = DoResolve (ec);
2790 if (!FieldInfo.IsStatic && (InstanceExpression.Type.IsValueType && !(InstanceExpression is IMemoryLocation))) {
2791 Report.Error (1612, loc, "Cannot modify the return value of `{0}' because it is not a variable",
2792 InstanceExpression.GetSignatureForError ());
2796 FieldBase fb = TypeManager.GetField (FieldInfo);
2800 if (!FieldInfo.IsInitOnly)
2804 // InitOnly fields can only be assigned in constructors
2807 if (ec.IsConstructor){
2808 if (IsStatic && !ec.IsStatic)
2809 Report_AssignToReadonly (false);
2811 if (ec.ContainerType == FieldInfo.DeclaringType)
2815 Report_AssignToReadonly (!IsStatic);
2820 public override void CheckMarshallByRefAccess (Type container)
2822 if (!IsStatic && Type.IsValueType && !container.IsSubclassOf (TypeManager.mbr_type) && DeclaringType.IsSubclassOf (TypeManager.mbr_type)) {
2823 Report.SymbolRelatedToPreviousError (DeclaringType);
2824 Report.Error (1690, loc, "Cannot call methods, properties, or indexers on `{0}' because it is a value type member of a marshal-by-reference class",
2825 GetSignatureForError ());
2829 public bool VerifyFixed ()
2831 IVariable variable = InstanceExpression as IVariable;
2832 // A variable of the form V.I is fixed when V is a fixed variable of a struct type.
2833 // We defer the InstanceExpression check after the variable check to avoid a
2834 // separate null check on InstanceExpression.
2835 return variable != null && InstanceExpression.Type.IsValueType && variable.VerifyFixed ();
2838 public override int GetHashCode()
2840 return FieldInfo.GetHashCode ();
2843 public override bool Equals (object obj)
2845 FieldExpr fe = obj as FieldExpr;
2849 if (FieldInfo != fe.FieldInfo)
2852 if (InstanceExpression == null || fe.InstanceExpression == null)
2855 return InstanceExpression.Equals (fe.InstanceExpression);
2858 public void Emit (EmitContext ec, bool leave_copy)
2860 ILGenerator ig = ec.ig;
2861 bool is_volatile = false;
2863 if (FieldInfo is FieldBuilder){
2864 FieldBase f = TypeManager.GetField (FieldInfo);
2866 if ((f.ModFlags & Modifiers.VOLATILE) != 0)
2869 f.SetMemberIsUsed ();
2873 if (FieldInfo.IsStatic){
2875 ig.Emit (OpCodes.Volatile);
2877 ig.Emit (OpCodes.Ldsfld, FieldInfo);
2880 EmitInstance (ec, false);
2883 ig.Emit (OpCodes.Volatile);
2885 IFixedBuffer ff = AttributeTester.GetFixedBuffer (FieldInfo);
2888 ig.Emit (OpCodes.Ldflda, FieldInfo);
2889 ig.Emit (OpCodes.Ldflda, ff.Element);
2892 ig.Emit (OpCodes.Ldfld, FieldInfo);
2897 ec.ig.Emit (OpCodes.Dup);
2898 if (!FieldInfo.IsStatic) {
2899 temp = new LocalTemporary (ec, this.Type);
2905 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
2907 FieldAttributes fa = FieldInfo.Attributes;
2908 bool is_static = (fa & FieldAttributes.Static) != 0;
2909 bool is_readonly = (fa & FieldAttributes.InitOnly) != 0;
2910 ILGenerator ig = ec.ig;
2911 prepared = prepare_for_load;
2913 if (is_readonly && !ec.IsConstructor){
2914 Report_AssignToReadonly (!is_static);
2918 EmitInstance (ec, prepare_for_load);
2922 ec.ig.Emit (OpCodes.Dup);
2923 if (!FieldInfo.IsStatic) {
2924 temp = new LocalTemporary (ec, this.Type);
2929 if (FieldInfo is FieldBuilder){
2930 FieldBase f = TypeManager.GetField (FieldInfo);
2932 if ((f.ModFlags & Modifiers.VOLATILE) != 0)
2933 ig.Emit (OpCodes.Volatile);
2940 ig.Emit (OpCodes.Stsfld, FieldInfo);
2942 ig.Emit (OpCodes.Stfld, FieldInfo);
2948 public override void Emit (EmitContext ec)
2953 public void AddressOf (EmitContext ec, AddressOp mode)
2955 ILGenerator ig = ec.ig;
2957 if (FieldInfo is FieldBuilder){
2958 FieldBase f = TypeManager.GetField (FieldInfo);
2960 if ((f.ModFlags & Modifiers.VOLATILE) != 0){
2961 Report.Warning (420, 1, loc, "`{0}': A volatile fields cannot be passed using a ref or out parameter",
2962 f.GetSignatureForError ());
2966 if ((mode & AddressOp.Store) != 0)
2968 if ((mode & AddressOp.Load) != 0)
2969 f.SetMemberIsUsed ();
2974 // Handle initonly fields specially: make a copy and then
2975 // get the address of the copy.
2978 if (FieldInfo.IsInitOnly){
2980 if (ec.IsConstructor){
2981 if (FieldInfo.IsStatic){
2993 local = ig.DeclareLocal (type);
2994 ig.Emit (OpCodes.Stloc, local);
2995 ig.Emit (OpCodes.Ldloca, local);
3000 if (FieldInfo.IsStatic){
3001 ig.Emit (OpCodes.Ldsflda, FieldInfo);
3003 EmitInstance (ec, false);
3004 ig.Emit (OpCodes.Ldflda, FieldInfo);
3010 // A FieldExpr whose address can not be taken
3012 public class FieldExprNoAddress : FieldExpr, IMemoryLocation {
3013 public FieldExprNoAddress (FieldInfo fi, Location loc) : base (fi, loc)
3017 public new void AddressOf (EmitContext ec, AddressOp mode)
3019 Report.Error (-215, "Report this: Taking the address of a remapped parameter not supported");
3024 /// Expression that evaluates to a Property. The Assign class
3025 /// might set the `Value' expression if we are in an assignment.
3027 /// This is not an LValue because we need to re-write the expression, we
3028 /// can not take data from the stack and store it.
3030 public class PropertyExpr : MemberExpr, IAssignMethod {
3031 public readonly PropertyInfo PropertyInfo;
3034 // This is set externally by the `BaseAccess' class
3037 MethodInfo getter, setter;
3042 LocalTemporary temp;
3045 internal static PtrHashtable AccessorTable = new PtrHashtable ();
3047 public PropertyExpr (EmitContext ec, PropertyInfo pi, Location l)
3050 eclass = ExprClass.PropertyAccess;
3054 type = TypeManager.TypeToCoreType (pi.PropertyType);
3056 ResolveAccessors (ec);
3059 public override string Name {
3061 return PropertyInfo.Name;
3065 public override bool IsInstance {
3071 public override bool IsStatic {
3077 public override Type DeclaringType {
3079 return PropertyInfo.DeclaringType;
3083 public override string GetSignatureForError ()
3085 return TypeManager.GetFullNameSignature (PropertyInfo);
3088 void FindAccessors (Type invocation_type)
3090 BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic |
3091 BindingFlags.Static | BindingFlags.Instance |
3092 BindingFlags.DeclaredOnly;
3094 Type current = PropertyInfo.DeclaringType;
3095 for (; current != null; current = current.BaseType) {
3096 MemberInfo[] group = TypeManager.MemberLookup (
3097 invocation_type, invocation_type, current,
3098 MemberTypes.Property, flags, PropertyInfo.Name, null);
3103 if (group.Length != 1)
3104 // Oooops, can this ever happen ?
3107 PropertyInfo pi = (PropertyInfo) group [0];
3110 getter = pi.GetGetMethod (true);
3113 setter = pi.GetSetMethod (true);
3115 MethodInfo accessor = getter != null ? getter : setter;
3117 if (!accessor.IsVirtual)
3123 // We also perform the permission checking here, as the PropertyInfo does not
3124 // hold the information for the accessibility of its setter/getter
3126 void ResolveAccessors (EmitContext ec)
3128 FindAccessors (ec.ContainerType);
3130 if (getter != null) {
3131 IMethodData md = TypeManager.GetMethod (getter);
3133 md.SetMemberIsUsed ();
3135 AccessorTable [getter] = PropertyInfo;
3136 is_static = getter.IsStatic;
3139 if (setter != null) {
3140 IMethodData md = TypeManager.GetMethod (setter);
3142 md.SetMemberIsUsed ();
3144 AccessorTable [setter] = PropertyInfo;
3145 is_static = setter.IsStatic;
3149 bool InstanceResolve (EmitContext ec, bool must_do_cs1540_check)
3152 InstanceExpression = null;
3156 if (InstanceExpression == null) {
3157 SimpleName.Error_ObjectRefRequired (ec, loc, PropertyInfo.Name);
3161 InstanceExpression = InstanceExpression.DoResolve (ec);
3162 if (InstanceExpression == null)
3165 InstanceExpression.CheckMarshallByRefAccess (ec.ContainerType);
3167 if (must_do_cs1540_check && InstanceExpression != EmptyExpression.Null) {
3168 if ((InstanceExpression.Type != ec.ContainerType) &&
3169 ec.ContainerType.IsSubclassOf (InstanceExpression.Type)) {
3170 Report.Error (1540, loc, "Cannot access protected member `" +
3171 PropertyInfo.DeclaringType + "." + PropertyInfo.Name +
3172 "' via a qualifier of type `" +
3173 TypeManager.CSharpName (InstanceExpression.Type) +
3174 "'; the qualifier must be of type `" +
3175 TypeManager.CSharpName (ec.ContainerType) +
3176 "' (or derived from it)");
3184 void Error_PropertyNotFound (MethodInfo mi, bool getter)
3186 // TODO: correctly we should compare arguments but it will lead to bigger changes
3187 if (mi is MethodBuilder) {
3188 Error_TypeDoesNotContainDefinition (loc, PropertyInfo.DeclaringType, Name);
3192 StringBuilder sig = new StringBuilder (TypeManager.CSharpName (mi.DeclaringType));
3194 ParameterData iparams = TypeManager.GetParameterData (mi);
3195 sig.Append (getter ? "get_" : "set_");
3197 sig.Append (iparams.GetSignatureForError ());
3199 Report.SymbolRelatedToPreviousError (mi);
3200 Report.Error (1546, loc, "Property `{0}' is not supported by the C# language. Try to call the accessor method `{1}' directly",
3201 Name, sig.ToString ());
3204 override public Expression DoResolve (EmitContext ec)
3209 if (getter != null){
3210 if (TypeManager.GetArgumentTypes (getter).Length != 0){
3211 Error_PropertyNotFound (getter, true);
3216 if (getter == null){
3218 // The following condition happens if the PropertyExpr was
3219 // created, but is invalid (ie, the property is inaccessible),
3220 // and we did not want to embed the knowledge about this in
3221 // the caller routine. This only avoids double error reporting.
3226 if (InstanceExpression != EmptyExpression.Null) {
3227 Report.Error (154, loc, "The property or indexer `{0}' cannot be used in this context because it lacks the `get' accessor",
3228 TypeManager.GetFullNameSignature (PropertyInfo));
3233 bool must_do_cs1540_check = false;
3234 if (getter != null &&
3235 !IsAccessorAccessible (ec.ContainerType, getter, out must_do_cs1540_check)) {
3236 PropertyBase.PropertyMethod pm = TypeManager.GetMethod (getter) as PropertyBase.PropertyMethod;
3237 if (pm != null && pm.HasCustomAccessModifier) {
3238 Report.SymbolRelatedToPreviousError (pm);
3239 Report.Error (271, loc, "The property or indexer `{0}' cannot be used in this context because the get accessor is inaccessible",
3240 TypeManager.CSharpSignature (getter));
3243 ErrorIsInaccesible (loc, TypeManager.CSharpSignature (getter));
3247 if (!InstanceResolve (ec, must_do_cs1540_check))
3251 // Only base will allow this invocation to happen.
3253 if (IsBase && getter.IsAbstract) {
3254 Error_CannotCallAbstractBase (TypeManager.GetFullNameSignature (PropertyInfo));
3258 if (PropertyInfo.PropertyType.IsPointer && !ec.InUnsafe){
3268 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
3270 if (setter == null){
3272 // The following condition happens if the PropertyExpr was
3273 // created, but is invalid (ie, the property is inaccessible),
3274 // and we did not want to embed the knowledge about this in
3275 // the caller routine. This only avoids double error reporting.
3280 Report.Error (200, loc, " Property or indexer `{0}' cannot be assigned to (it is read only)",
3281 TypeManager.GetFullNameSignature (PropertyInfo));
3285 if (TypeManager.GetArgumentTypes (setter).Length != 1){
3286 Error_PropertyNotFound (setter, false);
3290 bool must_do_cs1540_check;
3291 if (!IsAccessorAccessible (ec.ContainerType, setter, out must_do_cs1540_check)) {
3292 PropertyBase.PropertyMethod pm = TypeManager.GetMethod (setter) as PropertyBase.PropertyMethod;
3293 if (pm != null && pm.HasCustomAccessModifier) {
3294 Report.SymbolRelatedToPreviousError (pm);
3295 Report.Error (272, loc, "The property or indexer `{0}' cannot be used in this context because the set accessor is inaccessible",
3296 TypeManager.CSharpSignature (setter));
3299 ErrorIsInaccesible (loc, TypeManager.CSharpSignature (setter));
3303 if (!InstanceResolve (ec, must_do_cs1540_check))
3307 // Only base will allow this invocation to happen.
3309 if (IsBase && setter.IsAbstract){
3310 Error_CannotCallAbstractBase (TypeManager.GetFullNameSignature (PropertyInfo));
3315 // Check that we are not making changes to a temporary memory location
3317 if (InstanceExpression != null && InstanceExpression.Type.IsValueType && !(InstanceExpression is IMemoryLocation)) {
3318 Report.Error (1612, loc, "Cannot modify the return value of `{0}' because it is not a variable",
3319 InstanceExpression.GetSignatureForError ());
3326 public override void Emit (EmitContext ec)
3331 public void Emit (EmitContext ec, bool leave_copy)
3334 EmitInstance (ec, false);
3337 // Special case: length of single dimension array property is turned into ldlen
3339 if ((getter == TypeManager.system_int_array_get_length) ||
3340 (getter == TypeManager.int_array_get_length)){
3341 Type iet = InstanceExpression.Type;
3344 // System.Array.Length can be called, but the Type does not
3345 // support invoking GetArrayRank, so test for that case first
3347 if (iet != TypeManager.array_type && (iet.GetArrayRank () == 1)) {
3348 ec.ig.Emit (OpCodes.Ldlen);
3349 ec.ig.Emit (OpCodes.Conv_I4);
3354 Invocation.EmitCall (ec, IsBase, IsStatic, new EmptyAddressOf (), getter, null, loc);
3359 ec.ig.Emit (OpCodes.Dup);
3361 temp = new LocalTemporary (ec, this.Type);
3367 // Implements the IAssignMethod interface for assignments
3369 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
3371 prepared = prepare_for_load;
3373 EmitInstance (ec, prepare_for_load);
3377 ec.ig.Emit (OpCodes.Dup);
3379 temp = new LocalTemporary (ec, this.Type);
3384 ArrayList args = new ArrayList (1);
3385 args.Add (new Argument (new EmptyAddressOf (), Argument.AType.Expression));
3387 Invocation.EmitCall (ec, IsBase, IsStatic, new EmptyAddressOf (), setter, args, loc);
3395 /// Fully resolved expression that evaluates to an Event
3397 public class EventExpr : MemberExpr {
3398 public readonly EventInfo EventInfo;
3401 MethodInfo add_accessor, remove_accessor;
3403 public EventExpr (EventInfo ei, Location loc)
3407 eclass = ExprClass.EventAccess;
3409 add_accessor = TypeManager.GetAddMethod (ei);
3410 remove_accessor = TypeManager.GetRemoveMethod (ei);
3412 if (add_accessor.IsStatic || remove_accessor.IsStatic)
3415 if (EventInfo is MyEventBuilder){
3416 MyEventBuilder eb = (MyEventBuilder) EventInfo;
3417 type = eb.EventType;
3420 type = EventInfo.EventHandlerType;
3423 public override string Name {
3425 return EventInfo.Name;
3429 public override bool IsInstance {
3435 public override bool IsStatic {
3441 public override Type DeclaringType {
3443 return EventInfo.DeclaringType;
3447 public override Expression ResolveMemberAccess (EmitContext ec, Expression left, Location loc,
3448 SimpleName original)
3451 // If the event is local to this class, we transform ourselves into a FieldExpr
3454 if (EventInfo.DeclaringType == ec.ContainerType ||
3455 TypeManager.IsNestedChildOf(ec.ContainerType, EventInfo.DeclaringType)) {
3456 MemberInfo mi = TypeManager.GetPrivateFieldOfEvent (EventInfo);
3459 MemberExpr ml = (MemberExpr) ExprClassFromMemberInfo (ec, mi, loc);
3462 Report.Error (-200, loc, "Internal error!!");
3466 InstanceExpression = null;
3468 return ml.ResolveMemberAccess (ec, left, loc, original);
3472 return base.ResolveMemberAccess (ec, left, loc, original);
3476 bool InstanceResolve (EmitContext ec, bool must_do_cs1540_check)
3479 InstanceExpression = null;
3483 if (InstanceExpression == null) {
3484 SimpleName.Error_ObjectRefRequired (ec, loc, EventInfo.Name);
3488 InstanceExpression = InstanceExpression.DoResolve (ec);
3489 if (InstanceExpression == null)
3493 // This is using the same mechanism as the CS1540 check in PropertyExpr.
3494 // However, in the Event case, we reported a CS0122 instead.
3496 if (must_do_cs1540_check && InstanceExpression != EmptyExpression.Null) {
3497 if ((InstanceExpression.Type != ec.ContainerType) &&
3498 ec.ContainerType.IsSubclassOf (InstanceExpression.Type)) {
3499 ErrorIsInaccesible (loc, TypeManager.CSharpSignature (EventInfo));
3507 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
3509 return DoResolve (ec);
3512 public override Expression DoResolve (EmitContext ec)
3514 bool must_do_cs1540_check;
3515 if (!(IsAccessorAccessible (ec.ContainerType, add_accessor, out must_do_cs1540_check) &&
3516 IsAccessorAccessible (ec.ContainerType, remove_accessor, out must_do_cs1540_check))) {
3517 ErrorIsInaccesible (loc, TypeManager.CSharpSignature (EventInfo));
3521 if (!InstanceResolve (ec, must_do_cs1540_check))
3527 public override void Emit (EmitContext ec)
3529 if (InstanceExpression is This)
3530 Report.Error (79, loc, "The event `{0}' can only appear on the left hand side of += or -=", GetSignatureForError ());
3532 Report.Error (70, loc, "The event `{0}' can only appear on the left hand side of += or -= "+
3533 "(except on the defining type)", Name);
3536 public override string GetSignatureForError ()
3538 return TypeManager.CSharpSignature (EventInfo);
3541 public void EmitAddOrRemove (EmitContext ec, Expression source)
3543 BinaryDelegate source_del = (BinaryDelegate) source;
3544 Expression handler = source_del.Right;
3546 Argument arg = new Argument (handler, Argument.AType.Expression);
3547 ArrayList args = new ArrayList ();
3551 if (source_del.IsAddition)
3552 Invocation.EmitCall (
3553 ec, false, IsStatic, InstanceExpression, add_accessor, args, loc);
3555 Invocation.EmitCall (
3556 ec, false, IsStatic, InstanceExpression, remove_accessor, args, loc);