2 // ecore.cs: Core of the Expression representation for the intermediate tree.
5 // Miguel de Icaza (miguel@ximian.com)
7 // (C) 2001, 2002, 2003 Ximian, Inc.
11 namespace Mono.CSharp {
13 using System.Collections;
14 using System.Diagnostics;
15 using System.Reflection;
16 using System.Reflection.Emit;
20 /// The ExprClass class contains the is used to pass the
21 /// classification of an expression (value, variable, namespace,
22 /// type, method group, property access, event access, indexer access,
25 public enum ExprClass : byte {
40 /// This is used to tell Resolve in which types of expressions we're
44 public enum ResolveFlags {
45 // Returns Value, Variable, PropertyAccess, EventAccess or IndexerAccess.
48 // Returns a type expression.
51 // Returns a method group.
54 // Mask of all the expression class flags.
57 // Disable control flow analysis while resolving the expression.
58 // This is used when resolving the instance expression of a field expression.
59 DisableFlowAnalysis = 8,
61 // Set if this is resolving the first part of a MemberAccess.
66 // This is just as a hint to AddressOf of what will be done with the
69 public enum AddressOp {
76 /// This interface is implemented by variables
78 public interface IMemoryLocation {
80 /// The AddressOf method should generate code that loads
81 /// the address of the object and leaves it on the stack.
83 /// The `mode' argument is used to notify the expression
84 /// of whether this will be used to read from the address or
85 /// write to the address.
87 /// This is just a hint that can be used to provide good error
88 /// reporting, and should have no other side effects.
90 void AddressOf (EmitContext ec, AddressOp mode);
94 /// We are either a namespace or a type.
95 /// If we're a type, `IsType' is true and we may use `Type' to get
96 /// a TypeExpr representing that type.
98 public interface IAlias {
107 TypeExpr ResolveAsType (EmitContext ec);
111 /// This interface is implemented by variables
113 public interface IVariable {
114 VariableInfo VariableInfo {
122 /// Base class for expressions
124 public abstract class Expression {
125 public ExprClass eclass;
127 protected Location loc;
139 public Location Location {
146 /// Utility wrapper routine for Error, just to beautify the code
148 public void Error (int error, string s)
150 if (!Location.IsNull (loc))
151 Report.Error (error, loc, s);
153 Report.Error (error, s);
157 /// Utility wrapper routine for Warning, just to beautify the code
159 public void Warning (int code, string format, params object[] args)
161 Report.Warning (code, loc, format, args);
164 // Not nice but we have broken hierarchy
165 public virtual void CheckMarshallByRefAccess (Type container) {}
168 /// Tests presence of ObsoleteAttribute and report proper error
170 protected void CheckObsoleteAttribute (Type type)
172 ObsoleteAttribute obsolete_attr = AttributeTester.GetObsoleteAttribute (type);
173 if (obsolete_attr == null)
176 AttributeTester.Report_ObsoleteMessage (obsolete_attr, type.FullName, loc);
179 public virtual string GetSignatureForError ()
181 return TypeManager.CSharpName (type);
184 public static bool IsAccessorAccessible (Type invocation_type, MethodInfo mi, out bool must_do_cs1540_check)
186 MethodAttributes ma = mi.Attributes & MethodAttributes.MemberAccessMask;
188 must_do_cs1540_check = false; // by default we do not check for this
191 // If only accessible to the current class or children
193 if (ma == MethodAttributes.Private)
194 return TypeManager.IsPrivateAccessible (invocation_type, mi.DeclaringType) ||
195 TypeManager.IsNestedChildOf (invocation_type, mi.DeclaringType);
197 if (mi.DeclaringType.Assembly == invocation_type.Assembly) {
198 if (ma == MethodAttributes.Assembly || ma == MethodAttributes.FamORAssem)
201 if (ma == MethodAttributes.Assembly || ma == MethodAttributes.FamANDAssem)
205 // Family and FamANDAssem require that we derive.
206 // FamORAssem requires that we derive if in different assemblies.
207 if (ma == MethodAttributes.Family ||
208 ma == MethodAttributes.FamANDAssem ||
209 ma == MethodAttributes.FamORAssem) {
210 if (!TypeManager.IsNestedFamilyAccessible (invocation_type, mi.DeclaringType))
213 if (!TypeManager.IsNestedChildOf (invocation_type, mi.DeclaringType))
214 must_do_cs1540_check = true;
223 /// Performs semantic analysis on the Expression
227 /// The Resolve method is invoked to perform the semantic analysis
230 /// The return value is an expression (it can be the
231 /// same expression in some cases) or a new
232 /// expression that better represents this node.
234 /// For example, optimizations of Unary (LiteralInt)
235 /// would return a new LiteralInt with a negated
238 /// If there is an error during semantic analysis,
239 /// then an error should be reported (using Report)
240 /// and a null value should be returned.
242 /// There are two side effects expected from calling
243 /// Resolve(): the the field variable "eclass" should
244 /// be set to any value of the enumeration
245 /// `ExprClass' and the type variable should be set
246 /// to a valid type (this is the type of the
249 public abstract Expression DoResolve (EmitContext ec);
251 public virtual Expression DoResolveLValue (EmitContext ec, Expression right_side)
257 // This is used if the expression should be resolved as a type or namespace name.
258 // the default implementation fails.
260 public virtual FullNamedExpression ResolveAsTypeStep (EmitContext ec)
266 // This is used to resolve the expression as a type, a null
267 // value will be returned if the expression is not a type
270 public virtual TypeExpr ResolveAsTypeTerminal (EmitContext ec)
272 int errors = Report.Errors;
274 FullNamedExpression fne = ResolveAsTypeStep (ec);
277 if (errors == Report.Errors)
278 NamespaceEntry.Error_NamespaceNotFound (Location, ToString ());
282 if (fne.eclass != ExprClass.Type) {
283 if (errors == Report.Errors)
284 Report.Error (118, Location, "`{0}' denotes a `{1}', where a type was expected",
285 fne.FullName, fne.ExprClassName ());
289 TypeExpr te = fne as TypeExpr;
291 if (!te.CheckAccessLevel (ec.DeclSpace)) {
292 ErrorIsInaccesible (loc, TypeManager.CSharpName (te.Type));
296 ConstructedType ct = te as ConstructedType;
297 if ((ct != null) && !ec.ResolvingTypeTree && !ct.CheckConstraints (ec))
303 public static void ErrorIsInaccesible (Location loc, string name)
305 Report.Error (122, loc, "`{0}' is inaccessible due to its protection level", name);
308 ResolveFlags ExprClassToResolveFlags ()
312 case ExprClass.Namespace:
313 return ResolveFlags.Type;
315 case ExprClass.MethodGroup:
316 return ResolveFlags.MethodGroup;
318 case ExprClass.Value:
319 case ExprClass.Variable:
320 case ExprClass.PropertyAccess:
321 case ExprClass.EventAccess:
322 case ExprClass.IndexerAccess:
323 return ResolveFlags.VariableOrValue;
326 throw new Exception ("Expression " + GetType () +
327 " ExprClass is Invalid after resolve");
333 /// Resolves an expression and performs semantic analysis on it.
337 /// Currently Resolve wraps DoResolve to perform sanity
338 /// checking and assertion checking on what we expect from Resolve.
340 public Expression Resolve (EmitContext ec, ResolveFlags flags)
342 if ((flags & ResolveFlags.MaskExprClass) == ResolveFlags.Type)
343 return ResolveAsTypeStep (ec);
345 bool old_do_flow_analysis = ec.DoFlowAnalysis;
346 if ((flags & ResolveFlags.DisableFlowAnalysis) != 0)
347 ec.DoFlowAnalysis = false;
350 bool intermediate = (flags & ResolveFlags.Intermediate) == ResolveFlags.Intermediate;
351 if (this is SimpleName)
352 e = ((SimpleName) this).DoResolve (ec, intermediate);
357 ec.DoFlowAnalysis = old_do_flow_analysis;
362 if ((flags & e.ExprClassToResolveFlags ()) == 0) {
363 e.Error_UnexpectedKind (flags, loc);
367 if (e.type == null && !(e is Namespace)) {
368 throw new Exception (
369 "Expression " + e.GetType () +
370 " did not set its type after Resolve\n" +
371 "called from: " + this.GetType ());
378 /// Resolves an expression and performs semantic analysis on it.
380 public Expression Resolve (EmitContext ec)
382 Expression e = Resolve (ec, ResolveFlags.VariableOrValue | ResolveFlags.MethodGroup);
384 if (e != null && e.eclass == ExprClass.MethodGroup && RootContext.Version == LanguageVersion.ISO_1) {
385 ((MethodGroupExpr) e).ReportUsageError ();
392 /// Resolves an expression for LValue assignment
396 /// Currently ResolveLValue wraps DoResolveLValue to perform sanity
397 /// checking and assertion checking on what we expect from Resolve
399 public Expression ResolveLValue (EmitContext ec, Expression right_side, Location loc)
401 int errors = Report.Errors;
402 Expression e = DoResolveLValue (ec, right_side);
405 if (errors == Report.Errors)
406 Report.Error (131, loc, "The left-hand side of an assignment or mutating operation must be a variable, property or indexer");
411 if (e.eclass == ExprClass.Invalid)
412 throw new Exception ("Expression " + e +
413 " ExprClass is Invalid after resolve");
415 if (e.eclass == ExprClass.MethodGroup) {
416 ((MethodGroupExpr) e).ReportUsageError ();
420 if ((e.type == null) && !(e is ConstructedType))
421 throw new Exception ("Expression " + e +
422 " did not set its type after Resolve");
429 /// Emits the code for the expression
433 /// The Emit method is invoked to generate the code
434 /// for the expression.
436 public abstract void Emit (EmitContext ec);
438 public virtual void EmitBranchable (EmitContext ec, Label target, bool onTrue)
441 ec.ig.Emit (onTrue ? OpCodes.Brtrue : OpCodes.Brfalse, target);
445 /// Protected constructor. Only derivate types should
446 /// be able to be created
449 protected Expression ()
451 eclass = ExprClass.Invalid;
456 /// Returns a literalized version of a literal FieldInfo
460 /// The possible return values are:
461 /// IntConstant, UIntConstant
462 /// LongLiteral, ULongConstant
463 /// FloatConstant, DoubleConstant
466 /// The value returned is already resolved.
468 public static Constant Constantify (object v, Type t)
470 if (t == TypeManager.int32_type)
471 return new IntConstant ((int) v);
472 else if (t == TypeManager.uint32_type)
473 return new UIntConstant ((uint) v);
474 else if (t == TypeManager.int64_type)
475 return new LongConstant ((long) v);
476 else if (t == TypeManager.uint64_type)
477 return new ULongConstant ((ulong) v);
478 else if (t == TypeManager.float_type)
479 return new FloatConstant ((float) v);
480 else if (t == TypeManager.double_type)
481 return new DoubleConstant ((double) v);
482 else if (t == TypeManager.string_type)
483 return new StringConstant ((string) v);
484 else if (t == TypeManager.short_type)
485 return new ShortConstant ((short)v);
486 else if (t == TypeManager.ushort_type)
487 return new UShortConstant ((ushort)v);
488 else if (t == TypeManager.sbyte_type)
489 return new SByteConstant (((sbyte)v));
490 else if (t == TypeManager.byte_type)
491 return new ByteConstant ((byte)v);
492 else if (t == TypeManager.char_type)
493 return new CharConstant ((char)v);
494 else if (t == TypeManager.bool_type)
495 return new BoolConstant ((bool) v);
496 else if (t == TypeManager.decimal_type)
497 return new DecimalConstant ((decimal) v);
498 else if (TypeManager.IsEnumType (t)){
499 Type real_type = TypeManager.TypeToCoreType (v.GetType ());
501 real_type = System.Enum.GetUnderlyingType (real_type);
503 Constant e = Constantify (v, real_type);
505 return new EnumConstant (e, t);
506 } else if (v == null && !TypeManager.IsValueType (t))
507 return NullLiteral.Null;
509 throw new Exception ("Unknown type for constant (" + t +
514 /// Returns a fully formed expression after a MemberLookup
516 public static Expression ExprClassFromMemberInfo (EmitContext ec, MemberInfo mi, Location loc)
519 return new EventExpr ((EventInfo) mi, loc);
520 else if (mi is FieldInfo)
521 return new FieldExpr ((FieldInfo) mi, loc);
522 else if (mi is PropertyInfo)
523 return new PropertyExpr (ec, (PropertyInfo) mi, loc);
524 else if (mi is Type){
525 return new TypeExpression ((System.Type) mi, loc);
531 protected static ArrayList almostMatchedMembers = new ArrayList (4);
534 // FIXME: Probably implement a cache for (t,name,current_access_set)?
536 // This code could use some optimizations, but we need to do some
537 // measurements. For example, we could use a delegate to `flag' when
538 // something can not any longer be a method-group (because it is something
542 // If the return value is an Array, then it is an array of
545 // If the return value is an MemberInfo, it is anything, but a Method
549 // FIXME: When calling MemberLookup inside an `Invocation', we should pass
550 // the arguments here and have MemberLookup return only the methods that
551 // match the argument count/type, unlike we are doing now (we delay this
554 // This is so we can catch correctly attempts to invoke instance methods
555 // from a static body (scan for error 120 in ResolveSimpleName).
558 // FIXME: Potential optimization, have a static ArrayList
561 public static Expression MemberLookup (EmitContext ec, Type queried_type, string name,
562 MemberTypes mt, BindingFlags bf, Location loc)
564 return MemberLookup (ec, ec.ContainerType, null, queried_type, name, mt, bf, loc);
568 // Lookup type `queried_type' for code in class `container_type' with a qualifier of
569 // `qualifier_type' or null to lookup members in the current class.
572 public static Expression MemberLookup (EmitContext ec, Type container_type,
573 Type qualifier_type, Type queried_type,
574 string name, MemberTypes mt,
575 BindingFlags bf, Location loc)
577 almostMatchedMembers.Clear ();
579 MemberInfo [] mi = TypeManager.MemberLookup (
580 container_type, qualifier_type, queried_type, mt, bf, name,
581 almostMatchedMembers);
586 int count = mi.Length;
588 if (mi [0] is MethodBase)
589 return new MethodGroupExpr (mi, loc);
594 return ExprClassFromMemberInfo (ec, mi [0], loc);
597 public const MemberTypes AllMemberTypes =
598 MemberTypes.Constructor |
602 MemberTypes.NestedType |
603 MemberTypes.Property;
605 public const BindingFlags AllBindingFlags =
606 BindingFlags.Public |
607 BindingFlags.Static |
608 BindingFlags.Instance;
610 public static Expression MemberLookup (EmitContext ec, Type queried_type,
611 string name, Location loc)
613 return MemberLookup (ec, ec.ContainerType, null, queried_type, name,
614 AllMemberTypes, AllBindingFlags, loc);
617 public static Expression MemberLookup (EmitContext ec, Type qualifier_type,
618 Type queried_type, string name, Location loc)
620 if (ec.ResolvingTypeTree)
621 return MemberLookup (ec, ec.ContainerType, qualifier_type,
622 queried_type, name, MemberTypes.NestedType,
623 AllBindingFlags, loc);
625 return MemberLookup (ec, ec.ContainerType, qualifier_type,
626 queried_type, name, AllMemberTypes,
627 AllBindingFlags, loc);
630 public static Expression MethodLookup (EmitContext ec, Type queried_type,
631 string name, Location loc)
633 return MemberLookup (ec, ec.ContainerType, null, queried_type, name,
634 MemberTypes.Method, AllBindingFlags, loc);
638 /// This is a wrapper for MemberLookup that is not used to "probe", but
639 /// to find a final definition. If the final definition is not found, we
640 /// look for private members and display a useful debugging message if we
643 public static Expression MemberLookupFinal (EmitContext ec, Type qualifier_type,
644 Type queried_type, string name,
647 return MemberLookupFinal (ec, qualifier_type, queried_type, name,
648 AllMemberTypes, AllBindingFlags, loc);
651 public static Expression MemberLookupFinal (EmitContext ec, Type qualifier_type,
652 Type queried_type, string name,
653 MemberTypes mt, BindingFlags bf,
658 int errors = Report.Errors;
660 e = MemberLookup (ec, ec.ContainerType, qualifier_type, queried_type,
663 if (e == null && errors == Report.Errors)
664 // No errors were reported by MemberLookup, but there was an error.
665 MemberLookupFailed (ec, qualifier_type, queried_type, name, null, true, loc);
670 public static void MemberLookupFailed (EmitContext ec, Type qualifier_type,
671 Type queried_type, string name,
672 string class_name, bool complain_if_none_found,
675 if (almostMatchedMembers.Count != 0) {
676 for (int i = 0; i < almostMatchedMembers.Count; ++i) {
677 MemberInfo m = (MemberInfo) almostMatchedMembers [i];
678 for (int j = 0; j < i; ++j) {
679 if (m == almostMatchedMembers [j]) {
687 Type declaring_type = m.DeclaringType;
689 Report.SymbolRelatedToPreviousError (m);
690 if (qualifier_type == null) {
691 Report.Error (38, loc, "Cannot access a nonstatic member of outer type `{0}' via nested type `{1}'",
692 TypeManager.CSharpName (m.DeclaringType),
693 TypeManager.CSharpName (ec.ContainerType));
694 } else if (qualifier_type != ec.ContainerType &&
695 TypeManager.IsNestedFamilyAccessible (ec.ContainerType, declaring_type)) {
696 // Although a derived class can access protected members of
697 // its base class it cannot do so through an instance of the
698 // base class (CS1540). If the qualifier_type is a base of the
699 // ec.ContainerType and the lookup succeeds with the latter one,
700 // then we are in this situation.
701 Report.Error (1540, loc,
702 "Cannot access protected member `{0}' via a qualifier of type `{1}';"
703 + " the qualifier must be of type `{2}' (or derived from it)",
704 TypeManager.GetFullNameSignature (m),
705 TypeManager.CSharpName (qualifier_type),
706 TypeManager.CSharpName (ec.ContainerType));
708 ErrorIsInaccesible (loc, TypeManager.GetFullNameSignature (m));
711 almostMatchedMembers.Clear ();
715 MemberInfo[] lookup = TypeManager.MemberLookup (queried_type, null, queried_type,
716 AllMemberTypes, AllBindingFlags |
717 BindingFlags.NonPublic, name, null);
719 if (lookup == null) {
720 if (!complain_if_none_found)
723 if (class_name != null)
724 Report.Error (103, loc, "The name `{0}' does not exist in the context of `{1}'",
728 117, loc, "`" + TypeManager.CSharpName (queried_type) + "' does not contain a " +
729 "definition for `" + name + "'");
733 if (TypeManager.MemberLookup (queried_type, null, queried_type,
734 AllMemberTypes, AllBindingFlags |
735 BindingFlags.NonPublic, name, null) == null) {
736 if ((lookup.Length == 1) && (lookup [0] is Type)) {
737 Type t = (Type) lookup [0];
739 Report.Error (305, loc,
740 "Using the generic type `{0}' " +
741 "requires {1} type arguments",
742 TypeManager.GetFullName (t),
743 TypeManager.GetNumberOfTypeArguments (t));
748 MemberList ml = TypeManager.FindMembers (qualifier_type, MemberTypes.Constructor,
749 BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly, null, null);
750 if (name == ".ctor" && ml.Count == 0)
752 Report.Error (143, loc, String.Format ("The type `{0}' has no constructors defined", TypeManager.CSharpName (queried_type)));
756 ErrorIsInaccesible (loc, TypeManager.GetFullNameSignature (lookup [0]));
760 /// Returns an expression that can be used to invoke operator true
761 /// on the expression if it exists.
763 static public Expression GetOperatorTrue (EmitContext ec, Expression e, Location loc)
765 return GetOperatorTrueOrFalse (ec, e, true, loc);
769 /// Returns an expression that can be used to invoke operator false
770 /// on the expression if it exists.
772 static public Expression GetOperatorFalse (EmitContext ec, Expression e, Location loc)
774 return GetOperatorTrueOrFalse (ec, e, false, loc);
777 static Expression GetOperatorTrueOrFalse (EmitContext ec, Expression e, bool is_true, Location loc)
780 Expression operator_group;
782 if (TypeManager.IsNullableType (e.Type))
783 return new Nullable.OperatorTrueOrFalse (e, is_true, loc).Resolve (ec);
785 operator_group = MethodLookup (ec, e.Type, is_true ? "op_True" : "op_False", loc);
786 if (operator_group == null)
789 ArrayList arguments = new ArrayList ();
790 arguments.Add (new Argument (e, Argument.AType.Expression));
791 method = Invocation.OverloadResolve (
792 ec, (MethodGroupExpr) operator_group, arguments, false, loc);
797 return new StaticCallExpr ((MethodInfo) method, arguments, loc);
801 /// Resolves the expression `e' into a boolean expression: either through
802 /// an implicit conversion, or through an `operator true' invocation
804 public static Expression ResolveBoolean (EmitContext ec, Expression e, Location loc)
810 if (e.Type == TypeManager.bool_type)
813 Expression converted = Convert.ImplicitConversion (ec, e, TypeManager.bool_type, Location.Null);
815 if (converted != null)
819 // If no implicit conversion to bool exists, try using `operator true'
821 Expression operator_true = Expression.GetOperatorTrue (ec, e, loc);
822 if (operator_true == null){
823 Report.Error (31, loc, "Can not convert the expression to a boolean");
826 return operator_true;
829 public string ExprClassName ()
832 case ExprClass.Invalid:
834 case ExprClass.Value:
836 case ExprClass.Variable:
838 case ExprClass.Namespace:
842 case ExprClass.MethodGroup:
843 return "method group";
844 case ExprClass.PropertyAccess:
845 return "property access";
846 case ExprClass.EventAccess:
847 return "event access";
848 case ExprClass.IndexerAccess:
849 return "indexer access";
850 case ExprClass.Nothing:
853 throw new Exception ("Should not happen");
857 /// Reports that we were expecting `expr' to be of class `expected'
859 public void Error_UnexpectedKind (string expected, Location loc)
861 Report.Error (118, loc,
862 "Expression denotes a `{0}', where a `{1}' was expected", ExprClassName (), expected);
865 public void Error_UnexpectedKind (ResolveFlags flags, Location loc)
867 string [] valid = new string [4];
870 if ((flags & ResolveFlags.VariableOrValue) != 0) {
871 valid [count++] = "variable";
872 valid [count++] = "value";
875 if ((flags & ResolveFlags.Type) != 0)
876 valid [count++] = "type";
878 if ((flags & ResolveFlags.MethodGroup) != 0)
879 valid [count++] = "method group";
882 valid [count++] = "unknown";
884 StringBuilder sb = new StringBuilder (valid [0]);
885 for (int i = 1; i < count - 1; i++) {
887 sb.Append (valid [i]);
890 sb.Append ("' or `");
891 sb.Append (valid [count - 1]);
894 Report.Error (119, loc,
895 "Expression denotes a `{0}', where a `{1}' was expected", ExprClassName (), sb);
898 static public void Error_ConstantValueCannotBeConverted (Location l, string val, Type t)
900 Report.Error (31, l, "Constant value `" + val + "' cannot be converted to " +
901 TypeManager.CSharpName (t));
904 public static void UnsafeError (Location loc)
906 Report.Error (214, loc, "Pointers and fixed size buffers may only be used in an unsafe context");
910 /// Converts the IntConstant, UIntConstant, LongConstant or
911 /// ULongConstant into the integral target_type. Notice
912 /// that we do not return an `Expression' we do return
913 /// a boxed integral type.
915 /// FIXME: Since I added the new constants, we need to
916 /// also support conversions from CharConstant, ByteConstant,
917 /// SByteConstant, UShortConstant, ShortConstant
919 /// This is used by the switch statement, so the domain
920 /// of work is restricted to the literals above, and the
921 /// targets are int32, uint32, char, byte, sbyte, ushort,
922 /// short, uint64 and int64
924 public static object ConvertIntLiteral (Constant c, Type target_type, Location loc)
926 if (!Convert.ImplicitStandardConversionExists (Convert.ConstantEC, c, target_type)){
927 Convert.Error_CannotImplicitConversion (loc, c.Type, target_type);
933 if (c.Type == target_type)
934 return ((Constant) c).GetValue ();
937 // Make into one of the literals we handle, we dont really care
938 // about this value as we will just return a few limited types
940 if (c is EnumConstant)
941 c = ((EnumConstant)c).WidenToCompilerConstant ();
943 if (c is IntConstant){
944 int v = ((IntConstant) c).Value;
946 if (target_type == TypeManager.uint32_type){
949 } else if (target_type == TypeManager.char_type){
950 if (v >= Char.MinValue && v <= Char.MaxValue)
952 } else if (target_type == TypeManager.byte_type){
953 if (v >= Byte.MinValue && v <= Byte.MaxValue)
955 } else if (target_type == TypeManager.sbyte_type){
956 if (v >= SByte.MinValue && v <= SByte.MaxValue)
958 } else if (target_type == TypeManager.short_type){
959 if (v >= Int16.MinValue && v <= UInt16.MaxValue)
961 } else if (target_type == TypeManager.ushort_type){
962 if (v >= UInt16.MinValue && v <= UInt16.MaxValue)
964 } else if (target_type == TypeManager.int64_type)
966 else if (target_type == TypeManager.uint64_type){
972 } else if (c is UIntConstant){
973 uint v = ((UIntConstant) c).Value;
975 if (target_type == TypeManager.int32_type){
976 if (v <= Int32.MaxValue)
978 } else if (target_type == TypeManager.char_type){
979 if (v >= Char.MinValue && v <= Char.MaxValue)
981 } else if (target_type == TypeManager.byte_type){
982 if (v <= Byte.MaxValue)
984 } else if (target_type == TypeManager.sbyte_type){
985 if (v <= SByte.MaxValue)
987 } else if (target_type == TypeManager.short_type){
988 if (v <= UInt16.MaxValue)
990 } else if (target_type == TypeManager.ushort_type){
991 if (v <= UInt16.MaxValue)
993 } else if (target_type == TypeManager.int64_type)
995 else if (target_type == TypeManager.uint64_type)
998 } else if (c is LongConstant){
999 long v = ((LongConstant) c).Value;
1001 if (target_type == TypeManager.int32_type){
1002 if (v >= UInt32.MinValue && v <= UInt32.MaxValue)
1004 } else if (target_type == TypeManager.uint32_type){
1005 if (v >= 0 && v <= UInt32.MaxValue)
1007 } else if (target_type == TypeManager.char_type){
1008 if (v >= Char.MinValue && v <= Char.MaxValue)
1010 } else if (target_type == TypeManager.byte_type){
1011 if (v >= Byte.MinValue && v <= Byte.MaxValue)
1013 } else if (target_type == TypeManager.sbyte_type){
1014 if (v >= SByte.MinValue && v <= SByte.MaxValue)
1016 } else if (target_type == TypeManager.short_type){
1017 if (v >= Int16.MinValue && v <= UInt16.MaxValue)
1019 } else if (target_type == TypeManager.ushort_type){
1020 if (v >= UInt16.MinValue && v <= UInt16.MaxValue)
1022 } else if (target_type == TypeManager.uint64_type){
1027 } else if (c is ULongConstant){
1028 ulong v = ((ULongConstant) c).Value;
1030 if (target_type == TypeManager.int32_type){
1031 if (v <= Int32.MaxValue)
1033 } else if (target_type == TypeManager.uint32_type){
1034 if (v <= UInt32.MaxValue)
1036 } else if (target_type == TypeManager.char_type){
1037 if (v >= Char.MinValue && v <= Char.MaxValue)
1039 } else if (target_type == TypeManager.byte_type){
1040 if (v >= Byte.MinValue && v <= Byte.MaxValue)
1042 } else if (target_type == TypeManager.sbyte_type){
1043 if (v <= (int) SByte.MaxValue)
1045 } else if (target_type == TypeManager.short_type){
1046 if (v <= UInt16.MaxValue)
1048 } else if (target_type == TypeManager.ushort_type){
1049 if (v <= UInt16.MaxValue)
1051 } else if (target_type == TypeManager.int64_type){
1052 if (v <= Int64.MaxValue)
1056 } else if (c is ByteConstant){
1057 byte v = ((ByteConstant) c).Value;
1059 if (target_type == TypeManager.int32_type)
1061 else if (target_type == TypeManager.uint32_type)
1063 else if (target_type == TypeManager.char_type)
1065 else if (target_type == TypeManager.sbyte_type){
1066 if (v <= SByte.MaxValue)
1068 } else if (target_type == TypeManager.short_type)
1070 else if (target_type == TypeManager.ushort_type)
1072 else if (target_type == TypeManager.int64_type)
1074 else if (target_type == TypeManager.uint64_type)
1077 } else if (c is SByteConstant){
1078 sbyte v = ((SByteConstant) c).Value;
1080 if (target_type == TypeManager.int32_type)
1082 else if (target_type == TypeManager.uint32_type){
1085 } else if (target_type == TypeManager.char_type){
1088 } else if (target_type == TypeManager.byte_type){
1091 } else if (target_type == TypeManager.short_type)
1093 else if (target_type == TypeManager.ushort_type){
1096 } else if (target_type == TypeManager.int64_type)
1098 else if (target_type == TypeManager.uint64_type){
1103 } else if (c is ShortConstant){
1104 short v = ((ShortConstant) c).Value;
1106 if (target_type == TypeManager.int32_type){
1108 } else if (target_type == TypeManager.uint32_type){
1111 } else if (target_type == TypeManager.char_type){
1114 } else if (target_type == TypeManager.byte_type){
1115 if (v >= Byte.MinValue && v <= Byte.MaxValue)
1117 } else if (target_type == TypeManager.sbyte_type){
1118 if (v >= SByte.MinValue && v <= SByte.MaxValue)
1120 } else if (target_type == TypeManager.ushort_type){
1123 } else if (target_type == TypeManager.int64_type)
1125 else if (target_type == TypeManager.uint64_type)
1129 } else if (c is UShortConstant){
1130 ushort v = ((UShortConstant) c).Value;
1132 if (target_type == TypeManager.int32_type)
1134 else if (target_type == TypeManager.uint32_type)
1136 else if (target_type == TypeManager.char_type){
1137 if (v >= Char.MinValue && v <= Char.MaxValue)
1139 } else if (target_type == TypeManager.byte_type){
1140 if (v >= Byte.MinValue && v <= Byte.MaxValue)
1142 } else if (target_type == TypeManager.sbyte_type){
1143 if (v <= SByte.MaxValue)
1145 } else if (target_type == TypeManager.short_type){
1146 if (v <= Int16.MaxValue)
1148 } else if (target_type == TypeManager.int64_type)
1150 else if (target_type == TypeManager.uint64_type)
1154 } else if (c is CharConstant){
1155 char v = ((CharConstant) c).Value;
1157 if (target_type == TypeManager.int32_type)
1159 else if (target_type == TypeManager.uint32_type)
1161 else if (target_type == TypeManager.byte_type){
1162 if (v >= Byte.MinValue && v <= Byte.MaxValue)
1164 } else if (target_type == TypeManager.sbyte_type){
1165 if (v <= SByte.MaxValue)
1167 } else if (target_type == TypeManager.short_type){
1168 if (v <= Int16.MaxValue)
1170 } else if (target_type == TypeManager.ushort_type)
1172 else if (target_type == TypeManager.int64_type)
1174 else if (target_type == TypeManager.uint64_type)
1179 Error_ConstantValueCannotBeConverted (loc, s, target_type);
1184 // Load the object from the pointer.
1186 public static void LoadFromPtr (ILGenerator ig, Type t)
1188 if (t == TypeManager.int32_type)
1189 ig.Emit (OpCodes.Ldind_I4);
1190 else if (t == TypeManager.uint32_type)
1191 ig.Emit (OpCodes.Ldind_U4);
1192 else if (t == TypeManager.short_type)
1193 ig.Emit (OpCodes.Ldind_I2);
1194 else if (t == TypeManager.ushort_type)
1195 ig.Emit (OpCodes.Ldind_U2);
1196 else if (t == TypeManager.char_type)
1197 ig.Emit (OpCodes.Ldind_U2);
1198 else if (t == TypeManager.byte_type)
1199 ig.Emit (OpCodes.Ldind_U1);
1200 else if (t == TypeManager.sbyte_type)
1201 ig.Emit (OpCodes.Ldind_I1);
1202 else if (t == TypeManager.uint64_type)
1203 ig.Emit (OpCodes.Ldind_I8);
1204 else if (t == TypeManager.int64_type)
1205 ig.Emit (OpCodes.Ldind_I8);
1206 else if (t == TypeManager.float_type)
1207 ig.Emit (OpCodes.Ldind_R4);
1208 else if (t == TypeManager.double_type)
1209 ig.Emit (OpCodes.Ldind_R8);
1210 else if (t == TypeManager.bool_type)
1211 ig.Emit (OpCodes.Ldind_I1);
1212 else if (t == TypeManager.intptr_type)
1213 ig.Emit (OpCodes.Ldind_I);
1214 else if (TypeManager.IsEnumType (t)) {
1215 if (t == TypeManager.enum_type)
1216 ig.Emit (OpCodes.Ldind_Ref);
1218 LoadFromPtr (ig, TypeManager.EnumToUnderlying (t));
1219 } else if (t.IsValueType || t.IsGenericParameter)
1220 ig.Emit (OpCodes.Ldobj, t);
1221 else if (t.IsPointer)
1222 ig.Emit (OpCodes.Ldind_I);
1224 ig.Emit (OpCodes.Ldind_Ref);
1228 // The stack contains the pointer and the value of type `type'
1230 public static void StoreFromPtr (ILGenerator ig, Type type)
1232 if (TypeManager.IsEnumType (type))
1233 type = TypeManager.EnumToUnderlying (type);
1234 if (type == TypeManager.int32_type || type == TypeManager.uint32_type)
1235 ig.Emit (OpCodes.Stind_I4);
1236 else if (type == TypeManager.int64_type || type == TypeManager.uint64_type)
1237 ig.Emit (OpCodes.Stind_I8);
1238 else if (type == TypeManager.char_type || type == TypeManager.short_type ||
1239 type == TypeManager.ushort_type)
1240 ig.Emit (OpCodes.Stind_I2);
1241 else if (type == TypeManager.float_type)
1242 ig.Emit (OpCodes.Stind_R4);
1243 else if (type == TypeManager.double_type)
1244 ig.Emit (OpCodes.Stind_R8);
1245 else if (type == TypeManager.byte_type || type == TypeManager.sbyte_type ||
1246 type == TypeManager.bool_type)
1247 ig.Emit (OpCodes.Stind_I1);
1248 else if (type == TypeManager.intptr_type)
1249 ig.Emit (OpCodes.Stind_I);
1250 else if (type.IsValueType || type.IsGenericParameter)
1251 ig.Emit (OpCodes.Stobj, type);
1253 ig.Emit (OpCodes.Stind_Ref);
1257 // Returns the size of type `t' if known, otherwise, 0
1259 public static int GetTypeSize (Type t)
1261 t = TypeManager.TypeToCoreType (t);
1262 if (t == TypeManager.int32_type ||
1263 t == TypeManager.uint32_type ||
1264 t == TypeManager.float_type)
1266 else if (t == TypeManager.int64_type ||
1267 t == TypeManager.uint64_type ||
1268 t == TypeManager.double_type)
1270 else if (t == TypeManager.byte_type ||
1271 t == TypeManager.sbyte_type ||
1272 t == TypeManager.bool_type)
1274 else if (t == TypeManager.short_type ||
1275 t == TypeManager.char_type ||
1276 t == TypeManager.ushort_type)
1278 else if (t == TypeManager.decimal_type)
1284 public static void Error_NegativeArrayIndex (Location loc)
1286 Report.Error (248, loc, "Cannot create an array with a negative size");
1289 protected void Error_CannotCallAbstractBase (string name)
1291 Report.Error (205, loc, "Cannot call an abstract base member `{0}'", name);
1295 // Converts `source' to an int, uint, long or ulong.
1297 public Expression ExpressionToArrayArgument (EmitContext ec, Expression source, Location loc)
1301 bool old_checked = ec.CheckState;
1302 ec.CheckState = true;
1304 target = Convert.ImplicitConversion (ec, source, TypeManager.int32_type, loc);
1305 if (target == null){
1306 target = Convert.ImplicitConversion (ec, source, TypeManager.uint32_type, loc);
1307 if (target == null){
1308 target = Convert.ImplicitConversion (ec, source, TypeManager.int64_type, loc);
1309 if (target == null){
1310 target = Convert.ImplicitConversion (ec, source, TypeManager.uint64_type, loc);
1312 Convert.Error_CannotImplicitConversion (loc, source.Type, TypeManager.int32_type);
1316 ec.CheckState = old_checked;
1319 // Only positive constants are allowed at compile time
1321 if (target is Constant){
1322 if (target is IntConstant){
1323 if (((IntConstant) target).Value < 0){
1324 Error_NegativeArrayIndex (loc);
1329 if (target is LongConstant){
1330 if (((LongConstant) target).Value < 0){
1331 Error_NegativeArrayIndex (loc);
1344 /// This is just a base class for expressions that can
1345 /// appear on statements (invocations, object creation,
1346 /// assignments, post/pre increment and decrement). The idea
1347 /// being that they would support an extra Emition interface that
1348 /// does not leave a result on the stack.
1350 public abstract class ExpressionStatement : Expression {
1352 public virtual ExpressionStatement ResolveStatement (EmitContext ec)
1354 Expression e = Resolve (ec);
1358 ExpressionStatement es = e as ExpressionStatement;
1360 Error (201, "Only assignment, call, increment, decrement and new object " +
1361 "expressions can be used as a statement");
1367 /// Requests the expression to be emitted in a `statement'
1368 /// context. This means that no new value is left on the
1369 /// stack after invoking this method (constrasted with
1370 /// Emit that will always leave a value on the stack).
1372 public abstract void EmitStatement (EmitContext ec);
1376 /// This kind of cast is used to encapsulate the child
1377 /// whose type is child.Type into an expression that is
1378 /// reported to return "return_type". This is used to encapsulate
1379 /// expressions which have compatible types, but need to be dealt
1380 /// at higher levels with.
1382 /// For example, a "byte" expression could be encapsulated in one
1383 /// of these as an "unsigned int". The type for the expression
1384 /// would be "unsigned int".
1387 public class EmptyCast : Expression {
1388 protected Expression child;
1390 public Expression Child {
1396 public EmptyCast (Expression child, Type return_type)
1398 eclass = child.eclass;
1399 loc = child.Location;
1404 public override Expression DoResolve (EmitContext ec)
1406 // This should never be invoked, we are born in fully
1407 // initialized state.
1412 public override void Emit (EmitContext ec)
1418 /// This is a numeric cast to a Decimal
1420 public class CastToDecimal : EmptyCast {
1422 MethodInfo conversion_operator;
1424 public CastToDecimal (EmitContext ec, Expression child)
1425 : this (ec, child, false)
1429 public CastToDecimal (EmitContext ec, Expression child, bool find_explicit)
1430 : base (child, TypeManager.decimal_type)
1432 conversion_operator = GetConversionOperator (ec, find_explicit);
1434 if (conversion_operator == null)
1435 Convert.Error_CannotImplicitConversion (loc, child.Type, type);
1438 // Returns the implicit operator that converts from
1439 // 'child.Type' to System.Decimal.
1440 MethodInfo GetConversionOperator (EmitContext ec, bool find_explicit)
1442 string operator_name = "op_Implicit";
1445 operator_name = "op_Explicit";
1447 MethodGroupExpr opers = Expression.MethodLookup (
1448 ec, type, operator_name, loc) as MethodGroupExpr;
1451 Convert.Error_CannotImplicitConversion (loc, child.Type, type);
1453 foreach (MethodInfo oper in opers.Methods) {
1454 ParameterData pd = TypeManager.GetParameterData (oper);
1456 if (pd.ParameterType (0) == child.Type && oper.ReturnType == type)
1462 public override void Emit (EmitContext ec)
1464 ILGenerator ig = ec.ig;
1467 ig.Emit (OpCodes.Call, conversion_operator);
1471 /// This is an explicit numeric cast from a Decimal
1473 public class CastFromDecimal : EmptyCast
1475 MethodInfo conversion_operator;
1476 public CastFromDecimal (EmitContext ec, Expression child, Type return_type)
1477 : base (child, return_type)
1479 if (child.Type != TypeManager.decimal_type)
1480 throw new InternalErrorException (
1481 "The expected type is Decimal, instead it is " + child.Type.FullName);
1483 conversion_operator = GetConversionOperator (ec);
1484 if (conversion_operator == null)
1485 Convert.Error_CannotImplicitConversion (loc, child.Type, type);
1488 // Returns the explicit operator that converts from an
1489 // express of type System.Decimal to 'type'.
1490 MethodInfo GetConversionOperator (EmitContext ec)
1492 MethodGroupExpr opers = Expression.MethodLookup (
1493 ec, child.Type, "op_Explicit", loc) as MethodGroupExpr;
1496 Convert.Error_CannotImplicitConversion (loc, child.Type, type);
1498 foreach (MethodInfo oper in opers.Methods) {
1499 ParameterData pd = TypeManager.GetParameterData (oper);
1501 if (pd.ParameterType (0) == child.Type && oper.ReturnType == type)
1507 public override void Emit (EmitContext ec)
1509 ILGenerator ig = ec.ig;
1512 ig.Emit (OpCodes.Call, conversion_operator);
1517 // We need to special case this since an empty cast of
1518 // a NullLiteral is still a Constant
1520 public class NullCast : Constant {
1521 protected Expression child;
1523 public NullCast (Expression child, Type return_type)
1525 eclass = child.eclass;
1530 override public string AsString ()
1535 public override object GetValue ()
1540 public override Expression DoResolve (EmitContext ec)
1542 // This should never be invoked, we are born in fully
1543 // initialized state.
1548 public override void Emit (EmitContext ec)
1553 public override bool IsDefaultValue {
1555 throw new NotImplementedException ();
1559 public override bool IsNegative {
1568 /// This class is used to wrap literals which belong inside Enums
1570 public class EnumConstant : Constant {
1571 public Constant Child;
1573 public EnumConstant (Constant child, Type enum_type)
1575 eclass = child.eclass;
1580 public override Expression DoResolve (EmitContext ec)
1582 // This should never be invoked, we are born in fully
1583 // initialized state.
1588 public override void Emit (EmitContext ec)
1593 public override object GetValue ()
1595 return Child.GetValue ();
1598 public object GetValueAsEnumType ()
1600 return System.Enum.ToObject (type, Child.GetValue ());
1604 // Converts from one of the valid underlying types for an enumeration
1605 // (int32, uint32, int64, uint64, short, ushort, byte, sbyte) to
1606 // one of the internal compiler literals: Int/UInt/Long/ULong Literals.
1608 public Constant WidenToCompilerConstant ()
1610 Type t = TypeManager.EnumToUnderlying (Child.Type);
1611 object v = ((Constant) Child).GetValue ();;
1613 if (t == TypeManager.int32_type)
1614 return new IntConstant ((int) v);
1615 if (t == TypeManager.uint32_type)
1616 return new UIntConstant ((uint) v);
1617 if (t == TypeManager.int64_type)
1618 return new LongConstant ((long) v);
1619 if (t == TypeManager.uint64_type)
1620 return new ULongConstant ((ulong) v);
1621 if (t == TypeManager.short_type)
1622 return new ShortConstant ((short) v);
1623 if (t == TypeManager.ushort_type)
1624 return new UShortConstant ((ushort) v);
1625 if (t == TypeManager.byte_type)
1626 return new ByteConstant ((byte) v);
1627 if (t == TypeManager.sbyte_type)
1628 return new SByteConstant ((sbyte) v);
1630 throw new Exception ("Invalid enumeration underlying type: " + t);
1634 // Extracts the value in the enumeration on its native representation
1636 public object GetPlainValue ()
1638 Type t = TypeManager.EnumToUnderlying (Child.Type);
1639 object v = ((Constant) Child).GetValue ();;
1641 if (t == TypeManager.int32_type)
1643 if (t == TypeManager.uint32_type)
1645 if (t == TypeManager.int64_type)
1647 if (t == TypeManager.uint64_type)
1649 if (t == TypeManager.short_type)
1651 if (t == TypeManager.ushort_type)
1653 if (t == TypeManager.byte_type)
1655 if (t == TypeManager.sbyte_type)
1661 public override string AsString ()
1663 return Child.AsString ();
1666 public override DoubleConstant ConvertToDouble ()
1668 return Child.ConvertToDouble ();
1671 public override FloatConstant ConvertToFloat ()
1673 return Child.ConvertToFloat ();
1676 public override ULongConstant ConvertToULong ()
1678 return Child.ConvertToULong ();
1681 public override LongConstant ConvertToLong ()
1683 return Child.ConvertToLong ();
1686 public override UIntConstant ConvertToUInt ()
1688 return Child.ConvertToUInt ();
1691 public override IntConstant ConvertToInt ()
1693 return Child.ConvertToInt ();
1696 public override bool IsDefaultValue {
1698 return Child.IsDefaultValue;
1702 public override bool IsZeroInteger {
1703 get { return Child.IsZeroInteger; }
1706 public override bool IsNegative {
1708 return Child.IsNegative;
1714 /// This kind of cast is used to encapsulate Value Types in objects.
1716 /// The effect of it is to box the value type emitted by the previous
1719 public class BoxedCast : EmptyCast {
1721 public BoxedCast (Expression expr)
1722 : base (expr, TypeManager.object_type)
1724 eclass = ExprClass.Value;
1727 public BoxedCast (Expression expr, Type target_type)
1728 : base (expr, target_type)
1730 eclass = ExprClass.Value;
1733 public override Expression DoResolve (EmitContext ec)
1735 // This should never be invoked, we are born in fully
1736 // initialized state.
1741 public override void Emit (EmitContext ec)
1745 ec.ig.Emit (OpCodes.Box, child.Type);
1749 public class UnboxCast : EmptyCast {
1750 public UnboxCast (Expression expr, Type return_type)
1751 : base (expr, return_type)
1755 public override Expression DoResolve (EmitContext ec)
1757 // This should never be invoked, we are born in fully
1758 // initialized state.
1763 public override void Emit (EmitContext ec)
1766 ILGenerator ig = ec.ig;
1769 if (t.IsGenericParameter)
1770 ig.Emit (OpCodes.Unbox_Any, t);
1772 ig.Emit (OpCodes.Unbox, t);
1774 LoadFromPtr (ig, t);
1780 /// This is used to perform explicit numeric conversions.
1782 /// Explicit numeric conversions might trigger exceptions in a checked
1783 /// context, so they should generate the conv.ovf opcodes instead of
1786 public class ConvCast : EmptyCast {
1787 public enum Mode : byte {
1788 I1_U1, I1_U2, I1_U4, I1_U8, I1_CH,
1790 I2_I1, I2_U1, I2_U2, I2_U4, I2_U8, I2_CH,
1791 U2_I1, U2_U1, U2_I2, U2_CH,
1792 I4_I1, I4_U1, I4_I2, I4_U2, I4_U4, I4_U8, I4_CH,
1793 U4_I1, U4_U1, U4_I2, U4_U2, U4_I4, U4_CH,
1794 I8_I1, I8_U1, I8_I2, I8_U2, I8_I4, I8_U4, I8_U8, I8_CH,
1795 U8_I1, U8_U1, U8_I2, U8_U2, U8_I4, U8_U4, U8_I8, U8_CH,
1796 CH_I1, CH_U1, CH_I2,
1797 R4_I1, R4_U1, R4_I2, R4_U2, R4_I4, R4_U4, R4_I8, R4_U8, R4_CH,
1798 R8_I1, R8_U1, R8_I2, R8_U2, R8_I4, R8_U4, R8_I8, R8_U8, R8_CH, R8_R4
1804 public ConvCast (EmitContext ec, Expression child, Type return_type, Mode m)
1805 : base (child, return_type)
1807 checked_state = ec.CheckState;
1811 public override Expression DoResolve (EmitContext ec)
1813 // This should never be invoked, we are born in fully
1814 // initialized state.
1819 public override string ToString ()
1821 return String.Format ("ConvCast ({0}, {1})", mode, child);
1824 public override void Emit (EmitContext ec)
1826 ILGenerator ig = ec.ig;
1832 case Mode.I1_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1833 case Mode.I1_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1834 case Mode.I1_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1835 case Mode.I1_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1836 case Mode.I1_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1838 case Mode.U1_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1839 case Mode.U1_CH: /* nothing */ break;
1841 case Mode.I2_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1842 case Mode.I2_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1843 case Mode.I2_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1844 case Mode.I2_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1845 case Mode.I2_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1846 case Mode.I2_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1848 case Mode.U2_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1849 case Mode.U2_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
1850 case Mode.U2_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
1851 case Mode.U2_CH: /* nothing */ break;
1853 case Mode.I4_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1854 case Mode.I4_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1855 case Mode.I4_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
1856 case Mode.I4_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1857 case Mode.I4_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1858 case Mode.I4_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1859 case Mode.I4_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1861 case Mode.U4_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1862 case Mode.U4_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
1863 case Mode.U4_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
1864 case Mode.U4_U2: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
1865 case Mode.U4_I4: ig.Emit (OpCodes.Conv_Ovf_I4_Un); break;
1866 case Mode.U4_CH: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
1868 case Mode.I8_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1869 case Mode.I8_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1870 case Mode.I8_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
1871 case Mode.I8_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1872 case Mode.I8_I4: ig.Emit (OpCodes.Conv_Ovf_I4); break;
1873 case Mode.I8_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1874 case Mode.I8_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1875 case Mode.I8_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1877 case Mode.U8_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1878 case Mode.U8_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
1879 case Mode.U8_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
1880 case Mode.U8_U2: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
1881 case Mode.U8_I4: ig.Emit (OpCodes.Conv_Ovf_I4_Un); break;
1882 case Mode.U8_U4: ig.Emit (OpCodes.Conv_Ovf_U4_Un); break;
1883 case Mode.U8_I8: ig.Emit (OpCodes.Conv_Ovf_I8_Un); break;
1884 case Mode.U8_CH: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
1886 case Mode.CH_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1887 case Mode.CH_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
1888 case Mode.CH_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
1890 case Mode.R4_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1891 case Mode.R4_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1892 case Mode.R4_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
1893 case Mode.R4_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1894 case Mode.R4_I4: ig.Emit (OpCodes.Conv_Ovf_I4); break;
1895 case Mode.R4_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1896 case Mode.R4_I8: ig.Emit (OpCodes.Conv_Ovf_I8); break;
1897 case Mode.R4_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1898 case Mode.R4_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1900 case Mode.R8_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1901 case Mode.R8_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1902 case Mode.R8_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
1903 case Mode.R8_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1904 case Mode.R8_I4: ig.Emit (OpCodes.Conv_Ovf_I4); break;
1905 case Mode.R8_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1906 case Mode.R8_I8: ig.Emit (OpCodes.Conv_Ovf_I8); break;
1907 case Mode.R8_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1908 case Mode.R8_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1909 case Mode.R8_R4: ig.Emit (OpCodes.Conv_R4); break;
1913 case Mode.I1_U1: ig.Emit (OpCodes.Conv_U1); break;
1914 case Mode.I1_U2: ig.Emit (OpCodes.Conv_U2); break;
1915 case Mode.I1_U4: ig.Emit (OpCodes.Conv_U4); break;
1916 case Mode.I1_U8: ig.Emit (OpCodes.Conv_I8); break;
1917 case Mode.I1_CH: ig.Emit (OpCodes.Conv_U2); break;
1919 case Mode.U1_I1: ig.Emit (OpCodes.Conv_I1); break;
1920 case Mode.U1_CH: ig.Emit (OpCodes.Conv_U2); break;
1922 case Mode.I2_I1: ig.Emit (OpCodes.Conv_I1); break;
1923 case Mode.I2_U1: ig.Emit (OpCodes.Conv_U1); break;
1924 case Mode.I2_U2: ig.Emit (OpCodes.Conv_U2); break;
1925 case Mode.I2_U4: ig.Emit (OpCodes.Conv_U4); break;
1926 case Mode.I2_U8: ig.Emit (OpCodes.Conv_I8); break;
1927 case Mode.I2_CH: ig.Emit (OpCodes.Conv_U2); break;
1929 case Mode.U2_I1: ig.Emit (OpCodes.Conv_I1); break;
1930 case Mode.U2_U1: ig.Emit (OpCodes.Conv_U1); break;
1931 case Mode.U2_I2: ig.Emit (OpCodes.Conv_I2); break;
1932 case Mode.U2_CH: /* nothing */ break;
1934 case Mode.I4_I1: ig.Emit (OpCodes.Conv_I1); break;
1935 case Mode.I4_U1: ig.Emit (OpCodes.Conv_U1); break;
1936 case Mode.I4_I2: ig.Emit (OpCodes.Conv_I2); break;
1937 case Mode.I4_U4: /* nothing */ break;
1938 case Mode.I4_U2: ig.Emit (OpCodes.Conv_U2); break;
1939 case Mode.I4_U8: ig.Emit (OpCodes.Conv_I8); break;
1940 case Mode.I4_CH: ig.Emit (OpCodes.Conv_U2); break;
1942 case Mode.U4_I1: ig.Emit (OpCodes.Conv_I1); break;
1943 case Mode.U4_U1: ig.Emit (OpCodes.Conv_U1); break;
1944 case Mode.U4_I2: ig.Emit (OpCodes.Conv_I2); break;
1945 case Mode.U4_U2: ig.Emit (OpCodes.Conv_U2); break;
1946 case Mode.U4_I4: /* nothing */ break;
1947 case Mode.U4_CH: ig.Emit (OpCodes.Conv_U2); break;
1949 case Mode.I8_I1: ig.Emit (OpCodes.Conv_I1); break;
1950 case Mode.I8_U1: ig.Emit (OpCodes.Conv_U1); break;
1951 case Mode.I8_I2: ig.Emit (OpCodes.Conv_I2); break;
1952 case Mode.I8_U2: ig.Emit (OpCodes.Conv_U2); break;
1953 case Mode.I8_I4: ig.Emit (OpCodes.Conv_I4); break;
1954 case Mode.I8_U4: ig.Emit (OpCodes.Conv_U4); break;
1955 case Mode.I8_U8: /* nothing */ break;
1956 case Mode.I8_CH: ig.Emit (OpCodes.Conv_U2); break;
1958 case Mode.U8_I1: ig.Emit (OpCodes.Conv_I1); break;
1959 case Mode.U8_U1: ig.Emit (OpCodes.Conv_U1); break;
1960 case Mode.U8_I2: ig.Emit (OpCodes.Conv_I2); break;
1961 case Mode.U8_U2: ig.Emit (OpCodes.Conv_U2); break;
1962 case Mode.U8_I4: ig.Emit (OpCodes.Conv_I4); break;
1963 case Mode.U8_U4: ig.Emit (OpCodes.Conv_U4); break;
1964 case Mode.U8_I8: /* nothing */ break;
1965 case Mode.U8_CH: ig.Emit (OpCodes.Conv_U2); break;
1967 case Mode.CH_I1: ig.Emit (OpCodes.Conv_I1); break;
1968 case Mode.CH_U1: ig.Emit (OpCodes.Conv_U1); break;
1969 case Mode.CH_I2: ig.Emit (OpCodes.Conv_I2); break;
1971 case Mode.R4_I1: ig.Emit (OpCodes.Conv_I1); break;
1972 case Mode.R4_U1: ig.Emit (OpCodes.Conv_U1); break;
1973 case Mode.R4_I2: ig.Emit (OpCodes.Conv_I2); break;
1974 case Mode.R4_U2: ig.Emit (OpCodes.Conv_U2); break;
1975 case Mode.R4_I4: ig.Emit (OpCodes.Conv_I4); break;
1976 case Mode.R4_U4: ig.Emit (OpCodes.Conv_U4); break;
1977 case Mode.R4_I8: ig.Emit (OpCodes.Conv_I8); break;
1978 case Mode.R4_U8: ig.Emit (OpCodes.Conv_U8); break;
1979 case Mode.R4_CH: ig.Emit (OpCodes.Conv_U2); break;
1981 case Mode.R8_I1: ig.Emit (OpCodes.Conv_I1); break;
1982 case Mode.R8_U1: ig.Emit (OpCodes.Conv_U1); break;
1983 case Mode.R8_I2: ig.Emit (OpCodes.Conv_I2); break;
1984 case Mode.R8_U2: ig.Emit (OpCodes.Conv_U2); break;
1985 case Mode.R8_I4: ig.Emit (OpCodes.Conv_I4); break;
1986 case Mode.R8_U4: ig.Emit (OpCodes.Conv_U4); break;
1987 case Mode.R8_I8: ig.Emit (OpCodes.Conv_I8); break;
1988 case Mode.R8_U8: ig.Emit (OpCodes.Conv_U8); break;
1989 case Mode.R8_CH: ig.Emit (OpCodes.Conv_U2); break;
1990 case Mode.R8_R4: ig.Emit (OpCodes.Conv_R4); break;
1996 public class OpcodeCast : EmptyCast {
2000 public OpcodeCast (Expression child, Type return_type, OpCode op)
2001 : base (child, return_type)
2005 second_valid = false;
2008 public OpcodeCast (Expression child, Type return_type, OpCode op, OpCode op2)
2009 : base (child, return_type)
2014 second_valid = true;
2017 public override Expression DoResolve (EmitContext ec)
2019 // This should never be invoked, we are born in fully
2020 // initialized state.
2025 public override void Emit (EmitContext ec)
2036 /// This kind of cast is used to encapsulate a child and cast it
2037 /// to the class requested
2039 public class ClassCast : EmptyCast {
2040 public ClassCast (Expression child, Type return_type)
2041 : base (child, return_type)
2046 public override Expression DoResolve (EmitContext ec)
2048 // This should never be invoked, we are born in fully
2049 // initialized state.
2054 public override void Emit (EmitContext ec)
2058 if (child.Type.IsGenericParameter)
2059 ec.ig.Emit (OpCodes.Box, child.Type);
2061 if (type.IsGenericParameter)
2062 ec.ig.Emit (OpCodes.Unbox_Any, type);
2064 ec.ig.Emit (OpCodes.Castclass, type);
2069 /// SimpleName expressions are formed of a single word and only happen at the beginning
2070 /// of a dotted-name.
2072 public class SimpleName : Expression {
2074 public readonly TypeArguments Arguments;
2077 public SimpleName (string name, Location l)
2083 public SimpleName (string name, TypeArguments args, Location l)
2090 public SimpleName (string name, TypeParameter[] type_params, Location l)
2095 Arguments = new TypeArguments (l);
2096 foreach (TypeParameter type_param in type_params)
2097 Arguments.Add (new TypeParameterExpr (type_param, l));
2100 public static string RemoveGenericArity (string name)
2103 StringBuilder sb = new StringBuilder ();
2104 while (start < name.Length) {
2105 int pos = name.IndexOf ('`', start);
2107 sb.Append (name.Substring (start));
2111 sb.Append (name.Substring (start, pos-start));
2114 while ((pos < name.Length) && Char.IsNumber (name [pos]))
2120 return sb.ToString ();
2123 public SimpleName GetMethodGroup ()
2125 return new SimpleName (RemoveGenericArity (Name), Arguments, loc);
2128 public static void Error_ObjectRefRequired (EmitContext ec, Location l, string name)
2130 if (ec.IsFieldInitializer)
2131 Report.Error (236, l,
2132 "A field initializer cannot reference the nonstatic field, method, or property `{0}'",
2135 if (name.LastIndexOf ('.') > 0)
2136 name = name.Substring (name.LastIndexOf ('.') + 1);
2139 120, l, "`{0}': An object reference is required for the nonstatic field, method or property",
2144 public bool IdenticalNameAndTypeName (EmitContext ec, Expression resolved_to, Location loc)
2146 return resolved_to != null && resolved_to.Type != null &&
2147 resolved_to.Type.Name == Name &&
2148 (ec.DeclSpace.LookupType (Name, loc, /* ignore_cs0104 = */ true) != null);
2151 public override Expression DoResolve (EmitContext ec)
2153 return SimpleNameResolve (ec, null, false);
2156 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
2158 return SimpleNameResolve (ec, right_side, false);
2162 public Expression DoResolve (EmitContext ec, bool intermediate)
2164 return SimpleNameResolve (ec, null, intermediate);
2167 private bool IsNestedChild (Type t, Type parent)
2172 while (parent != null) {
2173 if (parent.IsGenericInstance)
2174 parent = parent.GetGenericTypeDefinition ();
2176 if (TypeManager.IsNestedChildOf (t, parent))
2179 parent = parent.BaseType;
2185 FullNamedExpression ResolveNested (EmitContext ec, Type t)
2187 if (!t.IsGenericTypeDefinition)
2190 DeclSpace ds = ec.DeclSpace;
2191 while (ds != null) {
2192 if (IsNestedChild (t, ds.TypeBuilder))
2201 Type[] gen_params = t.GetGenericArguments ();
2203 int arg_count = Arguments != null ? Arguments.Count : 0;
2205 for (; (ds != null) && ds.IsGeneric; ds = ds.Parent) {
2206 if (arg_count + ds.CountTypeParameters == gen_params.Length) {
2207 TypeArguments new_args = new TypeArguments (loc);
2208 foreach (TypeParameter param in ds.TypeParameters)
2209 new_args.Add (new TypeParameterExpr (param, loc));
2211 if (Arguments != null)
2212 new_args.Add (Arguments);
2214 return new ConstructedType (t, new_args, loc);
2221 public override FullNamedExpression ResolveAsTypeStep (EmitContext ec)
2223 FullNamedExpression dt = ec.DeclSpace.LookupGeneric (Name, loc);
2225 return dt.ResolveAsTypeStep (ec);
2227 int errors = Report.Errors;
2228 dt = ec.DeclSpace.LookupType (Name, loc, /*ignore_cs0104=*/ false);
2229 if (Report.Errors != errors)
2232 if ((dt == null) || (dt.Type == null))
2235 FullNamedExpression nested = ResolveNested (ec, dt.Type);
2237 return nested.ResolveAsTypeStep (ec);
2239 if (Arguments != null) {
2240 ConstructedType ct = new ConstructedType (dt, Arguments, loc);
2241 return ct.ResolveAsTypeStep (ec);
2247 Expression SimpleNameResolve (EmitContext ec, Expression right_side, bool intermediate)
2253 Expression e = DoSimpleNameResolve (ec, right_side, intermediate);
2257 if (ec.CurrentBlock == null || ec.CurrentBlock.CheckInvariantMeaningInBlock (Name, e, Location))
2264 /// 7.5.2: Simple Names.
2266 /// Local Variables and Parameters are handled at
2267 /// parse time, so they never occur as SimpleNames.
2269 /// The `intermediate' flag is used by MemberAccess only
2270 /// and it is used to inform us that it is ok for us to
2271 /// avoid the static check, because MemberAccess might end
2272 /// up resolving the Name as a Type name and the access as
2273 /// a static type access.
2275 /// ie: Type Type; .... { Type.GetType (""); }
2277 /// Type is both an instance variable and a Type; Type.GetType
2278 /// is the static method not an instance method of type.
2280 Expression DoSimpleNameResolve (EmitContext ec, Expression right_side, bool intermediate)
2282 Expression e = null;
2285 // Stage 1: Performed by the parser (binding to locals or parameters).
2287 Block current_block = ec.CurrentBlock;
2288 if (current_block != null){
2289 LocalInfo vi = current_block.GetLocalInfo (Name);
2293 var = new LocalVariableReference (ec.CurrentBlock, Name, loc);
2295 if (right_side != null)
2296 return var.ResolveLValue (ec, right_side, loc);
2298 return var.Resolve (ec);
2301 ParameterReference pref = current_block.Toplevel.GetParameterReference (Name, loc);
2303 if (right_side != null)
2304 return pref.ResolveLValue (ec, right_side, loc);
2306 return pref.Resolve (ec);
2311 // Stage 2: Lookup members
2314 DeclSpace lookup_ds = ec.DeclSpace;
2315 Type almost_matched_type = null;
2316 ArrayList almost_matched = null;
2318 if (lookup_ds.TypeBuilder == null)
2321 e = MemberLookup (ec, lookup_ds.TypeBuilder, Name, loc);
2325 if (almost_matched == null && almostMatchedMembers.Count > 0) {
2326 almost_matched_type = lookup_ds.TypeBuilder;
2327 almost_matched = (ArrayList) almostMatchedMembers.Clone ();
2330 lookup_ds =lookup_ds.Parent;
2331 } while (lookup_ds != null);
2333 if (e == null && ec.ContainerType != null)
2334 e = MemberLookup (ec, ec.ContainerType, Name, loc);
2337 if (almost_matched == null && almostMatchedMembers.Count > 0) {
2338 almost_matched_type = ec.ContainerType;
2339 almost_matched = (ArrayList) almostMatchedMembers.Clone ();
2341 e = ResolveAsTypeStep (ec);
2345 if (almost_matched != null)
2346 almostMatchedMembers = almost_matched;
2347 if (almost_matched_type == null)
2348 almost_matched_type = ec.ContainerType;
2349 MemberLookupFailed (ec, null, almost_matched_type, ((SimpleName) this).Name, ec.DeclSpace.Name, true, loc);
2356 if (e is MemberExpr) {
2357 MemberExpr me = (MemberExpr) e;
2360 if (me.IsInstance) {
2361 if (ec.IsStatic || ec.IsFieldInitializer) {
2363 // Note that an MemberExpr can be both IsInstance and IsStatic.
2364 // An unresolved MethodGroupExpr can contain both kinds of methods
2365 // and each predicate is true if the MethodGroupExpr contains
2366 // at least one of that kind of method.
2370 (!intermediate || !IdenticalNameAndTypeName (ec, me, loc))) {
2371 Error_ObjectRefRequired (ec, loc, me.GetSignatureForError ());
2376 // Pass the buck to MemberAccess and Invocation.
2378 left = EmptyExpression.Null;
2380 left = ec.GetThis (loc);
2383 left = new TypeExpression (ec.ContainerType, loc);
2386 e = me.ResolveMemberAccess (ec, left, loc, null);
2390 me = e as MemberExpr;
2394 if (Arguments != null) {
2395 MethodGroupExpr mg = me as MethodGroupExpr;
2399 return mg.ResolveGeneric (ec, Arguments);
2403 TypeManager.IsNestedFamilyAccessible (me.InstanceExpression.Type, me.DeclaringType) &&
2404 me.InstanceExpression.Type != me.DeclaringType &&
2405 !TypeManager.IsFamilyAccessible (me.InstanceExpression.Type, me.DeclaringType) &&
2406 (!intermediate || !IdenticalNameAndTypeName (ec, e, loc))) {
2407 Report.Error (38, loc, "Cannot access a nonstatic member of outer type `{0}' via nested type `{1}'",
2408 TypeManager.CSharpName (me.DeclaringType), TypeManager.CSharpName (me.InstanceExpression.Type));
2412 return (right_side != null)
2413 ? me.DoResolveLValue (ec, right_side)
2414 : me.DoResolve (ec);
2420 public override void Emit (EmitContext ec)
2423 // If this is ever reached, then we failed to
2424 // find the name as a namespace
2427 Error (103, "The name `" + Name +
2428 "' does not exist in the class `" +
2429 ec.DeclSpace.Name + "'");
2432 public override string ToString ()
2437 public override string GetSignatureForError ()
2444 /// Represents a namespace or a type. The name of the class was inspired by
2445 /// section 10.8.1 (Fully Qualified Names).
2447 public abstract class FullNamedExpression : Expression {
2448 public override FullNamedExpression ResolveAsTypeStep (EmitContext ec)
2453 public abstract string FullName {
2459 /// Fully resolved expression that evaluates to a type
2461 public abstract class TypeExpr : FullNamedExpression {
2462 override public FullNamedExpression ResolveAsTypeStep (EmitContext ec)
2464 TypeExpr t = DoResolveAsTypeStep (ec);
2468 eclass = ExprClass.Type;
2472 override public Expression DoResolve (EmitContext ec)
2474 return ResolveAsTypeTerminal (ec);
2477 override public void Emit (EmitContext ec)
2479 throw new Exception ("Should never be called");
2482 public virtual bool CheckAccessLevel (DeclSpace ds)
2484 return ds.CheckAccessLevel (Type);
2487 public virtual bool AsAccessible (DeclSpace ds, int flags)
2489 return ds.AsAccessible (Type, flags);
2492 public virtual bool IsClass {
2493 get { return Type.IsClass; }
2496 public virtual bool IsValueType {
2497 get { return Type.IsValueType; }
2500 public virtual bool IsInterface {
2501 get { return Type.IsInterface; }
2504 public virtual bool IsSealed {
2505 get { return Type.IsSealed; }
2508 public virtual bool CanInheritFrom ()
2510 if (Type == TypeManager.enum_type ||
2511 (Type == TypeManager.value_type && RootContext.StdLib) ||
2512 Type == TypeManager.multicast_delegate_type ||
2513 Type == TypeManager.delegate_type ||
2514 Type == TypeManager.array_type)
2520 protected abstract TypeExpr DoResolveAsTypeStep (EmitContext ec);
2522 public virtual Type ResolveType (EmitContext ec)
2524 TypeExpr t = ResolveAsTypeTerminal (ec);
2531 public abstract string Name {
2535 public override bool Equals (object obj)
2537 TypeExpr tobj = obj as TypeExpr;
2541 return Type == tobj.Type;
2544 public override int GetHashCode ()
2546 return Type.GetHashCode ();
2549 public override string ToString ()
2555 public class TypeExpression : TypeExpr {
2556 public TypeExpression (Type t, Location l)
2559 eclass = ExprClass.Type;
2563 protected override TypeExpr DoResolveAsTypeStep (EmitContext ec)
2568 public override string Name {
2570 return Type.ToString ();
2574 public override string FullName {
2576 return Type.FullName != null ? Type.FullName : Type.Name;
2582 /// Used to create types from a fully qualified name. These are just used
2583 /// by the parser to setup the core types. A TypeLookupExpression is always
2584 /// classified as a type.
2586 public class TypeLookupExpression : TypeExpr {
2589 public TypeLookupExpression (string name)
2594 protected override TypeExpr DoResolveAsTypeStep (EmitContext ec)
2597 FullNamedExpression t = ec.DeclSpace.LookupType (name, Location.Null, /*ignore_cs0104=*/ false);
2599 NamespaceEntry.Error_NamespaceNotFound (loc, name);
2602 if (!(t is TypeExpr)) {
2603 Report.Error (118, Location, "`{0}' denotes a `{1}', where a type was expected",
2604 t.FullName, t.ExprClassName ());
2608 type = ((TypeExpr) t).ResolveType (ec);
2614 public override string Name {
2620 public override string FullName {
2628 /// Represents an "unbound generic type", ie. typeof (Foo<>).
2631 public class UnboundTypeExpression : TypeLookupExpression {
2632 public UnboundTypeExpression (string name)
2637 public class TypeAliasExpression : TypeExpr {
2638 FullNamedExpression alias;
2643 public TypeAliasExpression (FullNamedExpression alias, TypeArguments args, Location l)
2649 eclass = ExprClass.Type;
2651 name = alias.FullName + "<" + args.ToString () + ">";
2653 name = alias.FullName;
2656 public override string Name {
2657 get { return alias.FullName; }
2660 public override string FullName {
2661 get { return name; }
2664 protected override TypeExpr DoResolveAsTypeStep (EmitContext ec)
2666 texpr = alias.ResolveAsTypeTerminal (ec);
2670 Type type = texpr.Type;
2671 int num_args = TypeManager.GetNumberOfTypeArguments (type);
2674 if (num_args == 0) {
2675 Report.Error (308, loc,
2676 "The non-generic type `{0}' cannot " +
2677 "be used with type arguments.",
2678 TypeManager.CSharpName (type));
2682 ConstructedType ctype = new ConstructedType (type, args, loc);
2683 return ctype.ResolveAsTypeTerminal (ec);
2684 } else if (num_args > 0) {
2685 Report.Error (305, loc,
2686 "Using the generic type `{0}' " +
2687 "requires {1} type arguments",
2688 TypeManager.GetFullName (type), num_args);
2692 return new TypeExpression (type, loc);
2695 public override bool CheckAccessLevel (DeclSpace ds)
2697 return texpr.CheckAccessLevel (ds);
2700 public override bool AsAccessible (DeclSpace ds, int flags)
2702 return texpr.AsAccessible (ds, flags);
2705 public override bool IsClass {
2706 get { return texpr.IsClass; }
2709 public override bool IsValueType {
2710 get { return texpr.IsValueType; }
2713 public override bool IsInterface {
2714 get { return texpr.IsInterface; }
2717 public override bool IsSealed {
2718 get { return texpr.IsSealed; }
2723 /// This class denotes an expression which evaluates to a member
2724 /// of a struct or a class.
2726 public abstract class MemberExpr : Expression
2729 /// The name of this member.
2731 public abstract string Name {
2736 /// Whether this is an instance member.
2738 public abstract bool IsInstance {
2743 /// Whether this is a static member.
2745 public abstract bool IsStatic {
2750 /// The type which declares this member.
2752 public abstract Type DeclaringType {
2757 /// The instance expression associated with this member, if it's a
2758 /// non-static member.
2760 public Expression InstanceExpression;
2762 public static void error176 (Location loc, string name)
2764 Report.Error (176, loc, "Static member `{0}' cannot be accessed " +
2765 "with an instance reference, qualify it with a type name instead", name);
2769 // TODO: possible optimalization
2770 // Cache resolved constant result in FieldBuilder <-> expression map
2771 public virtual Expression ResolveMemberAccess (EmitContext ec, Expression left, Location loc,
2772 SimpleName original)
2776 // original == null || original.Resolve (...) ==> left
2779 if (left is TypeExpr) {
2781 SimpleName.Error_ObjectRefRequired (ec, loc, Name);
2789 if (original != null && original.IdenticalNameAndTypeName (ec, left, loc))
2792 error176 (loc, GetSignatureForError ());
2796 InstanceExpression = left;
2801 protected void EmitInstance (EmitContext ec, bool prepare_for_load)
2806 if (InstanceExpression == EmptyExpression.Null) {
2807 SimpleName.Error_ObjectRefRequired (ec, loc, Name);
2811 if (InstanceExpression.Type.IsValueType) {
2812 if (InstanceExpression is IMemoryLocation) {
2813 ((IMemoryLocation) InstanceExpression).AddressOf (ec, AddressOp.LoadStore);
2815 LocalTemporary t = new LocalTemporary (ec, InstanceExpression.Type);
2816 InstanceExpression.Emit (ec);
2818 t.AddressOf (ec, AddressOp.Store);
2821 InstanceExpression.Emit (ec);
2823 if (prepare_for_load)
2824 ec.ig.Emit (OpCodes.Dup);
2829 /// MethodGroup Expression.
2831 /// This is a fully resolved expression that evaluates to a type
2833 public class MethodGroupExpr : MemberExpr {
2834 public MethodBase [] Methods;
2835 bool has_type_arguments = false;
2836 bool identical_type_name = false;
2839 public MethodGroupExpr (MemberInfo [] mi, Location l)
2841 Methods = new MethodBase [mi.Length];
2842 mi.CopyTo (Methods, 0);
2843 eclass = ExprClass.MethodGroup;
2844 type = TypeManager.object_type;
2848 public MethodGroupExpr (ArrayList list, Location l)
2850 Methods = new MethodBase [list.Count];
2853 list.CopyTo (Methods, 0);
2855 foreach (MemberInfo m in list){
2856 if (!(m is MethodBase)){
2857 Console.WriteLine ("Name " + m.Name);
2858 Console.WriteLine ("Found a: " + m.GetType ().FullName);
2865 eclass = ExprClass.MethodGroup;
2866 type = TypeManager.object_type;
2869 public override Type DeclaringType {
2872 // We assume that the top-level type is in the end
2874 return Methods [Methods.Length - 1].DeclaringType;
2875 //return Methods [0].DeclaringType;
2879 public bool HasTypeArguments {
2881 return has_type_arguments;
2885 has_type_arguments = value;
2889 public bool IdenticalTypeName {
2891 return identical_type_name;
2895 identical_type_name = value;
2899 public bool IsBase {
2908 public override string GetSignatureForError ()
2910 return TypeManager.CSharpSignature (Methods [0]);
2913 public override string Name {
2915 return Methods [0].Name;
2919 public override bool IsInstance {
2921 foreach (MethodBase mb in Methods)
2929 public override bool IsStatic {
2931 foreach (MethodBase mb in Methods)
2939 public override Expression ResolveMemberAccess (EmitContext ec, Expression left, Location loc,
2940 SimpleName original)
2942 if (!(left is TypeExpr) &&
2943 original != null && original.IdenticalNameAndTypeName (ec, left, loc))
2944 IdenticalTypeName = true;
2946 return base.ResolveMemberAccess (ec, left, loc, original);
2949 override public Expression DoResolve (EmitContext ec)
2952 InstanceExpression = null;
2954 if (InstanceExpression != null) {
2955 InstanceExpression = InstanceExpression.DoResolve (ec);
2956 if (InstanceExpression == null)
2963 public void ReportUsageError ()
2965 Report.Error (654, loc, "Method `" + DeclaringType + "." +
2966 Name + "()' is referenced without parentheses");
2969 override public void Emit (EmitContext ec)
2971 ReportUsageError ();
2974 bool RemoveMethods (bool keep_static)
2976 ArrayList smethods = new ArrayList ();
2978 foreach (MethodBase mb in Methods){
2979 if (mb.IsStatic == keep_static)
2983 if (smethods.Count == 0)
2986 Methods = new MethodBase [smethods.Count];
2987 smethods.CopyTo (Methods, 0);
2993 /// Removes any instance methods from the MethodGroup, returns
2994 /// false if the resulting set is empty.
2996 public bool RemoveInstanceMethods ()
2998 return RemoveMethods (true);
3002 /// Removes any static methods from the MethodGroup, returns
3003 /// false if the resulting set is empty.
3005 public bool RemoveStaticMethods ()
3007 return RemoveMethods (false);
3010 public Expression ResolveGeneric (EmitContext ec, TypeArguments args)
3012 if (args.Resolve (ec) == false)
3015 Type[] atypes = args.Arguments;
3017 int first_count = 0;
3018 MethodInfo first = null;
3020 ArrayList list = new ArrayList ();
3021 foreach (MethodBase mb in Methods) {
3022 MethodInfo mi = mb as MethodInfo;
3023 if ((mi == null) || !mi.HasGenericParameters)
3026 Type[] gen_params = mi.GetGenericArguments ();
3028 if (first == null) {
3030 first_count = gen_params.Length;
3033 if (gen_params.Length != atypes.Length)
3036 list.Add (mi.BindGenericParameters (atypes));
3039 if (list.Count > 0) {
3040 MethodGroupExpr new_mg = new MethodGroupExpr (list, Location);
3041 new_mg.InstanceExpression = InstanceExpression;
3042 new_mg.HasTypeArguments = true;
3048 305, loc, "Using the generic method `{0}' " +
3049 "requires {1} type arguments", Name,
3053 308, loc, "The non-generic method `{0}' " +
3054 "cannot be used with type arguments", Name);
3061 /// Fully resolved expression that evaluates to a Field
3063 public class FieldExpr : MemberExpr, IAssignMethod, IMemoryLocation, IVariable {
3064 public readonly FieldInfo FieldInfo;
3065 VariableInfo variable_info;
3067 LocalTemporary temp;
3069 bool in_initializer;
3071 public FieldExpr (FieldInfo fi, Location l, bool in_initializer):
3074 this.in_initializer = in_initializer;
3077 public FieldExpr (FieldInfo fi, Location l)
3080 eclass = ExprClass.Variable;
3081 type = TypeManager.TypeToCoreType (fi.FieldType);
3085 public override string Name {
3087 return FieldInfo.Name;
3091 public override bool IsInstance {
3093 return !FieldInfo.IsStatic;
3097 public override bool IsStatic {
3099 return FieldInfo.IsStatic;
3103 public override Type DeclaringType {
3105 return FieldInfo.DeclaringType;
3109 public override string GetSignatureForError ()
3111 return TypeManager.GetFullNameSignature (FieldInfo);
3114 public VariableInfo VariableInfo {
3116 return variable_info;
3120 public override Expression ResolveMemberAccess (EmitContext ec, Expression left, Location loc,
3121 SimpleName original)
3123 bool left_is_type = left is TypeExpr;
3125 FieldInfo fi = FieldInfo.Mono_GetGenericFieldDefinition ();
3127 Type decl_type = fi.DeclaringType;
3129 bool is_emitted = fi is FieldBuilder;
3130 Type t = fi.FieldType;
3133 Const c = TypeManager.LookupConstant ((FieldBuilder) fi);
3137 if (!c.LookupConstantValue (out o))
3140 c.SetMemberIsUsed ();
3141 object real_value = ((Constant) c.Expr).GetValue ();
3143 Expression exp = Constantify (real_value, t);
3145 if (!left_is_type &&
3146 (original == null || !original.IdenticalNameAndTypeName (ec, left, loc))) {
3147 Report.SymbolRelatedToPreviousError (c);
3148 error176 (loc, c.GetSignatureForError ());
3157 // Decimal constants cannot be encoded in the constant blob, and thus are marked
3158 // as IsInitOnly ('readonly' in C# parlance). We get its value from the
3159 // DecimalConstantAttribute metadata.
3161 if (fi.IsInitOnly && !is_emitted && t == TypeManager.decimal_type) {
3162 object[] attrs = fi.GetCustomAttributes (TypeManager.decimal_constant_attribute_type, false);
3163 if (attrs.Length == 1)
3164 return new DecimalConstant (((System.Runtime.CompilerServices.DecimalConstantAttribute) attrs [0]).Value);
3171 o = TypeManager.GetValue ((FieldBuilder) fi);
3173 o = fi.GetValue (fi);
3175 if (decl_type.IsSubclassOf (TypeManager.enum_type)) {
3176 if (!left_is_type &&
3177 (original == null || !original.IdenticalNameAndTypeName (ec, left, loc))) {
3178 error176 (loc, TypeManager.GetFullNameSignature (FieldInfo));
3182 Expression enum_member = MemberLookup (
3183 ec, decl_type, "value__", MemberTypes.Field,
3184 AllBindingFlags | BindingFlags.NonPublic, loc);
3186 Enum en = TypeManager.LookupEnum (decl_type);
3190 c = Constantify (o, en.UnderlyingType);
3192 c = Constantify (o, enum_member.Type);
3194 return new EnumConstant (c, decl_type);
3197 Expression exp = Constantify (o, t);
3199 if (!left_is_type) {
3200 error176 (loc, TypeManager.GetFullNameSignature (FieldInfo));
3207 if (t.IsPointer && !ec.InUnsafe) {
3212 return base.ResolveMemberAccess (ec, left, loc, original);
3215 override public Expression DoResolve (EmitContext ec)
3217 if (ec.InRefOutArgumentResolving && FieldInfo.IsInitOnly && !ec.IsConstructor && FieldInfo.FieldType.IsValueType) {
3218 if (FieldInfo.FieldType is TypeBuilder) {
3219 if (FieldInfo.IsStatic)
3220 Report.Error (1651, loc, "Fields of static readonly field `{0}' cannot be passed ref or out (except in a static constructor)",
3221 GetSignatureForError ());
3223 Report.Error (1649, loc, "Members of readonly field `{0}.{1}' cannot be passed ref or out (except in a constructor)",
3224 TypeManager.CSharpName (DeclaringType), Name);
3226 if (FieldInfo.IsStatic)
3227 Report.Error (199, loc, "A static readonly field `{0}' cannot be passed ref or out (except in a static constructor)",
3230 Report.Error (192, loc, "A readonly field `{0}' cannot be passed ref or out (except in a constructor)",
3236 if (!FieldInfo.IsStatic){
3237 if (InstanceExpression == null){
3239 // This can happen when referencing an instance field using
3240 // a fully qualified type expression: TypeName.InstanceField = xxx
3242 SimpleName.Error_ObjectRefRequired (ec, loc, FieldInfo.Name);
3246 // Resolve the field's instance expression while flow analysis is turned
3247 // off: when accessing a field "a.b", we must check whether the field
3248 // "a.b" is initialized, not whether the whole struct "a" is initialized.
3249 InstanceExpression = InstanceExpression.Resolve (
3250 ec, ResolveFlags.VariableOrValue | ResolveFlags.DisableFlowAnalysis);
3251 if (InstanceExpression == null)
3255 if (!in_initializer) {
3256 ObsoleteAttribute oa;
3257 FieldBase f = TypeManager.GetField (FieldInfo);
3259 oa = f.GetObsoleteAttribute (f.Parent);
3261 AttributeTester.Report_ObsoleteMessage (oa, f.GetSignatureForError (), loc);
3262 // To be sure that type is external because we do not register generated fields
3263 } else if (!(FieldInfo.DeclaringType is TypeBuilder)) {
3264 oa = AttributeTester.GetMemberObsoleteAttribute (FieldInfo);
3266 AttributeTester.Report_ObsoleteMessage (oa, TypeManager.GetFullNameSignature (FieldInfo), loc);
3270 AnonymousContainer am = ec.CurrentAnonymousMethod;
3272 if (!FieldInfo.IsStatic){
3273 if (!am.IsIterator && (ec.TypeContainer is Struct)){
3274 Report.Error (1673, loc,
3275 "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",
3279 if ((am.ContainerAnonymousMethod == null) && (InstanceExpression is This))
3280 ec.CaptureField (this);
3284 // If the instance expression is a local variable or parameter.
3285 IVariable var = InstanceExpression as IVariable;
3286 if ((var == null) || (var.VariableInfo == null))
3289 VariableInfo vi = var.VariableInfo;
3290 if (!vi.IsFieldAssigned (ec, FieldInfo.Name, loc))
3293 variable_info = vi.GetSubStruct (FieldInfo.Name);
3297 void Report_AssignToReadonly (bool is_instance)
3302 msg = "A readonly field cannot be assigned to (except in a constructor or a variable initializer)";
3304 msg = "A static readonly field cannot be assigned to (except in a static constructor or a variable initializer)";
3306 Report.Error (is_instance ? 191 : 198, loc, msg);
3309 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
3311 IVariable var = InstanceExpression as IVariable;
3312 if ((var != null) && (var.VariableInfo != null))
3313 var.VariableInfo.SetFieldAssigned (ec, FieldInfo.Name);
3315 Expression e = DoResolve (ec);
3320 if (!FieldInfo.IsStatic && (InstanceExpression.Type.IsValueType && !(InstanceExpression is IMemoryLocation))) {
3321 Report.Error (1612, loc, "Cannot modify the return value of `{0}' because it is not a variable",
3322 InstanceExpression.GetSignatureForError ());
3326 FieldBase fb = TypeManager.GetField (FieldInfo);
3330 if (!FieldInfo.IsInitOnly)
3334 // InitOnly fields can only be assigned in constructors
3337 if (ec.IsConstructor){
3338 if (IsStatic && !ec.IsStatic)
3339 Report_AssignToReadonly (false);
3342 if (ec.TypeContainer.CurrentType != null)
3343 ctype = ec.TypeContainer.CurrentType;
3345 ctype = ec.ContainerType;
3347 if (TypeManager.IsEqual (ctype, FieldInfo.DeclaringType))
3351 Report_AssignToReadonly (!IsStatic);
3356 public override void CheckMarshallByRefAccess (Type container)
3358 if (!IsStatic && Type.IsValueType && !container.IsSubclassOf (TypeManager.mbr_type) && DeclaringType.IsSubclassOf (TypeManager.mbr_type)) {
3359 Report.SymbolRelatedToPreviousError (DeclaringType);
3360 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",
3361 GetSignatureForError ());
3365 public bool VerifyFixed ()
3367 IVariable variable = InstanceExpression as IVariable;
3368 // A variable of the form V.I is fixed when V is a fixed variable of a struct type.
3369 // We defer the InstanceExpression check after the variable check to avoid a
3370 // separate null check on InstanceExpression.
3371 return variable != null && InstanceExpression.Type.IsValueType && variable.VerifyFixed ();
3374 public override int GetHashCode()
3376 return FieldInfo.GetHashCode ();
3379 public override bool Equals (object obj)
3381 FieldExpr fe = obj as FieldExpr;
3385 if (FieldInfo != fe.FieldInfo)
3388 if (InstanceExpression == null || fe.InstanceExpression == null)
3391 return InstanceExpression.Equals (fe.InstanceExpression);
3394 public void Emit (EmitContext ec, bool leave_copy)
3396 ILGenerator ig = ec.ig;
3397 bool is_volatile = false;
3399 FieldInfo the_fi = FieldInfo.Mono_GetGenericFieldDefinition ();
3400 if (the_fi is FieldBuilder){
3401 FieldBase f = TypeManager.GetField (the_fi);
3403 if ((f.ModFlags & Modifiers.VOLATILE) != 0)
3406 f.SetMemberIsUsed ();
3410 if (FieldInfo.IsStatic){
3412 ig.Emit (OpCodes.Volatile);
3414 ig.Emit (OpCodes.Ldsfld, FieldInfo);
3417 EmitInstance (ec, false);
3420 ig.Emit (OpCodes.Volatile);
3422 IFixedBuffer ff = AttributeTester.GetFixedBuffer (FieldInfo);
3425 ig.Emit (OpCodes.Ldflda, FieldInfo);
3426 ig.Emit (OpCodes.Ldflda, ff.Element);
3429 ig.Emit (OpCodes.Ldfld, FieldInfo);
3434 ec.ig.Emit (OpCodes.Dup);
3435 if (!FieldInfo.IsStatic) {
3436 temp = new LocalTemporary (ec, this.Type);
3442 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
3444 FieldAttributes fa = FieldInfo.Attributes;
3445 bool is_static = (fa & FieldAttributes.Static) != 0;
3446 bool is_readonly = (fa & FieldAttributes.InitOnly) != 0;
3447 ILGenerator ig = ec.ig;
3448 prepared = prepare_for_load;
3450 if (is_readonly && !ec.IsConstructor){
3451 Report_AssignToReadonly (!is_static);
3455 EmitInstance (ec, prepare_for_load);
3459 ec.ig.Emit (OpCodes.Dup);
3460 if (!FieldInfo.IsStatic) {
3461 temp = new LocalTemporary (ec, this.Type);
3466 if (FieldInfo is FieldBuilder){
3467 FieldBase f = TypeManager.GetField (FieldInfo);
3469 if ((f.ModFlags & Modifiers.VOLATILE) != 0)
3470 ig.Emit (OpCodes.Volatile);
3477 ig.Emit (OpCodes.Stsfld, FieldInfo);
3479 ig.Emit (OpCodes.Stfld, FieldInfo);
3485 public override void Emit (EmitContext ec)
3490 public void AddressOf (EmitContext ec, AddressOp mode)
3492 ILGenerator ig = ec.ig;
3494 if (FieldInfo is FieldBuilder){
3495 FieldBase f = TypeManager.GetField (FieldInfo);
3497 if ((f.ModFlags & Modifiers.VOLATILE) != 0){
3498 Report.Warning (420, 1, loc, "`{0}': A volatile fields cannot be passed using a ref or out parameter",
3499 f.GetSignatureForError ());
3503 if ((mode & AddressOp.Store) != 0)
3505 if ((mode & AddressOp.Load) != 0)
3506 f.SetMemberIsUsed ();
3511 // Handle initonly fields specially: make a copy and then
3512 // get the address of the copy.
3515 if (FieldInfo.IsInitOnly){
3517 if (ec.IsConstructor){
3518 if (FieldInfo.IsStatic){
3530 local = ig.DeclareLocal (type);
3531 ig.Emit (OpCodes.Stloc, local);
3532 ig.Emit (OpCodes.Ldloca, local);
3537 if (FieldInfo.IsStatic){
3538 ig.Emit (OpCodes.Ldsflda, FieldInfo);
3540 EmitInstance (ec, false);
3541 ig.Emit (OpCodes.Ldflda, FieldInfo);
3547 // A FieldExpr whose address can not be taken
3549 public class FieldExprNoAddress : FieldExpr, IMemoryLocation {
3550 public FieldExprNoAddress (FieldInfo fi, Location loc) : base (fi, loc)
3554 public new void AddressOf (EmitContext ec, AddressOp mode)
3556 Report.Error (-215, "Report this: Taking the address of a remapped parameter not supported");
3561 /// Expression that evaluates to a Property. The Assign class
3562 /// might set the `Value' expression if we are in an assignment.
3564 /// This is not an LValue because we need to re-write the expression, we
3565 /// can not take data from the stack and store it.
3567 public class PropertyExpr : MemberExpr, IAssignMethod {
3568 public readonly PropertyInfo PropertyInfo;
3571 // This is set externally by the `BaseAccess' class
3574 MethodInfo getter, setter;
3579 LocalTemporary temp;
3582 internal static PtrHashtable AccessorTable = new PtrHashtable ();
3584 public PropertyExpr (EmitContext ec, PropertyInfo pi, Location l)
3587 eclass = ExprClass.PropertyAccess;
3591 type = TypeManager.TypeToCoreType (pi.PropertyType);
3593 ResolveAccessors (ec);
3596 public override string Name {
3598 return PropertyInfo.Name;
3602 public override bool IsInstance {
3608 public override bool IsStatic {
3614 public override Type DeclaringType {
3616 return PropertyInfo.DeclaringType;
3620 public override string GetSignatureForError ()
3622 return TypeManager.GetFullNameSignature (PropertyInfo);
3625 void FindAccessors (Type invocation_type)
3627 BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic |
3628 BindingFlags.Static | BindingFlags.Instance |
3629 BindingFlags.DeclaredOnly;
3631 Type current = PropertyInfo.DeclaringType;
3632 for (; current != null; current = current.BaseType) {
3633 MemberInfo[] group = TypeManager.MemberLookup (
3634 invocation_type, invocation_type, current,
3635 MemberTypes.Property, flags, PropertyInfo.Name, null);
3640 if (group.Length != 1)
3641 // Oooops, can this ever happen ?
3644 PropertyInfo pi = (PropertyInfo) group [0];
3647 getter = pi.GetGetMethod (true);
3650 setter = pi.GetSetMethod (true);
3652 MethodInfo accessor = getter != null ? getter : setter;
3654 if (!accessor.IsVirtual)
3660 // We also perform the permission checking here, as the PropertyInfo does not
3661 // hold the information for the accessibility of its setter/getter
3663 void ResolveAccessors (EmitContext ec)
3665 FindAccessors (ec.ContainerType);
3667 if (getter != null) {
3668 IMethodData md = TypeManager.GetMethod (getter);
3670 md.SetMemberIsUsed ();
3672 AccessorTable [getter] = PropertyInfo;
3673 is_static = getter.IsStatic;
3676 if (setter != null) {
3677 IMethodData md = TypeManager.GetMethod (setter);
3679 md.SetMemberIsUsed ();
3681 AccessorTable [setter] = PropertyInfo;
3682 is_static = setter.IsStatic;
3686 bool InstanceResolve (EmitContext ec, bool must_do_cs1540_check)
3689 InstanceExpression = null;
3693 if (InstanceExpression == null) {
3694 SimpleName.Error_ObjectRefRequired (ec, loc, PropertyInfo.Name);
3698 InstanceExpression = InstanceExpression.DoResolve (ec);
3699 if (InstanceExpression == null)
3702 InstanceExpression.CheckMarshallByRefAccess (ec.ContainerType);
3704 if (must_do_cs1540_check && InstanceExpression != EmptyExpression.Null) {
3705 if ((InstanceExpression.Type != ec.ContainerType) &&
3706 ec.ContainerType.IsSubclassOf (InstanceExpression.Type)) {
3707 Report.Error (1540, loc, "Cannot access protected member `" +
3708 PropertyInfo.DeclaringType + "." + PropertyInfo.Name +
3709 "' via a qualifier of type `" +
3710 TypeManager.CSharpName (InstanceExpression.Type) +
3711 "'; the qualifier must be of type `" +
3712 TypeManager.CSharpName (ec.ContainerType) +
3713 "' (or derived from it)");
3721 override public Expression DoResolve (EmitContext ec)
3726 if (getter != null){
3727 if (TypeManager.GetArgumentTypes (getter).Length != 0){
3729 117, loc, "`{0}' does not contain a " +
3730 "definition for `{1}'.", getter.DeclaringType,
3736 if (getter == null){
3738 // The following condition happens if the PropertyExpr was
3739 // created, but is invalid (ie, the property is inaccessible),
3740 // and we did not want to embed the knowledge about this in
3741 // the caller routine. This only avoids double error reporting.
3746 if (InstanceExpression != EmptyExpression.Null) {
3747 Report.Error (154, loc, "The property or indexer `{0}' cannot be used in this context because it lacks the `get' accessor",
3748 TypeManager.GetFullNameSignature (PropertyInfo));
3753 bool must_do_cs1540_check = false;
3754 if (getter != null &&
3755 !IsAccessorAccessible (ec.ContainerType, getter, out must_do_cs1540_check)) {
3756 PropertyBase.PropertyMethod pm = TypeManager.GetMethod (getter) as PropertyBase.PropertyMethod;
3757 if (pm != null && pm.HasCustomAccessModifier) {
3758 Report.SymbolRelatedToPreviousError (pm);
3759 Report.Error (271, loc, "The property or indexer `{0}' cannot be used in this context because the get accessor is inaccessible",
3760 TypeManager.CSharpSignature (getter));
3763 ErrorIsInaccesible (loc, TypeManager.CSharpSignature (getter));
3767 if (!InstanceResolve (ec, must_do_cs1540_check))
3771 // Only base will allow this invocation to happen.
3773 if (IsBase && getter.IsAbstract) {
3774 Error_CannotCallAbstractBase (TypeManager.GetFullNameSignature (PropertyInfo));
3778 if (PropertyInfo.PropertyType.IsPointer && !ec.InUnsafe){
3788 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
3790 if (setter == null){
3792 // The following condition happens if the PropertyExpr was
3793 // created, but is invalid (ie, the property is inaccessible),
3794 // and we did not want to embed the knowledge about this in
3795 // the caller routine. This only avoids double error reporting.
3800 Report.Error (200, loc, " Property or indexer `{0}' cannot be assigned to (it is read only)",
3801 TypeManager.GetFullNameSignature (PropertyInfo));
3805 if (TypeManager.GetArgumentTypes (setter).Length != 1){
3807 117, loc, "`{0}' does not contain a " +
3808 "definition for `{1}'.", getter.DeclaringType,
3813 bool must_do_cs1540_check;
3814 if (!IsAccessorAccessible (ec.ContainerType, setter, out must_do_cs1540_check)) {
3815 PropertyBase.PropertyMethod pm = TypeManager.GetMethod (setter) as PropertyBase.PropertyMethod;
3816 if (pm != null && pm.HasCustomAccessModifier) {
3817 Report.SymbolRelatedToPreviousError (pm);
3818 Report.Error (272, loc, "The property or indexer `{0}' cannot be used in this context because the set accessor is inaccessible",
3819 TypeManager.CSharpSignature (setter));
3822 ErrorIsInaccesible (loc, TypeManager.CSharpSignature (setter));
3826 if (!InstanceResolve (ec, must_do_cs1540_check))
3830 // Only base will allow this invocation to happen.
3832 if (IsBase && setter.IsAbstract){
3833 Error_CannotCallAbstractBase (TypeManager.GetFullNameSignature (PropertyInfo));
3838 // Check that we are not making changes to a temporary memory location
3840 if (InstanceExpression != null && InstanceExpression.Type.IsValueType && !(InstanceExpression is IMemoryLocation)) {
3841 Report.Error (1612, loc, "Cannot modify the return value of `{0}' because it is not a variable",
3842 InstanceExpression.GetSignatureForError ());
3849 public override void Emit (EmitContext ec)
3854 public void Emit (EmitContext ec, bool leave_copy)
3857 EmitInstance (ec, false);
3860 // Special case: length of single dimension array property is turned into ldlen
3862 if ((getter == TypeManager.system_int_array_get_length) ||
3863 (getter == TypeManager.int_array_get_length)){
3864 Type iet = InstanceExpression.Type;
3867 // System.Array.Length can be called, but the Type does not
3868 // support invoking GetArrayRank, so test for that case first
3870 if (iet != TypeManager.array_type && (iet.GetArrayRank () == 1)) {
3871 ec.ig.Emit (OpCodes.Ldlen);
3872 ec.ig.Emit (OpCodes.Conv_I4);
3877 Invocation.EmitCall (ec, IsBase, IsStatic, new EmptyAddressOf (), getter, null, loc);
3882 ec.ig.Emit (OpCodes.Dup);
3884 temp = new LocalTemporary (ec, this.Type);
3890 // Implements the IAssignMethod interface for assignments
3892 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
3894 prepared = prepare_for_load;
3896 EmitInstance (ec, prepare_for_load);
3900 ec.ig.Emit (OpCodes.Dup);
3902 temp = new LocalTemporary (ec, this.Type);
3907 ArrayList args = new ArrayList (1);
3908 args.Add (new Argument (new EmptyAddressOf (), Argument.AType.Expression));
3910 Invocation.EmitCall (ec, IsBase, IsStatic, new EmptyAddressOf (), setter, args, loc);
3918 /// Fully resolved expression that evaluates to an Event
3920 public class EventExpr : MemberExpr {
3921 public readonly EventInfo EventInfo;
3924 MethodInfo add_accessor, remove_accessor;
3926 public EventExpr (EventInfo ei, Location loc)
3930 eclass = ExprClass.EventAccess;
3932 add_accessor = TypeManager.GetAddMethod (ei);
3933 remove_accessor = TypeManager.GetRemoveMethod (ei);
3935 if (add_accessor.IsStatic || remove_accessor.IsStatic)
3938 if (EventInfo is MyEventBuilder){
3939 MyEventBuilder eb = (MyEventBuilder) EventInfo;
3940 type = eb.EventType;
3943 type = EventInfo.EventHandlerType;
3946 public override string Name {
3948 return EventInfo.Name;
3952 public override bool IsInstance {
3958 public override bool IsStatic {
3964 public override Type DeclaringType {
3966 return EventInfo.DeclaringType;
3970 public override Expression ResolveMemberAccess (EmitContext ec, Expression left, Location loc,
3971 SimpleName original)
3974 // If the event is local to this class, we transform ourselves into a FieldExpr
3977 if (EventInfo.DeclaringType == ec.ContainerType ||
3978 TypeManager.IsNestedChildOf(ec.ContainerType, EventInfo.DeclaringType)) {
3979 MemberInfo mi = TypeManager.GetPrivateFieldOfEvent (EventInfo);
3982 MemberExpr ml = (MemberExpr) ExprClassFromMemberInfo (ec, mi, loc);
3985 Report.Error (-200, loc, "Internal error!!");
3989 InstanceExpression = null;
3991 return ml.ResolveMemberAccess (ec, left, loc, original);
3995 return base.ResolveMemberAccess (ec, left, loc, original);
3999 bool InstanceResolve (EmitContext ec, bool must_do_cs1540_check)
4002 InstanceExpression = null;
4006 if (InstanceExpression == null) {
4007 SimpleName.Error_ObjectRefRequired (ec, loc, EventInfo.Name);
4011 InstanceExpression = InstanceExpression.DoResolve (ec);
4012 if (InstanceExpression == null)
4016 // This is using the same mechanism as the CS1540 check in PropertyExpr.
4017 // However, in the Event case, we reported a CS0122 instead.
4019 if (must_do_cs1540_check && InstanceExpression != EmptyExpression.Null) {
4020 if ((InstanceExpression.Type != ec.ContainerType) &&
4021 ec.ContainerType.IsSubclassOf (InstanceExpression.Type)) {
4022 ErrorIsInaccesible (loc, TypeManager.CSharpSignature (EventInfo));
4030 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
4032 return DoResolve (ec);
4035 public override Expression DoResolve (EmitContext ec)
4037 bool must_do_cs1540_check;
4038 if (!(IsAccessorAccessible (ec.ContainerType, add_accessor, out must_do_cs1540_check) &&
4039 IsAccessorAccessible (ec.ContainerType, remove_accessor, out must_do_cs1540_check))) {
4040 ErrorIsInaccesible (loc, TypeManager.CSharpSignature (EventInfo));
4044 if (!InstanceResolve (ec, must_do_cs1540_check))
4050 public override void Emit (EmitContext ec)
4052 if (InstanceExpression is This)
4053 Report.Error (79, loc, "The event `{0}' can only appear on the left hand side of += or -=", GetSignatureForError ());
4055 Report.Error (70, loc, "The event `{0}' can only appear on the left hand side of += or -= "+
4056 "(except on the defining type)", Name);
4059 public override string GetSignatureForError ()
4061 return TypeManager.CSharpSignature (EventInfo);
4064 public void EmitAddOrRemove (EmitContext ec, Expression source)
4066 BinaryDelegate source_del = (BinaryDelegate) source;
4067 Expression handler = source_del.Right;
4069 Argument arg = new Argument (handler, Argument.AType.Expression);
4070 ArrayList args = new ArrayList ();
4074 if (source_del.IsAddition)
4075 Invocation.EmitCall (
4076 ec, false, IsStatic, InstanceExpression, add_accessor, args, loc);
4078 Invocation.EmitCall (
4079 ec, false, IsStatic, InstanceExpression, remove_accessor, args, loc);