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) {}
148 public virtual string GetSignatureForError ()
150 return TypeManager.CSharpName (type);
153 public static bool IsAccessorAccessible (Type invocation_type, MethodInfo mi, out bool must_do_cs1540_check)
155 MethodAttributes ma = mi.Attributes & MethodAttributes.MemberAccessMask;
157 must_do_cs1540_check = false; // by default we do not check for this
160 // If only accessible to the current class or children
162 if (ma == MethodAttributes.Private)
163 return invocation_type == mi.DeclaringType ||
164 TypeManager.IsNestedChildOf (invocation_type, mi.DeclaringType);
166 if (mi.DeclaringType.Assembly == invocation_type.Assembly) {
167 if (ma == MethodAttributes.Assembly || ma == MethodAttributes.FamORAssem)
170 if (ma == MethodAttributes.Assembly || ma == MethodAttributes.FamANDAssem)
174 // Family and FamANDAssem require that we derive.
175 // FamORAssem requires that we derive if in different assemblies.
176 if (ma == MethodAttributes.Family ||
177 ma == MethodAttributes.FamANDAssem ||
178 ma == MethodAttributes.FamORAssem) {
179 if (!TypeManager.IsNestedFamilyAccessible (invocation_type, mi.DeclaringType))
182 if (!TypeManager.IsNestedChildOf (invocation_type, mi.DeclaringType))
183 must_do_cs1540_check = true;
192 /// Performs semantic analysis on the Expression
196 /// The Resolve method is invoked to perform the semantic analysis
199 /// The return value is an expression (it can be the
200 /// same expression in some cases) or a new
201 /// expression that better represents this node.
203 /// For example, optimizations of Unary (LiteralInt)
204 /// would return a new LiteralInt with a negated
207 /// If there is an error during semantic analysis,
208 /// then an error should be reported (using Report)
209 /// and a null value should be returned.
211 /// There are two side effects expected from calling
212 /// Resolve(): the the field variable "eclass" should
213 /// be set to any value of the enumeration
214 /// `ExprClass' and the type variable should be set
215 /// to a valid type (this is the type of the
218 public abstract Expression DoResolve (EmitContext ec);
220 public virtual Expression DoResolveLValue (EmitContext ec, Expression right_side)
226 // This is used if the expression should be resolved as a type or namespace name.
227 // the default implementation fails.
229 public virtual FullNamedExpression ResolveAsTypeStep (EmitContext ec, bool silent)
235 // This is used to resolve the expression as a type, a null
236 // value will be returned if the expression is not a type
239 public TypeExpr ResolveAsTypeTerminal (EmitContext ec, bool silent)
241 int errors = Report.Errors;
243 FullNamedExpression fne = ResolveAsTypeStep (ec, silent);
248 if (fne.eclass != ExprClass.Type) {
249 if (!silent && errors == Report.Errors)
250 fne.Error_UnexpectedKind (null, "type", loc);
254 TypeExpr te = fne as TypeExpr;
256 if (!te.CheckAccessLevel (ec.DeclSpace)) {
257 ErrorIsInaccesible (loc, TypeManager.CSharpName (te.Type));
265 public static void ErrorIsInaccesible (Location loc, string name)
267 Report.Error (122, loc, "`{0}' is inaccessible due to its protection level", name);
270 public virtual void Error_ValueCannotBeConverted (Location loc, Type t)
272 Convert.Error_CannotImplicitConversion (loc, Type, t);
275 protected static void Error_TypeDoesNotContainDefinition (Location loc, Type type, string name)
277 Report.Error (117, loc, "`{0}' does not contain a definition for `{1}'",
278 TypeManager.CSharpName (type), name);
281 ResolveFlags ExprClassToResolveFlags ()
285 case ExprClass.Namespace:
286 return ResolveFlags.Type;
288 case ExprClass.MethodGroup:
289 return ResolveFlags.MethodGroup;
291 case ExprClass.Value:
292 case ExprClass.Variable:
293 case ExprClass.PropertyAccess:
294 case ExprClass.EventAccess:
295 case ExprClass.IndexerAccess:
296 return ResolveFlags.VariableOrValue;
299 throw new Exception ("Expression " + GetType () +
300 " ExprClass is Invalid after resolve");
306 /// Resolves an expression and performs semantic analysis on it.
310 /// Currently Resolve wraps DoResolve to perform sanity
311 /// checking and assertion checking on what we expect from Resolve.
313 public Expression Resolve (EmitContext ec, ResolveFlags flags)
315 if ((flags & ResolveFlags.MaskExprClass) == ResolveFlags.Type)
316 return ResolveAsTypeStep (ec, false);
318 bool old_do_flow_analysis = ec.DoFlowAnalysis;
319 bool old_omit_struct_analysis = ec.OmitStructFlowAnalysis;
320 if ((flags & ResolveFlags.DisableFlowAnalysis) != 0)
321 ec.DoFlowAnalysis = false;
322 if ((flags & ResolveFlags.DisableStructFlowAnalysis) != 0)
323 ec.OmitStructFlowAnalysis = true;
326 bool intermediate = (flags & ResolveFlags.Intermediate) == ResolveFlags.Intermediate;
327 if (this is SimpleName)
328 e = ((SimpleName) this).DoResolve (ec, intermediate);
333 ec.DoFlowAnalysis = old_do_flow_analysis;
334 ec.OmitStructFlowAnalysis = old_omit_struct_analysis;
339 if ((flags & e.ExprClassToResolveFlags ()) == 0) {
340 e.Error_UnexpectedKind (flags, loc);
344 if (e.type == null && !(e is Namespace)) {
345 throw new Exception (
346 "Expression " + e.GetType () +
347 " did not set its type after Resolve\n" +
348 "called from: " + this.GetType ());
355 /// Resolves an expression and performs semantic analysis on it.
357 public Expression Resolve (EmitContext ec)
359 Expression e = Resolve (ec, ResolveFlags.VariableOrValue | ResolveFlags.MethodGroup);
361 if (e != null && e.eclass == ExprClass.MethodGroup && RootContext.Version == LanguageVersion.ISO_1) {
362 ((MethodGroupExpr) e).ReportUsageError ();
368 public Constant ResolveAsConstant (EmitContext ec, MemberCore mc)
370 Expression e = Resolve (ec);
372 Constant c = e as Constant;
376 EmptyCast empty = e as EmptyCast;
378 c = empty.Child as Constant;
380 // TODO: not sure about this maybe there is easier way how to use EmptyCast
389 Const.Error_ExpressionMustBeConstant (loc, mc.GetSignatureForError ());
394 /// Resolves an expression for LValue assignment
398 /// Currently ResolveLValue wraps DoResolveLValue to perform sanity
399 /// checking and assertion checking on what we expect from Resolve
401 public Expression ResolveLValue (EmitContext ec, Expression right_side, Location loc)
403 int errors = Report.Errors;
404 Expression e = DoResolveLValue (ec, right_side);
407 if (errors == Report.Errors)
408 Report.Error (131, loc, "The left-hand side of an assignment or mutating operation must be a variable, property or indexer");
413 if (e.eclass == ExprClass.Invalid)
414 throw new Exception ("Expression " + e +
415 " ExprClass is Invalid after resolve");
417 if (e.eclass == ExprClass.MethodGroup) {
418 ((MethodGroupExpr) e).ReportUsageError ();
423 throw new Exception ("Expression " + e +
424 " did not set its type after Resolve");
431 /// Emits the code for the expression
435 /// The Emit method is invoked to generate the code
436 /// for the expression.
438 public abstract void Emit (EmitContext ec);
440 public virtual void EmitBranchable (EmitContext ec, Label target, bool onTrue)
443 ec.ig.Emit (onTrue ? OpCodes.Brtrue : OpCodes.Brfalse, target);
447 /// Protected constructor. Only derivate types should
448 /// be able to be created
451 protected Expression ()
453 eclass = ExprClass.Invalid;
458 /// Returns a literalized version of a literal FieldInfo
462 /// The possible return values are:
463 /// IntConstant, UIntConstant
464 /// LongLiteral, ULongConstant
465 /// FloatConstant, DoubleConstant
468 /// The value returned is already resolved.
470 public static Constant Constantify (object v, Type t)
472 if (t == TypeManager.int32_type)
473 return new IntConstant ((int) v, Location.Null);
474 else if (t == TypeManager.uint32_type)
475 return new UIntConstant ((uint) v, Location.Null);
476 else if (t == TypeManager.int64_type)
477 return new LongConstant ((long) v, Location.Null);
478 else if (t == TypeManager.uint64_type)
479 return new ULongConstant ((ulong) v, Location.Null);
480 else if (t == TypeManager.float_type)
481 return new FloatConstant ((float) v, Location.Null);
482 else if (t == TypeManager.double_type)
483 return new DoubleConstant ((double) v, Location.Null);
484 else if (t == TypeManager.string_type)
485 return new StringConstant ((string) v, Location.Null);
486 else if (t == TypeManager.short_type)
487 return new ShortConstant ((short)v, Location.Null);
488 else if (t == TypeManager.ushort_type)
489 return new UShortConstant ((ushort)v, Location.Null);
490 else if (t == TypeManager.sbyte_type)
491 return new SByteConstant ((sbyte)v, Location.Null);
492 else if (t == TypeManager.byte_type)
493 return new ByteConstant ((byte)v, Location.Null);
494 else if (t == TypeManager.char_type)
495 return new CharConstant ((char)v, Location.Null);
496 else if (t == TypeManager.bool_type)
497 return new BoolConstant ((bool) v, Location.Null);
498 else if (t == TypeManager.decimal_type)
499 return new DecimalConstant ((decimal) v, Location.Null);
500 else if (TypeManager.IsEnumType (t)){
501 Type real_type = TypeManager.TypeToCoreType (v.GetType ());
503 real_type = System.Enum.GetUnderlyingType (real_type);
505 Constant e = Constantify (v, real_type);
507 return new EnumConstant (e, t);
508 } else if (v == null && !TypeManager.IsValueType (t))
509 return new NullLiteral (Location.Null);
511 throw new Exception ("Unknown type for constant (" + t +
516 /// Returns a fully formed expression after a MemberLookup
519 // TODO: This can be heavily cached
520 public static Expression ExprClassFromMemberInfo (EmitContext ec, MemberInfo mi, Location loc)
523 return new EventExpr ((EventInfo) mi, loc);
524 else if (mi is FieldInfo)
525 return new FieldExpr ((FieldInfo) mi, loc);
526 else if (mi is PropertyInfo)
527 return new PropertyExpr (ec, (PropertyInfo) mi, loc);
528 else if (mi is Type){
529 return new TypeExpression ((System.Type) mi, loc);
535 protected static ArrayList almostMatchedMembers = new ArrayList (4);
538 // FIXME: Probably implement a cache for (t,name,current_access_set)?
540 // This code could use some optimizations, but we need to do some
541 // measurements. For example, we could use a delegate to `flag' when
542 // something can not any longer be a method-group (because it is something
546 // If the return value is an Array, then it is an array of
549 // If the return value is an MemberInfo, it is anything, but a Method
553 // FIXME: When calling MemberLookup inside an `Invocation', we should pass
554 // the arguments here and have MemberLookup return only the methods that
555 // match the argument count/type, unlike we are doing now (we delay this
558 // This is so we can catch correctly attempts to invoke instance methods
559 // from a static body (scan for error 120 in ResolveSimpleName).
562 // FIXME: Potential optimization, have a static ArrayList
565 public static Expression MemberLookup (EmitContext ec, Type queried_type, string name,
566 MemberTypes mt, BindingFlags bf, Location loc)
568 return MemberLookup (ec, ec.ContainerType, null, queried_type, name, mt, bf, loc);
572 // Lookup type `queried_type' for code in class `container_type' with a qualifier of
573 // `qualifier_type' or null to lookup members in the current class.
576 public static Expression MemberLookup (EmitContext ec, Type container_type,
577 Type qualifier_type, Type queried_type,
578 string name, MemberTypes mt,
579 BindingFlags bf, Location loc)
581 almostMatchedMembers.Clear ();
583 MemberInfo [] mi = TypeManager.MemberLookup (container_type, qualifier_type,
584 queried_type, mt, bf, name, almostMatchedMembers);
589 int count = mi.Length;
591 if (mi [0] is MethodBase)
592 return new MethodGroupExpr (mi, loc);
597 return ExprClassFromMemberInfo (ec, mi [0], loc);
600 public const MemberTypes AllMemberTypes =
601 MemberTypes.Constructor |
605 MemberTypes.NestedType |
606 MemberTypes.Property;
608 public const BindingFlags AllBindingFlags =
609 BindingFlags.Public |
610 BindingFlags.Static |
611 BindingFlags.Instance;
613 public static Expression MemberLookup (EmitContext ec, Type queried_type,
614 string name, Location loc)
616 return MemberLookup (ec, ec.ContainerType, null, queried_type, name,
617 AllMemberTypes, AllBindingFlags, loc);
620 public static Expression MemberLookup (EmitContext ec, Type qualifier_type,
621 Type queried_type, string name, Location loc)
623 return MemberLookup (ec, ec.ContainerType, qualifier_type, queried_type,
624 name, AllMemberTypes, AllBindingFlags, loc);
627 public static Expression MethodLookup (EmitContext ec, Type queried_type,
628 string name, Location loc)
630 return MemberLookup (ec, ec.ContainerType, null, queried_type, name,
631 MemberTypes.Method, AllBindingFlags, loc);
635 /// This is a wrapper for MemberLookup that is not used to "probe", but
636 /// to find a final definition. If the final definition is not found, we
637 /// look for private members and display a useful debugging message if we
640 public static Expression MemberLookupFinal (EmitContext ec, Type qualifier_type,
641 Type queried_type, string name, Location loc)
643 return MemberLookupFinal (ec, qualifier_type, queried_type, name,
644 AllMemberTypes, AllBindingFlags, loc);
647 public static Expression MemberLookupFinal (EmitContext ec, Type qualifier_type,
648 Type queried_type, string name,
649 MemberTypes mt, BindingFlags bf,
654 int errors = Report.Errors;
656 e = MemberLookup (ec, ec.ContainerType, qualifier_type, queried_type, name, mt, bf, loc);
658 if (e == null && errors == Report.Errors)
659 // No errors were reported by MemberLookup, but there was an error.
660 MemberLookupFailed (ec, qualifier_type, queried_type, name, null, true, loc);
665 public static void MemberLookupFailed (EmitContext ec, Type qualifier_type,
666 Type queried_type, string name,
667 string class_name, bool complain_if_none_found,
670 if (almostMatchedMembers.Count != 0) {
671 for (int i = 0; i < almostMatchedMembers.Count; ++i) {
672 MemberInfo m = (MemberInfo) almostMatchedMembers [i];
673 for (int j = 0; j < i; ++j) {
674 if (m == almostMatchedMembers [j]) {
682 Type declaring_type = m.DeclaringType;
684 Report.SymbolRelatedToPreviousError (m);
685 if (qualifier_type == null) {
686 Report.Error (38, loc, "Cannot access a nonstatic member of outer type `{0}' via nested type `{1}'",
687 TypeManager.CSharpName (m.DeclaringType),
688 TypeManager.CSharpName (ec.ContainerType));
690 } else if (qualifier_type != ec.ContainerType &&
691 TypeManager.IsNestedFamilyAccessible (ec.ContainerType, declaring_type)) {
692 // Although a derived class can access protected members of
693 // its base class it cannot do so through an instance of the
694 // base class (CS1540). If the qualifier_type is a base of the
695 // ec.ContainerType and the lookup succeeds with the latter one,
696 // then we are in this situation.
697 Report.Error (1540, loc,
698 "Cannot access protected member `{0}' via a qualifier of type `{1}';"
699 + " the qualifier must be of type `{2}' (or derived from it)",
700 TypeManager.GetFullNameSignature (m),
701 TypeManager.CSharpName (qualifier_type),
702 TypeManager.CSharpName (ec.ContainerType));
704 ErrorIsInaccesible (loc, TypeManager.GetFullNameSignature (m));
707 almostMatchedMembers.Clear ();
711 MemberInfo[] lookup = TypeManager.MemberLookup (queried_type, null, queried_type,
712 AllMemberTypes, AllBindingFlags |
713 BindingFlags.NonPublic, name, null);
715 if (lookup == null) {
716 if (!complain_if_none_found)
719 if (class_name != null)
720 Report.Error (103, loc, "The name `{0}' does not exist in the context of `{1}'",
723 Error_TypeDoesNotContainDefinition (loc, queried_type, name);
727 MemberList ml = TypeManager.FindMembers (queried_type, MemberTypes.Constructor,
728 BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly, null, null);
729 if (name == ".ctor" && ml.Count == 0)
731 Report.Error (143, loc, String.Format ("The type `{0}' has no constructors defined", TypeManager.CSharpName (queried_type)));
735 ErrorIsInaccesible (loc, TypeManager.GetFullNameSignature (lookup [0]));
739 /// Returns an expression that can be used to invoke operator true
740 /// on the expression if it exists.
742 static public StaticCallExpr GetOperatorTrue (EmitContext ec, Expression e, Location loc)
744 return GetOperatorTrueOrFalse (ec, e, true, loc);
748 /// Returns an expression that can be used to invoke operator false
749 /// on the expression if it exists.
751 static public StaticCallExpr GetOperatorFalse (EmitContext ec, Expression e, Location loc)
753 return GetOperatorTrueOrFalse (ec, e, false, loc);
756 static StaticCallExpr GetOperatorTrueOrFalse (EmitContext ec, Expression e, bool is_true, Location loc)
759 Expression operator_group;
761 operator_group = MethodLookup (ec, e.Type, is_true ? "op_True" : "op_False", loc);
762 if (operator_group == null)
765 ArrayList arguments = new ArrayList ();
766 arguments.Add (new Argument (e, Argument.AType.Expression));
767 method = Invocation.OverloadResolve (
768 ec, (MethodGroupExpr) operator_group, arguments, false, loc);
773 return new StaticCallExpr ((MethodInfo) method, arguments, loc);
777 /// Resolves the expression `e' into a boolean expression: either through
778 /// an implicit conversion, or through an `operator true' invocation
780 public static Expression ResolveBoolean (EmitContext ec, Expression e, Location loc)
786 if (e.Type == TypeManager.bool_type)
789 Expression converted = Convert.ImplicitConversion (ec, e, TypeManager.bool_type, Location.Null);
791 if (converted != null)
795 // If no implicit conversion to bool exists, try using `operator true'
797 Expression operator_true = Expression.GetOperatorTrue (ec, e, loc);
798 if (operator_true == null){
799 Report.Error (31, loc, "Can not convert the expression to a boolean");
802 return operator_true;
805 public virtual string ExprClassName
809 case ExprClass.Invalid:
811 case ExprClass.Value:
813 case ExprClass.Variable:
815 case ExprClass.Namespace:
819 case ExprClass.MethodGroup:
820 return "method group";
821 case ExprClass.PropertyAccess:
822 return "property access";
823 case ExprClass.EventAccess:
824 return "event access";
825 case ExprClass.IndexerAccess:
826 return "indexer access";
827 case ExprClass.Nothing:
830 throw new Exception ("Should not happen");
835 /// Reports that we were expecting `expr' to be of class `expected'
837 public void Error_UnexpectedKind (EmitContext ec, string expected, Location loc)
839 Error_UnexpectedKind (ec, expected, ExprClassName, loc);
842 public void Error_UnexpectedKind (EmitContext ec, string expected, string was, Location loc)
844 string name = GetSignatureForError ();
846 name = ec.DeclSpace.GetSignatureForError () + '.' + name;
848 Report.Error (118, loc, "`{0}' is a `{1}' but a `{2}' was expected",
849 name, was, expected);
852 public void Error_UnexpectedKind (ResolveFlags flags, Location loc)
854 string [] valid = new string [4];
857 if ((flags & ResolveFlags.VariableOrValue) != 0) {
858 valid [count++] = "variable";
859 valid [count++] = "value";
862 if ((flags & ResolveFlags.Type) != 0)
863 valid [count++] = "type";
865 if ((flags & ResolveFlags.MethodGroup) != 0)
866 valid [count++] = "method group";
869 valid [count++] = "unknown";
871 StringBuilder sb = new StringBuilder (valid [0]);
872 for (int i = 1; i < count - 1; i++) {
874 sb.Append (valid [i]);
877 sb.Append ("' or `");
878 sb.Append (valid [count - 1]);
881 Report.Error (119, loc,
882 "Expression denotes a `{0}', where a `{1}' was expected", ExprClassName, sb);
885 public static void UnsafeError (Location loc)
887 Report.Error (214, loc, "Pointers and fixed size buffers may only be used in an unsafe context");
891 // Load the object from the pointer.
893 public static void LoadFromPtr (ILGenerator ig, Type t)
895 if (t == TypeManager.int32_type)
896 ig.Emit (OpCodes.Ldind_I4);
897 else if (t == TypeManager.uint32_type)
898 ig.Emit (OpCodes.Ldind_U4);
899 else if (t == TypeManager.short_type)
900 ig.Emit (OpCodes.Ldind_I2);
901 else if (t == TypeManager.ushort_type)
902 ig.Emit (OpCodes.Ldind_U2);
903 else if (t == TypeManager.char_type)
904 ig.Emit (OpCodes.Ldind_U2);
905 else if (t == TypeManager.byte_type)
906 ig.Emit (OpCodes.Ldind_U1);
907 else if (t == TypeManager.sbyte_type)
908 ig.Emit (OpCodes.Ldind_I1);
909 else if (t == TypeManager.uint64_type)
910 ig.Emit (OpCodes.Ldind_I8);
911 else if (t == TypeManager.int64_type)
912 ig.Emit (OpCodes.Ldind_I8);
913 else if (t == TypeManager.float_type)
914 ig.Emit (OpCodes.Ldind_R4);
915 else if (t == TypeManager.double_type)
916 ig.Emit (OpCodes.Ldind_R8);
917 else if (t == TypeManager.bool_type)
918 ig.Emit (OpCodes.Ldind_I1);
919 else if (t == TypeManager.intptr_type)
920 ig.Emit (OpCodes.Ldind_I);
921 else if (TypeManager.IsEnumType (t)) {
922 if (t == TypeManager.enum_type)
923 ig.Emit (OpCodes.Ldind_Ref);
925 LoadFromPtr (ig, TypeManager.EnumToUnderlying (t));
926 } else if (t.IsValueType)
927 ig.Emit (OpCodes.Ldobj, t);
928 else if (t.IsPointer)
929 ig.Emit (OpCodes.Ldind_I);
931 ig.Emit (OpCodes.Ldind_Ref);
935 // The stack contains the pointer and the value of type `type'
937 public static void StoreFromPtr (ILGenerator ig, Type type)
939 if (TypeManager.IsEnumType (type))
940 type = TypeManager.EnumToUnderlying (type);
941 if (type == TypeManager.int32_type || type == TypeManager.uint32_type)
942 ig.Emit (OpCodes.Stind_I4);
943 else if (type == TypeManager.int64_type || type == TypeManager.uint64_type)
944 ig.Emit (OpCodes.Stind_I8);
945 else if (type == TypeManager.char_type || type == TypeManager.short_type ||
946 type == TypeManager.ushort_type)
947 ig.Emit (OpCodes.Stind_I2);
948 else if (type == TypeManager.float_type)
949 ig.Emit (OpCodes.Stind_R4);
950 else if (type == TypeManager.double_type)
951 ig.Emit (OpCodes.Stind_R8);
952 else if (type == TypeManager.byte_type || type == TypeManager.sbyte_type ||
953 type == TypeManager.bool_type)
954 ig.Emit (OpCodes.Stind_I1);
955 else if (type == TypeManager.intptr_type)
956 ig.Emit (OpCodes.Stind_I);
957 else if (type.IsValueType)
958 ig.Emit (OpCodes.Stobj, type);
960 ig.Emit (OpCodes.Stind_Ref);
964 // Returns the size of type `t' if known, otherwise, 0
966 public static int GetTypeSize (Type t)
968 t = TypeManager.TypeToCoreType (t);
969 if (t == TypeManager.int32_type ||
970 t == TypeManager.uint32_type ||
971 t == TypeManager.float_type)
973 else if (t == TypeManager.int64_type ||
974 t == TypeManager.uint64_type ||
975 t == TypeManager.double_type)
977 else if (t == TypeManager.byte_type ||
978 t == TypeManager.sbyte_type ||
979 t == TypeManager.bool_type)
981 else if (t == TypeManager.short_type ||
982 t == TypeManager.char_type ||
983 t == TypeManager.ushort_type)
985 else if (t == TypeManager.decimal_type)
991 public static void Error_NegativeArrayIndex (Location loc)
993 Report.Error (248, loc, "Cannot create an array with a negative size");
996 protected void Error_CannotCallAbstractBase (string name)
998 Report.Error (205, loc, "Cannot call an abstract base member `{0}'", name);
1002 // Converts `source' to an int, uint, long or ulong.
1004 public Expression ExpressionToArrayArgument (EmitContext ec, Expression source, Location loc)
1008 bool old_checked = ec.CheckState;
1009 ec.CheckState = true;
1011 target = Convert.ImplicitConversion (ec, source, TypeManager.int32_type, loc);
1012 if (target == null){
1013 target = Convert.ImplicitConversion (ec, source, TypeManager.uint32_type, loc);
1014 if (target == null){
1015 target = Convert.ImplicitConversion (ec, source, TypeManager.int64_type, loc);
1016 if (target == null){
1017 target = Convert.ImplicitConversion (ec, source, TypeManager.uint64_type, loc);
1019 Convert.Error_CannotImplicitConversion (loc, source.Type, TypeManager.int32_type);
1023 ec.CheckState = old_checked;
1026 // Only positive constants are allowed at compile time
1028 if (target is Constant){
1029 if (target is IntConstant){
1030 if (((IntConstant) target).Value < 0){
1031 Error_NegativeArrayIndex (loc);
1036 if (target is LongConstant){
1037 if (((LongConstant) target).Value < 0){
1038 Error_NegativeArrayIndex (loc);
1051 /// This is just a base class for expressions that can
1052 /// appear on statements (invocations, object creation,
1053 /// assignments, post/pre increment and decrement). The idea
1054 /// being that they would support an extra Emition interface that
1055 /// does not leave a result on the stack.
1057 public abstract class ExpressionStatement : Expression {
1059 public virtual ExpressionStatement ResolveStatement (EmitContext ec)
1061 Expression e = Resolve (ec);
1065 ExpressionStatement es = e as ExpressionStatement;
1067 Error (201, "Only assignment, call, increment, decrement and new object " +
1068 "expressions can be used as a statement");
1074 /// Requests the expression to be emitted in a `statement'
1075 /// context. This means that no new value is left on the
1076 /// stack after invoking this method (constrasted with
1077 /// Emit that will always leave a value on the stack).
1079 public abstract void EmitStatement (EmitContext ec);
1083 /// This kind of cast is used to encapsulate the child
1084 /// whose type is child.Type into an expression that is
1085 /// reported to return "return_type". This is used to encapsulate
1086 /// expressions which have compatible types, but need to be dealt
1087 /// at higher levels with.
1089 /// For example, a "byte" expression could be encapsulated in one
1090 /// of these as an "unsigned int". The type for the expression
1091 /// would be "unsigned int".
1094 public class EmptyCast : Expression {
1095 protected Expression child;
1097 public Expression Child {
1103 public EmptyCast (Expression child, Type return_type)
1105 eclass = child.eclass;
1106 loc = child.Location;
1111 public override Expression DoResolve (EmitContext ec)
1113 // This should never be invoked, we are born in fully
1114 // initialized state.
1119 public override void Emit (EmitContext ec)
1125 /// This is a numeric cast to a Decimal
1127 public class CastToDecimal : EmptyCast {
1129 MethodInfo conversion_operator;
1131 public CastToDecimal (EmitContext ec, Expression child)
1132 : this (ec, child, false)
1136 public CastToDecimal (EmitContext ec, Expression child, bool find_explicit)
1137 : base (child, TypeManager.decimal_type)
1139 conversion_operator = GetConversionOperator (ec, find_explicit);
1141 if (conversion_operator == null)
1142 Convert.Error_CannotImplicitConversion (loc, child.Type, type);
1145 // Returns the implicit operator that converts from
1146 // 'child.Type' to System.Decimal.
1147 MethodInfo GetConversionOperator (EmitContext ec, bool find_explicit)
1149 string operator_name = "op_Implicit";
1152 operator_name = "op_Explicit";
1154 MethodGroupExpr opers = Expression.MethodLookup (
1155 ec, type, operator_name, loc) as MethodGroupExpr;
1158 Convert.Error_CannotImplicitConversion (loc, child.Type, type);
1160 foreach (MethodInfo oper in opers.Methods) {
1161 ParameterData pd = TypeManager.GetParameterData (oper);
1163 if (pd.ParameterType (0) == child.Type && oper.ReturnType == type)
1169 public override void Emit (EmitContext ec)
1171 ILGenerator ig = ec.ig;
1174 ig.Emit (OpCodes.Call, conversion_operator);
1178 /// This is an explicit numeric cast from a Decimal
1180 public class CastFromDecimal : EmptyCast
1182 MethodInfo conversion_operator;
1183 public CastFromDecimal (EmitContext ec, Expression child, Type return_type)
1184 : base (child, return_type)
1186 if (child.Type != TypeManager.decimal_type)
1187 throw new InternalErrorException (
1188 "The expected type is Decimal, instead it is " + child.Type.FullName);
1190 conversion_operator = GetConversionOperator (ec);
1191 if (conversion_operator == null)
1192 Convert.Error_CannotImplicitConversion (loc, child.Type, type);
1195 // Returns the explicit operator that converts from an
1196 // express of type System.Decimal to 'type'.
1197 MethodInfo GetConversionOperator (EmitContext ec)
1199 MethodGroupExpr opers = Expression.MethodLookup (
1200 ec, child.Type, "op_Explicit", loc) as MethodGroupExpr;
1203 Convert.Error_CannotImplicitConversion (loc, child.Type, type);
1205 foreach (MethodInfo oper in opers.Methods) {
1206 ParameterData pd = TypeManager.GetParameterData (oper);
1208 if (pd.ParameterType (0) == child.Type && oper.ReturnType == type)
1214 public override void Emit (EmitContext ec)
1216 ILGenerator ig = ec.ig;
1219 ig.Emit (OpCodes.Call, conversion_operator);
1224 // We need to special case this since an empty cast of
1225 // a NullLiteral is still a Constant
1227 public class NullCast : Constant {
1228 protected Expression child;
1230 public NullCast (Expression child, Type return_type):
1231 base (Location.Null)
1233 eclass = child.eclass;
1238 override public string AsString ()
1243 public override object GetValue ()
1248 public override Expression DoResolve (EmitContext ec)
1250 // This should never be invoked, we are born in fully
1251 // initialized state.
1256 public override void Emit (EmitContext ec)
1261 public override Constant Increment ()
1263 throw new NotSupportedException ();
1266 public override bool IsDefaultValue {
1268 throw new NotImplementedException ();
1272 public override bool IsNegative {
1281 /// This class is used to wrap literals which belong inside Enums
1283 public class EnumConstant : Constant {
1284 public Constant Child;
1286 public EnumConstant (Constant child, Type enum_type):
1287 base (child.Location)
1289 eclass = child.eclass;
1294 public override Expression DoResolve (EmitContext ec)
1296 // This should never be invoked, we are born in fully
1297 // initialized state.
1302 public override void Emit (EmitContext ec)
1307 public override object GetValue ()
1309 return Child.GetValue ();
1312 public override object GetTypedValue ()
1314 // FIXME: runtime is not ready to work with just emited enums
1315 if (!RootContext.StdLib) {
1316 return Child.GetValue ();
1319 return System.Enum.ToObject (type, Child.GetValue ());
1322 public override void Error_ValueCannotBeConverted (Location loc, Type t)
1324 Convert.Error_CannotImplicitConversion (loc, Type, t);
1327 public override string AsString ()
1329 return Child.AsString ();
1332 public override DoubleConstant ConvertToDouble ()
1334 return Child.ConvertToDouble ();
1337 public override FloatConstant ConvertToFloat ()
1339 return Child.ConvertToFloat ();
1342 public override ULongConstant ConvertToULong ()
1344 return Child.ConvertToULong ();
1347 public override LongConstant ConvertToLong ()
1349 return Child.ConvertToLong ();
1352 public override UIntConstant ConvertToUInt ()
1354 return Child.ConvertToUInt ();
1357 public override IntConstant ConvertToInt ()
1359 return Child.ConvertToInt ();
1362 public override Constant Increment()
1364 return new EnumConstant (Child.Increment (), type);
1367 public override bool IsDefaultValue {
1369 return Child.IsDefaultValue;
1373 public override bool IsZeroInteger {
1374 get { return Child.IsZeroInteger; }
1377 public override bool IsNegative {
1379 return Child.IsNegative;
1383 public override Constant ToType (Type type, Location loc)
1386 // This is workaround of mono bug. It can be removed when the latest corlib spreads enough
1387 if (TypeManager.IsEnumType (type.UnderlyingSystemType))
1390 if (type.UnderlyingSystemType != Child.Type)
1391 Child = Child.ToType (type.UnderlyingSystemType, loc);
1395 if (!Convert.ImplicitStandardConversionExists (Convert.ConstantEC, this, type)){
1396 Error_ValueCannotBeConverted (loc, type);
1400 return Child.ToType (type, loc);
1406 /// This kind of cast is used to encapsulate Value Types in objects.
1408 /// The effect of it is to box the value type emitted by the previous
1411 public class BoxedCast : EmptyCast {
1413 public BoxedCast (Expression expr, Type target_type)
1414 : base (expr, target_type)
1416 eclass = ExprClass.Value;
1419 public override Expression DoResolve (EmitContext ec)
1421 // This should never be invoked, we are born in fully
1422 // initialized state.
1427 public override void Emit (EmitContext ec)
1431 ec.ig.Emit (OpCodes.Box, child.Type);
1435 public class UnboxCast : EmptyCast {
1436 public UnboxCast (Expression expr, Type return_type)
1437 : base (expr, return_type)
1441 public override Expression DoResolve (EmitContext ec)
1443 // This should never be invoked, we are born in fully
1444 // initialized state.
1449 public override void Emit (EmitContext ec)
1452 ILGenerator ig = ec.ig;
1455 ig.Emit (OpCodes.Unbox, t);
1457 LoadFromPtr (ig, t);
1462 /// This is used to perform explicit numeric conversions.
1464 /// Explicit numeric conversions might trigger exceptions in a checked
1465 /// context, so they should generate the conv.ovf opcodes instead of
1468 public class ConvCast : EmptyCast {
1469 public enum Mode : byte {
1470 I1_U1, I1_U2, I1_U4, I1_U8, I1_CH,
1472 I2_I1, I2_U1, I2_U2, I2_U4, I2_U8, I2_CH,
1473 U2_I1, U2_U1, U2_I2, U2_CH,
1474 I4_I1, I4_U1, I4_I2, I4_U2, I4_U4, I4_U8, I4_CH,
1475 U4_I1, U4_U1, U4_I2, U4_U2, U4_I4, U4_CH,
1476 I8_I1, I8_U1, I8_I2, I8_U2, I8_I4, I8_U4, I8_U8, I8_CH,
1477 U8_I1, U8_U1, U8_I2, U8_U2, U8_I4, U8_U4, U8_I8, U8_CH,
1478 CH_I1, CH_U1, CH_I2,
1479 R4_I1, R4_U1, R4_I2, R4_U2, R4_I4, R4_U4, R4_I8, R4_U8, R4_CH,
1480 R8_I1, R8_U1, R8_I2, R8_U2, R8_I4, R8_U4, R8_I8, R8_U8, R8_CH, R8_R4
1484 // TODO: is redundant as can be read in Emit directly
1487 public ConvCast (EmitContext ec, Expression child, Type return_type, Mode m)
1488 : base (child, return_type)
1490 checked_state = ec.CheckState;
1494 public override Expression DoResolve (EmitContext ec)
1496 // This should never be invoked, we are born in fully
1497 // initialized state.
1502 public override string ToString ()
1504 return String.Format ("ConvCast ({0}, {1})", mode, child);
1507 public override void Emit (EmitContext ec)
1509 ILGenerator ig = ec.ig;
1515 case Mode.I1_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1516 case Mode.I1_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1517 case Mode.I1_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1518 case Mode.I1_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1519 case Mode.I1_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1521 case Mode.U1_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1522 case Mode.U1_CH: /* nothing */ break;
1524 case Mode.I2_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1525 case Mode.I2_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1526 case Mode.I2_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1527 case Mode.I2_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1528 case Mode.I2_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1529 case Mode.I2_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1531 case Mode.U2_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1532 case Mode.U2_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
1533 case Mode.U2_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
1534 case Mode.U2_CH: /* nothing */ break;
1536 case Mode.I4_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1537 case Mode.I4_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1538 case Mode.I4_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
1539 case Mode.I4_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1540 case Mode.I4_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1541 case Mode.I4_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1542 case Mode.I4_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1544 case Mode.U4_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1545 case Mode.U4_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
1546 case Mode.U4_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
1547 case Mode.U4_U2: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
1548 case Mode.U4_I4: ig.Emit (OpCodes.Conv_Ovf_I4_Un); break;
1549 case Mode.U4_CH: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
1551 case Mode.I8_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1552 case Mode.I8_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1553 case Mode.I8_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
1554 case Mode.I8_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1555 case Mode.I8_I4: ig.Emit (OpCodes.Conv_Ovf_I4); break;
1556 case Mode.I8_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1557 case Mode.I8_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1558 case Mode.I8_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1560 case Mode.U8_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1561 case Mode.U8_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
1562 case Mode.U8_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
1563 case Mode.U8_U2: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
1564 case Mode.U8_I4: ig.Emit (OpCodes.Conv_Ovf_I4_Un); break;
1565 case Mode.U8_U4: ig.Emit (OpCodes.Conv_Ovf_U4_Un); break;
1566 case Mode.U8_I8: ig.Emit (OpCodes.Conv_Ovf_I8_Un); break;
1567 case Mode.U8_CH: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
1569 case Mode.CH_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1570 case Mode.CH_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
1571 case Mode.CH_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
1573 case Mode.R4_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1574 case Mode.R4_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1575 case Mode.R4_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
1576 case Mode.R4_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1577 case Mode.R4_I4: ig.Emit (OpCodes.Conv_Ovf_I4); break;
1578 case Mode.R4_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1579 case Mode.R4_I8: ig.Emit (OpCodes.Conv_Ovf_I8); break;
1580 case Mode.R4_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1581 case Mode.R4_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1583 case Mode.R8_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1584 case Mode.R8_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1585 case Mode.R8_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
1586 case Mode.R8_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1587 case Mode.R8_I4: ig.Emit (OpCodes.Conv_Ovf_I4); break;
1588 case Mode.R8_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1589 case Mode.R8_I8: ig.Emit (OpCodes.Conv_Ovf_I8); break;
1590 case Mode.R8_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1591 case Mode.R8_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1592 case Mode.R8_R4: ig.Emit (OpCodes.Conv_R4); break;
1596 case Mode.I1_U1: ig.Emit (OpCodes.Conv_U1); break;
1597 case Mode.I1_U2: ig.Emit (OpCodes.Conv_U2); break;
1598 case Mode.I1_U4: ig.Emit (OpCodes.Conv_U4); break;
1599 case Mode.I1_U8: ig.Emit (OpCodes.Conv_I8); break;
1600 case Mode.I1_CH: ig.Emit (OpCodes.Conv_U2); break;
1602 case Mode.U1_I1: ig.Emit (OpCodes.Conv_I1); break;
1603 case Mode.U1_CH: ig.Emit (OpCodes.Conv_U2); break;
1605 case Mode.I2_I1: ig.Emit (OpCodes.Conv_I1); break;
1606 case Mode.I2_U1: ig.Emit (OpCodes.Conv_U1); break;
1607 case Mode.I2_U2: ig.Emit (OpCodes.Conv_U2); break;
1608 case Mode.I2_U4: ig.Emit (OpCodes.Conv_U4); break;
1609 case Mode.I2_U8: ig.Emit (OpCodes.Conv_I8); break;
1610 case Mode.I2_CH: ig.Emit (OpCodes.Conv_U2); break;
1612 case Mode.U2_I1: ig.Emit (OpCodes.Conv_I1); break;
1613 case Mode.U2_U1: ig.Emit (OpCodes.Conv_U1); break;
1614 case Mode.U2_I2: ig.Emit (OpCodes.Conv_I2); break;
1615 case Mode.U2_CH: /* nothing */ break;
1617 case Mode.I4_I1: ig.Emit (OpCodes.Conv_I1); break;
1618 case Mode.I4_U1: ig.Emit (OpCodes.Conv_U1); break;
1619 case Mode.I4_I2: ig.Emit (OpCodes.Conv_I2); break;
1620 case Mode.I4_U4: /* nothing */ break;
1621 case Mode.I4_U2: ig.Emit (OpCodes.Conv_U2); break;
1622 case Mode.I4_U8: ig.Emit (OpCodes.Conv_I8); break;
1623 case Mode.I4_CH: ig.Emit (OpCodes.Conv_U2); break;
1625 case Mode.U4_I1: ig.Emit (OpCodes.Conv_I1); break;
1626 case Mode.U4_U1: ig.Emit (OpCodes.Conv_U1); break;
1627 case Mode.U4_I2: ig.Emit (OpCodes.Conv_I2); break;
1628 case Mode.U4_U2: ig.Emit (OpCodes.Conv_U2); break;
1629 case Mode.U4_I4: /* nothing */ break;
1630 case Mode.U4_CH: ig.Emit (OpCodes.Conv_U2); break;
1632 case Mode.I8_I1: ig.Emit (OpCodes.Conv_I1); break;
1633 case Mode.I8_U1: ig.Emit (OpCodes.Conv_U1); break;
1634 case Mode.I8_I2: ig.Emit (OpCodes.Conv_I2); break;
1635 case Mode.I8_U2: ig.Emit (OpCodes.Conv_U2); break;
1636 case Mode.I8_I4: ig.Emit (OpCodes.Conv_I4); break;
1637 case Mode.I8_U4: ig.Emit (OpCodes.Conv_U4); break;
1638 case Mode.I8_U8: /* nothing */ break;
1639 case Mode.I8_CH: ig.Emit (OpCodes.Conv_U2); break;
1641 case Mode.U8_I1: ig.Emit (OpCodes.Conv_I1); break;
1642 case Mode.U8_U1: ig.Emit (OpCodes.Conv_U1); break;
1643 case Mode.U8_I2: ig.Emit (OpCodes.Conv_I2); break;
1644 case Mode.U8_U2: ig.Emit (OpCodes.Conv_U2); break;
1645 case Mode.U8_I4: ig.Emit (OpCodes.Conv_I4); break;
1646 case Mode.U8_U4: ig.Emit (OpCodes.Conv_U4); break;
1647 case Mode.U8_I8: /* nothing */ break;
1648 case Mode.U8_CH: ig.Emit (OpCodes.Conv_U2); break;
1650 case Mode.CH_I1: ig.Emit (OpCodes.Conv_I1); break;
1651 case Mode.CH_U1: ig.Emit (OpCodes.Conv_U1); break;
1652 case Mode.CH_I2: ig.Emit (OpCodes.Conv_I2); break;
1654 case Mode.R4_I1: ig.Emit (OpCodes.Conv_I1); break;
1655 case Mode.R4_U1: ig.Emit (OpCodes.Conv_U1); break;
1656 case Mode.R4_I2: ig.Emit (OpCodes.Conv_I2); break;
1657 case Mode.R4_U2: ig.Emit (OpCodes.Conv_U2); break;
1658 case Mode.R4_I4: ig.Emit (OpCodes.Conv_I4); break;
1659 case Mode.R4_U4: ig.Emit (OpCodes.Conv_U4); break;
1660 case Mode.R4_I8: ig.Emit (OpCodes.Conv_I8); break;
1661 case Mode.R4_U8: ig.Emit (OpCodes.Conv_U8); break;
1662 case Mode.R4_CH: ig.Emit (OpCodes.Conv_U2); break;
1664 case Mode.R8_I1: ig.Emit (OpCodes.Conv_I1); break;
1665 case Mode.R8_U1: ig.Emit (OpCodes.Conv_U1); break;
1666 case Mode.R8_I2: ig.Emit (OpCodes.Conv_I2); break;
1667 case Mode.R8_U2: ig.Emit (OpCodes.Conv_U2); break;
1668 case Mode.R8_I4: ig.Emit (OpCodes.Conv_I4); break;
1669 case Mode.R8_U4: ig.Emit (OpCodes.Conv_U4); break;
1670 case Mode.R8_I8: ig.Emit (OpCodes.Conv_I8); break;
1671 case Mode.R8_U8: ig.Emit (OpCodes.Conv_U8); break;
1672 case Mode.R8_CH: ig.Emit (OpCodes.Conv_U2); break;
1673 case Mode.R8_R4: ig.Emit (OpCodes.Conv_R4); break;
1679 public class OpcodeCast : EmptyCast {
1683 public OpcodeCast (Expression child, Type return_type, OpCode op)
1684 : base (child, return_type)
1688 second_valid = false;
1691 public OpcodeCast (Expression child, Type return_type, OpCode op, OpCode op2)
1692 : base (child, return_type)
1697 second_valid = true;
1700 public override Expression DoResolve (EmitContext ec)
1702 // This should never be invoked, we are born in fully
1703 // initialized state.
1708 public override void Emit (EmitContext ec)
1719 /// This kind of cast is used to encapsulate a child and cast it
1720 /// to the class requested
1722 public class ClassCast : EmptyCast {
1723 public ClassCast (Expression child, Type return_type)
1724 : base (child, return_type)
1729 public override Expression DoResolve (EmitContext ec)
1731 // This should never be invoked, we are born in fully
1732 // initialized state.
1737 public override void Emit (EmitContext ec)
1741 ec.ig.Emit (OpCodes.Castclass, type);
1747 /// SimpleName expressions are formed of a single word and only happen at the beginning
1748 /// of a dotted-name.
1750 public class SimpleName : Expression {
1754 public SimpleName (string name, Location l)
1760 public static void Error_ObjectRefRequired (EmitContext ec, Location l, string name)
1762 if (ec.IsFieldInitializer)
1763 Report.Error (236, l,
1764 "A field initializer cannot reference the nonstatic field, method, or property `{0}'",
1767 if (name.LastIndexOf ('.') > 0)
1768 name = name.Substring (name.LastIndexOf ('.') + 1);
1771 120, l, "`{0}': An object reference is required for the nonstatic field, method or property",
1776 public bool IdenticalNameAndTypeName (EmitContext ec, Expression resolved_to, Location loc)
1778 return resolved_to != null && resolved_to.Type != null &&
1779 resolved_to.Type.Name == Name &&
1780 (ec.DeclSpace.LookupType (Name, loc, /* ignore_cs0104 = */ true) != null);
1783 public override Expression DoResolve (EmitContext ec)
1785 return SimpleNameResolve (ec, null, false);
1788 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
1790 return SimpleNameResolve (ec, right_side, false);
1794 public Expression DoResolve (EmitContext ec, bool intermediate)
1796 return SimpleNameResolve (ec, null, intermediate);
1799 public override FullNamedExpression ResolveAsTypeStep (EmitContext ec, bool silent)
1801 int errors = Report.Errors;
1802 FullNamedExpression fne = ec.DeclSpace.LookupType (Name, loc, /*ignore_cs0104=*/ false);
1806 if (silent || errors != Report.Errors)
1809 MemberCore mc = ec.DeclSpace.GetDefinition (Name);
1811 Error_UnexpectedKind (ec, "type", GetMemberType (mc), loc);
1813 NamespaceEntry.Error_NamespaceNotFound (loc, Name);
1819 // TODO: I am still not convinced about this. If someone else will need it
1820 // implement this as virtual property in MemberCore hierarchy
1821 string GetMemberType (MemberCore mc)
1823 if (mc is PropertyBase)
1827 if (mc is FieldBase)
1833 Expression SimpleNameResolve (EmitContext ec, Expression right_side, bool intermediate)
1839 Expression e = DoSimpleNameResolve (ec, right_side, intermediate);
1843 if (ec.CurrentBlock == null || ec.CurrentBlock.CheckInvariantMeaningInBlock (Name, e, Location))
1850 /// 7.5.2: Simple Names.
1852 /// Local Variables and Parameters are handled at
1853 /// parse time, so they never occur as SimpleNames.
1855 /// The `intermediate' flag is used by MemberAccess only
1856 /// and it is used to inform us that it is ok for us to
1857 /// avoid the static check, because MemberAccess might end
1858 /// up resolving the Name as a Type name and the access as
1859 /// a static type access.
1861 /// ie: Type Type; .... { Type.GetType (""); }
1863 /// Type is both an instance variable and a Type; Type.GetType
1864 /// is the static method not an instance method of type.
1866 Expression DoSimpleNameResolve (EmitContext ec, Expression right_side, bool intermediate)
1868 Expression e = null;
1871 // Stage 1: Performed by the parser (binding to locals or parameters).
1873 Block current_block = ec.CurrentBlock;
1874 if (current_block != null){
1875 LocalInfo vi = current_block.GetLocalInfo (Name);
1877 LocalVariableReference var = new LocalVariableReference (ec.CurrentBlock, Name, loc);
1878 if (right_side != null) {
1879 return var.ResolveLValue (ec, right_side, loc);
1881 ResolveFlags rf = ResolveFlags.VariableOrValue;
1883 rf |= ResolveFlags.DisableFlowAnalysis;
1884 return var.Resolve (ec, rf);
1888 ParameterReference pref = current_block.Toplevel.GetParameterReference (Name, loc);
1890 if (right_side != null)
1891 return pref.ResolveLValue (ec, right_side, loc);
1893 return pref.Resolve (ec);
1898 // Stage 2: Lookup members
1901 DeclSpace lookup_ds = ec.DeclSpace;
1902 Type almost_matched_type = null;
1903 ArrayList almost_matched = null;
1905 if (lookup_ds.TypeBuilder == null)
1908 e = MemberLookup (ec, lookup_ds.TypeBuilder, Name, loc);
1912 if (almost_matched == null && almostMatchedMembers.Count > 0) {
1913 almost_matched_type = lookup_ds.TypeBuilder;
1914 almost_matched = (ArrayList) almostMatchedMembers.Clone ();
1917 lookup_ds =lookup_ds.Parent;
1918 } while (lookup_ds != null);
1920 if (e == null && ec.ContainerType != null)
1921 e = MemberLookup (ec, ec.ContainerType, Name, loc);
1924 if (almost_matched == null && almostMatchedMembers.Count > 0) {
1925 almost_matched_type = ec.ContainerType;
1926 almost_matched = (ArrayList) almostMatchedMembers.Clone ();
1928 e = ResolveAsTypeStep (ec, false);
1932 if (almost_matched != null)
1933 almostMatchedMembers = almost_matched;
1934 if (almost_matched_type == null)
1935 almost_matched_type = ec.ContainerType;
1936 MemberLookupFailed (ec, null, almost_matched_type, ((SimpleName) this).Name, ec.DeclSpace.Name, true, loc);
1943 if (e is MemberExpr) {
1944 MemberExpr me = (MemberExpr) e;
1947 if (me.IsInstance) {
1948 if (ec.IsStatic || ec.IsFieldInitializer) {
1950 // Note that an MemberExpr can be both IsInstance and IsStatic.
1951 // An unresolved MethodGroupExpr can contain both kinds of methods
1952 // and each predicate is true if the MethodGroupExpr contains
1953 // at least one of that kind of method.
1957 (!intermediate || !IdenticalNameAndTypeName (ec, me, loc))) {
1958 Error_ObjectRefRequired (ec, loc, me.GetSignatureForError ());
1963 // Pass the buck to MemberAccess and Invocation.
1965 left = EmptyExpression.Null;
1967 left = ec.GetThis (loc);
1970 left = new TypeExpression (ec.ContainerType, loc);
1973 e = me.ResolveMemberAccess (ec, left, loc, null);
1977 me = e as MemberExpr;
1982 TypeManager.IsNestedFamilyAccessible (me.InstanceExpression.Type, me.DeclaringType) &&
1983 me.InstanceExpression.Type != me.DeclaringType &&
1984 !me.InstanceExpression.Type.IsSubclassOf (me.DeclaringType) &&
1985 (!intermediate || !IdenticalNameAndTypeName (ec, e, loc))) {
1986 Report.Error (38, loc, "Cannot access a nonstatic member of outer type `{0}' via nested type `{1}'",
1987 TypeManager.CSharpName (me.DeclaringType), TypeManager.CSharpName (me.InstanceExpression.Type));
1991 return (right_side != null)
1992 ? me.DoResolveLValue (ec, right_side)
1993 : me.DoResolve (ec);
1999 public override void Emit (EmitContext ec)
2002 // If this is ever reached, then we failed to
2003 // find the name as a namespace
2006 Error (103, "The name `" + Name +
2007 "' does not exist in the class `" +
2008 ec.DeclSpace.Name + "'");
2011 public override string ToString ()
2016 public override string GetSignatureForError ()
2023 /// Represents a namespace or a type. The name of the class was inspired by
2024 /// section 10.8.1 (Fully Qualified Names).
2026 public abstract class FullNamedExpression : Expression {
2027 public override FullNamedExpression ResolveAsTypeStep (EmitContext ec, bool silent)
2032 public abstract string FullName {
2038 /// Fully resolved expression that evaluates to a type
2040 public abstract class TypeExpr : FullNamedExpression {
2041 override public FullNamedExpression ResolveAsTypeStep (EmitContext ec, bool silent)
2043 TypeExpr t = DoResolveAsTypeStep (ec);
2047 eclass = ExprClass.Type;
2051 override public Expression DoResolve (EmitContext ec)
2053 return ResolveAsTypeTerminal (ec, false);
2056 override public void Emit (EmitContext ec)
2058 throw new Exception ("Should never be called");
2061 public virtual bool CheckAccessLevel (DeclSpace ds)
2063 return ds.CheckAccessLevel (Type);
2066 public virtual bool AsAccessible (DeclSpace ds, int flags)
2068 return ds.AsAccessible (Type, flags);
2071 public virtual bool IsClass {
2072 get { return Type.IsClass; }
2075 public virtual bool IsValueType {
2076 get { return Type.IsValueType; }
2079 public virtual bool IsInterface {
2080 get { return Type.IsInterface; }
2083 public virtual bool IsSealed {
2084 get { return Type.IsSealed; }
2087 public virtual bool CanInheritFrom ()
2089 if (Type == TypeManager.enum_type ||
2090 (Type == TypeManager.value_type && RootContext.StdLib) ||
2091 Type == TypeManager.multicast_delegate_type ||
2092 Type == TypeManager.delegate_type ||
2093 Type == TypeManager.array_type)
2099 public abstract TypeExpr DoResolveAsTypeStep (EmitContext ec);
2101 public Type ResolveType (EmitContext ec)
2103 TypeExpr t = ResolveAsTypeTerminal (ec, false);
2107 if (ec.TestObsoleteMethodUsage) {
2108 ObsoleteAttribute obsolete_attr = AttributeTester.GetObsoleteAttribute (t.Type);
2109 if (obsolete_attr != null) {
2110 AttributeTester.Report_ObsoleteMessage (obsolete_attr, Name, Location);
2117 public abstract string Name {
2121 public override bool Equals (object obj)
2123 TypeExpr tobj = obj as TypeExpr;
2127 return Type == tobj.Type;
2130 public override int GetHashCode ()
2132 return Type.GetHashCode ();
2135 public override string ToString ()
2141 public class TypeExpression : TypeExpr {
2142 public TypeExpression (Type t, Location l)
2145 eclass = ExprClass.Type;
2149 public override TypeExpr DoResolveAsTypeStep (EmitContext ec)
2154 public override string Name {
2155 get { return Type.ToString (); }
2158 public override string FullName {
2159 get { return Type.FullName; }
2164 /// Used to create types from a fully qualified name. These are just used
2165 /// by the parser to setup the core types. A TypeLookupExpression is always
2166 /// classified as a type.
2168 public class TypeLookupExpression : TypeExpr {
2171 public TypeLookupExpression (string name)
2176 static readonly char [] dot_array = { '.' };
2177 public override TypeExpr DoResolveAsTypeStep (EmitContext ec)
2182 // If name is of the form `N.I', first lookup `N', then search a member `I' in it.
2184 string lookup_name = name;
2185 int pos = name.IndexOf ('.');
2187 rest = name.Substring (pos + 1);
2188 lookup_name = name.Substring (0, pos);
2191 FullNamedExpression resolved = Namespace.Root.Lookup (ec.DeclSpace, lookup_name, Location.Null);
2193 if (resolved != null && rest != null) {
2194 // Now handle the rest of the the name.
2195 string [] elements = rest.Split (dot_array);
2197 int count = elements.Length;
2199 while (i < count && resolved != null && resolved is Namespace) {
2200 Namespace ns = resolved as Namespace;
2201 element = elements [i++];
2202 lookup_name += "." + element;
2203 resolved = ns.Lookup (ec.DeclSpace, element, Location.Null);
2206 if (resolved != null && resolved is TypeExpr) {
2207 Type t = ((TypeExpr) resolved).Type;
2209 if (!ec.DeclSpace.CheckAccessLevel (t)) {
2211 lookup_name = t.FullName;
2218 t = TypeManager.GetNestedType (t, elements [i++]);
2223 if (resolved == null) {
2224 NamespaceEntry.Error_NamespaceNotFound (loc, lookup_name);
2228 if (!(resolved is TypeExpr)) {
2229 resolved.Error_UnexpectedKind (ec, "type", loc);
2233 type = ((TypeExpr) resolved).ResolveType (ec);
2237 public override string Name {
2238 get { return name; }
2241 public override string FullName {
2242 get { return name; }
2246 public class TypeAliasExpression : TypeExpr {
2249 public TypeAliasExpression (TypeExpr texpr, Location l)
2252 loc = texpr.Location;
2254 eclass = ExprClass.Type;
2257 public override string Name {
2258 get { return texpr.Name; }
2261 public override string FullName {
2262 get { return texpr.FullName; }
2265 public override TypeExpr DoResolveAsTypeStep (EmitContext ec)
2267 Type type = texpr.ResolveType (ec);
2271 return new TypeExpression (type, loc);
2274 public override bool CheckAccessLevel (DeclSpace ds)
2276 return texpr.CheckAccessLevel (ds);
2279 public override bool AsAccessible (DeclSpace ds, int flags)
2281 return texpr.AsAccessible (ds, flags);
2284 public override bool IsClass {
2285 get { return texpr.IsClass; }
2288 public override bool IsValueType {
2289 get { return texpr.IsValueType; }
2292 public override bool IsInterface {
2293 get { return texpr.IsInterface; }
2296 public override bool IsSealed {
2297 get { return texpr.IsSealed; }
2302 /// This class denotes an expression which evaluates to a member
2303 /// of a struct or a class.
2305 public abstract class MemberExpr : Expression
2308 /// The name of this member.
2310 public abstract string Name {
2315 /// Whether this is an instance member.
2317 public abstract bool IsInstance {
2322 /// Whether this is a static member.
2324 public abstract bool IsStatic {
2329 /// The type which declares this member.
2331 public abstract Type DeclaringType {
2336 /// The instance expression associated with this member, if it's a
2337 /// non-static member.
2339 public Expression InstanceExpression;
2341 public static void error176 (Location loc, string name)
2343 Report.Error (176, loc, "Static member `{0}' cannot be accessed " +
2344 "with an instance reference, qualify it with a type name instead", name);
2347 protected bool CheckIntermediateModification ()
2349 if (!InstanceExpression.Type.IsValueType)
2352 if (InstanceExpression is UnboxCast) {
2353 Report.Error (445, loc, "Cannot modify the result of an unboxing conversion");
2357 if (!(InstanceExpression is IMemoryLocation)) {
2358 Report.Error (1612, loc, "Cannot modify the return value of `{0}' because it is not a variable",
2359 InstanceExpression.GetSignatureForError ());
2366 // TODO: possible optimalization
2367 // Cache resolved constant result in FieldBuilder <-> expression map
2368 public virtual Expression ResolveMemberAccess (EmitContext ec, Expression left, Location loc,
2369 SimpleName original)
2373 // original == null || original.Resolve (...) ==> left
2376 if (left is TypeExpr) {
2378 SimpleName.Error_ObjectRefRequired (ec, loc, Name);
2386 if (original != null && original.IdenticalNameAndTypeName (ec, left, loc))
2389 error176 (loc, GetSignatureForError ());
2393 InstanceExpression = left;
2398 protected void EmitInstance (EmitContext ec, bool prepare_for_load)
2403 if (InstanceExpression == EmptyExpression.Null) {
2404 SimpleName.Error_ObjectRefRequired (ec, loc, Name);
2408 if (InstanceExpression.Type.IsValueType) {
2409 if (InstanceExpression is IMemoryLocation) {
2410 ((IMemoryLocation) InstanceExpression).AddressOf (ec, AddressOp.LoadStore);
2412 LocalTemporary t = new LocalTemporary (ec, InstanceExpression.Type);
2413 InstanceExpression.Emit (ec);
2415 t.AddressOf (ec, AddressOp.Store);
2418 InstanceExpression.Emit (ec);
2420 if (prepare_for_load)
2421 ec.ig.Emit (OpCodes.Dup);
2426 /// MethodGroup Expression.
2428 /// This is a fully resolved expression that evaluates to a type
2430 public class MethodGroupExpr : MemberExpr {
2431 public MethodBase [] Methods;
2432 bool identical_type_name = false;
2435 public MethodGroupExpr (MemberInfo [] mi, Location l)
2437 Methods = new MethodBase [mi.Length];
2438 mi.CopyTo (Methods, 0);
2439 eclass = ExprClass.MethodGroup;
2440 type = TypeManager.object_type;
2444 public MethodGroupExpr (ArrayList list, Location l)
2446 Methods = new MethodBase [list.Count];
2449 list.CopyTo (Methods, 0);
2451 foreach (MemberInfo m in list){
2452 if (!(m is MethodBase)){
2453 Console.WriteLine ("Name " + m.Name);
2454 Console.WriteLine ("Found a: " + m.GetType ().FullName);
2461 eclass = ExprClass.MethodGroup;
2462 type = TypeManager.object_type;
2465 public override Type DeclaringType {
2468 // The methods are arranged in this order:
2469 // derived type -> base type
2471 return Methods [0].DeclaringType;
2475 public bool IdenticalTypeName {
2477 return identical_type_name;
2481 identical_type_name = value;
2485 public bool IsBase {
2494 public override string GetSignatureForError ()
2496 return TypeManager.CSharpSignature (Methods [0]);
2499 public override string Name {
2501 return Methods [0].Name;
2505 public override bool IsInstance {
2507 foreach (MethodBase mb in Methods)
2515 public override bool IsStatic {
2517 foreach (MethodBase mb in Methods)
2525 public override Expression ResolveMemberAccess (EmitContext ec, Expression left, Location loc,
2526 SimpleName original)
2528 if (!(left is TypeExpr) &&
2529 original != null && original.IdenticalNameAndTypeName (ec, left, loc))
2530 IdenticalTypeName = true;
2532 return base.ResolveMemberAccess (ec, left, loc, original);
2535 override public Expression DoResolve (EmitContext ec)
2538 InstanceExpression = null;
2540 if (InstanceExpression != null) {
2541 InstanceExpression = InstanceExpression.DoResolve (ec);
2542 if (InstanceExpression == null)
2549 public void ReportUsageError ()
2551 Report.Error (654, loc, "Method `" + DeclaringType + "." +
2552 Name + "()' is referenced without parentheses");
2555 override public void Emit (EmitContext ec)
2557 ReportUsageError ();
2560 bool RemoveMethods (bool keep_static)
2562 ArrayList smethods = new ArrayList ();
2564 foreach (MethodBase mb in Methods){
2565 if (mb.IsStatic == keep_static)
2569 if (smethods.Count == 0)
2572 Methods = new MethodBase [smethods.Count];
2573 smethods.CopyTo (Methods, 0);
2579 /// Removes any instance methods from the MethodGroup, returns
2580 /// false if the resulting set is empty.
2582 public bool RemoveInstanceMethods ()
2584 return RemoveMethods (true);
2588 /// Removes any static methods from the MethodGroup, returns
2589 /// false if the resulting set is empty.
2591 public bool RemoveStaticMethods ()
2593 return RemoveMethods (false);
2598 /// Fully resolved expression that evaluates to a Field
2600 public class FieldExpr : MemberExpr, IAssignMethod, IMemoryLocation, IVariable {
2601 public readonly FieldInfo FieldInfo;
2602 VariableInfo variable_info;
2604 LocalTemporary temp;
2606 bool in_initializer;
2608 public FieldExpr (FieldInfo fi, Location l, bool in_initializer):
2611 this.in_initializer = in_initializer;
2614 public FieldExpr (FieldInfo fi, Location l)
2617 eclass = ExprClass.Variable;
2618 type = fi.FieldType;
2622 public override string Name {
2624 return FieldInfo.Name;
2628 public override bool IsInstance {
2630 return !FieldInfo.IsStatic;
2634 public override bool IsStatic {
2636 return FieldInfo.IsStatic;
2640 public override Type DeclaringType {
2642 return FieldInfo.DeclaringType;
2646 public override string GetSignatureForError ()
2648 return TypeManager.GetFullNameSignature (FieldInfo);
2651 public VariableInfo VariableInfo {
2653 return variable_info;
2657 public override Expression ResolveMemberAccess (EmitContext ec, Expression left, Location loc,
2658 SimpleName original)
2660 Type t = FieldInfo.FieldType;
2662 if (FieldInfo.IsLiteral || (FieldInfo.IsInitOnly && t == TypeManager.decimal_type)) {
2663 IConstant ic = TypeManager.GetConstant (FieldInfo);
2665 if (FieldInfo.IsLiteral) {
2666 ic = new ExternalConstant (FieldInfo);
2668 ic = ExternalConstant.CreateDecimal (FieldInfo);
2670 return base.ResolveMemberAccess (ec, left, loc, original);
2673 TypeManager.RegisterConstant (FieldInfo, ic);
2676 bool left_is_type = left is TypeExpr;
2677 if (!left_is_type && (original == null || !original.IdenticalNameAndTypeName (ec, left, loc))) {
2678 Report.SymbolRelatedToPreviousError (FieldInfo);
2679 error176 (loc, TypeManager.GetFullNameSignature (FieldInfo));
2683 if (ic.ResolveValue ())
2684 ic.CheckObsoleteness (loc);
2689 if (t.IsPointer && !ec.InUnsafe) {
2694 return base.ResolveMemberAccess (ec, left, loc, original);
2697 override public Expression DoResolve (EmitContext ec)
2699 if (ec.InRefOutArgumentResolving && FieldInfo.IsInitOnly && !ec.IsConstructor && FieldInfo.FieldType.IsValueType) {
2700 if (FieldInfo.FieldType is TypeBuilder) {
2701 if (FieldInfo.IsStatic)
2702 Report.Error (1651, loc, "Fields of static readonly field `{0}' cannot be passed ref or out (except in a static constructor)",
2703 GetSignatureForError ());
2705 Report.Error (1649, loc, "Members of readonly field `{0}.{1}' cannot be passed ref or out (except in a constructor)",
2706 TypeManager.CSharpName (DeclaringType), Name);
2708 if (FieldInfo.IsStatic)
2709 Report.Error (199, loc, "A static readonly field `{0}' cannot be passed ref or out (except in a static constructor)",
2712 Report.Error (192, loc, "A readonly field `{0}' cannot be passed ref or out (except in a constructor)",
2718 if (!FieldInfo.IsStatic){
2719 if (InstanceExpression == null){
2721 // This can happen when referencing an instance field using
2722 // a fully qualified type expression: TypeName.InstanceField = xxx
2724 SimpleName.Error_ObjectRefRequired (ec, loc, FieldInfo.Name);
2728 // Resolve the field's instance expression while flow analysis is turned
2729 // off: when accessing a field "a.b", we must check whether the field
2730 // "a.b" is initialized, not whether the whole struct "a" is initialized.
2731 InstanceExpression = InstanceExpression.Resolve (
2732 ec, ResolveFlags.VariableOrValue | ResolveFlags.DisableFlowAnalysis);
2733 if (InstanceExpression == null)
2737 if (!in_initializer && !ec.IsFieldInitializer) {
2738 ObsoleteAttribute oa;
2739 FieldBase f = TypeManager.GetField (FieldInfo);
2741 f.CheckObsoleteness (loc);
2743 // To be sure that type is external because we do not register generated fields
2744 } else if (!(FieldInfo.DeclaringType is TypeBuilder)) {
2745 oa = AttributeTester.GetMemberObsoleteAttribute (FieldInfo);
2747 AttributeTester.Report_ObsoleteMessage (oa, TypeManager.GetFullNameSignature (FieldInfo), loc);
2751 AnonymousContainer am = ec.CurrentAnonymousMethod;
2753 if (!FieldInfo.IsStatic){
2754 if (!am.IsIterator && (ec.TypeContainer is Struct)){
2755 Report.Error (1673, loc,
2756 "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",
2760 if ((am.ContainerAnonymousMethod == null) && (InstanceExpression is This))
2761 ec.CaptureField (this);
2765 // If the instance expression is a local variable or parameter.
2766 IVariable var = InstanceExpression as IVariable;
2767 if ((var == null) || (var.VariableInfo == null))
2770 VariableInfo vi = var.VariableInfo;
2771 if (!vi.IsFieldAssigned (ec, FieldInfo.Name, loc))
2774 variable_info = vi.GetSubStruct (FieldInfo.Name);
2778 void Report_AssignToReadonly (bool is_instance)
2783 msg = "A readonly field cannot be assigned to (except in a constructor or a variable initializer)";
2785 msg = "A static readonly field cannot be assigned to (except in a static constructor or a variable initializer)";
2787 Report.Error (is_instance ? 191 : 198, loc, msg);
2790 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
2792 IVariable var = InstanceExpression as IVariable;
2793 if ((var != null) && (var.VariableInfo != null))
2794 var.VariableInfo.SetFieldAssigned (ec, FieldInfo.Name);
2796 Expression e = DoResolve (ec);
2801 if (!FieldInfo.IsStatic && !CheckIntermediateModification ())
2804 FieldBase fb = TypeManager.GetField (FieldInfo);
2808 if (!FieldInfo.IsInitOnly)
2812 // InitOnly fields can only be assigned in constructors
2815 if (ec.IsConstructor){
2816 if (IsStatic && !ec.IsStatic)
2817 Report_AssignToReadonly (false);
2819 if (ec.ContainerType == FieldInfo.DeclaringType)
2823 Report_AssignToReadonly (!IsStatic);
2828 public override void CheckMarshallByRefAccess (Type container)
2830 if (!IsStatic && Type.IsValueType && !container.IsSubclassOf (TypeManager.mbr_type) && DeclaringType.IsSubclassOf (TypeManager.mbr_type)) {
2831 Report.SymbolRelatedToPreviousError (DeclaringType);
2832 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",
2833 GetSignatureForError ());
2837 public bool VerifyFixed ()
2839 IVariable variable = InstanceExpression as IVariable;
2840 // A variable of the form V.I is fixed when V is a fixed variable of a struct type.
2841 // We defer the InstanceExpression check after the variable check to avoid a
2842 // separate null check on InstanceExpression.
2843 return variable != null && InstanceExpression.Type.IsValueType && variable.VerifyFixed ();
2846 public override int GetHashCode()
2848 return FieldInfo.GetHashCode ();
2851 public override bool Equals (object obj)
2853 FieldExpr fe = obj as FieldExpr;
2857 if (FieldInfo != fe.FieldInfo)
2860 if (InstanceExpression == null || fe.InstanceExpression == null)
2863 return InstanceExpression.Equals (fe.InstanceExpression);
2866 public void Emit (EmitContext ec, bool leave_copy)
2868 ILGenerator ig = ec.ig;
2869 bool is_volatile = false;
2871 if (FieldInfo is FieldBuilder){
2872 FieldBase f = TypeManager.GetField (FieldInfo);
2874 if ((f.ModFlags & Modifiers.VOLATILE) != 0)
2877 f.SetMemberIsUsed ();
2881 if (FieldInfo.IsStatic){
2883 ig.Emit (OpCodes.Volatile);
2885 ig.Emit (OpCodes.Ldsfld, FieldInfo);
2888 EmitInstance (ec, false);
2891 ig.Emit (OpCodes.Volatile);
2893 IFixedBuffer ff = AttributeTester.GetFixedBuffer (FieldInfo);
2896 ig.Emit (OpCodes.Ldflda, FieldInfo);
2897 ig.Emit (OpCodes.Ldflda, ff.Element);
2900 ig.Emit (OpCodes.Ldfld, FieldInfo);
2905 ec.ig.Emit (OpCodes.Dup);
2906 if (!FieldInfo.IsStatic) {
2907 temp = new LocalTemporary (ec, this.Type);
2913 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
2915 FieldAttributes fa = FieldInfo.Attributes;
2916 bool is_static = (fa & FieldAttributes.Static) != 0;
2917 bool is_readonly = (fa & FieldAttributes.InitOnly) != 0;
2918 ILGenerator ig = ec.ig;
2919 prepared = prepare_for_load;
2921 if (is_readonly && !ec.IsConstructor){
2922 Report_AssignToReadonly (!is_static);
2926 EmitInstance (ec, prepare_for_load);
2930 ec.ig.Emit (OpCodes.Dup);
2931 if (!FieldInfo.IsStatic) {
2932 temp = new LocalTemporary (ec, this.Type);
2937 if (FieldInfo is FieldBuilder){
2938 FieldBase f = TypeManager.GetField (FieldInfo);
2940 if ((f.ModFlags & Modifiers.VOLATILE) != 0)
2941 ig.Emit (OpCodes.Volatile);
2948 ig.Emit (OpCodes.Stsfld, FieldInfo);
2950 ig.Emit (OpCodes.Stfld, FieldInfo);
2956 public override void Emit (EmitContext ec)
2961 public void AddressOf (EmitContext ec, AddressOp mode)
2963 ILGenerator ig = ec.ig;
2965 if (FieldInfo is FieldBuilder){
2966 FieldBase f = TypeManager.GetField (FieldInfo);
2968 if ((f.ModFlags & Modifiers.VOLATILE) != 0){
2969 Report.Warning (420, 1, loc, "`{0}': A volatile fields cannot be passed using a ref or out parameter",
2970 f.GetSignatureForError ());
2974 if ((mode & AddressOp.Store) != 0)
2976 if ((mode & AddressOp.Load) != 0)
2977 f.SetMemberIsUsed ();
2982 // Handle initonly fields specially: make a copy and then
2983 // get the address of the copy.
2986 if (FieldInfo.IsInitOnly){
2988 if (ec.IsConstructor){
2989 if (FieldInfo.IsStatic){
3001 local = ig.DeclareLocal (type);
3002 ig.Emit (OpCodes.Stloc, local);
3003 ig.Emit (OpCodes.Ldloca, local);
3008 if (FieldInfo.IsStatic){
3009 ig.Emit (OpCodes.Ldsflda, FieldInfo);
3011 EmitInstance (ec, false);
3012 ig.Emit (OpCodes.Ldflda, FieldInfo);
3018 // A FieldExpr whose address can not be taken
3020 public class FieldExprNoAddress : FieldExpr, IMemoryLocation {
3021 public FieldExprNoAddress (FieldInfo fi, Location loc) : base (fi, loc)
3025 public new void AddressOf (EmitContext ec, AddressOp mode)
3027 Report.Error (-215, "Report this: Taking the address of a remapped parameter not supported");
3032 /// Expression that evaluates to a Property. The Assign class
3033 /// might set the `Value' expression if we are in an assignment.
3035 /// This is not an LValue because we need to re-write the expression, we
3036 /// can not take data from the stack and store it.
3038 public class PropertyExpr : MemberExpr, IAssignMethod {
3039 public readonly PropertyInfo PropertyInfo;
3042 // This is set externally by the `BaseAccess' class
3045 MethodInfo getter, setter;
3050 LocalTemporary temp;
3053 internal static PtrHashtable AccessorTable = new PtrHashtable ();
3055 public PropertyExpr (EmitContext ec, PropertyInfo pi, Location l)
3058 eclass = ExprClass.PropertyAccess;
3062 type = TypeManager.TypeToCoreType (pi.PropertyType);
3064 ResolveAccessors (ec);
3067 public override string Name {
3069 return PropertyInfo.Name;
3073 public override bool IsInstance {
3079 public override bool IsStatic {
3085 public override Type DeclaringType {
3087 return PropertyInfo.DeclaringType;
3091 public override string GetSignatureForError ()
3093 return TypeManager.GetFullNameSignature (PropertyInfo);
3096 void FindAccessors (Type invocation_type)
3098 BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic |
3099 BindingFlags.Static | BindingFlags.Instance |
3100 BindingFlags.DeclaredOnly;
3102 Type current = PropertyInfo.DeclaringType;
3103 for (; current != null; current = current.BaseType) {
3104 MemberInfo[] group = TypeManager.MemberLookup (
3105 invocation_type, invocation_type, current,
3106 MemberTypes.Property, flags, PropertyInfo.Name, null);
3111 if (group.Length != 1)
3112 // Oooops, can this ever happen ?
3115 PropertyInfo pi = (PropertyInfo) group [0];
3118 getter = pi.GetGetMethod (true);
3121 setter = pi.GetSetMethod (true);
3123 MethodInfo accessor = getter != null ? getter : setter;
3125 if (!accessor.IsVirtual)
3131 // We also perform the permission checking here, as the PropertyInfo does not
3132 // hold the information for the accessibility of its setter/getter
3134 void ResolveAccessors (EmitContext ec)
3136 FindAccessors (ec.ContainerType);
3138 if (getter != null) {
3139 IMethodData md = TypeManager.GetMethod (getter);
3141 md.SetMemberIsUsed ();
3143 AccessorTable [getter] = PropertyInfo;
3144 is_static = getter.IsStatic;
3147 if (setter != null) {
3148 IMethodData md = TypeManager.GetMethod (setter);
3150 md.SetMemberIsUsed ();
3152 AccessorTable [setter] = PropertyInfo;
3153 is_static = setter.IsStatic;
3157 bool InstanceResolve (EmitContext ec, bool must_do_cs1540_check)
3160 InstanceExpression = null;
3164 if (InstanceExpression == null) {
3165 SimpleName.Error_ObjectRefRequired (ec, loc, PropertyInfo.Name);
3169 InstanceExpression = InstanceExpression.DoResolve (ec);
3170 if (InstanceExpression == null)
3173 InstanceExpression.CheckMarshallByRefAccess (ec.ContainerType);
3175 if (must_do_cs1540_check && InstanceExpression != EmptyExpression.Null) {
3176 if ((InstanceExpression.Type != ec.ContainerType) &&
3177 ec.ContainerType.IsSubclassOf (InstanceExpression.Type)) {
3178 Report.Error (1540, loc, "Cannot access protected member `" +
3179 PropertyInfo.DeclaringType + "." + PropertyInfo.Name +
3180 "' via a qualifier of type `" +
3181 TypeManager.CSharpName (InstanceExpression.Type) +
3182 "'; the qualifier must be of type `" +
3183 TypeManager.CSharpName (ec.ContainerType) +
3184 "' (or derived from it)");
3192 void Error_PropertyNotFound (MethodInfo mi, bool getter)
3194 // TODO: correctly we should compare arguments but it will lead to bigger changes
3195 if (mi is MethodBuilder) {
3196 Error_TypeDoesNotContainDefinition (loc, PropertyInfo.DeclaringType, Name);
3200 StringBuilder sig = new StringBuilder (TypeManager.CSharpName (mi.DeclaringType));
3202 ParameterData iparams = TypeManager.GetParameterData (mi);
3203 sig.Append (getter ? "get_" : "set_");
3205 sig.Append (iparams.GetSignatureForError ());
3207 Report.SymbolRelatedToPreviousError (mi);
3208 Report.Error (1546, loc, "Property `{0}' is not supported by the C# language. Try to call the accessor method `{1}' directly",
3209 Name, sig.ToString ());
3212 override public Expression DoResolve (EmitContext ec)
3217 if (getter != null){
3218 if (TypeManager.GetArgumentTypes (getter).Length != 0){
3219 Error_PropertyNotFound (getter, true);
3224 if (getter == null){
3226 // The following condition happens if the PropertyExpr was
3227 // created, but is invalid (ie, the property is inaccessible),
3228 // and we did not want to embed the knowledge about this in
3229 // the caller routine. This only avoids double error reporting.
3234 if (InstanceExpression != EmptyExpression.Null) {
3235 Report.Error (154, loc, "The property or indexer `{0}' cannot be used in this context because it lacks the `get' accessor",
3236 TypeManager.GetFullNameSignature (PropertyInfo));
3241 bool must_do_cs1540_check = false;
3242 if (getter != null &&
3243 !IsAccessorAccessible (ec.ContainerType, getter, out must_do_cs1540_check)) {
3244 PropertyBase.PropertyMethod pm = TypeManager.GetMethod (getter) as PropertyBase.PropertyMethod;
3245 if (pm != null && pm.HasCustomAccessModifier) {
3246 Report.SymbolRelatedToPreviousError (pm);
3247 Report.Error (271, loc, "The property or indexer `{0}' cannot be used in this context because the get accessor is inaccessible",
3248 TypeManager.CSharpSignature (getter));
3251 ErrorIsInaccesible (loc, TypeManager.CSharpSignature (getter));
3255 if (!InstanceResolve (ec, must_do_cs1540_check))
3259 // Only base will allow this invocation to happen.
3261 if (IsBase && getter.IsAbstract) {
3262 Error_CannotCallAbstractBase (TypeManager.GetFullNameSignature (PropertyInfo));
3266 if (PropertyInfo.PropertyType.IsPointer && !ec.InUnsafe){
3276 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
3278 if (setter == null){
3280 // The following condition happens if the PropertyExpr was
3281 // created, but is invalid (ie, the property is inaccessible),
3282 // and we did not want to embed the knowledge about this in
3283 // the caller routine. This only avoids double error reporting.
3288 Report.Error (200, loc, " Property or indexer `{0}' cannot be assigned to (it is read only)",
3289 TypeManager.GetFullNameSignature (PropertyInfo));
3293 if (TypeManager.GetArgumentTypes (setter).Length != 1){
3294 Error_PropertyNotFound (setter, false);
3298 bool must_do_cs1540_check;
3299 if (!IsAccessorAccessible (ec.ContainerType, setter, out must_do_cs1540_check)) {
3300 PropertyBase.PropertyMethod pm = TypeManager.GetMethod (setter) as PropertyBase.PropertyMethod;
3301 if (pm != null && pm.HasCustomAccessModifier) {
3302 Report.SymbolRelatedToPreviousError (pm);
3303 Report.Error (272, loc, "The property or indexer `{0}' cannot be used in this context because the set accessor is inaccessible",
3304 TypeManager.CSharpSignature (setter));
3307 ErrorIsInaccesible (loc, TypeManager.CSharpSignature (setter));
3311 if (!InstanceResolve (ec, must_do_cs1540_check))
3315 // Only base will allow this invocation to happen.
3317 if (IsBase && setter.IsAbstract){
3318 Error_CannotCallAbstractBase (TypeManager.GetFullNameSignature (PropertyInfo));
3323 // Check that we are not making changes to a temporary memory location
3325 if (InstanceExpression != null && !CheckIntermediateModification ())
3331 public override void Emit (EmitContext ec)
3336 public void Emit (EmitContext ec, bool leave_copy)
3339 EmitInstance (ec, false);
3342 // Special case: length of single dimension array property is turned into ldlen
3344 if ((getter == TypeManager.system_int_array_get_length) ||
3345 (getter == TypeManager.int_array_get_length)){
3346 Type iet = InstanceExpression.Type;
3349 // System.Array.Length can be called, but the Type does not
3350 // support invoking GetArrayRank, so test for that case first
3352 if (iet != TypeManager.array_type && (iet.GetArrayRank () == 1)) {
3353 ec.ig.Emit (OpCodes.Ldlen);
3354 ec.ig.Emit (OpCodes.Conv_I4);
3359 Invocation.EmitCall (ec, IsBase, IsStatic, new EmptyAddressOf (), getter, null, loc);
3364 ec.ig.Emit (OpCodes.Dup);
3366 temp = new LocalTemporary (ec, this.Type);
3372 // Implements the IAssignMethod interface for assignments
3374 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
3376 prepared = prepare_for_load;
3378 EmitInstance (ec, prepare_for_load);
3382 ec.ig.Emit (OpCodes.Dup);
3384 temp = new LocalTemporary (ec, this.Type);
3389 ArrayList args = new ArrayList (1);
3390 args.Add (new Argument (new EmptyAddressOf (), Argument.AType.Expression));
3392 Invocation.EmitCall (ec, IsBase, IsStatic, new EmptyAddressOf (), setter, args, loc);
3400 /// Fully resolved expression that evaluates to an Event
3402 public class EventExpr : MemberExpr {
3403 public readonly EventInfo EventInfo;
3406 MethodInfo add_accessor, remove_accessor;
3408 public EventExpr (EventInfo ei, Location loc)
3412 eclass = ExprClass.EventAccess;
3414 add_accessor = TypeManager.GetAddMethod (ei);
3415 remove_accessor = TypeManager.GetRemoveMethod (ei);
3417 if (add_accessor.IsStatic || remove_accessor.IsStatic)
3420 if (EventInfo is MyEventBuilder){
3421 MyEventBuilder eb = (MyEventBuilder) EventInfo;
3422 type = eb.EventType;
3425 type = EventInfo.EventHandlerType;
3428 public override string Name {
3430 return EventInfo.Name;
3434 public override bool IsInstance {
3440 public override bool IsStatic {
3446 public override Type DeclaringType {
3448 return EventInfo.DeclaringType;
3452 public override Expression ResolveMemberAccess (EmitContext ec, Expression left, Location loc,
3453 SimpleName original)
3456 // If the event is local to this class, we transform ourselves into a FieldExpr
3459 if (EventInfo.DeclaringType == ec.ContainerType ||
3460 TypeManager.IsNestedChildOf(ec.ContainerType, EventInfo.DeclaringType)) {
3461 MemberInfo mi = TypeManager.GetPrivateFieldOfEvent (EventInfo);
3464 MemberExpr ml = (MemberExpr) ExprClassFromMemberInfo (ec, mi, loc);
3467 Report.Error (-200, loc, "Internal error!!");
3471 InstanceExpression = null;
3473 return ml.ResolveMemberAccess (ec, left, loc, original);
3477 return base.ResolveMemberAccess (ec, left, loc, original);
3481 bool InstanceResolve (EmitContext ec, bool must_do_cs1540_check)
3484 InstanceExpression = null;
3488 if (InstanceExpression == null) {
3489 SimpleName.Error_ObjectRefRequired (ec, loc, EventInfo.Name);
3493 InstanceExpression = InstanceExpression.DoResolve (ec);
3494 if (InstanceExpression == null)
3498 // This is using the same mechanism as the CS1540 check in PropertyExpr.
3499 // However, in the Event case, we reported a CS0122 instead.
3501 if (must_do_cs1540_check && InstanceExpression != EmptyExpression.Null) {
3502 if ((InstanceExpression.Type != ec.ContainerType) &&
3503 ec.ContainerType.IsSubclassOf (InstanceExpression.Type)) {
3504 ErrorIsInaccesible (loc, TypeManager.CSharpSignature (EventInfo));
3512 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
3514 return DoResolve (ec);
3517 public override Expression DoResolve (EmitContext ec)
3519 bool must_do_cs1540_check;
3520 if (!(IsAccessorAccessible (ec.ContainerType, add_accessor, out must_do_cs1540_check) &&
3521 IsAccessorAccessible (ec.ContainerType, remove_accessor, out must_do_cs1540_check))) {
3522 ErrorIsInaccesible (loc, TypeManager.CSharpSignature (EventInfo));
3526 if (!InstanceResolve (ec, must_do_cs1540_check))
3532 public override void Emit (EmitContext ec)
3534 if (InstanceExpression is This)
3535 Report.Error (79, loc, "The event `{0}' can only appear on the left hand side of += or -=", GetSignatureForError ());
3537 Report.Error (70, loc, "The event `{0}' can only appear on the left hand side of += or -= "+
3538 "(except on the defining type)", Name);
3541 public override string GetSignatureForError ()
3543 return TypeManager.CSharpSignature (EventInfo);
3546 public void EmitAddOrRemove (EmitContext ec, Expression source)
3548 BinaryDelegate source_del = (BinaryDelegate) source;
3549 Expression handler = source_del.Right;
3551 Argument arg = new Argument (handler, Argument.AType.Expression);
3552 ArrayList args = new ArrayList ();
3556 if (source_del.IsAddition)
3557 Invocation.EmitCall (
3558 ec, false, IsStatic, InstanceExpression, add_accessor, args, loc);
3560 Invocation.EmitCall (
3561 ec, false, IsStatic, InstanceExpression, remove_accessor, args, loc);
3566 public class TemporaryVariable : Expression, IMemoryLocation
3570 public TemporaryVariable (Type type, Location loc)
3574 eclass = ExprClass.Value;
3577 public override Expression DoResolve (EmitContext ec)
3582 TypeExpr te = new TypeExpression (type, loc);
3583 li = ec.CurrentBlock.AddTemporaryVariable (te, loc);
3584 if (!li.Resolve (ec))
3587 AnonymousContainer am = ec.CurrentAnonymousMethod;
3588 if ((am != null) && am.IsIterator)
3589 ec.CaptureVariable (li);
3594 public override void Emit (EmitContext ec)
3596 ILGenerator ig = ec.ig;
3598 if (li.FieldBuilder != null) {
3599 ig.Emit (OpCodes.Ldarg_0);
3600 ig.Emit (OpCodes.Ldfld, li.FieldBuilder);
3602 ig.Emit (OpCodes.Ldloc, li.LocalBuilder);
3606 public void EmitLoadAddress (EmitContext ec)
3608 ILGenerator ig = ec.ig;
3610 if (li.FieldBuilder != null) {
3611 ig.Emit (OpCodes.Ldarg_0);
3612 ig.Emit (OpCodes.Ldflda, li.FieldBuilder);
3614 ig.Emit (OpCodes.Ldloca, li.LocalBuilder);
3618 public void Store (EmitContext ec, Expression right_side)
3620 if (li.FieldBuilder != null)
3621 ec.ig.Emit (OpCodes.Ldarg_0);
3623 right_side.Emit (ec);
3624 if (li.FieldBuilder != null) {
3625 ec.ig.Emit (OpCodes.Stfld, li.FieldBuilder);
3627 ec.ig.Emit (OpCodes.Stloc, li.LocalBuilder);
3631 public void EmitThis (EmitContext ec)
3633 if (li.FieldBuilder != null) {
3634 ec.ig.Emit (OpCodes.Ldarg_0);
3638 public void EmitStore (ILGenerator ig)
3640 if (li.FieldBuilder != null)
3641 ig.Emit (OpCodes.Stfld, li.FieldBuilder);
3643 ig.Emit (OpCodes.Stloc, li.LocalBuilder);
3646 public void AddressOf (EmitContext ec, AddressOp mode)
3648 EmitLoadAddress (ec);