2 // ecore.cs: Core of the Expression representation for the intermediate tree.
5 // Miguel de Icaza (miguel@ximian.com)
7 // (C) 2001, 2002, 2003 Ximian, Inc.
11 namespace Mono.CSharp {
13 using System.Collections;
14 using System.Diagnostics;
15 using System.Reflection;
16 using System.Reflection.Emit;
20 /// The ExprClass class contains the is used to pass the
21 /// classification of an expression (value, variable, namespace,
22 /// type, method group, property access, event access, indexer access,
25 public enum ExprClass : byte {
40 /// This is used to tell Resolve in which types of expressions we're
44 public enum ResolveFlags {
45 // Returns Value, Variable, PropertyAccess, EventAccess or IndexerAccess.
48 // Returns a type expression.
51 // Returns a method group.
54 // Mask of all the expression class flags.
57 // Disable control flow analysis while resolving the expression.
58 // This is used when resolving the instance expression of a field expression.
59 DisableFlowAnalysis = 8,
61 // Set if this is resolving the first part of a MemberAccess.
66 // This is just as a hint to AddressOf of what will be done with the
69 public enum AddressOp {
76 /// This interface is implemented by variables
78 public interface IMemoryLocation {
80 /// The AddressOf method should generate code that loads
81 /// the address of the object and leaves it on the stack.
83 /// The `mode' argument is used to notify the expression
84 /// of whether this will be used to read from the address or
85 /// write to the address.
87 /// This is just a hint that can be used to provide good error
88 /// reporting, and should have no other side effects.
90 void AddressOf (EmitContext ec, AddressOp mode);
94 /// We are either a namespace or a type.
95 /// If we're a type, `IsType' is true and we may use `Type' to get
96 /// a TypeExpr representing that type.
98 public interface IAlias {
107 TypeExpr ResolveAsType (EmitContext ec);
111 /// This interface is implemented by variables
113 public interface IVariable {
114 VariableInfo VariableInfo {
118 bool VerifyFixed (bool is_expression);
122 /// This interface denotes an expression which evaluates to a member
123 /// of a struct or a class.
125 public interface IMemberExpr
128 /// The name of this member.
135 /// Whether this is an instance member.
142 /// Whether this is a static member.
149 /// The type which declares this member.
156 /// The instance expression associated with this member, if it's a
157 /// non-static member.
159 Expression InstanceExpression {
165 /// Base class for expressions
167 public abstract class Expression {
168 public ExprClass eclass;
170 protected Location loc;
182 public Location Location {
189 /// Utility wrapper routine for Error, just to beautify the code
191 public void Error (int error, string s)
193 if (!Location.IsNull (loc))
194 Report.Error (error, loc, s);
196 Report.Error (error, s);
200 /// Utility wrapper routine for Warning, just to beautify the code
202 public void Warning (int code, string format, params object[] args)
204 Report.Warning (code, loc, format, args);
207 // Not nice but we have broken hierarchy
208 public virtual void CheckMarshallByRefAccess (Type container) {}
211 /// Tests presence of ObsoleteAttribute and report proper error
213 protected void CheckObsoleteAttribute (Type type)
215 ObsoleteAttribute obsolete_attr = AttributeTester.GetObsoleteAttribute (type);
216 if (obsolete_attr == null)
219 AttributeTester.Report_ObsoleteMessage (obsolete_attr, type.FullName, loc);
222 public static bool IsAccessorAccessible (Type invocation_type, MethodInfo mi, out bool must_do_cs1540_check)
224 MethodAttributes ma = mi.Attributes & MethodAttributes.MemberAccessMask;
226 must_do_cs1540_check = false; // by default we do not check for this
229 // If only accessible to the current class or children
231 if (ma == MethodAttributes.Private) {
232 Type declaring_type = mi.DeclaringType;
234 if (invocation_type != declaring_type)
235 return TypeManager.IsNestedChildOf (invocation_type, declaring_type);
240 // FamAndAssem requires that we not only derivate, but we are on the
243 if (ma == MethodAttributes.FamANDAssem){
244 return (mi.DeclaringType.Assembly != invocation_type.Assembly);
247 // Assembly and FamORAssem succeed if we're in the same assembly.
248 if ((ma == MethodAttributes.Assembly) || (ma == MethodAttributes.FamORAssem)){
249 if (mi.DeclaringType.Assembly == invocation_type.Assembly)
253 // We already know that we aren't in the same assembly.
254 if (ma == MethodAttributes.Assembly)
257 // Family and FamANDAssem require that we derive.
258 if ((ma == MethodAttributes.Family) || (ma == MethodAttributes.FamANDAssem) || (ma == MethodAttributes.FamORAssem)){
259 if (!TypeManager.IsNestedFamilyAccessible (invocation_type, mi.DeclaringType))
262 if (!TypeManager.IsNestedChildOf (invocation_type, mi.DeclaringType))
263 must_do_cs1540_check = true;
272 /// Performs semantic analysis on the Expression
276 /// The Resolve method is invoked to perform the semantic analysis
279 /// The return value is an expression (it can be the
280 /// same expression in some cases) or a new
281 /// expression that better represents this node.
283 /// For example, optimizations of Unary (LiteralInt)
284 /// would return a new LiteralInt with a negated
287 /// If there is an error during semantic analysis,
288 /// then an error should be reported (using Report)
289 /// and a null value should be returned.
291 /// There are two side effects expected from calling
292 /// Resolve(): the the field variable "eclass" should
293 /// be set to any value of the enumeration
294 /// `ExprClass' and the type variable should be set
295 /// to a valid type (this is the type of the
298 public abstract Expression DoResolve (EmitContext ec);
300 public virtual Expression DoResolveLValue (EmitContext ec, Expression right_side)
302 return DoResolve (ec);
306 // This is used if the expression should be resolved as a type or namespace name.
307 // the default implementation fails.
309 public virtual FullNamedExpression ResolveAsTypeStep (EmitContext ec)
315 // This is used to resolve the expression as a type, a null
316 // value will be returned if the expression is not a type
319 public TypeExpr ResolveAsTypeTerminal (EmitContext ec, bool silent)
321 int errors = Report.Errors;
323 FullNamedExpression fne = ResolveAsTypeStep (ec);
326 if (!silent && errors == Report.Errors)
327 Report.Error (246, Location, "Cannot find type '{0}'", ToString ());
331 if (fne.eclass != ExprClass.Type) {
332 if (!silent && errors == Report.Errors)
333 Report.Error (118, Location, "'{0}' denotes a '{1}', where a type was expected",
334 fne.FullName, fne.ExprClassName ());
338 TypeExpr te = fne as TypeExpr;
340 if (!te.CheckAccessLevel (ec.DeclSpace)) {
341 Report.Error (122, Location, "'{0}' is inaccessible due to its protection level", te.Name);
349 /// Resolves an expression and performs semantic analysis on it.
353 /// Currently Resolve wraps DoResolve to perform sanity
354 /// checking and assertion checking on what we expect from Resolve.
356 public Expression Resolve (EmitContext ec, ResolveFlags flags)
358 if ((flags & ResolveFlags.MaskExprClass) == ResolveFlags.Type)
359 return ResolveAsTypeStep (ec);
361 bool old_do_flow_analysis = ec.DoFlowAnalysis;
362 if ((flags & ResolveFlags.DisableFlowAnalysis) != 0)
363 ec.DoFlowAnalysis = false;
366 bool intermediate = (flags & ResolveFlags.Intermediate) == ResolveFlags.Intermediate;
367 if (this is SimpleName)
368 e = ((SimpleName) this).DoResolveAllowStatic (ec, intermediate);
373 ec.DoFlowAnalysis = old_do_flow_analysis;
378 if ((e is TypeExpr) || (e is ComposedCast) || (e is Namespace)) {
379 if ((flags & ResolveFlags.Type) == 0) {
380 e.Error_UnexpectedKind (flags, loc);
389 case ExprClass.Namespace:
390 if ((flags & ResolveFlags.VariableOrValue) == 0) {
391 e.Error_UnexpectedKind (flags, loc);
396 case ExprClass.MethodGroup:
397 if (RootContext.Version == LanguageVersion.ISO_1){
398 if ((flags & ResolveFlags.MethodGroup) == 0) {
399 ((MethodGroupExpr) e).ReportUsageError ();
405 case ExprClass.Value:
406 case ExprClass.Variable:
407 case ExprClass.PropertyAccess:
408 case ExprClass.EventAccess:
409 case ExprClass.IndexerAccess:
410 if ((flags & ResolveFlags.VariableOrValue) == 0) {
411 Console.WriteLine ("I got: {0} and {1}", e.GetType (), e);
412 Console.WriteLine ("I am {0} and {1}", this.GetType (), this);
413 FieldInfo fi = ((FieldExpr) e).FieldInfo;
415 Console.WriteLine ("{0} and {1}", fi.DeclaringType, fi.Name);
416 e.Error_UnexpectedKind (flags, loc);
422 throw new Exception ("Expression " + e.GetType () +
423 " ExprClass is Invalid after resolve");
426 if (e.type == null && !(e is Namespace)) {
427 throw new Exception (
428 "Expression " + e.GetType () +
429 " did not set its type after Resolve\n" +
430 "called from: " + this.GetType ());
437 /// Resolves an expression and performs semantic analysis on it.
439 public Expression Resolve (EmitContext ec)
441 return Resolve (ec, ResolveFlags.VariableOrValue);
445 /// Resolves an expression for LValue assignment
449 /// Currently ResolveLValue wraps DoResolveLValue to perform sanity
450 /// checking and assertion checking on what we expect from Resolve
452 public Expression ResolveLValue (EmitContext ec, Expression right_side)
454 Expression e = DoResolveLValue (ec, right_side);
457 if (e is SimpleName){
458 SimpleName s = (SimpleName) e;
459 MemberLookupFailed (ec, null, ec.ContainerType, s.Name,
460 ec.DeclSpace.Name, loc);
464 if (e.eclass == ExprClass.Invalid)
465 throw new Exception ("Expression " + e +
466 " ExprClass is Invalid after resolve");
468 if (e.eclass == ExprClass.MethodGroup) {
469 ((MethodGroupExpr) e).ReportUsageError ();
474 throw new Exception ("Expression " + e +
475 " did not set its type after Resolve");
482 /// Emits the code for the expression
486 /// The Emit method is invoked to generate the code
487 /// for the expression.
489 public abstract void Emit (EmitContext ec);
491 public virtual void EmitBranchable (EmitContext ec, Label target, bool onTrue)
494 ec.ig.Emit (onTrue ? OpCodes.Brtrue : OpCodes.Brfalse, target);
498 /// Protected constructor. Only derivate types should
499 /// be able to be created
502 protected Expression ()
504 eclass = ExprClass.Invalid;
509 /// Returns a literalized version of a literal FieldInfo
513 /// The possible return values are:
514 /// IntConstant, UIntConstant
515 /// LongLiteral, ULongConstant
516 /// FloatConstant, DoubleConstant
519 /// The value returned is already resolved.
521 public static Constant Constantify (object v, Type t)
523 if (t == TypeManager.int32_type)
524 return new IntConstant ((int) v);
525 else if (t == TypeManager.uint32_type)
526 return new UIntConstant ((uint) v);
527 else if (t == TypeManager.int64_type)
528 return new LongConstant ((long) v);
529 else if (t == TypeManager.uint64_type)
530 return new ULongConstant ((ulong) v);
531 else if (t == TypeManager.float_type)
532 return new FloatConstant ((float) v);
533 else if (t == TypeManager.double_type)
534 return new DoubleConstant ((double) v);
535 else if (t == TypeManager.string_type)
536 return new StringConstant ((string) v);
537 else if (t == TypeManager.short_type)
538 return new ShortConstant ((short)v);
539 else if (t == TypeManager.ushort_type)
540 return new UShortConstant ((ushort)v);
541 else if (t == TypeManager.sbyte_type)
542 return new SByteConstant (((sbyte)v));
543 else if (t == TypeManager.byte_type)
544 return new ByteConstant ((byte)v);
545 else if (t == TypeManager.char_type)
546 return new CharConstant ((char)v);
547 else if (t == TypeManager.bool_type)
548 return new BoolConstant ((bool) v);
549 else if (t == TypeManager.decimal_type)
550 return new DecimalConstant ((decimal) v);
551 else if (TypeManager.IsEnumType (t)){
552 Type real_type = TypeManager.TypeToCoreType (v.GetType ());
554 real_type = System.Enum.GetUnderlyingType (real_type);
556 Constant e = Constantify (v, real_type);
558 return new EnumConstant (e, t);
559 } else if (v == null && !TypeManager.IsValueType (t))
560 return NullLiteral.Null;
562 throw new Exception ("Unknown type for constant (" + t +
567 /// Returns a fully formed expression after a MemberLookup
569 public static Expression ExprClassFromMemberInfo (EmitContext ec, MemberInfo mi, Location loc)
572 return new EventExpr ((EventInfo) mi, loc);
573 else if (mi is FieldInfo)
574 return new FieldExpr ((FieldInfo) mi, loc);
575 else if (mi is PropertyInfo)
576 return new PropertyExpr (ec, (PropertyInfo) mi, loc);
577 else if (mi is Type){
578 return new TypeExpression ((System.Type) mi, loc);
584 protected static ArrayList almostMatchedMembers = new ArrayList (4);
587 // FIXME: Probably implement a cache for (t,name,current_access_set)?
589 // This code could use some optimizations, but we need to do some
590 // measurements. For example, we could use a delegate to `flag' when
591 // something can not any longer be a method-group (because it is something
595 // If the return value is an Array, then it is an array of
598 // If the return value is an MemberInfo, it is anything, but a Method
602 // FIXME: When calling MemberLookup inside an `Invocation', we should pass
603 // the arguments here and have MemberLookup return only the methods that
604 // match the argument count/type, unlike we are doing now (we delay this
607 // This is so we can catch correctly attempts to invoke instance methods
608 // from a static body (scan for error 120 in ResolveSimpleName).
611 // FIXME: Potential optimization, have a static ArrayList
614 public static Expression MemberLookup (EmitContext ec, Type queried_type, string name,
615 MemberTypes mt, BindingFlags bf, Location loc)
617 return MemberLookup (ec, ec.ContainerType, null, queried_type, name, mt, bf, loc);
621 // Lookup type `queried_type' for code in class `container_type' with a qualifier of
622 // `qualifier_type' or null to lookup members in the current class.
625 public static Expression MemberLookup (EmitContext ec, Type container_type,
626 Type qualifier_type, Type queried_type,
627 string name, MemberTypes mt,
628 BindingFlags bf, Location loc)
630 almostMatchedMembers.Clear ();
632 MemberInfo [] mi = TypeManager.MemberLookup (container_type, qualifier_type,
633 queried_type, mt, bf, name, almostMatchedMembers);
638 int count = mi.Length;
640 if (mi [0] is MethodBase)
641 return new MethodGroupExpr (mi, loc);
646 return ExprClassFromMemberInfo (ec, mi [0], loc);
649 public const MemberTypes AllMemberTypes =
650 MemberTypes.Constructor |
654 MemberTypes.NestedType |
655 MemberTypes.Property;
657 public const BindingFlags AllBindingFlags =
658 BindingFlags.Public |
659 BindingFlags.Static |
660 BindingFlags.Instance;
662 public static Expression MemberLookup (EmitContext ec, Type queried_type,
663 string name, Location loc)
665 return MemberLookup (ec, ec.ContainerType, null, queried_type, name,
666 AllMemberTypes, AllBindingFlags, loc);
669 public static Expression MemberLookup (EmitContext ec, Type qualifier_type,
670 Type queried_type, string name, Location loc)
672 return MemberLookup (ec, ec.ContainerType, qualifier_type, queried_type,
673 name, AllMemberTypes, AllBindingFlags, loc);
676 public static Expression MethodLookup (EmitContext ec, Type queried_type,
677 string name, Location loc)
679 return MemberLookup (ec, ec.ContainerType, null, queried_type, name,
680 MemberTypes.Method, AllBindingFlags, loc);
684 /// This is a wrapper for MemberLookup that is not used to "probe", but
685 /// to find a final definition. If the final definition is not found, we
686 /// look for private members and display a useful debugging message if we
689 public static Expression MemberLookupFinal (EmitContext ec, Type qualifier_type,
690 Type queried_type, string name, Location loc)
692 return MemberLookupFinal (ec, qualifier_type, queried_type, name,
693 AllMemberTypes, AllBindingFlags, loc);
696 public static Expression MemberLookupFinal (EmitContext ec, Type qualifier_type,
697 Type queried_type, string name,
698 MemberTypes mt, BindingFlags bf,
703 int errors = Report.Errors;
705 e = MemberLookup (ec, ec.ContainerType, qualifier_type, queried_type, name, mt, bf, loc);
707 if (e == null && errors == Report.Errors)
708 // No errors were reported by MemberLookup, but there was an error.
709 MemberLookupFailed (ec, qualifier_type, queried_type, name, null, loc);
714 public static void MemberLookupFailed (EmitContext ec, Type qualifier_type,
715 Type queried_type, string name,
716 string class_name, Location loc)
718 if (almostMatchedMembers.Count != 0) {
719 if (qualifier_type == null) {
720 foreach (MemberInfo m in almostMatchedMembers)
721 Report.Error (38, loc,
722 "Cannot access non-static member `{0}' via nested type `{1}'",
723 TypeManager.GetFullNameSignature (m),
724 TypeManager.CSharpName (ec.ContainerType));
728 if (qualifier_type != ec.ContainerType) {
729 // Although a derived class can access protected members of
730 // its base class it cannot do so through an instance of the
731 // base class (CS1540). If the qualifier_type is a base of the
732 // ec.ContainerType and the lookup succeeds with the latter one,
733 // then we are in this situation.
734 for (int i = 0; i < almostMatchedMembers.Count; ++i) {
735 MemberInfo m = (MemberInfo) almostMatchedMembers [i];
736 for (int j = 0; j < i; ++j) {
737 if (m == almostMatchedMembers [j]) {
745 Report.SymbolRelatedToPreviousError (m);
746 Report.Error (1540, loc,
747 "Cannot access protected member `{0}' via a qualifier of type `{1}';"
748 + " the qualifier must be of type `{2}' (or derived from it)",
749 TypeManager.GetFullNameSignature (m),
750 TypeManager.CSharpName (qualifier_type),
751 TypeManager.CSharpName (ec.ContainerType));
755 almostMatchedMembers.Clear ();
758 object lookup = TypeManager.MemberLookup (queried_type, null, queried_type,
759 AllMemberTypes, AllBindingFlags |
760 BindingFlags.NonPublic, name, null);
762 if (lookup == null) {
763 if (class_name != null)
764 Report.Error (103, loc, "The name `" + name + "' could not be " +
765 "found in `" + class_name + "'");
768 117, loc, "`" + queried_type + "' does not contain a " +
769 "definition for `" + name + "'");
773 if (name == ".ctor" && TypeManager.FindMembers (qualifier_type, MemberTypes.Constructor,
774 BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly, null, null).Count == 0)
776 Report.Error (143, loc, String.Format ("The type '{0}' has no constructors defined", TypeManager.CSharpName (queried_type)));
780 if (qualifier_type != null) {
781 Report.Error (122, loc, "'{0}' is inaccessible due to its protection level", TypeManager.CSharpName (qualifier_type) + "." + name);
783 Report.Error (122, loc, "'{0}' is inaccessible due to its protection level", name);
787 static public MemberInfo GetFieldFromEvent (EventExpr event_expr)
789 EventInfo ei = event_expr.EventInfo;
791 return TypeManager.GetPrivateFieldOfEvent (ei);
795 /// Returns an expression that can be used to invoke operator true
796 /// on the expression if it exists.
798 static public StaticCallExpr GetOperatorTrue (EmitContext ec, Expression e, Location loc)
800 return GetOperatorTrueOrFalse (ec, e, true, loc);
804 /// Returns an expression that can be used to invoke operator false
805 /// on the expression if it exists.
807 static public StaticCallExpr GetOperatorFalse (EmitContext ec, Expression e, Location loc)
809 return GetOperatorTrueOrFalse (ec, e, false, loc);
812 static StaticCallExpr GetOperatorTrueOrFalse (EmitContext ec, Expression e, bool is_true, Location loc)
815 Expression operator_group;
817 operator_group = MethodLookup (ec, e.Type, is_true ? "op_True" : "op_False", loc);
818 if (operator_group == null)
821 ArrayList arguments = new ArrayList ();
822 arguments.Add (new Argument (e, Argument.AType.Expression));
823 method = Invocation.OverloadResolve (
824 ec, (MethodGroupExpr) operator_group, arguments, false, loc);
829 return new StaticCallExpr ((MethodInfo) method, arguments, loc);
833 /// Resolves the expression `e' into a boolean expression: either through
834 /// an implicit conversion, or through an `operator true' invocation
836 public static Expression ResolveBoolean (EmitContext ec, Expression e, Location loc)
842 if (e.Type == TypeManager.bool_type)
845 Expression converted = Convert.ImplicitConversion (ec, e, TypeManager.bool_type, new Location (-1));
847 if (converted != null)
851 // If no implicit conversion to bool exists, try using `operator true'
853 Expression operator_true = Expression.GetOperatorTrue (ec, e, loc);
854 if (operator_true == null){
855 Report.Error (31, loc, "Can not convert the expression to a boolean");
858 return operator_true;
861 public string ExprClassName ()
864 case ExprClass.Invalid:
866 case ExprClass.Value:
868 case ExprClass.Variable:
870 case ExprClass.Namespace:
874 case ExprClass.MethodGroup:
875 return "method group";
876 case ExprClass.PropertyAccess:
877 return "property access";
878 case ExprClass.EventAccess:
879 return "event access";
880 case ExprClass.IndexerAccess:
881 return "indexer access";
882 case ExprClass.Nothing:
885 throw new Exception ("Should not happen");
889 /// Reports that we were expecting `expr' to be of class `expected'
891 public void Error_UnexpectedKind (string expected, Location loc)
893 Report.Error (118, loc, "Expression denotes a `" + ExprClassName () +
894 "' where a `" + expected + "' was expected");
897 public void Error_UnexpectedKind (ResolveFlags flags, Location loc)
899 ArrayList valid = new ArrayList (10);
901 if ((flags & ResolveFlags.VariableOrValue) != 0) {
902 valid.Add ("variable");
906 if ((flags & ResolveFlags.Type) != 0)
909 if ((flags & ResolveFlags.MethodGroup) != 0)
910 valid.Add ("method group");
912 if (valid.Count == 0)
913 valid.Add ("unknown");
915 StringBuilder sb = new StringBuilder ();
916 for (int i = 0; i < valid.Count; i++) {
919 else if (i == valid.Count)
921 sb.Append (valid [i]);
924 Report.Error (119, loc, "Expression denotes a `" + ExprClassName () + "' where " +
925 "a `" + sb.ToString () + "' was expected");
928 static public void Error_ConstantValueCannotBeConverted (Location l, string val, Type t)
930 Report.Error (31, l, "Constant value `" + val + "' cannot be converted to " +
931 TypeManager.CSharpName (t));
934 public static void UnsafeError (Location loc)
936 Report.Error (214, loc, "Pointers may only be used in an unsafe context");
940 /// Converts the IntConstant, UIntConstant, LongConstant or
941 /// ULongConstant into the integral target_type. Notice
942 /// that we do not return an `Expression' we do return
943 /// a boxed integral type.
945 /// FIXME: Since I added the new constants, we need to
946 /// also support conversions from CharConstant, ByteConstant,
947 /// SByteConstant, UShortConstant, ShortConstant
949 /// This is used by the switch statement, so the domain
950 /// of work is restricted to the literals above, and the
951 /// targets are int32, uint32, char, byte, sbyte, ushort,
952 /// short, uint64 and int64
954 public static object ConvertIntLiteral (Constant c, Type target_type, Location loc)
956 if (!Convert.ImplicitStandardConversionExists (Convert.ConstantEC, c, target_type)){
957 Convert.Error_CannotImplicitConversion (loc, c.Type, target_type);
963 if (c.Type == target_type)
964 return ((Constant) c).GetValue ();
967 // Make into one of the literals we handle, we dont really care
968 // about this value as we will just return a few limited types
970 if (c is EnumConstant)
971 c = ((EnumConstant)c).WidenToCompilerConstant ();
973 if (c is IntConstant){
974 int v = ((IntConstant) c).Value;
976 if (target_type == TypeManager.uint32_type){
979 } else if (target_type == TypeManager.char_type){
980 if (v >= Char.MinValue && v <= Char.MaxValue)
982 } else if (target_type == TypeManager.byte_type){
983 if (v >= Byte.MinValue && v <= Byte.MaxValue)
985 } else if (target_type == TypeManager.sbyte_type){
986 if (v >= SByte.MinValue && v <= SByte.MaxValue)
988 } else if (target_type == TypeManager.short_type){
989 if (v >= Int16.MinValue && v <= UInt16.MaxValue)
991 } else if (target_type == TypeManager.ushort_type){
992 if (v >= UInt16.MinValue && v <= UInt16.MaxValue)
994 } else if (target_type == TypeManager.int64_type)
996 else if (target_type == TypeManager.uint64_type){
1002 } else if (c is UIntConstant){
1003 uint v = ((UIntConstant) c).Value;
1005 if (target_type == TypeManager.int32_type){
1006 if (v <= Int32.MaxValue)
1008 } else if (target_type == TypeManager.char_type){
1009 if (v >= Char.MinValue && v <= Char.MaxValue)
1011 } else if (target_type == TypeManager.byte_type){
1012 if (v <= Byte.MaxValue)
1014 } else if (target_type == TypeManager.sbyte_type){
1015 if (v <= SByte.MaxValue)
1017 } else if (target_type == TypeManager.short_type){
1018 if (v <= UInt16.MaxValue)
1020 } else if (target_type == TypeManager.ushort_type){
1021 if (v <= UInt16.MaxValue)
1023 } else if (target_type == TypeManager.int64_type)
1025 else if (target_type == TypeManager.uint64_type)
1028 } else if (c is LongConstant){
1029 long v = ((LongConstant) c).Value;
1031 if (target_type == TypeManager.int32_type){
1032 if (v >= UInt32.MinValue && v <= UInt32.MaxValue)
1034 } else if (target_type == TypeManager.uint32_type){
1035 if (v >= 0 && v <= UInt32.MaxValue)
1037 } else if (target_type == TypeManager.char_type){
1038 if (v >= Char.MinValue && v <= Char.MaxValue)
1040 } else if (target_type == TypeManager.byte_type){
1041 if (v >= Byte.MinValue && v <= Byte.MaxValue)
1043 } else if (target_type == TypeManager.sbyte_type){
1044 if (v >= SByte.MinValue && v <= SByte.MaxValue)
1046 } else if (target_type == TypeManager.short_type){
1047 if (v >= Int16.MinValue && v <= UInt16.MaxValue)
1049 } else if (target_type == TypeManager.ushort_type){
1050 if (v >= UInt16.MinValue && v <= UInt16.MaxValue)
1052 } else if (target_type == TypeManager.uint64_type){
1057 } else if (c is ULongConstant){
1058 ulong v = ((ULongConstant) c).Value;
1060 if (target_type == TypeManager.int32_type){
1061 if (v <= Int32.MaxValue)
1063 } else if (target_type == TypeManager.uint32_type){
1064 if (v <= UInt32.MaxValue)
1066 } else if (target_type == TypeManager.char_type){
1067 if (v >= Char.MinValue && v <= Char.MaxValue)
1069 } else if (target_type == TypeManager.byte_type){
1070 if (v >= Byte.MinValue && v <= Byte.MaxValue)
1072 } else if (target_type == TypeManager.sbyte_type){
1073 if (v <= (int) SByte.MaxValue)
1075 } else if (target_type == TypeManager.short_type){
1076 if (v <= UInt16.MaxValue)
1078 } else if (target_type == TypeManager.ushort_type){
1079 if (v <= UInt16.MaxValue)
1081 } else if (target_type == TypeManager.int64_type){
1082 if (v <= Int64.MaxValue)
1086 } else if (c is ByteConstant){
1087 byte v = ((ByteConstant) c).Value;
1089 if (target_type == TypeManager.int32_type)
1091 else if (target_type == TypeManager.uint32_type)
1093 else if (target_type == TypeManager.char_type)
1095 else if (target_type == TypeManager.sbyte_type){
1096 if (v <= SByte.MaxValue)
1098 } else if (target_type == TypeManager.short_type)
1100 else if (target_type == TypeManager.ushort_type)
1102 else if (target_type == TypeManager.int64_type)
1104 else if (target_type == TypeManager.uint64_type)
1107 } else if (c is SByteConstant){
1108 sbyte v = ((SByteConstant) c).Value;
1110 if (target_type == TypeManager.int32_type)
1112 else if (target_type == TypeManager.uint32_type){
1115 } else if (target_type == TypeManager.char_type){
1118 } else if (target_type == TypeManager.byte_type){
1121 } else if (target_type == TypeManager.short_type)
1123 else if (target_type == TypeManager.ushort_type){
1126 } else if (target_type == TypeManager.int64_type)
1128 else if (target_type == TypeManager.uint64_type){
1133 } else if (c is ShortConstant){
1134 short v = ((ShortConstant) c).Value;
1136 if (target_type == TypeManager.int32_type){
1138 } else if (target_type == TypeManager.uint32_type){
1141 } else if (target_type == TypeManager.char_type){
1144 } else if (target_type == TypeManager.byte_type){
1145 if (v >= Byte.MinValue && v <= Byte.MaxValue)
1147 } else if (target_type == TypeManager.sbyte_type){
1148 if (v >= SByte.MinValue && v <= SByte.MaxValue)
1150 } else if (target_type == TypeManager.ushort_type){
1153 } else if (target_type == TypeManager.int64_type)
1155 else if (target_type == TypeManager.uint64_type)
1159 } else if (c is UShortConstant){
1160 ushort v = ((UShortConstant) c).Value;
1162 if (target_type == TypeManager.int32_type)
1164 else if (target_type == TypeManager.uint32_type)
1166 else if (target_type == TypeManager.char_type){
1167 if (v >= Char.MinValue && v <= Char.MaxValue)
1169 } else if (target_type == TypeManager.byte_type){
1170 if (v >= Byte.MinValue && v <= Byte.MaxValue)
1172 } else if (target_type == TypeManager.sbyte_type){
1173 if (v <= SByte.MaxValue)
1175 } else if (target_type == TypeManager.short_type){
1176 if (v <= Int16.MaxValue)
1178 } else if (target_type == TypeManager.int64_type)
1180 else if (target_type == TypeManager.uint64_type)
1184 } else if (c is CharConstant){
1185 char v = ((CharConstant) c).Value;
1187 if (target_type == TypeManager.int32_type)
1189 else if (target_type == TypeManager.uint32_type)
1191 else if (target_type == TypeManager.byte_type){
1192 if (v >= Byte.MinValue && v <= Byte.MaxValue)
1194 } else if (target_type == TypeManager.sbyte_type){
1195 if (v <= SByte.MaxValue)
1197 } else if (target_type == TypeManager.short_type){
1198 if (v <= Int16.MaxValue)
1200 } else if (target_type == TypeManager.ushort_type)
1202 else if (target_type == TypeManager.int64_type)
1204 else if (target_type == TypeManager.uint64_type)
1209 Error_ConstantValueCannotBeConverted (loc, s, target_type);
1214 // Load the object from the pointer.
1216 public static void LoadFromPtr (ILGenerator ig, Type t)
1218 if (t == TypeManager.int32_type)
1219 ig.Emit (OpCodes.Ldind_I4);
1220 else if (t == TypeManager.uint32_type)
1221 ig.Emit (OpCodes.Ldind_U4);
1222 else if (t == TypeManager.short_type)
1223 ig.Emit (OpCodes.Ldind_I2);
1224 else if (t == TypeManager.ushort_type)
1225 ig.Emit (OpCodes.Ldind_U2);
1226 else if (t == TypeManager.char_type)
1227 ig.Emit (OpCodes.Ldind_U2);
1228 else if (t == TypeManager.byte_type)
1229 ig.Emit (OpCodes.Ldind_U1);
1230 else if (t == TypeManager.sbyte_type)
1231 ig.Emit (OpCodes.Ldind_I1);
1232 else if (t == TypeManager.uint64_type)
1233 ig.Emit (OpCodes.Ldind_I8);
1234 else if (t == TypeManager.int64_type)
1235 ig.Emit (OpCodes.Ldind_I8);
1236 else if (t == TypeManager.float_type)
1237 ig.Emit (OpCodes.Ldind_R4);
1238 else if (t == TypeManager.double_type)
1239 ig.Emit (OpCodes.Ldind_R8);
1240 else if (t == TypeManager.bool_type)
1241 ig.Emit (OpCodes.Ldind_I1);
1242 else if (t == TypeManager.intptr_type)
1243 ig.Emit (OpCodes.Ldind_I);
1244 else if (TypeManager.IsEnumType (t)) {
1245 if (t == TypeManager.enum_type)
1246 ig.Emit (OpCodes.Ldind_Ref);
1248 LoadFromPtr (ig, TypeManager.EnumToUnderlying (t));
1249 } else if (t.IsValueType)
1250 ig.Emit (OpCodes.Ldobj, t);
1251 else if (t.IsPointer)
1252 ig.Emit (OpCodes.Ldind_I);
1254 ig.Emit (OpCodes.Ldind_Ref);
1258 // The stack contains the pointer and the value of type `type'
1260 public static void StoreFromPtr (ILGenerator ig, Type type)
1262 if (TypeManager.IsEnumType (type))
1263 type = TypeManager.EnumToUnderlying (type);
1264 if (type == TypeManager.int32_type || type == TypeManager.uint32_type)
1265 ig.Emit (OpCodes.Stind_I4);
1266 else if (type == TypeManager.int64_type || type == TypeManager.uint64_type)
1267 ig.Emit (OpCodes.Stind_I8);
1268 else if (type == TypeManager.char_type || type == TypeManager.short_type ||
1269 type == TypeManager.ushort_type)
1270 ig.Emit (OpCodes.Stind_I2);
1271 else if (type == TypeManager.float_type)
1272 ig.Emit (OpCodes.Stind_R4);
1273 else if (type == TypeManager.double_type)
1274 ig.Emit (OpCodes.Stind_R8);
1275 else if (type == TypeManager.byte_type || type == TypeManager.sbyte_type ||
1276 type == TypeManager.bool_type)
1277 ig.Emit (OpCodes.Stind_I1);
1278 else if (type == TypeManager.intptr_type)
1279 ig.Emit (OpCodes.Stind_I);
1280 else if (type.IsValueType)
1281 ig.Emit (OpCodes.Stobj, type);
1283 ig.Emit (OpCodes.Stind_Ref);
1287 // Returns the size of type `t' if known, otherwise, 0
1289 public static int GetTypeSize (Type t)
1291 t = TypeManager.TypeToCoreType (t);
1292 if (t == TypeManager.int32_type ||
1293 t == TypeManager.uint32_type ||
1294 t == TypeManager.float_type)
1296 else if (t == TypeManager.int64_type ||
1297 t == TypeManager.uint64_type ||
1298 t == TypeManager.double_type)
1300 else if (t == TypeManager.byte_type ||
1301 t == TypeManager.sbyte_type ||
1302 t == TypeManager.bool_type)
1304 else if (t == TypeManager.short_type ||
1305 t == TypeManager.char_type ||
1306 t == TypeManager.ushort_type)
1308 else if (t == TypeManager.decimal_type)
1314 public static void Error_NegativeArrayIndex (Location loc)
1316 Report.Error (248, loc, "Cannot create an array with a negative size");
1320 // Converts `source' to an int, uint, long or ulong.
1322 public Expression ExpressionToArrayArgument (EmitContext ec, Expression source, Location loc)
1326 bool old_checked = ec.CheckState;
1327 ec.CheckState = true;
1329 target = Convert.ImplicitConversion (ec, source, TypeManager.int32_type, loc);
1330 if (target == null){
1331 target = Convert.ImplicitConversion (ec, source, TypeManager.uint32_type, loc);
1332 if (target == null){
1333 target = Convert.ImplicitConversion (ec, source, TypeManager.int64_type, loc);
1334 if (target == null){
1335 target = Convert.ImplicitConversion (ec, source, TypeManager.uint64_type, loc);
1337 Convert.Error_CannotImplicitConversion (loc, source.Type, TypeManager.int32_type);
1341 ec.CheckState = old_checked;
1344 // Only positive constants are allowed at compile time
1346 if (target is Constant){
1347 if (target is IntConstant){
1348 if (((IntConstant) target).Value < 0){
1349 Error_NegativeArrayIndex (loc);
1354 if (target is LongConstant){
1355 if (((LongConstant) target).Value < 0){
1356 Error_NegativeArrayIndex (loc);
1369 /// This is just a base class for expressions that can
1370 /// appear on statements (invocations, object creation,
1371 /// assignments, post/pre increment and decrement). The idea
1372 /// being that they would support an extra Emition interface that
1373 /// does not leave a result on the stack.
1375 public abstract class ExpressionStatement : Expression {
1377 public virtual ExpressionStatement ResolveStatement (EmitContext ec)
1379 Expression e = Resolve (ec);
1383 ExpressionStatement es = e as ExpressionStatement;
1385 Error (201, "Only assignment, call, increment, decrement and new object " +
1386 "expressions can be used as a statement");
1392 /// Requests the expression to be emitted in a `statement'
1393 /// context. This means that no new value is left on the
1394 /// stack after invoking this method (constrasted with
1395 /// Emit that will always leave a value on the stack).
1397 public abstract void EmitStatement (EmitContext ec);
1401 /// This kind of cast is used to encapsulate the child
1402 /// whose type is child.Type into an expression that is
1403 /// reported to return "return_type". This is used to encapsulate
1404 /// expressions which have compatible types, but need to be dealt
1405 /// at higher levels with.
1407 /// For example, a "byte" expression could be encapsulated in one
1408 /// of these as an "unsigned int". The type for the expression
1409 /// would be "unsigned int".
1412 public class EmptyCast : Expression {
1413 protected Expression child;
1415 public Expression Child {
1421 public EmptyCast (Expression child, Type return_type)
1423 eclass = child.eclass;
1428 public override Expression DoResolve (EmitContext ec)
1430 // This should never be invoked, we are born in fully
1431 // initialized state.
1436 public override void Emit (EmitContext ec)
1443 // We need to special case this since an empty cast of
1444 // a NullLiteral is still a Constant
1446 public class NullCast : Constant {
1447 protected Expression child;
1449 public NullCast (Expression child, Type return_type)
1451 eclass = child.eclass;
1456 override public string AsString ()
1461 public override object GetValue ()
1466 public override Expression DoResolve (EmitContext ec)
1468 // This should never be invoked, we are born in fully
1469 // initialized state.
1474 public override void Emit (EmitContext ec)
1479 public override bool IsNegative {
1488 /// This class is used to wrap literals which belong inside Enums
1490 public class EnumConstant : Constant {
1491 public Constant Child;
1493 public EnumConstant (Constant child, Type enum_type)
1495 eclass = child.eclass;
1500 public override Expression DoResolve (EmitContext ec)
1502 // This should never be invoked, we are born in fully
1503 // initialized state.
1508 public override void Emit (EmitContext ec)
1513 public override object GetValue ()
1515 return Child.GetValue ();
1518 public object GetValueAsEnumType ()
1520 return System.Enum.ToObject (type, Child.GetValue ());
1524 // Converts from one of the valid underlying types for an enumeration
1525 // (int32, uint32, int64, uint64, short, ushort, byte, sbyte) to
1526 // one of the internal compiler literals: Int/UInt/Long/ULong Literals.
1528 public Constant WidenToCompilerConstant ()
1530 Type t = TypeManager.EnumToUnderlying (Child.Type);
1531 object v = ((Constant) Child).GetValue ();;
1533 if (t == TypeManager.int32_type)
1534 return new IntConstant ((int) v);
1535 if (t == TypeManager.uint32_type)
1536 return new UIntConstant ((uint) v);
1537 if (t == TypeManager.int64_type)
1538 return new LongConstant ((long) v);
1539 if (t == TypeManager.uint64_type)
1540 return new ULongConstant ((ulong) v);
1541 if (t == TypeManager.short_type)
1542 return new ShortConstant ((short) v);
1543 if (t == TypeManager.ushort_type)
1544 return new UShortConstant ((ushort) v);
1545 if (t == TypeManager.byte_type)
1546 return new ByteConstant ((byte) v);
1547 if (t == TypeManager.sbyte_type)
1548 return new SByteConstant ((sbyte) v);
1550 throw new Exception ("Invalid enumeration underlying type: " + t);
1554 // Extracts the value in the enumeration on its native representation
1556 public object GetPlainValue ()
1558 Type t = TypeManager.EnumToUnderlying (Child.Type);
1559 object v = ((Constant) Child).GetValue ();;
1561 if (t == TypeManager.int32_type)
1563 if (t == TypeManager.uint32_type)
1565 if (t == TypeManager.int64_type)
1567 if (t == TypeManager.uint64_type)
1569 if (t == TypeManager.short_type)
1571 if (t == TypeManager.ushort_type)
1573 if (t == TypeManager.byte_type)
1575 if (t == TypeManager.sbyte_type)
1581 public override string AsString ()
1583 return Child.AsString ();
1586 public override DoubleConstant ConvertToDouble ()
1588 return Child.ConvertToDouble ();
1591 public override FloatConstant ConvertToFloat ()
1593 return Child.ConvertToFloat ();
1596 public override ULongConstant ConvertToULong ()
1598 return Child.ConvertToULong ();
1601 public override LongConstant ConvertToLong ()
1603 return Child.ConvertToLong ();
1606 public override UIntConstant ConvertToUInt ()
1608 return Child.ConvertToUInt ();
1611 public override IntConstant ConvertToInt ()
1613 return Child.ConvertToInt ();
1616 public override bool IsZeroInteger {
1617 get { return Child.IsZeroInteger; }
1620 public override bool IsNegative {
1622 return Child.IsNegative;
1628 /// This kind of cast is used to encapsulate Value Types in objects.
1630 /// The effect of it is to box the value type emitted by the previous
1633 public class BoxedCast : EmptyCast {
1635 public BoxedCast (Expression expr)
1636 : base (expr, TypeManager.object_type)
1638 eclass = ExprClass.Value;
1641 public BoxedCast (Expression expr, Type target_type)
1642 : base (expr, target_type)
1644 eclass = ExprClass.Value;
1647 public override Expression DoResolve (EmitContext ec)
1649 // This should never be invoked, we are born in fully
1650 // initialized state.
1655 public override void Emit (EmitContext ec)
1659 ec.ig.Emit (OpCodes.Box, child.Type);
1663 public class UnboxCast : EmptyCast {
1664 public UnboxCast (Expression expr, Type return_type)
1665 : base (expr, return_type)
1669 public override Expression DoResolve (EmitContext ec)
1671 // This should never be invoked, we are born in fully
1672 // initialized state.
1677 public override void Emit (EmitContext ec)
1680 ILGenerator ig = ec.ig;
1683 ig.Emit (OpCodes.Unbox, t);
1685 LoadFromPtr (ig, t);
1690 /// This is used to perform explicit numeric conversions.
1692 /// Explicit numeric conversions might trigger exceptions in a checked
1693 /// context, so they should generate the conv.ovf opcodes instead of
1696 public class ConvCast : EmptyCast {
1697 public enum Mode : byte {
1698 I1_U1, I1_U2, I1_U4, I1_U8, I1_CH,
1700 I2_I1, I2_U1, I2_U2, I2_U4, I2_U8, I2_CH,
1701 U2_I1, U2_U1, U2_I2, U2_CH,
1702 I4_I1, I4_U1, I4_I2, I4_U2, I4_U4, I4_U8, I4_CH,
1703 U4_I1, U4_U1, U4_I2, U4_U2, U4_I4, U4_CH,
1704 I8_I1, I8_U1, I8_I2, I8_U2, I8_I4, I8_U4, I8_U8, I8_CH,
1705 U8_I1, U8_U1, U8_I2, U8_U2, U8_I4, U8_U4, U8_I8, U8_CH,
1706 CH_I1, CH_U1, CH_I2,
1707 R4_I1, R4_U1, R4_I2, R4_U2, R4_I4, R4_U4, R4_I8, R4_U8, R4_CH,
1708 R8_I1, R8_U1, R8_I2, R8_U2, R8_I4, R8_U4, R8_I8, R8_U8, R8_CH, R8_R4
1714 public ConvCast (EmitContext ec, Expression child, Type return_type, Mode m)
1715 : base (child, return_type)
1717 checked_state = ec.CheckState;
1721 public override Expression DoResolve (EmitContext ec)
1723 // This should never be invoked, we are born in fully
1724 // initialized state.
1729 public override string ToString ()
1731 return String.Format ("ConvCast ({0}, {1})", mode, child);
1734 public override void Emit (EmitContext ec)
1736 ILGenerator ig = ec.ig;
1742 case Mode.I1_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1743 case Mode.I1_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1744 case Mode.I1_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1745 case Mode.I1_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1746 case Mode.I1_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1748 case Mode.U1_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1749 case Mode.U1_CH: /* nothing */ break;
1751 case Mode.I2_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1752 case Mode.I2_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1753 case Mode.I2_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1754 case Mode.I2_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1755 case Mode.I2_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1756 case Mode.I2_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1758 case Mode.U2_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1759 case Mode.U2_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
1760 case Mode.U2_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
1761 case Mode.U2_CH: /* nothing */ break;
1763 case Mode.I4_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1764 case Mode.I4_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1765 case Mode.I4_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
1766 case Mode.I4_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1767 case Mode.I4_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1768 case Mode.I4_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1769 case Mode.I4_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1771 case Mode.U4_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1772 case Mode.U4_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
1773 case Mode.U4_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
1774 case Mode.U4_U2: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
1775 case Mode.U4_I4: ig.Emit (OpCodes.Conv_Ovf_I4_Un); break;
1776 case Mode.U4_CH: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
1778 case Mode.I8_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1779 case Mode.I8_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1780 case Mode.I8_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
1781 case Mode.I8_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1782 case Mode.I8_I4: ig.Emit (OpCodes.Conv_Ovf_I4); break;
1783 case Mode.I8_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1784 case Mode.I8_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1785 case Mode.I8_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1787 case Mode.U8_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1788 case Mode.U8_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
1789 case Mode.U8_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
1790 case Mode.U8_U2: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
1791 case Mode.U8_I4: ig.Emit (OpCodes.Conv_Ovf_I4_Un); break;
1792 case Mode.U8_U4: ig.Emit (OpCodes.Conv_Ovf_U4_Un); break;
1793 case Mode.U8_I8: ig.Emit (OpCodes.Conv_Ovf_I8_Un); break;
1794 case Mode.U8_CH: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
1796 case Mode.CH_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1797 case Mode.CH_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
1798 case Mode.CH_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
1800 case Mode.R4_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1801 case Mode.R4_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1802 case Mode.R4_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
1803 case Mode.R4_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1804 case Mode.R4_I4: ig.Emit (OpCodes.Conv_Ovf_I4); break;
1805 case Mode.R4_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1806 case Mode.R4_I8: ig.Emit (OpCodes.Conv_Ovf_I8); break;
1807 case Mode.R4_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1808 case Mode.R4_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1810 case Mode.R8_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1811 case Mode.R8_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1812 case Mode.R8_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
1813 case Mode.R8_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1814 case Mode.R8_I4: ig.Emit (OpCodes.Conv_Ovf_I4); break;
1815 case Mode.R8_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1816 case Mode.R8_I8: ig.Emit (OpCodes.Conv_Ovf_I8); break;
1817 case Mode.R8_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1818 case Mode.R8_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1819 case Mode.R8_R4: ig.Emit (OpCodes.Conv_R4); break;
1823 case Mode.I1_U1: ig.Emit (OpCodes.Conv_U1); break;
1824 case Mode.I1_U2: ig.Emit (OpCodes.Conv_U2); break;
1825 case Mode.I1_U4: ig.Emit (OpCodes.Conv_U4); break;
1826 case Mode.I1_U8: ig.Emit (OpCodes.Conv_I8); break;
1827 case Mode.I1_CH: ig.Emit (OpCodes.Conv_U2); break;
1829 case Mode.U1_I1: ig.Emit (OpCodes.Conv_I1); break;
1830 case Mode.U1_CH: ig.Emit (OpCodes.Conv_U2); break;
1832 case Mode.I2_I1: ig.Emit (OpCodes.Conv_I1); break;
1833 case Mode.I2_U1: ig.Emit (OpCodes.Conv_U1); break;
1834 case Mode.I2_U2: ig.Emit (OpCodes.Conv_U2); break;
1835 case Mode.I2_U4: ig.Emit (OpCodes.Conv_U4); break;
1836 case Mode.I2_U8: ig.Emit (OpCodes.Conv_I8); break;
1837 case Mode.I2_CH: ig.Emit (OpCodes.Conv_U2); break;
1839 case Mode.U2_I1: ig.Emit (OpCodes.Conv_I1); break;
1840 case Mode.U2_U1: ig.Emit (OpCodes.Conv_U1); break;
1841 case Mode.U2_I2: ig.Emit (OpCodes.Conv_I2); break;
1842 case Mode.U2_CH: /* nothing */ break;
1844 case Mode.I4_I1: ig.Emit (OpCodes.Conv_I1); break;
1845 case Mode.I4_U1: ig.Emit (OpCodes.Conv_U1); break;
1846 case Mode.I4_I2: ig.Emit (OpCodes.Conv_I2); break;
1847 case Mode.I4_U4: /* nothing */ break;
1848 case Mode.I4_U2: ig.Emit (OpCodes.Conv_U2); break;
1849 case Mode.I4_U8: ig.Emit (OpCodes.Conv_I8); break;
1850 case Mode.I4_CH: ig.Emit (OpCodes.Conv_U2); break;
1852 case Mode.U4_I1: ig.Emit (OpCodes.Conv_I1); break;
1853 case Mode.U4_U1: ig.Emit (OpCodes.Conv_U1); break;
1854 case Mode.U4_I2: ig.Emit (OpCodes.Conv_I2); break;
1855 case Mode.U4_U2: ig.Emit (OpCodes.Conv_U2); break;
1856 case Mode.U4_I4: /* nothing */ break;
1857 case Mode.U4_CH: ig.Emit (OpCodes.Conv_U2); break;
1859 case Mode.I8_I1: ig.Emit (OpCodes.Conv_I1); break;
1860 case Mode.I8_U1: ig.Emit (OpCodes.Conv_U1); break;
1861 case Mode.I8_I2: ig.Emit (OpCodes.Conv_I2); break;
1862 case Mode.I8_U2: ig.Emit (OpCodes.Conv_U2); break;
1863 case Mode.I8_I4: ig.Emit (OpCodes.Conv_I4); break;
1864 case Mode.I8_U4: ig.Emit (OpCodes.Conv_U4); break;
1865 case Mode.I8_U8: /* nothing */ break;
1866 case Mode.I8_CH: ig.Emit (OpCodes.Conv_U2); break;
1868 case Mode.U8_I1: ig.Emit (OpCodes.Conv_I1); break;
1869 case Mode.U8_U1: ig.Emit (OpCodes.Conv_U1); break;
1870 case Mode.U8_I2: ig.Emit (OpCodes.Conv_I2); break;
1871 case Mode.U8_U2: ig.Emit (OpCodes.Conv_U2); break;
1872 case Mode.U8_I4: ig.Emit (OpCodes.Conv_I4); break;
1873 case Mode.U8_U4: ig.Emit (OpCodes.Conv_U4); break;
1874 case Mode.U8_I8: /* nothing */ break;
1875 case Mode.U8_CH: ig.Emit (OpCodes.Conv_U2); break;
1877 case Mode.CH_I1: ig.Emit (OpCodes.Conv_I1); break;
1878 case Mode.CH_U1: ig.Emit (OpCodes.Conv_U1); break;
1879 case Mode.CH_I2: ig.Emit (OpCodes.Conv_I2); break;
1881 case Mode.R4_I1: ig.Emit (OpCodes.Conv_I1); break;
1882 case Mode.R4_U1: ig.Emit (OpCodes.Conv_U1); break;
1883 case Mode.R4_I2: ig.Emit (OpCodes.Conv_I2); break;
1884 case Mode.R4_U2: ig.Emit (OpCodes.Conv_U2); break;
1885 case Mode.R4_I4: ig.Emit (OpCodes.Conv_I4); break;
1886 case Mode.R4_U4: ig.Emit (OpCodes.Conv_U4); break;
1887 case Mode.R4_I8: ig.Emit (OpCodes.Conv_I8); break;
1888 case Mode.R4_U8: ig.Emit (OpCodes.Conv_U8); break;
1889 case Mode.R4_CH: ig.Emit (OpCodes.Conv_U2); break;
1891 case Mode.R8_I1: ig.Emit (OpCodes.Conv_I1); break;
1892 case Mode.R8_U1: ig.Emit (OpCodes.Conv_U1); break;
1893 case Mode.R8_I2: ig.Emit (OpCodes.Conv_I2); break;
1894 case Mode.R8_U2: ig.Emit (OpCodes.Conv_U2); break;
1895 case Mode.R8_I4: ig.Emit (OpCodes.Conv_I4); break;
1896 case Mode.R8_U4: ig.Emit (OpCodes.Conv_U4); break;
1897 case Mode.R8_I8: ig.Emit (OpCodes.Conv_I8); break;
1898 case Mode.R8_U8: ig.Emit (OpCodes.Conv_U8); break;
1899 case Mode.R8_CH: ig.Emit (OpCodes.Conv_U2); break;
1900 case Mode.R8_R4: ig.Emit (OpCodes.Conv_R4); break;
1906 public class OpcodeCast : EmptyCast {
1910 public OpcodeCast (Expression child, Type return_type, OpCode op)
1911 : base (child, return_type)
1915 second_valid = false;
1918 public OpcodeCast (Expression child, Type return_type, OpCode op, OpCode op2)
1919 : base (child, return_type)
1924 second_valid = true;
1927 public override Expression DoResolve (EmitContext ec)
1929 // This should never be invoked, we are born in fully
1930 // initialized state.
1935 public override void Emit (EmitContext ec)
1946 /// This kind of cast is used to encapsulate a child and cast it
1947 /// to the class requested
1949 public class ClassCast : EmptyCast {
1950 public ClassCast (Expression child, Type return_type)
1951 : base (child, return_type)
1956 public override Expression DoResolve (EmitContext ec)
1958 // This should never be invoked, we are born in fully
1959 // initialized state.
1964 public override void Emit (EmitContext ec)
1968 ec.ig.Emit (OpCodes.Castclass, type);
1974 /// SimpleName expressions are formed of a single word and only happen at the beginning
1975 /// of a dotted-name.
1977 public class SimpleName : Expression {
1980 public SimpleName (string name, Location l)
1986 public static void Error_ObjectRefRequired (EmitContext ec, Location l, string name)
1988 if (ec.IsFieldInitializer)
1991 "A field initializer cannot reference the non-static field, " +
1992 "method or property `"+name+"'");
1996 "An object reference is required " +
1997 "for the non-static field `"+name+"'");
2001 // Checks whether we are trying to access an instance
2002 // property, method or field from a static body.
2004 Expression MemberStaticCheck (EmitContext ec, Expression e)
2006 if (e is IMemberExpr){
2007 IMemberExpr member = (IMemberExpr) e;
2009 if (!member.IsStatic){
2010 Error_ObjectRefRequired (ec, loc, Name);
2018 public override Expression DoResolve (EmitContext ec)
2020 return SimpleNameResolve (ec, null, false, false);
2023 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
2025 return SimpleNameResolve (ec, right_side, false, false);
2029 public Expression DoResolveAllowStatic (EmitContext ec, bool intermediate)
2031 return SimpleNameResolve (ec, null, true, intermediate);
2034 public override FullNamedExpression ResolveAsTypeStep (EmitContext ec)
2036 DeclSpace ds = ec.DeclSpace;
2037 FullNamedExpression dt;
2039 int errors = Report.Errors;
2040 dt = ec.ResolvingTypeTree
2041 ? ds.FindType (loc, Name)
2042 : ds.LookupType (Name, true, loc);
2043 if (Report.Errors != errors)
2049 Expression SimpleNameResolve (EmitContext ec, Expression right_side,
2050 bool allow_static, bool intermediate)
2052 Expression e = DoSimpleNameResolve (ec, right_side, allow_static, intermediate);
2056 Block current_block = ec.CurrentBlock;
2057 if (current_block != null){
2058 if (current_block.IsVariableNameUsedInChildBlock (Name)) {
2059 Report.Error (135, Location,
2060 "'{0}' has a different meaning in a child block", Name);
2069 /// 7.5.2: Simple Names.
2071 /// Local Variables and Parameters are handled at
2072 /// parse time, so they never occur as SimpleNames.
2074 /// The `allow_static' flag is used by MemberAccess only
2075 /// and it is used to inform us that it is ok for us to
2076 /// avoid the static check, because MemberAccess might end
2077 /// up resolving the Name as a Type name and the access as
2078 /// a static type access.
2080 /// ie: Type Type; .... { Type.GetType (""); }
2082 /// Type is both an instance variable and a Type; Type.GetType
2083 /// is the static method not an instance method of type.
2085 Expression DoSimpleNameResolve (EmitContext ec, Expression right_side, bool allow_static, bool intermediate)
2087 Expression e = null;
2090 // Stage 1: Performed by the parser (binding to locals or parameters).
2092 Block current_block = ec.CurrentBlock;
2093 if (current_block != null){
2094 LocalInfo vi = current_block.GetLocalInfo (Name);
2098 var = new LocalVariableReference (ec.CurrentBlock, Name, loc);
2100 if (right_side != null)
2101 return var.ResolveLValue (ec, right_side);
2103 return var.Resolve (ec);
2106 ParameterReference pref = current_block.GetParameterReference (Name, loc);
2108 if (right_side != null)
2109 return pref.ResolveLValue (ec, right_side);
2111 return pref.Resolve (ec);
2116 // Stage 2: Lookup members
2119 DeclSpace lookup_ds = ec.DeclSpace;
2120 Type almost_matched_type = null;
2121 ArrayList almost_matched = null;
2123 if (lookup_ds.TypeBuilder == null)
2126 e = MemberLookup (ec, lookup_ds.TypeBuilder, Name, loc);
2130 if (almost_matched == null && almostMatchedMembers.Count > 0) {
2131 almost_matched_type = lookup_ds.TypeBuilder;
2132 almost_matched = (ArrayList) almostMatchedMembers.Clone ();
2135 lookup_ds =lookup_ds.Parent;
2136 } while (lookup_ds != null);
2138 if (e == null && ec.ContainerType != null)
2139 e = MemberLookup (ec, ec.ContainerType, Name, loc);
2142 if (almost_matched == null && almostMatchedMembers.Count > 0) {
2143 almost_matched_type = ec.ContainerType;
2144 almost_matched = (ArrayList) almostMatchedMembers.Clone ();
2146 e = ResolveAsTypeStep (ec);
2150 if (almost_matched != null)
2151 almostMatchedMembers = almost_matched;
2152 if (almost_matched_type == null)
2153 almost_matched_type = ec.ContainerType;
2154 MemberLookupFailed (ec, null, almost_matched_type, ((SimpleName) this).Name, ec.DeclSpace.Name, loc);
2161 if (e is IMemberExpr) {
2162 e = MemberAccess.ResolveMemberAccess (ec, e, null, loc, this);
2166 IMemberExpr me = e as IMemberExpr;
2170 // This fails if ResolveMemberAccess() was unable to decide whether
2171 // it's a field or a type of the same name.
2173 if (!me.IsStatic && (me.InstanceExpression == null))
2177 TypeManager.IsNestedFamilyAccessible (me.InstanceExpression.Type, me.DeclaringType) &&
2178 me.InstanceExpression.Type != me.DeclaringType &&
2179 !me.InstanceExpression.Type.IsSubclassOf (me.DeclaringType) &&
2180 (!intermediate || !MemberAccess.IdenticalNameAndTypeName (ec, this, e, loc))) {
2181 Error (38, "Cannot access nonstatic member `" + me.Name + "' of " +
2182 "outer type `" + me.DeclaringType + "' via nested type `" +
2183 me.InstanceExpression.Type + "'");
2187 return (right_side != null)
2188 ? e.DoResolveLValue (ec, right_side)
2192 if (ec.IsStatic || ec.IsFieldInitializer){
2196 return MemberStaticCheck (ec, e);
2201 public override void Emit (EmitContext ec)
2204 // If this is ever reached, then we failed to
2205 // find the name as a namespace
2208 Error (103, "The name `" + Name +
2209 "' does not exist in the class `" +
2210 ec.DeclSpace.Name + "'");
2213 public override string ToString ()
2220 /// Represents a namespace or a type. The name of the class was inspired by
2221 /// section 10.8.1 (Fully Qualified Names).
2223 public abstract class FullNamedExpression : Expression {
2224 public override FullNamedExpression ResolveAsTypeStep (EmitContext ec)
2229 public abstract string FullName {
2235 /// Fully resolved expression that evaluates to a type
2237 public abstract class TypeExpr : FullNamedExpression {
2238 override public FullNamedExpression ResolveAsTypeStep (EmitContext ec)
2240 TypeExpr t = DoResolveAsTypeStep (ec);
2244 eclass = ExprClass.Type;
2248 override public Expression DoResolve (EmitContext ec)
2250 return ResolveAsTypeTerminal (ec, false);
2253 override public void Emit (EmitContext ec)
2255 throw new Exception ("Should never be called");
2258 public virtual bool CheckAccessLevel (DeclSpace ds)
2260 return ds.CheckAccessLevel (Type);
2263 public virtual bool AsAccessible (DeclSpace ds, int flags)
2265 return ds.AsAccessible (Type, flags);
2268 public virtual bool IsClass {
2269 get { return Type.IsClass; }
2272 public virtual bool IsValueType {
2273 get { return Type.IsValueType; }
2276 public virtual bool IsInterface {
2277 get { return Type.IsInterface; }
2280 public virtual bool IsSealed {
2281 get { return Type.IsSealed; }
2284 public virtual bool CanInheritFrom ()
2286 if (Type == TypeManager.enum_type ||
2287 (Type == TypeManager.value_type && RootContext.StdLib) ||
2288 Type == TypeManager.multicast_delegate_type ||
2289 Type == TypeManager.delegate_type ||
2290 Type == TypeManager.array_type)
2296 public virtual bool IsAttribute {
2298 return Type == TypeManager.attribute_type ||
2299 Type.IsSubclassOf (TypeManager.attribute_type);
2303 public abstract TypeExpr DoResolveAsTypeStep (EmitContext ec);
2305 public virtual Type ResolveType (EmitContext ec)
2307 TypeExpr t = ResolveAsTypeTerminal (ec, false);
2314 public abstract string Name {
2318 public override bool Equals (object obj)
2320 TypeExpr tobj = obj as TypeExpr;
2324 return Type == tobj.Type;
2327 public override int GetHashCode ()
2329 return Type.GetHashCode ();
2332 public override string ToString ()
2338 public class TypeExpression : TypeExpr {
2339 public TypeExpression (Type t, Location l)
2342 eclass = ExprClass.Type;
2346 public override TypeExpr DoResolveAsTypeStep (EmitContext ec)
2351 public override string Name {
2353 return Type.ToString ();
2357 public override string FullName {
2359 return Type.FullName;
2365 /// Used to create types from a fully qualified name. These are just used
2366 /// by the parser to setup the core types. A TypeLookupExpression is always
2367 /// classified as a type.
2369 public class TypeLookupExpression : TypeExpr {
2372 public TypeLookupExpression (string name)
2377 public override TypeExpr DoResolveAsTypeStep (EmitContext ec)
2380 FullNamedExpression t = ec.DeclSpace.LookupType (name, false, Location.Null);
2383 if (!(t is TypeExpr))
2385 type = ((TypeExpr) t).ResolveType (ec);
2391 public override string Name {
2397 public override string FullName {
2404 public class TypeAliasExpression : TypeExpr {
2407 public TypeAliasExpression (TypeExpr texpr, Location l)
2410 loc = texpr.Location;
2412 eclass = ExprClass.Type;
2415 public override string Name {
2416 get { return texpr.Name; }
2419 public override string FullName {
2420 get { return texpr.FullName; }
2423 public override TypeExpr DoResolveAsTypeStep (EmitContext ec)
2425 Type type = texpr.ResolveType (ec);
2429 return new TypeExpression (type, loc);
2432 public override bool CheckAccessLevel (DeclSpace ds)
2434 return texpr.CheckAccessLevel (ds);
2437 public override bool AsAccessible (DeclSpace ds, int flags)
2439 return texpr.AsAccessible (ds, flags);
2442 public override bool IsClass {
2443 get { return texpr.IsClass; }
2446 public override bool IsValueType {
2447 get { return texpr.IsValueType; }
2450 public override bool IsInterface {
2451 get { return texpr.IsInterface; }
2454 public override bool IsSealed {
2455 get { return texpr.IsSealed; }
2458 public override bool IsAttribute {
2459 get { return texpr.IsAttribute; }
2464 /// MethodGroup Expression.
2466 /// This is a fully resolved expression that evaluates to a type
2468 public class MethodGroupExpr : Expression, IMemberExpr {
2469 public MethodBase [] Methods;
2470 Expression instance_expression = null;
2471 bool is_explicit_impl = false;
2472 bool identical_type_name = false;
2475 public MethodGroupExpr (MemberInfo [] mi, Location l)
2477 Methods = new MethodBase [mi.Length];
2478 mi.CopyTo (Methods, 0);
2479 eclass = ExprClass.MethodGroup;
2480 type = TypeManager.object_type;
2484 public MethodGroupExpr (ArrayList list, Location l)
2486 Methods = new MethodBase [list.Count];
2489 list.CopyTo (Methods, 0);
2491 foreach (MemberInfo m in list){
2492 if (!(m is MethodBase)){
2493 Console.WriteLine ("Name " + m.Name);
2494 Console.WriteLine ("Found a: " + m.GetType ().FullName);
2501 eclass = ExprClass.MethodGroup;
2502 type = TypeManager.object_type;
2505 public Type DeclaringType {
2508 // The methods are arranged in this order:
2509 // derived type -> base type
2511 return Methods [0].DeclaringType;
2516 // `A method group may have associated an instance expression'
2518 public Expression InstanceExpression {
2520 return instance_expression;
2524 instance_expression = value;
2528 public bool IsExplicitImpl {
2530 return is_explicit_impl;
2534 is_explicit_impl = value;
2538 public bool IdenticalTypeName {
2540 return identical_type_name;
2544 identical_type_name = value;
2548 public bool IsBase {
2557 public string Name {
2559 return Methods [0].Name;
2563 public bool IsInstance {
2565 foreach (MethodBase mb in Methods)
2573 public bool IsStatic {
2575 foreach (MethodBase mb in Methods)
2583 override public Expression DoResolve (EmitContext ec)
2586 instance_expression = null;
2588 if (instance_expression != null) {
2589 instance_expression = instance_expression.DoResolve (ec);
2590 if (instance_expression == null)
2597 public void ReportUsageError ()
2599 Report.Error (654, loc, "Method `" + DeclaringType + "." +
2600 Name + "()' is referenced without parentheses");
2603 override public void Emit (EmitContext ec)
2605 ReportUsageError ();
2608 bool RemoveMethods (bool keep_static)
2610 ArrayList smethods = new ArrayList ();
2612 foreach (MethodBase mb in Methods){
2613 if (mb.IsStatic == keep_static)
2617 if (smethods.Count == 0)
2620 Methods = new MethodBase [smethods.Count];
2621 smethods.CopyTo (Methods, 0);
2627 /// Removes any instance methods from the MethodGroup, returns
2628 /// false if the resulting set is empty.
2630 public bool RemoveInstanceMethods ()
2632 return RemoveMethods (true);
2636 /// Removes any static methods from the MethodGroup, returns
2637 /// false if the resulting set is empty.
2639 public bool RemoveStaticMethods ()
2641 return RemoveMethods (false);
2646 /// Fully resolved expression that evaluates to a Field
2648 public class FieldExpr : Expression, IAssignMethod, IMemoryLocation, IMemberExpr, IVariable {
2649 public readonly FieldInfo FieldInfo;
2650 Expression instance_expr;
2651 VariableInfo variable_info;
2653 LocalTemporary temp;
2656 public FieldExpr (FieldInfo fi, Location l)
2659 eclass = ExprClass.Variable;
2660 type = fi.FieldType;
2664 public string Name {
2666 return FieldInfo.Name;
2670 public bool IsInstance {
2672 return !FieldInfo.IsStatic;
2676 public bool IsStatic {
2678 return FieldInfo.IsStatic;
2682 public Type DeclaringType {
2684 return FieldInfo.DeclaringType;
2688 public Expression InstanceExpression {
2690 return instance_expr;
2694 instance_expr = value;
2698 public VariableInfo VariableInfo {
2700 return variable_info;
2704 override public Expression DoResolve (EmitContext ec)
2706 if (!FieldInfo.IsStatic){
2707 if (instance_expr == null){
2709 // This can happen when referencing an instance field using
2710 // a fully qualified type expression: TypeName.InstanceField = xxx
2712 SimpleName.Error_ObjectRefRequired (ec, loc, FieldInfo.Name);
2716 // Resolve the field's instance expression while flow analysis is turned
2717 // off: when accessing a field "a.b", we must check whether the field
2718 // "a.b" is initialized, not whether the whole struct "a" is initialized.
2719 instance_expr = instance_expr.Resolve (ec, ResolveFlags.VariableOrValue |
2720 ResolveFlags.DisableFlowAnalysis);
2721 if (instance_expr == null)
2725 ObsoleteAttribute oa;
2726 FieldBase f = TypeManager.GetField (FieldInfo);
2728 oa = f.GetObsoleteAttribute (f.Parent);
2730 AttributeTester.Report_ObsoleteMessage (oa, f.GetSignatureForError (), loc);
2732 // To be sure that type is external because we do not register generated fields
2733 } else if (!(FieldInfo.DeclaringType is TypeBuilder)) {
2734 oa = AttributeTester.GetMemberObsoleteAttribute (FieldInfo);
2736 AttributeTester.Report_ObsoleteMessage (oa, TypeManager.GetFullNameSignature (FieldInfo), loc);
2739 if (ec.CurrentAnonymousMethod != null){
2740 if (!FieldInfo.IsStatic){
2741 if (ec.TypeContainer is Struct){
2742 Report.Error (1673, loc, "Can not reference instance variables in anonymous methods hosted in structs");
2745 ec.CaptureField (this);
2749 // If the instance expression is a local variable or parameter.
2750 IVariable var = instance_expr as IVariable;
2751 if ((var == null) || (var.VariableInfo == null))
2754 VariableInfo vi = var.VariableInfo;
2755 if (!vi.IsFieldAssigned (ec, FieldInfo.Name, loc))
2758 variable_info = vi.GetSubStruct (FieldInfo.Name);
2762 void Report_AssignToReadonly (bool is_instance)
2767 msg = "Readonly field can not be assigned outside " +
2768 "of constructor or variable initializer";
2770 msg = "A static readonly field can only be assigned in " +
2771 "a static constructor";
2773 Report.Error (is_instance ? 191 : 198, loc, msg);
2776 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
2778 IVariable var = instance_expr as IVariable;
2779 if ((var != null) && (var.VariableInfo != null))
2780 var.VariableInfo.SetFieldAssigned (ec, FieldInfo.Name);
2782 Expression e = DoResolve (ec);
2787 if (!FieldInfo.IsStatic && (instance_expr.Type.IsValueType && !(instance_expr is IMemoryLocation))) {
2788 // FIXME: Provide better error reporting.
2789 Error (1612, "Cannot modify expression because it is not a variable.");
2793 if (!FieldInfo.IsInitOnly)
2796 FieldBase fb = TypeManager.GetField (FieldInfo);
2801 // InitOnly fields can only be assigned in constructors
2804 if (ec.IsConstructor){
2805 if (IsStatic && !ec.IsStatic)
2806 Report_AssignToReadonly (false);
2808 if (ec.ContainerType == FieldInfo.DeclaringType)
2812 Report_AssignToReadonly (!IsStatic);
2817 public override void CheckMarshallByRefAccess (Type container)
2819 if (!IsStatic && Type.IsValueType && !container.IsSubclassOf (TypeManager.mbr_type) && DeclaringType.IsSubclassOf (TypeManager.mbr_type)) {
2820 Report.SymbolRelatedToPreviousError (DeclaringType);
2821 Report.Error (1690, loc, "Cannot call '{0}' method, property, or indexer because it is a value type member of a marshal-by-reference class", Name);
2825 public bool VerifyFixed (bool is_expression)
2827 IVariable variable = instance_expr as IVariable;
2828 if ((variable == null) || !variable.VerifyFixed (true))
2834 public void Emit (EmitContext ec, bool leave_copy)
2836 ILGenerator ig = ec.ig;
2837 bool is_volatile = false;
2839 if (FieldInfo is FieldBuilder){
2840 FieldBase f = TypeManager.GetField (FieldInfo);
2842 if ((f.ModFlags & Modifiers.VOLATILE) != 0)
2845 f.status |= Field.Status.USED;
2849 if (FieldInfo.IsStatic){
2851 ig.Emit (OpCodes.Volatile);
2853 ig.Emit (OpCodes.Ldsfld, FieldInfo);
2859 ig.Emit (OpCodes.Volatile);
2861 ig.Emit (OpCodes.Ldfld, FieldInfo);
2865 ec.ig.Emit (OpCodes.Dup);
2866 if (!FieldInfo.IsStatic) {
2867 temp = new LocalTemporary (ec, this.Type);
2873 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
2875 FieldAttributes fa = FieldInfo.Attributes;
2876 bool is_static = (fa & FieldAttributes.Static) != 0;
2877 bool is_readonly = (fa & FieldAttributes.InitOnly) != 0;
2878 ILGenerator ig = ec.ig;
2879 prepared = prepare_for_load;
2881 if (is_readonly && !ec.IsConstructor){
2882 Report_AssignToReadonly (!is_static);
2888 if (prepare_for_load)
2889 ig.Emit (OpCodes.Dup);
2894 ec.ig.Emit (OpCodes.Dup);
2895 if (!FieldInfo.IsStatic) {
2896 temp = new LocalTemporary (ec, this.Type);
2901 if (FieldInfo is FieldBuilder){
2902 FieldBase f = TypeManager.GetField (FieldInfo);
2904 if ((f.ModFlags & Modifiers.VOLATILE) != 0)
2905 ig.Emit (OpCodes.Volatile);
2907 f.status |= Field.Status.ASSIGNED;
2912 ig.Emit (OpCodes.Stsfld, FieldInfo);
2914 ig.Emit (OpCodes.Stfld, FieldInfo);
2920 void EmitInstance (EmitContext ec)
2922 if (instance_expr.Type.IsValueType) {
2923 if (instance_expr is IMemoryLocation) {
2924 ((IMemoryLocation) instance_expr).AddressOf (ec, AddressOp.LoadStore);
2926 LocalTemporary t = new LocalTemporary (ec, instance_expr.Type);
2927 instance_expr.Emit (ec);
2929 t.AddressOf (ec, AddressOp.Store);
2932 instance_expr.Emit (ec);
2935 public override void Emit (EmitContext ec)
2940 public void AddressOf (EmitContext ec, AddressOp mode)
2942 ILGenerator ig = ec.ig;
2944 if (FieldInfo is FieldBuilder){
2945 FieldBase f = TypeManager.GetField (FieldInfo);
2947 if ((f.ModFlags & Modifiers.VOLATILE) != 0){
2948 Error (676, "volatile variable: can not take its address, or pass as ref/out parameter");
2952 if ((mode & AddressOp.Store) != 0)
2953 f.status |= Field.Status.ASSIGNED;
2954 if ((mode & AddressOp.Load) != 0)
2955 f.status |= Field.Status.USED;
2960 // Handle initonly fields specially: make a copy and then
2961 // get the address of the copy.
2964 if (FieldInfo.IsInitOnly){
2966 if (ec.IsConstructor){
2967 if (FieldInfo.IsStatic){
2979 local = ig.DeclareLocal (type);
2980 ig.Emit (OpCodes.Stloc, local);
2981 ig.Emit (OpCodes.Ldloca, local);
2986 if (FieldInfo.IsStatic){
2987 ig.Emit (OpCodes.Ldsflda, FieldInfo);
2990 ig.Emit (OpCodes.Ldflda, FieldInfo);
2996 // A FieldExpr whose address can not be taken
2998 public class FieldExprNoAddress : FieldExpr, IMemoryLocation {
2999 public FieldExprNoAddress (FieldInfo fi, Location loc) : base (fi, loc)
3003 public new void AddressOf (EmitContext ec, AddressOp mode)
3005 Report.Error (-215, "Report this: Taking the address of a remapped parameter not supported");
3010 /// Expression that evaluates to a Property. The Assign class
3011 /// might set the `Value' expression if we are in an assignment.
3013 /// This is not an LValue because we need to re-write the expression, we
3014 /// can not take data from the stack and store it.
3016 public class PropertyExpr : ExpressionStatement, IAssignMethod, IMemberExpr {
3017 public readonly PropertyInfo PropertyInfo;
3020 // This is set externally by the `BaseAccess' class
3023 MethodInfo getter, setter;
3026 Expression instance_expr;
3027 LocalTemporary temp;
3030 internal static PtrHashtable AccessorTable = new PtrHashtable ();
3032 public PropertyExpr (EmitContext ec, PropertyInfo pi, Location l)
3035 eclass = ExprClass.PropertyAccess;
3039 type = TypeManager.TypeToCoreType (pi.PropertyType);
3041 ResolveAccessors (ec);
3044 public string Name {
3046 return PropertyInfo.Name;
3050 public bool IsInstance {
3056 public bool IsStatic {
3062 public Type DeclaringType {
3064 return PropertyInfo.DeclaringType;
3069 // The instance expression associated with this expression
3071 public Expression InstanceExpression {
3073 instance_expr = value;
3077 return instance_expr;
3081 public bool VerifyAssignable ()
3083 if (setter == null) {
3084 Report.Error (200, loc,
3085 "The property `" + PropertyInfo.Name +
3086 "' can not be assigned to, as it has not set accessor");
3093 void FindAccessors (Type invocation_type)
3095 BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic |
3096 BindingFlags.Static | BindingFlags.Instance |
3097 BindingFlags.DeclaredOnly;
3099 Type current = PropertyInfo.DeclaringType;
3100 for (; current != null; current = current.BaseType) {
3101 MemberInfo[] group = TypeManager.MemberLookup (
3102 invocation_type, invocation_type, current,
3103 MemberTypes.Property, flags, PropertyInfo.Name, null);
3108 if (group.Length != 1)
3109 // Oooops, can this ever happen ?
3112 PropertyInfo pi = (PropertyInfo) group [0];
3115 getter = pi.GetGetMethod (true);
3118 setter = pi.GetSetMethod (true);
3120 MethodInfo accessor = getter != null ? getter : setter;
3122 if (!accessor.IsVirtual)
3128 // We also perform the permission checking here, as the PropertyInfo does not
3129 // hold the information for the accessibility of its setter/getter
3131 void ResolveAccessors (EmitContext ec)
3133 FindAccessors (ec.ContainerType);
3135 if (getter != null) {
3136 AccessorTable [getter] = PropertyInfo;
3137 is_static = getter.IsStatic;
3140 if (setter != null) {
3141 AccessorTable [setter] = PropertyInfo;
3142 is_static = setter.IsStatic;
3146 bool InstanceResolve (EmitContext ec, bool must_do_cs1540_check)
3148 if ((instance_expr == null) && ec.IsStatic && !is_static) {
3149 SimpleName.Error_ObjectRefRequired (ec, loc, PropertyInfo.Name);
3153 if (instance_expr != null) {
3154 instance_expr = instance_expr.DoResolve (ec);
3155 if (instance_expr == null)
3158 instance_expr.CheckMarshallByRefAccess (ec.ContainerType);
3161 if (must_do_cs1540_check && (instance_expr != null)) {
3162 if ((instance_expr.Type != ec.ContainerType) &&
3163 ec.ContainerType.IsSubclassOf (instance_expr.Type)) {
3164 Report.Error (1540, loc, "Cannot access protected member `" +
3165 PropertyInfo.DeclaringType + "." + PropertyInfo.Name +
3166 "' via a qualifier of type `" +
3167 TypeManager.CSharpName (instance_expr.Type) +
3168 "'; the qualifier must be of type `" +
3169 TypeManager.CSharpName (ec.ContainerType) +
3170 "' (or derived from it)");
3178 override public Expression DoResolve (EmitContext ec)
3180 if (getter != null){
3181 if (TypeManager.GetArgumentTypes (getter).Length != 0){
3183 117, loc, "`{0}' does not contain a " +
3184 "definition for `{1}'.", getter.DeclaringType,
3190 if (getter == null){
3192 // The following condition happens if the PropertyExpr was
3193 // created, but is invalid (ie, the property is inaccessible),
3194 // and we did not want to embed the knowledge about this in
3195 // the caller routine. This only avoids double error reporting.
3200 Report.Error (154, loc,
3201 "The property `" + PropertyInfo.Name +
3202 "' can not be used in " +
3203 "this context because it lacks a get accessor");
3207 bool must_do_cs1540_check;
3208 if (!IsAccessorAccessible (ec.ContainerType, getter, out must_do_cs1540_check)) {
3209 Report.Error (122, loc, "'{0}.get' is inaccessible due to its protection level", PropertyInfo.Name);
3213 if (!InstanceResolve (ec, must_do_cs1540_check))
3217 // Only base will allow this invocation to happen.
3219 if (IsBase && getter.IsAbstract){
3220 Report.Error (205, loc, "Cannot call an abstract base property: " +
3221 PropertyInfo.DeclaringType + "." +PropertyInfo.Name);
3228 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
3230 if (setter == null){
3232 // The following condition happens if the PropertyExpr was
3233 // created, but is invalid (ie, the property is inaccessible),
3234 // and we did not want to embed the knowledge about this in
3235 // the caller routine. This only avoids double error reporting.
3240 Report.Error (154, loc,
3241 "The property `" + PropertyInfo.Name +
3242 "' can not be used in " +
3243 "this context because it lacks a set accessor");
3247 if (TypeManager.GetArgumentTypes (setter).Length != 1){
3249 117, loc, "`{0}' does not contain a " +
3250 "definition for `{1}'.", getter.DeclaringType,
3255 bool must_do_cs1540_check;
3256 if (!IsAccessorAccessible (ec.ContainerType, setter, out must_do_cs1540_check)) {
3257 Report.Error (122, loc, "'{0}.set' is inaccessible due to its protection level", PropertyInfo.Name);
3261 if (!InstanceResolve (ec, must_do_cs1540_check))
3265 // Only base will allow this invocation to happen.
3267 if (IsBase && setter.IsAbstract){
3268 Report.Error (205, loc, "Cannot call an abstract base property: " +
3269 PropertyInfo.DeclaringType + "." +PropertyInfo.Name);
3274 // Check that we are not making changes to a temporary memory location
3276 if (instance_expr != null && instance_expr.Type.IsValueType && !(instance_expr is IMemoryLocation)) {
3277 // FIXME: Provide better error reporting.
3278 Error (1612, "Cannot modify expression because it is not a variable.");
3287 public override void Emit (EmitContext ec)
3292 void EmitInstance (EmitContext ec)
3297 if (instance_expr.Type.IsValueType) {
3298 if (instance_expr is IMemoryLocation) {
3299 ((IMemoryLocation) instance_expr).AddressOf (ec, AddressOp.LoadStore);
3301 LocalTemporary t = new LocalTemporary (ec, instance_expr.Type);
3302 instance_expr.Emit (ec);
3304 t.AddressOf (ec, AddressOp.Store);
3307 instance_expr.Emit (ec);
3310 ec.ig.Emit (OpCodes.Dup);
3314 public void Emit (EmitContext ec, bool leave_copy)
3320 // Special case: length of single dimension array property is turned into ldlen
3322 if ((getter == TypeManager.system_int_array_get_length) ||
3323 (getter == TypeManager.int_array_get_length)){
3324 Type iet = instance_expr.Type;
3327 // System.Array.Length can be called, but the Type does not
3328 // support invoking GetArrayRank, so test for that case first
3330 if (iet != TypeManager.array_type && (iet.GetArrayRank () == 1)) {
3331 ec.ig.Emit (OpCodes.Ldlen);
3332 ec.ig.Emit (OpCodes.Conv_I4);
3337 Invocation.EmitCall (ec, IsBase, IsStatic, new EmptyAddressOf (), getter, null, loc);
3342 ec.ig.Emit (OpCodes.Dup);
3344 temp = new LocalTemporary (ec, this.Type);
3350 // Implements the IAssignMethod interface for assignments
3352 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
3354 prepared = prepare_for_load;
3360 ec.ig.Emit (OpCodes.Dup);
3362 temp = new LocalTemporary (ec, this.Type);
3367 ArrayList args = new ArrayList (1);
3368 args.Add (new Argument (new EmptyAddressOf (), Argument.AType.Expression));
3370 Invocation.EmitCall (ec, IsBase, IsStatic, new EmptyAddressOf (), setter, args, loc);
3376 override public void EmitStatement (EmitContext ec)
3379 ec.ig.Emit (OpCodes.Pop);
3384 /// Fully resolved expression that evaluates to an Event
3386 public class EventExpr : Expression, IMemberExpr {
3387 public readonly EventInfo EventInfo;
3388 Expression instance_expr;
3391 MethodInfo add_accessor, remove_accessor;
3393 public EventExpr (EventInfo ei, Location loc)
3397 eclass = ExprClass.EventAccess;
3399 add_accessor = TypeManager.GetAddMethod (ei);
3400 remove_accessor = TypeManager.GetRemoveMethod (ei);
3402 if (add_accessor.IsStatic || remove_accessor.IsStatic)
3405 if (EventInfo is MyEventBuilder){
3406 MyEventBuilder eb = (MyEventBuilder) EventInfo;
3407 type = eb.EventType;
3410 type = EventInfo.EventHandlerType;
3413 public string Name {
3415 return EventInfo.Name;
3419 public bool IsInstance {
3425 public bool IsStatic {
3431 public Type DeclaringType {
3433 return EventInfo.DeclaringType;
3437 public Expression InstanceExpression {
3439 return instance_expr;
3443 instance_expr = value;
3447 bool InstanceResolve (EmitContext ec, bool must_do_cs1540_check)
3449 if ((instance_expr == null) && ec.IsStatic && !is_static) {
3450 SimpleName.Error_ObjectRefRequired (ec, loc, EventInfo.Name);
3454 if (instance_expr != null) {
3455 instance_expr = instance_expr.DoResolve (ec);
3456 if (instance_expr == null)
3461 // This is using the same mechanism as the CS1540 check in PropertyExpr.
3462 // However, in the Event case, we reported a CS0122 instead.
3464 if (must_do_cs1540_check && (instance_expr != null)) {
3465 if ((instance_expr.Type != ec.ContainerType) &&
3466 ec.ContainerType.IsSubclassOf (instance_expr.Type)) {
3467 Report.Error (122, loc, "'{0}' is inaccessible due to its protection level",
3468 DeclaringType.Name + "." + EventInfo.Name);
3477 public override Expression DoResolve (EmitContext ec)
3479 if (instance_expr != null) {
3480 instance_expr = instance_expr.DoResolve (ec);
3481 if (instance_expr == null)
3485 bool must_do_cs1540_check;
3486 if (!(IsAccessorAccessible (ec.ContainerType, add_accessor, out must_do_cs1540_check)
3487 && IsAccessorAccessible (ec.ContainerType, remove_accessor, out must_do_cs1540_check))) {
3489 Report.Error (122, loc, "'{0}' is inaccessible due to its protection level",
3490 DeclaringType.Name + "." + EventInfo.Name);
3494 if (!InstanceResolve (ec, must_do_cs1540_check))
3500 public override void Emit (EmitContext ec)
3502 if (instance_expr is This)
3503 Report.Error (79, loc, "The event `{0}' can only appear on the left hand side of += or -=, try calling the actual delegate", Name);
3505 Report.Error (70, loc, "The event `{0}' can only appear on the left hand side of += or -= "+
3506 "(except on the defining type)", Name);
3509 public void EmitAddOrRemove (EmitContext ec, Expression source)
3511 BinaryDelegate source_del = (BinaryDelegate) source;
3512 Expression handler = source_del.Right;
3514 Argument arg = new Argument (handler, Argument.AType.Expression);
3515 ArrayList args = new ArrayList ();
3519 if (source_del.IsAddition)
3520 Invocation.EmitCall (
3521 ec, false, IsStatic, instance_expr, add_accessor, args, loc);
3523 Invocation.EmitCall (
3524 ec, false, IsStatic, instance_expr, remove_accessor, args, loc);