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 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);
485 else if (t == TypeManager.uint32_type)
486 return new UIntConstant ((uint) v);
487 else if (t == TypeManager.int64_type)
488 return new LongConstant ((long) v);
489 else if (t == TypeManager.uint64_type)
490 return new ULongConstant ((ulong) v);
491 else if (t == TypeManager.float_type)
492 return new FloatConstant ((float) v);
493 else if (t == TypeManager.double_type)
494 return new DoubleConstant ((double) v);
495 else if (t == TypeManager.string_type)
496 return new StringConstant ((string) v);
497 else if (t == TypeManager.short_type)
498 return new ShortConstant ((short)v);
499 else if (t == TypeManager.ushort_type)
500 return new UShortConstant ((ushort)v);
501 else if (t == TypeManager.sbyte_type)
502 return new SByteConstant (((sbyte)v));
503 else if (t == TypeManager.byte_type)
504 return new ByteConstant ((byte)v);
505 else if (t == TypeManager.char_type)
506 return new CharConstant ((char)v);
507 else if (t == TypeManager.bool_type)
508 return new BoolConstant ((bool) v);
509 else if (t == TypeManager.decimal_type)
510 return new DecimalConstant ((decimal) v);
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 NullLiteral.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)
1241 eclass = child.eclass;
1246 override public string AsString ()
1251 public override object GetValue ()
1256 public override Expression DoResolve (EmitContext ec)
1258 // This should never be invoked, we are born in fully
1259 // initialized state.
1264 public override void Emit (EmitContext ec)
1269 public override Constant Increment ()
1271 throw new NotSupportedException ();
1274 public override bool IsDefaultValue {
1276 throw new NotImplementedException ();
1280 public override bool IsNegative {
1289 /// This class is used to wrap literals which belong inside Enums
1291 public class EnumConstant : Constant {
1292 public Constant Child;
1294 public EnumConstant (Constant child, Type enum_type)
1296 eclass = child.eclass;
1301 public override Expression DoResolve (EmitContext ec)
1303 // This should never be invoked, we are born in fully
1304 // initialized state.
1309 public override void Emit (EmitContext ec)
1314 public override object GetValue ()
1316 return Child.GetValue ();
1319 public override object GetTypedValue ()
1321 // FIXME: runtime is not ready to work with just emited enums
1322 if (!RootContext.StdLib) {
1323 return Child.GetValue ();
1326 return System.Enum.ToObject (type, Child.GetValue ());
1329 public override void Error_ValueCannotBeConverted (Location loc, Type t)
1331 Convert.Error_CannotImplicitConversion (loc, Type, t);
1334 public override string AsString ()
1336 return Child.AsString ();
1339 public override DoubleConstant ConvertToDouble ()
1341 return Child.ConvertToDouble ();
1344 public override FloatConstant ConvertToFloat ()
1346 return Child.ConvertToFloat ();
1349 public override ULongConstant ConvertToULong ()
1351 return Child.ConvertToULong ();
1354 public override LongConstant ConvertToLong ()
1356 return Child.ConvertToLong ();
1359 public override UIntConstant ConvertToUInt ()
1361 return Child.ConvertToUInt ();
1364 public override IntConstant ConvertToInt ()
1366 return Child.ConvertToInt ();
1369 public override Constant Increment()
1371 return new EnumConstant (Child.Increment (), type);
1374 public override bool IsDefaultValue {
1376 return Child.IsDefaultValue;
1380 public override bool IsZeroInteger {
1381 get { return Child.IsZeroInteger; }
1384 public override bool IsNegative {
1386 return Child.IsNegative;
1390 public override Constant ToType (Type type, Location loc)
1393 // This is workaround of mono bug. It can be removed when the latest corlib spreads enough
1394 if (TypeManager.IsEnumType (type.UnderlyingSystemType))
1397 if (type.UnderlyingSystemType != Child.Type)
1398 Child = Child.ToType (type.UnderlyingSystemType, loc);
1402 if (!Convert.ImplicitStandardConversionExists (Convert.ConstantEC, this, type)){
1403 Error_ValueCannotBeConverted (loc, type);
1407 return Child.ToType (type, loc);
1413 /// This kind of cast is used to encapsulate Value Types in objects.
1415 /// The effect of it is to box the value type emitted by the previous
1418 public class BoxedCast : EmptyCast {
1420 public BoxedCast (Expression expr, Type target_type)
1421 : base (expr, target_type)
1423 eclass = ExprClass.Value;
1426 public override Expression DoResolve (EmitContext ec)
1428 // This should never be invoked, we are born in fully
1429 // initialized state.
1434 public override void Emit (EmitContext ec)
1438 ec.ig.Emit (OpCodes.Box, child.Type);
1442 public class UnboxCast : EmptyCast {
1443 public UnboxCast (Expression expr, Type return_type)
1444 : base (expr, return_type)
1448 public override Expression DoResolve (EmitContext ec)
1450 // This should never be invoked, we are born in fully
1451 // initialized state.
1456 public override void Emit (EmitContext ec)
1459 ILGenerator ig = ec.ig;
1462 ig.Emit (OpCodes.Unbox, t);
1464 LoadFromPtr (ig, t);
1469 /// This is used to perform explicit numeric conversions.
1471 /// Explicit numeric conversions might trigger exceptions in a checked
1472 /// context, so they should generate the conv.ovf opcodes instead of
1475 public class ConvCast : EmptyCast {
1476 public enum Mode : byte {
1477 I1_U1, I1_U2, I1_U4, I1_U8, I1_CH,
1479 I2_I1, I2_U1, I2_U2, I2_U4, I2_U8, I2_CH,
1480 U2_I1, U2_U1, U2_I2, U2_CH,
1481 I4_I1, I4_U1, I4_I2, I4_U2, I4_U4, I4_U8, I4_CH,
1482 U4_I1, U4_U1, U4_I2, U4_U2, U4_I4, U4_CH,
1483 I8_I1, I8_U1, I8_I2, I8_U2, I8_I4, I8_U4, I8_U8, I8_CH,
1484 U8_I1, U8_U1, U8_I2, U8_U2, U8_I4, U8_U4, U8_I8, U8_CH,
1485 CH_I1, CH_U1, CH_I2,
1486 R4_I1, R4_U1, R4_I2, R4_U2, R4_I4, R4_U4, R4_I8, R4_U8, R4_CH,
1487 R8_I1, R8_U1, R8_I2, R8_U2, R8_I4, R8_U4, R8_I8, R8_U8, R8_CH, R8_R4
1493 public ConvCast (EmitContext ec, Expression child, Type return_type, Mode m)
1494 : base (child, return_type)
1496 checked_state = ec.CheckState;
1500 public override Expression DoResolve (EmitContext ec)
1502 // This should never be invoked, we are born in fully
1503 // initialized state.
1508 public override string ToString ()
1510 return String.Format ("ConvCast ({0}, {1})", mode, child);
1513 public override void Emit (EmitContext ec)
1515 ILGenerator ig = ec.ig;
1521 case Mode.I1_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1522 case Mode.I1_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1523 case Mode.I1_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1524 case Mode.I1_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1525 case Mode.I1_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1527 case Mode.U1_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1528 case Mode.U1_CH: /* nothing */ break;
1530 case Mode.I2_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1531 case Mode.I2_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1532 case Mode.I2_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1533 case Mode.I2_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1534 case Mode.I2_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1535 case Mode.I2_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1537 case Mode.U2_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1538 case Mode.U2_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
1539 case Mode.U2_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
1540 case Mode.U2_CH: /* nothing */ break;
1542 case Mode.I4_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1543 case Mode.I4_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1544 case Mode.I4_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
1545 case Mode.I4_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1546 case Mode.I4_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1547 case Mode.I4_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1548 case Mode.I4_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1550 case Mode.U4_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1551 case Mode.U4_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
1552 case Mode.U4_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
1553 case Mode.U4_U2: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
1554 case Mode.U4_I4: ig.Emit (OpCodes.Conv_Ovf_I4_Un); break;
1555 case Mode.U4_CH: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
1557 case Mode.I8_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1558 case Mode.I8_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1559 case Mode.I8_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
1560 case Mode.I8_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1561 case Mode.I8_I4: ig.Emit (OpCodes.Conv_Ovf_I4); break;
1562 case Mode.I8_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1563 case Mode.I8_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1564 case Mode.I8_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1566 case Mode.U8_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1567 case Mode.U8_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
1568 case Mode.U8_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
1569 case Mode.U8_U2: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
1570 case Mode.U8_I4: ig.Emit (OpCodes.Conv_Ovf_I4_Un); break;
1571 case Mode.U8_U4: ig.Emit (OpCodes.Conv_Ovf_U4_Un); break;
1572 case Mode.U8_I8: ig.Emit (OpCodes.Conv_Ovf_I8_Un); break;
1573 case Mode.U8_CH: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
1575 case Mode.CH_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1576 case Mode.CH_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
1577 case Mode.CH_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
1579 case Mode.R4_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1580 case Mode.R4_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1581 case Mode.R4_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
1582 case Mode.R4_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1583 case Mode.R4_I4: ig.Emit (OpCodes.Conv_Ovf_I4); break;
1584 case Mode.R4_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1585 case Mode.R4_I8: ig.Emit (OpCodes.Conv_Ovf_I8); break;
1586 case Mode.R4_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1587 case Mode.R4_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1589 case Mode.R8_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1590 case Mode.R8_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1591 case Mode.R8_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
1592 case Mode.R8_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1593 case Mode.R8_I4: ig.Emit (OpCodes.Conv_Ovf_I4); break;
1594 case Mode.R8_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1595 case Mode.R8_I8: ig.Emit (OpCodes.Conv_Ovf_I8); break;
1596 case Mode.R8_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1597 case Mode.R8_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1598 case Mode.R8_R4: ig.Emit (OpCodes.Conv_R4); break;
1602 case Mode.I1_U1: ig.Emit (OpCodes.Conv_U1); break;
1603 case Mode.I1_U2: ig.Emit (OpCodes.Conv_U2); break;
1604 case Mode.I1_U4: ig.Emit (OpCodes.Conv_U4); break;
1605 case Mode.I1_U8: ig.Emit (OpCodes.Conv_I8); break;
1606 case Mode.I1_CH: ig.Emit (OpCodes.Conv_U2); break;
1608 case Mode.U1_I1: ig.Emit (OpCodes.Conv_I1); break;
1609 case Mode.U1_CH: ig.Emit (OpCodes.Conv_U2); break;
1611 case Mode.I2_I1: ig.Emit (OpCodes.Conv_I1); break;
1612 case Mode.I2_U1: ig.Emit (OpCodes.Conv_U1); break;
1613 case Mode.I2_U2: ig.Emit (OpCodes.Conv_U2); break;
1614 case Mode.I2_U4: ig.Emit (OpCodes.Conv_U4); break;
1615 case Mode.I2_U8: ig.Emit (OpCodes.Conv_I8); break;
1616 case Mode.I2_CH: ig.Emit (OpCodes.Conv_U2); break;
1618 case Mode.U2_I1: ig.Emit (OpCodes.Conv_I1); break;
1619 case Mode.U2_U1: ig.Emit (OpCodes.Conv_U1); break;
1620 case Mode.U2_I2: ig.Emit (OpCodes.Conv_I2); break;
1621 case Mode.U2_CH: /* nothing */ break;
1623 case Mode.I4_I1: ig.Emit (OpCodes.Conv_I1); break;
1624 case Mode.I4_U1: ig.Emit (OpCodes.Conv_U1); break;
1625 case Mode.I4_I2: ig.Emit (OpCodes.Conv_I2); break;
1626 case Mode.I4_U4: /* nothing */ break;
1627 case Mode.I4_U2: ig.Emit (OpCodes.Conv_U2); break;
1628 case Mode.I4_U8: ig.Emit (OpCodes.Conv_I8); break;
1629 case Mode.I4_CH: ig.Emit (OpCodes.Conv_U2); break;
1631 case Mode.U4_I1: ig.Emit (OpCodes.Conv_I1); break;
1632 case Mode.U4_U1: ig.Emit (OpCodes.Conv_U1); break;
1633 case Mode.U4_I2: ig.Emit (OpCodes.Conv_I2); break;
1634 case Mode.U4_U2: ig.Emit (OpCodes.Conv_U2); break;
1635 case Mode.U4_I4: /* nothing */ break;
1636 case Mode.U4_CH: ig.Emit (OpCodes.Conv_U2); break;
1638 case Mode.I8_I1: ig.Emit (OpCodes.Conv_I1); break;
1639 case Mode.I8_U1: ig.Emit (OpCodes.Conv_U1); break;
1640 case Mode.I8_I2: ig.Emit (OpCodes.Conv_I2); break;
1641 case Mode.I8_U2: ig.Emit (OpCodes.Conv_U2); break;
1642 case Mode.I8_I4: ig.Emit (OpCodes.Conv_I4); break;
1643 case Mode.I8_U4: ig.Emit (OpCodes.Conv_U4); break;
1644 case Mode.I8_U8: /* nothing */ break;
1645 case Mode.I8_CH: ig.Emit (OpCodes.Conv_U2); break;
1647 case Mode.U8_I1: ig.Emit (OpCodes.Conv_I1); break;
1648 case Mode.U8_U1: ig.Emit (OpCodes.Conv_U1); break;
1649 case Mode.U8_I2: ig.Emit (OpCodes.Conv_I2); break;
1650 case Mode.U8_U2: ig.Emit (OpCodes.Conv_U2); break;
1651 case Mode.U8_I4: ig.Emit (OpCodes.Conv_I4); break;
1652 case Mode.U8_U4: ig.Emit (OpCodes.Conv_U4); break;
1653 case Mode.U8_I8: /* nothing */ break;
1654 case Mode.U8_CH: ig.Emit (OpCodes.Conv_U2); break;
1656 case Mode.CH_I1: ig.Emit (OpCodes.Conv_I1); break;
1657 case Mode.CH_U1: ig.Emit (OpCodes.Conv_U1); break;
1658 case Mode.CH_I2: ig.Emit (OpCodes.Conv_I2); break;
1660 case Mode.R4_I1: ig.Emit (OpCodes.Conv_I1); break;
1661 case Mode.R4_U1: ig.Emit (OpCodes.Conv_U1); break;
1662 case Mode.R4_I2: ig.Emit (OpCodes.Conv_I2); break;
1663 case Mode.R4_U2: ig.Emit (OpCodes.Conv_U2); break;
1664 case Mode.R4_I4: ig.Emit (OpCodes.Conv_I4); break;
1665 case Mode.R4_U4: ig.Emit (OpCodes.Conv_U4); break;
1666 case Mode.R4_I8: ig.Emit (OpCodes.Conv_I8); break;
1667 case Mode.R4_U8: ig.Emit (OpCodes.Conv_U8); break;
1668 case Mode.R4_CH: ig.Emit (OpCodes.Conv_U2); break;
1670 case Mode.R8_I1: ig.Emit (OpCodes.Conv_I1); break;
1671 case Mode.R8_U1: ig.Emit (OpCodes.Conv_U1); break;
1672 case Mode.R8_I2: ig.Emit (OpCodes.Conv_I2); break;
1673 case Mode.R8_U2: ig.Emit (OpCodes.Conv_U2); break;
1674 case Mode.R8_I4: ig.Emit (OpCodes.Conv_I4); break;
1675 case Mode.R8_U4: ig.Emit (OpCodes.Conv_U4); break;
1676 case Mode.R8_I8: ig.Emit (OpCodes.Conv_I8); break;
1677 case Mode.R8_U8: ig.Emit (OpCodes.Conv_U8); break;
1678 case Mode.R8_CH: ig.Emit (OpCodes.Conv_U2); break;
1679 case Mode.R8_R4: ig.Emit (OpCodes.Conv_R4); break;
1685 public class OpcodeCast : EmptyCast {
1689 public OpcodeCast (Expression child, Type return_type, OpCode op)
1690 : base (child, return_type)
1694 second_valid = false;
1697 public OpcodeCast (Expression child, Type return_type, OpCode op, OpCode op2)
1698 : base (child, return_type)
1703 second_valid = true;
1706 public override Expression DoResolve (EmitContext ec)
1708 // This should never be invoked, we are born in fully
1709 // initialized state.
1714 public override void Emit (EmitContext ec)
1725 /// This kind of cast is used to encapsulate a child and cast it
1726 /// to the class requested
1728 public class ClassCast : EmptyCast {
1729 public ClassCast (Expression child, Type return_type)
1730 : base (child, return_type)
1735 public override Expression DoResolve (EmitContext ec)
1737 // This should never be invoked, we are born in fully
1738 // initialized state.
1743 public override void Emit (EmitContext ec)
1747 ec.ig.Emit (OpCodes.Castclass, type);
1753 /// SimpleName expressions are formed of a single word and only happen at the beginning
1754 /// of a dotted-name.
1756 public class SimpleName : Expression {
1760 public SimpleName (string name, Location l)
1766 public static void Error_ObjectRefRequired (EmitContext ec, Location l, string name)
1768 if (ec.IsFieldInitializer)
1769 Report.Error (236, l,
1770 "A field initializer cannot reference the nonstatic field, method, or property `{0}'",
1773 if (name.LastIndexOf ('.') > 0)
1774 name = name.Substring (name.LastIndexOf ('.') + 1);
1777 120, l, "`{0}': An object reference is required for the nonstatic field, method or property",
1782 public bool IdenticalNameAndTypeName (EmitContext ec, Expression resolved_to, Location loc)
1784 return resolved_to != null && resolved_to.Type != null &&
1785 resolved_to.Type.Name == Name &&
1786 (ec.DeclSpace.LookupType (Name, loc, /* ignore_cs0104 = */ true) != null);
1789 public override Expression DoResolve (EmitContext ec)
1791 return SimpleNameResolve (ec, null, false);
1794 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
1796 return SimpleNameResolve (ec, right_side, false);
1800 public Expression DoResolve (EmitContext ec, bool intermediate)
1802 return SimpleNameResolve (ec, null, intermediate);
1805 public override FullNamedExpression ResolveAsTypeStep (EmitContext ec, bool silent)
1807 int errors = Report.Errors;
1808 FullNamedExpression fne = ec.DeclSpace.LookupType (Name, loc, /*ignore_cs0104=*/ false);
1812 if (silent || errors != Report.Errors)
1815 MemberCore mc = ec.DeclSpace.GetDefinition (Name);
1817 Error_UnexpectedKind (ec, "type", GetMemberType (mc), loc);
1819 NamespaceEntry.Error_NamespaceNotFound (loc, Name);
1825 // TODO: I am still not convinced about this. If someone else will need it
1826 // implement this as virtual property in MemberCore hierarchy
1827 string GetMemberType (MemberCore mc)
1829 if (mc is PropertyBase)
1833 if (mc is FieldBase)
1839 Expression SimpleNameResolve (EmitContext ec, Expression right_side, bool intermediate)
1845 Expression e = DoSimpleNameResolve (ec, right_side, intermediate);
1849 if (ec.CurrentBlock == null || ec.CurrentBlock.CheckInvariantMeaningInBlock (Name, e, Location))
1856 /// 7.5.2: Simple Names.
1858 /// Local Variables and Parameters are handled at
1859 /// parse time, so they never occur as SimpleNames.
1861 /// The `intermediate' flag is used by MemberAccess only
1862 /// and it is used to inform us that it is ok for us to
1863 /// avoid the static check, because MemberAccess might end
1864 /// up resolving the Name as a Type name and the access as
1865 /// a static type access.
1867 /// ie: Type Type; .... { Type.GetType (""); }
1869 /// Type is both an instance variable and a Type; Type.GetType
1870 /// is the static method not an instance method of type.
1872 Expression DoSimpleNameResolve (EmitContext ec, Expression right_side, bool intermediate)
1874 Expression e = null;
1877 // Stage 1: Performed by the parser (binding to locals or parameters).
1879 Block current_block = ec.CurrentBlock;
1880 if (current_block != null){
1881 LocalInfo vi = current_block.GetLocalInfo (Name);
1883 LocalVariableReference var = new LocalVariableReference (ec.CurrentBlock, Name, loc);
1884 if (right_side != null) {
1885 return var.ResolveLValue (ec, right_side, loc);
1887 ResolveFlags rf = ResolveFlags.VariableOrValue;
1889 rf |= ResolveFlags.DisableFlowAnalysis;
1890 return var.Resolve (ec, rf);
1894 ParameterReference pref = current_block.Toplevel.GetParameterReference (Name, loc);
1896 if (right_side != null)
1897 return pref.ResolveLValue (ec, right_side, loc);
1899 return pref.Resolve (ec);
1904 // Stage 2: Lookup members
1907 DeclSpace lookup_ds = ec.DeclSpace;
1908 Type almost_matched_type = null;
1909 ArrayList almost_matched = null;
1911 if (lookup_ds.TypeBuilder == null)
1914 e = MemberLookup (ec, lookup_ds.TypeBuilder, Name, loc);
1918 if (almost_matched == null && almostMatchedMembers.Count > 0) {
1919 almost_matched_type = lookup_ds.TypeBuilder;
1920 almost_matched = (ArrayList) almostMatchedMembers.Clone ();
1923 lookup_ds =lookup_ds.Parent;
1924 } while (lookup_ds != null);
1926 if (e == null && ec.ContainerType != null)
1927 e = MemberLookup (ec, ec.ContainerType, Name, loc);
1930 if (almost_matched == null && almostMatchedMembers.Count > 0) {
1931 almost_matched_type = ec.ContainerType;
1932 almost_matched = (ArrayList) almostMatchedMembers.Clone ();
1934 e = ResolveAsTypeStep (ec, false);
1938 if (almost_matched != null)
1939 almostMatchedMembers = almost_matched;
1940 if (almost_matched_type == null)
1941 almost_matched_type = ec.ContainerType;
1942 MemberLookupFailed (ec, null, almost_matched_type, ((SimpleName) this).Name, ec.DeclSpace.Name, true, loc);
1949 if (e is MemberExpr) {
1950 MemberExpr me = (MemberExpr) e;
1953 if (me.IsInstance) {
1954 if (ec.IsStatic || ec.IsFieldInitializer) {
1956 // Note that an MemberExpr can be both IsInstance and IsStatic.
1957 // An unresolved MethodGroupExpr can contain both kinds of methods
1958 // and each predicate is true if the MethodGroupExpr contains
1959 // at least one of that kind of method.
1963 (!intermediate || !IdenticalNameAndTypeName (ec, me, loc))) {
1964 Error_ObjectRefRequired (ec, loc, me.GetSignatureForError ());
1969 // Pass the buck to MemberAccess and Invocation.
1971 left = EmptyExpression.Null;
1973 left = ec.GetThis (loc);
1976 left = new TypeExpression (ec.ContainerType, loc);
1979 e = me.ResolveMemberAccess (ec, left, loc, null);
1983 me = e as MemberExpr;
1988 TypeManager.IsNestedFamilyAccessible (me.InstanceExpression.Type, me.DeclaringType) &&
1989 me.InstanceExpression.Type != me.DeclaringType &&
1990 !me.InstanceExpression.Type.IsSubclassOf (me.DeclaringType) &&
1991 (!intermediate || !IdenticalNameAndTypeName (ec, e, loc))) {
1992 Report.Error (38, loc, "Cannot access a nonstatic member of outer type `{0}' via nested type `{1}'",
1993 TypeManager.CSharpName (me.DeclaringType), TypeManager.CSharpName (me.InstanceExpression.Type));
1997 return (right_side != null)
1998 ? me.DoResolveLValue (ec, right_side)
1999 : me.DoResolve (ec);
2005 public override void Emit (EmitContext ec)
2008 // If this is ever reached, then we failed to
2009 // find the name as a namespace
2012 Error (103, "The name `" + Name +
2013 "' does not exist in the class `" +
2014 ec.DeclSpace.Name + "'");
2017 public override string ToString ()
2022 public override string GetSignatureForError ()
2029 /// Represents a namespace or a type. The name of the class was inspired by
2030 /// section 10.8.1 (Fully Qualified Names).
2032 public abstract class FullNamedExpression : Expression {
2033 public override FullNamedExpression ResolveAsTypeStep (EmitContext ec, bool silent)
2038 public abstract string FullName {
2044 /// Fully resolved expression that evaluates to a type
2046 public abstract class TypeExpr : FullNamedExpression {
2047 override public FullNamedExpression ResolveAsTypeStep (EmitContext ec, bool silent)
2049 TypeExpr t = DoResolveAsTypeStep (ec);
2053 eclass = ExprClass.Type;
2057 override public Expression DoResolve (EmitContext ec)
2059 return ResolveAsTypeTerminal (ec, false);
2062 override public void Emit (EmitContext ec)
2064 throw new Exception ("Should never be called");
2067 public virtual bool CheckAccessLevel (DeclSpace ds)
2069 return ds.CheckAccessLevel (Type);
2072 public virtual bool AsAccessible (DeclSpace ds, int flags)
2074 return ds.AsAccessible (Type, flags);
2077 public virtual bool IsClass {
2078 get { return Type.IsClass; }
2081 public virtual bool IsValueType {
2082 get { return Type.IsValueType; }
2085 public virtual bool IsInterface {
2086 get { return Type.IsInterface; }
2089 public virtual bool IsSealed {
2090 get { return Type.IsSealed; }
2093 public virtual bool CanInheritFrom ()
2095 if (Type == TypeManager.enum_type ||
2096 (Type == TypeManager.value_type && RootContext.StdLib) ||
2097 Type == TypeManager.multicast_delegate_type ||
2098 Type == TypeManager.delegate_type ||
2099 Type == TypeManager.array_type)
2105 public abstract TypeExpr DoResolveAsTypeStep (EmitContext ec);
2107 public virtual Type ResolveType (EmitContext ec)
2109 TypeExpr t = ResolveAsTypeTerminal (ec, false);
2116 public abstract string Name {
2120 public override bool Equals (object obj)
2122 TypeExpr tobj = obj as TypeExpr;
2126 return Type == tobj.Type;
2129 public override int GetHashCode ()
2131 return Type.GetHashCode ();
2134 public override string ToString ()
2140 public class TypeExpression : TypeExpr {
2141 public TypeExpression (Type t, Location l)
2144 eclass = ExprClass.Type;
2148 public override TypeExpr DoResolveAsTypeStep (EmitContext ec)
2153 public override string Name {
2154 get { return Type.ToString (); }
2157 public override string FullName {
2158 get { return Type.FullName; }
2163 /// Used to create types from a fully qualified name. These are just used
2164 /// by the parser to setup the core types. A TypeLookupExpression is always
2165 /// classified as a type.
2167 public class TypeLookupExpression : TypeExpr {
2170 public TypeLookupExpression (string name)
2175 static readonly char [] dot_array = { '.' };
2176 public override TypeExpr DoResolveAsTypeStep (EmitContext ec)
2181 // If name is of the form `N.I', first lookup `N', then search a member `I' in it.
2183 string lookup_name = name;
2184 int pos = name.IndexOf ('.');
2186 rest = name.Substring (pos + 1);
2187 lookup_name = name.Substring (0, pos);
2190 FullNamedExpression resolved = Namespace.Root.Lookup (ec.DeclSpace, lookup_name, Location.Null);
2192 if (resolved != null && rest != null) {
2193 // Now handle the rest of the the name.
2194 string [] elements = rest.Split (dot_array);
2196 int count = elements.Length;
2198 while (i < count && resolved != null && resolved is Namespace) {
2199 Namespace ns = resolved as Namespace;
2200 element = elements [i++];
2201 lookup_name += "." + element;
2202 resolved = ns.Lookup (ec.DeclSpace, element, Location.Null);
2205 if (resolved != null && resolved is TypeExpr) {
2206 Type t = ((TypeExpr) resolved).Type;
2208 if (!ec.DeclSpace.CheckAccessLevel (t)) {
2210 lookup_name = t.FullName;
2217 t = TypeManager.GetNestedType (t, elements [i++]);
2222 if (resolved == null) {
2223 NamespaceEntry.Error_NamespaceNotFound (loc, lookup_name);
2227 if (!(resolved is TypeExpr)) {
2228 resolved.Error_UnexpectedKind (ec, "type", loc);
2232 type = ((TypeExpr) resolved).ResolveType (ec);
2236 public override string Name {
2237 get { return name; }
2240 public override string FullName {
2241 get { return name; }
2245 public class TypeAliasExpression : TypeExpr {
2248 public TypeAliasExpression (TypeExpr texpr, Location l)
2251 loc = texpr.Location;
2253 eclass = ExprClass.Type;
2256 public override string Name {
2257 get { return texpr.Name; }
2260 public override string FullName {
2261 get { return texpr.FullName; }
2264 public override TypeExpr DoResolveAsTypeStep (EmitContext ec)
2266 Type type = texpr.ResolveType (ec);
2270 return new TypeExpression (type, loc);
2273 public override bool CheckAccessLevel (DeclSpace ds)
2275 return texpr.CheckAccessLevel (ds);
2278 public override bool AsAccessible (DeclSpace ds, int flags)
2280 return texpr.AsAccessible (ds, flags);
2283 public override bool IsClass {
2284 get { return texpr.IsClass; }
2287 public override bool IsValueType {
2288 get { return texpr.IsValueType; }
2291 public override bool IsInterface {
2292 get { return texpr.IsInterface; }
2295 public override bool IsSealed {
2296 get { return texpr.IsSealed; }
2301 /// This class denotes an expression which evaluates to a member
2302 /// of a struct or a class.
2304 public abstract class MemberExpr : Expression
2307 /// The name of this member.
2309 public abstract string Name {
2314 /// Whether this is an instance member.
2316 public abstract bool IsInstance {
2321 /// Whether this is a static member.
2323 public abstract bool IsStatic {
2328 /// The type which declares this member.
2330 public abstract Type DeclaringType {
2335 /// The instance expression associated with this member, if it's a
2336 /// non-static member.
2338 public Expression InstanceExpression;
2340 public static void error176 (Location loc, string name)
2342 Report.Error (176, loc, "Static member `{0}' cannot be accessed " +
2343 "with an instance reference, qualify it with a type name instead", name);
2347 // TODO: possible optimalization
2348 // Cache resolved constant result in FieldBuilder <-> expression map
2349 public virtual Expression ResolveMemberAccess (EmitContext ec, Expression left, Location loc,
2350 SimpleName original)
2354 // original == null || original.Resolve (...) ==> left
2357 if (left is TypeExpr) {
2359 SimpleName.Error_ObjectRefRequired (ec, loc, Name);
2367 if (original != null && original.IdenticalNameAndTypeName (ec, left, loc))
2370 error176 (loc, GetSignatureForError ());
2374 InstanceExpression = left;
2379 protected void EmitInstance (EmitContext ec, bool prepare_for_load)
2384 if (InstanceExpression == EmptyExpression.Null) {
2385 SimpleName.Error_ObjectRefRequired (ec, loc, Name);
2389 if (InstanceExpression.Type.IsValueType) {
2390 if (InstanceExpression is IMemoryLocation) {
2391 ((IMemoryLocation) InstanceExpression).AddressOf (ec, AddressOp.LoadStore);
2393 LocalTemporary t = new LocalTemporary (ec, InstanceExpression.Type);
2394 InstanceExpression.Emit (ec);
2396 t.AddressOf (ec, AddressOp.Store);
2399 InstanceExpression.Emit (ec);
2401 if (prepare_for_load)
2402 ec.ig.Emit (OpCodes.Dup);
2407 /// MethodGroup Expression.
2409 /// This is a fully resolved expression that evaluates to a type
2411 public class MethodGroupExpr : MemberExpr {
2412 public MethodBase [] Methods;
2413 bool identical_type_name = false;
2416 public MethodGroupExpr (MemberInfo [] mi, Location l)
2418 Methods = new MethodBase [mi.Length];
2419 mi.CopyTo (Methods, 0);
2420 eclass = ExprClass.MethodGroup;
2421 type = TypeManager.object_type;
2425 public MethodGroupExpr (ArrayList list, Location l)
2427 Methods = new MethodBase [list.Count];
2430 list.CopyTo (Methods, 0);
2432 foreach (MemberInfo m in list){
2433 if (!(m is MethodBase)){
2434 Console.WriteLine ("Name " + m.Name);
2435 Console.WriteLine ("Found a: " + m.GetType ().FullName);
2442 eclass = ExprClass.MethodGroup;
2443 type = TypeManager.object_type;
2446 public override Type DeclaringType {
2449 // The methods are arranged in this order:
2450 // derived type -> base type
2452 return Methods [0].DeclaringType;
2456 public bool IdenticalTypeName {
2458 return identical_type_name;
2462 identical_type_name = value;
2466 public bool IsBase {
2475 public override string GetSignatureForError ()
2477 return TypeManager.CSharpSignature (Methods [0]);
2480 public override string Name {
2482 return Methods [0].Name;
2486 public override bool IsInstance {
2488 foreach (MethodBase mb in Methods)
2496 public override bool IsStatic {
2498 foreach (MethodBase mb in Methods)
2506 public override Expression ResolveMemberAccess (EmitContext ec, Expression left, Location loc,
2507 SimpleName original)
2509 if (!(left is TypeExpr) &&
2510 original != null && original.IdenticalNameAndTypeName (ec, left, loc))
2511 IdenticalTypeName = true;
2513 return base.ResolveMemberAccess (ec, left, loc, original);
2516 override public Expression DoResolve (EmitContext ec)
2519 InstanceExpression = null;
2521 if (InstanceExpression != null) {
2522 InstanceExpression = InstanceExpression.DoResolve (ec);
2523 if (InstanceExpression == null)
2530 public void ReportUsageError ()
2532 Report.Error (654, loc, "Method `" + DeclaringType + "." +
2533 Name + "()' is referenced without parentheses");
2536 override public void Emit (EmitContext ec)
2538 ReportUsageError ();
2541 bool RemoveMethods (bool keep_static)
2543 ArrayList smethods = new ArrayList ();
2545 foreach (MethodBase mb in Methods){
2546 if (mb.IsStatic == keep_static)
2550 if (smethods.Count == 0)
2553 Methods = new MethodBase [smethods.Count];
2554 smethods.CopyTo (Methods, 0);
2560 /// Removes any instance methods from the MethodGroup, returns
2561 /// false if the resulting set is empty.
2563 public bool RemoveInstanceMethods ()
2565 return RemoveMethods (true);
2569 /// Removes any static methods from the MethodGroup, returns
2570 /// false if the resulting set is empty.
2572 public bool RemoveStaticMethods ()
2574 return RemoveMethods (false);
2579 /// Fully resolved expression that evaluates to a Field
2581 public class FieldExpr : MemberExpr, IAssignMethod, IMemoryLocation, IVariable {
2582 public readonly FieldInfo FieldInfo;
2583 VariableInfo variable_info;
2585 LocalTemporary temp;
2587 bool in_initializer;
2589 public FieldExpr (FieldInfo fi, Location l, bool in_initializer):
2592 this.in_initializer = in_initializer;
2595 public FieldExpr (FieldInfo fi, Location l)
2598 eclass = ExprClass.Variable;
2599 type = fi.FieldType;
2603 public override string Name {
2605 return FieldInfo.Name;
2609 public override bool IsInstance {
2611 return !FieldInfo.IsStatic;
2615 public override bool IsStatic {
2617 return FieldInfo.IsStatic;
2621 public override Type DeclaringType {
2623 return FieldInfo.DeclaringType;
2627 public override string GetSignatureForError ()
2629 return TypeManager.GetFullNameSignature (FieldInfo);
2632 public VariableInfo VariableInfo {
2634 return variable_info;
2638 public override Expression ResolveMemberAccess (EmitContext ec, Expression left, Location loc,
2639 SimpleName original)
2641 if (FieldInfo.IsLiteral) {
2642 IConstant ic = TypeManager.GetConstant (FieldInfo);
2644 ic = new ExternalConstant (FieldInfo);
2645 TypeManager.RegisterConstant (FieldInfo, ic);
2648 bool left_is_type = left is TypeExpr;
2649 if (!left_is_type && (original == null || !original.IdenticalNameAndTypeName (ec, left, loc))) {
2650 Report.SymbolRelatedToPreviousError (FieldInfo);
2651 error176 (loc, TypeManager.GetFullNameSignature (FieldInfo));
2655 if (ic.ResolveValue ())
2656 ic.CheckObsoleteness (loc);
2661 bool is_emitted = FieldInfo is FieldBuilder;
2662 Type t = FieldInfo.FieldType;
2665 // Decimal constants cannot be encoded in the constant blob, and thus are marked
2666 // as IsInitOnly ('readonly' in C# parlance). We get its value from the
2667 // DecimalConstantAttribute metadata.
2669 //TODO: incorporare in GetContant otherwise we miss all error checks + obsoleteness check
2670 if (FieldInfo.IsInitOnly && !is_emitted && t == TypeManager.decimal_type) {
2671 object[] attrs = FieldInfo.GetCustomAttributes (TypeManager.decimal_constant_attribute_type, false);
2672 if (attrs.Length == 1)
2673 return new DecimalConstant (((System.Runtime.CompilerServices.DecimalConstantAttribute) attrs [0]).Value);
2676 if (t.IsPointer && !ec.InUnsafe) {
2681 return base.ResolveMemberAccess (ec, left, loc, original);
2684 override public Expression DoResolve (EmitContext ec)
2686 if (ec.InRefOutArgumentResolving && FieldInfo.IsInitOnly && !ec.IsConstructor && FieldInfo.FieldType.IsValueType) {
2687 if (FieldInfo.FieldType is TypeBuilder) {
2688 if (FieldInfo.IsStatic)
2689 Report.Error (1651, loc, "Fields of static readonly field `{0}' cannot be passed ref or out (except in a static constructor)",
2690 GetSignatureForError ());
2692 Report.Error (1649, loc, "Members of readonly field `{0}.{1}' cannot be passed ref or out (except in a constructor)",
2693 TypeManager.CSharpName (DeclaringType), Name);
2695 if (FieldInfo.IsStatic)
2696 Report.Error (199, loc, "A static readonly field `{0}' cannot be passed ref or out (except in a static constructor)",
2699 Report.Error (192, loc, "A readonly field `{0}' cannot be passed ref or out (except in a constructor)",
2705 if (!FieldInfo.IsStatic){
2706 if (InstanceExpression == null){
2708 // This can happen when referencing an instance field using
2709 // a fully qualified type expression: TypeName.InstanceField = xxx
2711 SimpleName.Error_ObjectRefRequired (ec, loc, FieldInfo.Name);
2715 // Resolve the field's instance expression while flow analysis is turned
2716 // off: when accessing a field "a.b", we must check whether the field
2717 // "a.b" is initialized, not whether the whole struct "a" is initialized.
2718 InstanceExpression = InstanceExpression.Resolve (
2719 ec, ResolveFlags.VariableOrValue | ResolveFlags.DisableFlowAnalysis);
2720 if (InstanceExpression == null)
2724 if (!in_initializer) {
2725 ObsoleteAttribute oa;
2726 FieldBase f = TypeManager.GetField (FieldInfo);
2728 f.CheckObsoleteness (loc);
2730 // To be sure that type is external because we do not register generated fields
2731 } else if (!(FieldInfo.DeclaringType is TypeBuilder)) {
2732 oa = AttributeTester.GetMemberObsoleteAttribute (FieldInfo);
2734 AttributeTester.Report_ObsoleteMessage (oa, TypeManager.GetFullNameSignature (FieldInfo), loc);
2738 AnonymousContainer am = ec.CurrentAnonymousMethod;
2740 if (!FieldInfo.IsStatic){
2741 if (!am.IsIterator && (ec.TypeContainer is Struct)){
2742 Report.Error (1673, loc,
2743 "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",
2747 if ((am.ContainerAnonymousMethod == null) && (InstanceExpression is This))
2748 ec.CaptureField (this);
2752 // If the instance expression is a local variable or parameter.
2753 IVariable var = InstanceExpression as IVariable;
2754 if ((var == null) || (var.VariableInfo == null))
2757 VariableInfo vi = var.VariableInfo;
2758 if (!vi.IsFieldAssigned (ec, FieldInfo.Name, loc))
2761 variable_info = vi.GetSubStruct (FieldInfo.Name);
2765 void Report_AssignToReadonly (bool is_instance)
2770 msg = "A readonly field cannot be assigned to (except in a constructor or a variable initializer)";
2772 msg = "A static readonly field cannot be assigned to (except in a static constructor or a variable initializer)";
2774 Report.Error (is_instance ? 191 : 198, loc, msg);
2777 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
2779 IVariable var = InstanceExpression as IVariable;
2780 if ((var != null) && (var.VariableInfo != null))
2781 var.VariableInfo.SetFieldAssigned (ec, FieldInfo.Name);
2783 Expression e = DoResolve (ec);
2788 if (!FieldInfo.IsStatic && (InstanceExpression.Type.IsValueType && !(InstanceExpression is IMemoryLocation))) {
2789 Report.Error (1612, loc, "Cannot modify the return value of `{0}' because it is not a variable",
2790 InstanceExpression.GetSignatureForError ());
2794 FieldBase fb = TypeManager.GetField (FieldInfo);
2798 if (!FieldInfo.IsInitOnly)
2802 // InitOnly fields can only be assigned in constructors
2805 if (ec.IsConstructor){
2806 if (IsStatic && !ec.IsStatic)
2807 Report_AssignToReadonly (false);
2809 if (ec.ContainerType == FieldInfo.DeclaringType)
2813 Report_AssignToReadonly (!IsStatic);
2818 public override void CheckMarshallByRefAccess (Type container)
2820 if (!IsStatic && Type.IsValueType && !container.IsSubclassOf (TypeManager.mbr_type) && DeclaringType.IsSubclassOf (TypeManager.mbr_type)) {
2821 Report.SymbolRelatedToPreviousError (DeclaringType);
2822 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",
2823 GetSignatureForError ());
2827 public bool VerifyFixed ()
2829 IVariable variable = InstanceExpression as IVariable;
2830 // A variable of the form V.I is fixed when V is a fixed variable of a struct type.
2831 // We defer the InstanceExpression check after the variable check to avoid a
2832 // separate null check on InstanceExpression.
2833 return variable != null && InstanceExpression.Type.IsValueType && variable.VerifyFixed ();
2836 public override int GetHashCode()
2838 return FieldInfo.GetHashCode ();
2841 public override bool Equals (object obj)
2843 FieldExpr fe = obj as FieldExpr;
2847 if (FieldInfo != fe.FieldInfo)
2850 if (InstanceExpression == null || fe.InstanceExpression == null)
2853 return InstanceExpression.Equals (fe.InstanceExpression);
2856 public void Emit (EmitContext ec, bool leave_copy)
2858 ILGenerator ig = ec.ig;
2859 bool is_volatile = false;
2861 if (FieldInfo is FieldBuilder){
2862 FieldBase f = TypeManager.GetField (FieldInfo);
2864 if ((f.ModFlags & Modifiers.VOLATILE) != 0)
2867 f.SetMemberIsUsed ();
2871 if (FieldInfo.IsStatic){
2873 ig.Emit (OpCodes.Volatile);
2875 ig.Emit (OpCodes.Ldsfld, FieldInfo);
2878 EmitInstance (ec, false);
2881 ig.Emit (OpCodes.Volatile);
2883 IFixedBuffer ff = AttributeTester.GetFixedBuffer (FieldInfo);
2886 ig.Emit (OpCodes.Ldflda, FieldInfo);
2887 ig.Emit (OpCodes.Ldflda, ff.Element);
2890 ig.Emit (OpCodes.Ldfld, FieldInfo);
2895 ec.ig.Emit (OpCodes.Dup);
2896 if (!FieldInfo.IsStatic) {
2897 temp = new LocalTemporary (ec, this.Type);
2903 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
2905 FieldAttributes fa = FieldInfo.Attributes;
2906 bool is_static = (fa & FieldAttributes.Static) != 0;
2907 bool is_readonly = (fa & FieldAttributes.InitOnly) != 0;
2908 ILGenerator ig = ec.ig;
2909 prepared = prepare_for_load;
2911 if (is_readonly && !ec.IsConstructor){
2912 Report_AssignToReadonly (!is_static);
2916 EmitInstance (ec, prepare_for_load);
2920 ec.ig.Emit (OpCodes.Dup);
2921 if (!FieldInfo.IsStatic) {
2922 temp = new LocalTemporary (ec, this.Type);
2927 if (FieldInfo is FieldBuilder){
2928 FieldBase f = TypeManager.GetField (FieldInfo);
2930 if ((f.ModFlags & Modifiers.VOLATILE) != 0)
2931 ig.Emit (OpCodes.Volatile);
2938 ig.Emit (OpCodes.Stsfld, FieldInfo);
2940 ig.Emit (OpCodes.Stfld, FieldInfo);
2946 public override void Emit (EmitContext ec)
2951 public void AddressOf (EmitContext ec, AddressOp mode)
2953 ILGenerator ig = ec.ig;
2955 if (FieldInfo is FieldBuilder){
2956 FieldBase f = TypeManager.GetField (FieldInfo);
2958 if ((f.ModFlags & Modifiers.VOLATILE) != 0){
2959 Report.Warning (420, 1, loc, "`{0}': A volatile fields cannot be passed using a ref or out parameter",
2960 f.GetSignatureForError ());
2964 if ((mode & AddressOp.Store) != 0)
2966 if ((mode & AddressOp.Load) != 0)
2967 f.SetMemberIsUsed ();
2972 // Handle initonly fields specially: make a copy and then
2973 // get the address of the copy.
2976 if (FieldInfo.IsInitOnly){
2978 if (ec.IsConstructor){
2979 if (FieldInfo.IsStatic){
2991 local = ig.DeclareLocal (type);
2992 ig.Emit (OpCodes.Stloc, local);
2993 ig.Emit (OpCodes.Ldloca, local);
2998 if (FieldInfo.IsStatic){
2999 ig.Emit (OpCodes.Ldsflda, FieldInfo);
3001 EmitInstance (ec, false);
3002 ig.Emit (OpCodes.Ldflda, FieldInfo);
3008 // A FieldExpr whose address can not be taken
3010 public class FieldExprNoAddress : FieldExpr, IMemoryLocation {
3011 public FieldExprNoAddress (FieldInfo fi, Location loc) : base (fi, loc)
3015 public new void AddressOf (EmitContext ec, AddressOp mode)
3017 Report.Error (-215, "Report this: Taking the address of a remapped parameter not supported");
3022 /// Expression that evaluates to a Property. The Assign class
3023 /// might set the `Value' expression if we are in an assignment.
3025 /// This is not an LValue because we need to re-write the expression, we
3026 /// can not take data from the stack and store it.
3028 public class PropertyExpr : MemberExpr, IAssignMethod {
3029 public readonly PropertyInfo PropertyInfo;
3032 // This is set externally by the `BaseAccess' class
3035 MethodInfo getter, setter;
3040 LocalTemporary temp;
3043 internal static PtrHashtable AccessorTable = new PtrHashtable ();
3045 public PropertyExpr (EmitContext ec, PropertyInfo pi, Location l)
3048 eclass = ExprClass.PropertyAccess;
3052 type = TypeManager.TypeToCoreType (pi.PropertyType);
3054 ResolveAccessors (ec);
3057 public override string Name {
3059 return PropertyInfo.Name;
3063 public override bool IsInstance {
3069 public override bool IsStatic {
3075 public override Type DeclaringType {
3077 return PropertyInfo.DeclaringType;
3081 public override string GetSignatureForError ()
3083 return TypeManager.GetFullNameSignature (PropertyInfo);
3086 void FindAccessors (Type invocation_type)
3088 BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic |
3089 BindingFlags.Static | BindingFlags.Instance |
3090 BindingFlags.DeclaredOnly;
3092 Type current = PropertyInfo.DeclaringType;
3093 for (; current != null; current = current.BaseType) {
3094 MemberInfo[] group = TypeManager.MemberLookup (
3095 invocation_type, invocation_type, current,
3096 MemberTypes.Property, flags, PropertyInfo.Name, null);
3101 if (group.Length != 1)
3102 // Oooops, can this ever happen ?
3105 PropertyInfo pi = (PropertyInfo) group [0];
3108 getter = pi.GetGetMethod (true);
3111 setter = pi.GetSetMethod (true);
3113 MethodInfo accessor = getter != null ? getter : setter;
3115 if (!accessor.IsVirtual)
3121 // We also perform the permission checking here, as the PropertyInfo does not
3122 // hold the information for the accessibility of its setter/getter
3124 void ResolveAccessors (EmitContext ec)
3126 FindAccessors (ec.ContainerType);
3128 if (getter != null) {
3129 IMethodData md = TypeManager.GetMethod (getter);
3131 md.SetMemberIsUsed ();
3133 AccessorTable [getter] = PropertyInfo;
3134 is_static = getter.IsStatic;
3137 if (setter != null) {
3138 IMethodData md = TypeManager.GetMethod (setter);
3140 md.SetMemberIsUsed ();
3142 AccessorTable [setter] = PropertyInfo;
3143 is_static = setter.IsStatic;
3147 bool InstanceResolve (EmitContext ec, bool must_do_cs1540_check)
3150 InstanceExpression = null;
3154 if (InstanceExpression == null) {
3155 SimpleName.Error_ObjectRefRequired (ec, loc, PropertyInfo.Name);
3159 InstanceExpression = InstanceExpression.DoResolve (ec);
3160 if (InstanceExpression == null)
3163 InstanceExpression.CheckMarshallByRefAccess (ec.ContainerType);
3165 if (must_do_cs1540_check && InstanceExpression != EmptyExpression.Null) {
3166 if ((InstanceExpression.Type != ec.ContainerType) &&
3167 ec.ContainerType.IsSubclassOf (InstanceExpression.Type)) {
3168 Report.Error (1540, loc, "Cannot access protected member `" +
3169 PropertyInfo.DeclaringType + "." + PropertyInfo.Name +
3170 "' via a qualifier of type `" +
3171 TypeManager.CSharpName (InstanceExpression.Type) +
3172 "'; the qualifier must be of type `" +
3173 TypeManager.CSharpName (ec.ContainerType) +
3174 "' (or derived from it)");
3182 void Error_PropertyNotFound (MethodInfo mi, bool getter)
3184 // TODO: correctly we should compare arguments but it will lead to bigger changes
3185 if (mi is MethodBuilder) {
3186 Error_TypeDoesNotContainDefinition (loc, PropertyInfo.DeclaringType, Name);
3190 StringBuilder sig = new StringBuilder (TypeManager.CSharpName (mi.DeclaringType));
3192 ParameterData iparams = TypeManager.GetParameterData (mi);
3193 sig.Append (getter ? "get_" : "set_");
3195 sig.Append (iparams.GetSignatureForError ());
3197 Report.SymbolRelatedToPreviousError (mi);
3198 Report.Error (1546, loc, "Property `{0}' is not supported by the C# language. Try to call the accessor method `{1}' directly",
3199 Name, sig.ToString ());
3202 override public Expression DoResolve (EmitContext ec)
3207 if (getter != null){
3208 if (TypeManager.GetArgumentTypes (getter).Length != 0){
3209 Error_PropertyNotFound (getter, true);
3214 if (getter == null){
3216 // The following condition happens if the PropertyExpr was
3217 // created, but is invalid (ie, the property is inaccessible),
3218 // and we did not want to embed the knowledge about this in
3219 // the caller routine. This only avoids double error reporting.
3224 if (InstanceExpression != EmptyExpression.Null) {
3225 Report.Error (154, loc, "The property or indexer `{0}' cannot be used in this context because it lacks the `get' accessor",
3226 TypeManager.GetFullNameSignature (PropertyInfo));
3231 bool must_do_cs1540_check = false;
3232 if (getter != null &&
3233 !IsAccessorAccessible (ec.ContainerType, getter, out must_do_cs1540_check)) {
3234 PropertyBase.PropertyMethod pm = TypeManager.GetMethod (getter) as PropertyBase.PropertyMethod;
3235 if (pm != null && pm.HasCustomAccessModifier) {
3236 Report.SymbolRelatedToPreviousError (pm);
3237 Report.Error (271, loc, "The property or indexer `{0}' cannot be used in this context because the get accessor is inaccessible",
3238 TypeManager.CSharpSignature (getter));
3241 ErrorIsInaccesible (loc, TypeManager.CSharpSignature (getter));
3245 if (!InstanceResolve (ec, must_do_cs1540_check))
3249 // Only base will allow this invocation to happen.
3251 if (IsBase && getter.IsAbstract) {
3252 Error_CannotCallAbstractBase (TypeManager.GetFullNameSignature (PropertyInfo));
3256 if (PropertyInfo.PropertyType.IsPointer && !ec.InUnsafe){
3266 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
3268 if (setter == null){
3270 // The following condition happens if the PropertyExpr was
3271 // created, but is invalid (ie, the property is inaccessible),
3272 // and we did not want to embed the knowledge about this in
3273 // the caller routine. This only avoids double error reporting.
3278 Report.Error (200, loc, " Property or indexer `{0}' cannot be assigned to (it is read only)",
3279 TypeManager.GetFullNameSignature (PropertyInfo));
3283 if (TypeManager.GetArgumentTypes (setter).Length != 1){
3284 Error_PropertyNotFound (setter, false);
3288 bool must_do_cs1540_check;
3289 if (!IsAccessorAccessible (ec.ContainerType, setter, out must_do_cs1540_check)) {
3290 PropertyBase.PropertyMethod pm = TypeManager.GetMethod (setter) as PropertyBase.PropertyMethod;
3291 if (pm != null && pm.HasCustomAccessModifier) {
3292 Report.SymbolRelatedToPreviousError (pm);
3293 Report.Error (272, loc, "The property or indexer `{0}' cannot be used in this context because the set accessor is inaccessible",
3294 TypeManager.CSharpSignature (setter));
3297 ErrorIsInaccesible (loc, TypeManager.CSharpSignature (setter));
3301 if (!InstanceResolve (ec, must_do_cs1540_check))
3305 // Only base will allow this invocation to happen.
3307 if (IsBase && setter.IsAbstract){
3308 Error_CannotCallAbstractBase (TypeManager.GetFullNameSignature (PropertyInfo));
3313 // Check that we are not making changes to a temporary memory location
3315 if (InstanceExpression != null && InstanceExpression.Type.IsValueType && !(InstanceExpression is IMemoryLocation)) {
3316 Report.Error (1612, loc, "Cannot modify the return value of `{0}' because it is not a variable",
3317 InstanceExpression.GetSignatureForError ());
3324 public override void Emit (EmitContext ec)
3329 public void Emit (EmitContext ec, bool leave_copy)
3332 EmitInstance (ec, false);
3335 // Special case: length of single dimension array property is turned into ldlen
3337 if ((getter == TypeManager.system_int_array_get_length) ||
3338 (getter == TypeManager.int_array_get_length)){
3339 Type iet = InstanceExpression.Type;
3342 // System.Array.Length can be called, but the Type does not
3343 // support invoking GetArrayRank, so test for that case first
3345 if (iet != TypeManager.array_type && (iet.GetArrayRank () == 1)) {
3346 ec.ig.Emit (OpCodes.Ldlen);
3347 ec.ig.Emit (OpCodes.Conv_I4);
3352 Invocation.EmitCall (ec, IsBase, IsStatic, new EmptyAddressOf (), getter, null, loc);
3357 ec.ig.Emit (OpCodes.Dup);
3359 temp = new LocalTemporary (ec, this.Type);
3365 // Implements the IAssignMethod interface for assignments
3367 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
3369 prepared = prepare_for_load;
3371 EmitInstance (ec, prepare_for_load);
3375 ec.ig.Emit (OpCodes.Dup);
3377 temp = new LocalTemporary (ec, this.Type);
3382 ArrayList args = new ArrayList (1);
3383 args.Add (new Argument (new EmptyAddressOf (), Argument.AType.Expression));
3385 Invocation.EmitCall (ec, IsBase, IsStatic, new EmptyAddressOf (), setter, args, loc);
3393 /// Fully resolved expression that evaluates to an Event
3395 public class EventExpr : MemberExpr {
3396 public readonly EventInfo EventInfo;
3399 MethodInfo add_accessor, remove_accessor;
3401 public EventExpr (EventInfo ei, Location loc)
3405 eclass = ExprClass.EventAccess;
3407 add_accessor = TypeManager.GetAddMethod (ei);
3408 remove_accessor = TypeManager.GetRemoveMethod (ei);
3410 if (add_accessor.IsStatic || remove_accessor.IsStatic)
3413 if (EventInfo is MyEventBuilder){
3414 MyEventBuilder eb = (MyEventBuilder) EventInfo;
3415 type = eb.EventType;
3418 type = EventInfo.EventHandlerType;
3421 public override string Name {
3423 return EventInfo.Name;
3427 public override bool IsInstance {
3433 public override bool IsStatic {
3439 public override Type DeclaringType {
3441 return EventInfo.DeclaringType;
3445 public override Expression ResolveMemberAccess (EmitContext ec, Expression left, Location loc,
3446 SimpleName original)
3449 // If the event is local to this class, we transform ourselves into a FieldExpr
3452 if (EventInfo.DeclaringType == ec.ContainerType ||
3453 TypeManager.IsNestedChildOf(ec.ContainerType, EventInfo.DeclaringType)) {
3454 MemberInfo mi = TypeManager.GetPrivateFieldOfEvent (EventInfo);
3457 MemberExpr ml = (MemberExpr) ExprClassFromMemberInfo (ec, mi, loc);
3460 Report.Error (-200, loc, "Internal error!!");
3464 InstanceExpression = null;
3466 return ml.ResolveMemberAccess (ec, left, loc, original);
3470 return base.ResolveMemberAccess (ec, left, loc, original);
3474 bool InstanceResolve (EmitContext ec, bool must_do_cs1540_check)
3477 InstanceExpression = null;
3481 if (InstanceExpression == null) {
3482 SimpleName.Error_ObjectRefRequired (ec, loc, EventInfo.Name);
3486 InstanceExpression = InstanceExpression.DoResolve (ec);
3487 if (InstanceExpression == null)
3491 // This is using the same mechanism as the CS1540 check in PropertyExpr.
3492 // However, in the Event case, we reported a CS0122 instead.
3494 if (must_do_cs1540_check && InstanceExpression != EmptyExpression.Null) {
3495 if ((InstanceExpression.Type != ec.ContainerType) &&
3496 ec.ContainerType.IsSubclassOf (InstanceExpression.Type)) {
3497 ErrorIsInaccesible (loc, TypeManager.CSharpSignature (EventInfo));
3505 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
3507 return DoResolve (ec);
3510 public override Expression DoResolve (EmitContext ec)
3512 bool must_do_cs1540_check;
3513 if (!(IsAccessorAccessible (ec.ContainerType, add_accessor, out must_do_cs1540_check) &&
3514 IsAccessorAccessible (ec.ContainerType, remove_accessor, out must_do_cs1540_check))) {
3515 ErrorIsInaccesible (loc, TypeManager.CSharpSignature (EventInfo));
3519 if (!InstanceResolve (ec, must_do_cs1540_check))
3525 public override void Emit (EmitContext ec)
3527 if (InstanceExpression is This)
3528 Report.Error (79, loc, "The event `{0}' can only appear on the left hand side of += or -=", GetSignatureForError ());
3530 Report.Error (70, loc, "The event `{0}' can only appear on the left hand side of += or -= "+
3531 "(except on the defining type)", Name);
3534 public override string GetSignatureForError ()
3536 return TypeManager.CSharpSignature (EventInfo);
3539 public void EmitAddOrRemove (EmitContext ec, Expression source)
3541 BinaryDelegate source_del = (BinaryDelegate) source;
3542 Expression handler = source_del.Right;
3544 Argument arg = new Argument (handler, Argument.AType.Expression);
3545 ArrayList args = new ArrayList ();
3549 if (source_del.IsAddition)
3550 Invocation.EmitCall (
3551 ec, false, IsStatic, InstanceExpression, add_accessor, args, loc);
3553 Invocation.EmitCall (
3554 ec, false, IsStatic, InstanceExpression, remove_accessor, args, loc);