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 // Allows SimpleNames to be returned.
55 // This is used by MemberAccess to construct long names that can not be
56 // partially resolved (namespace-qualified names for example).
59 // Mask of all the expression class flags.
62 // Disable control flow analysis while resolving the expression.
63 // This is used when resolving the instance expression of a field expression.
64 DisableFlowAnalysis = 16,
66 // Set if this is resolving the first part of a MemberAccess.
71 // This is just as a hint to AddressOf of what will be done with the
74 public enum AddressOp {
81 /// This interface is implemented by variables
83 public interface IMemoryLocation {
85 /// The AddressOf method should generate code that loads
86 /// the address of the object and leaves it on the stack.
88 /// The `mode' argument is used to notify the expression
89 /// of whether this will be used to read from the address or
90 /// write to the address.
92 /// This is just a hint that can be used to provide good error
93 /// reporting, and should have no other side effects.
95 void AddressOf (EmitContext ec, AddressOp mode);
99 /// This interface is implemented by variables
101 public interface IVariable {
102 VariableInfo VariableInfo {
106 bool VerifyFixed (bool is_expression);
110 /// This interface denotes an expression which evaluates to a member
111 /// of a struct or a class.
113 public interface IMemberExpr
116 /// The name of this member.
123 /// Whether this is an instance member.
130 /// Whether this is a static member.
137 /// The type which declares this member.
144 /// The instance expression associated with this member, if it's a
145 /// non-static member.
147 Expression InstanceExpression {
153 /// Base class for expressions
155 public abstract class Expression {
156 public ExprClass eclass;
158 protected Location loc;
170 public Location Location {
177 /// Utility wrapper routine for Error, just to beautify the code
179 public void Error (int error, string s)
181 if (!Location.IsNull (loc))
182 Report.Error (error, loc, s);
184 Report.Error (error, s);
188 /// Utility wrapper routine for Warning, just to beautify the code
190 public void Warning (int code, string format, params object[] args)
192 Report.Warning (code, loc, format, args);
196 /// Tests presence of ObsoleteAttribute and report proper error
198 protected void CheckObsoleteAttribute (Type type)
200 ObsoleteAttribute obsolete_attr = AttributeTester.GetObsoleteAttribute (type);
201 if (obsolete_attr == null)
204 AttributeTester.Report_ObsoleteMessage (obsolete_attr, type.FullName, loc);
208 /// Performs semantic analysis on the Expression
212 /// The Resolve method is invoked to perform the semantic analysis
215 /// The return value is an expression (it can be the
216 /// same expression in some cases) or a new
217 /// expression that better represents this node.
219 /// For example, optimizations of Unary (LiteralInt)
220 /// would return a new LiteralInt with a negated
223 /// If there is an error during semantic analysis,
224 /// then an error should be reported (using Report)
225 /// and a null value should be returned.
227 /// There are two side effects expected from calling
228 /// Resolve(): the the field variable "eclass" should
229 /// be set to any value of the enumeration
230 /// `ExprClass' and the type variable should be set
231 /// to a valid type (this is the type of the
234 public abstract Expression DoResolve (EmitContext ec);
236 public virtual Expression DoResolveLValue (EmitContext ec, Expression right_side)
238 return DoResolve (ec);
242 // This is used if the expression should be resolved as a type.
243 // the default implementation fails. Use this method in
244 // those participants in the SimpleName chain system.
246 public virtual Expression ResolveAsTypeStep (EmitContext ec)
252 // This is used to resolve the expression as a type, a null
253 // value will be returned if the expression is not a type
256 public TypeExpr ResolveAsTypeTerminal (EmitContext ec, bool silent)
258 int errors = Report.Errors;
260 TypeExpr te = ResolveAsTypeStep (ec) as TypeExpr;
262 if (te == null || te.eclass != ExprClass.Type) {
263 if (!silent && errors == Report.Errors)
264 Report.Error (246, Location, "Cannot find type '{0}'", ToString ());
268 if (!te.CheckAccessLevel (ec.DeclSpace)) {
269 Report.Error (122, Location, "'{0}' is inaccessible due to its protection level", te.Name);
277 /// Resolves an expression and performs semantic analysis on it.
281 /// Currently Resolve wraps DoResolve to perform sanity
282 /// checking and assertion checking on what we expect from Resolve.
284 public Expression Resolve (EmitContext ec, ResolveFlags flags)
286 if ((flags & ResolveFlags.MaskExprClass) == ResolveFlags.Type)
287 return ResolveAsTypeStep (ec);
289 bool old_do_flow_analysis = ec.DoFlowAnalysis;
290 if ((flags & ResolveFlags.DisableFlowAnalysis) != 0)
291 ec.DoFlowAnalysis = false;
294 bool intermediate = (flags & ResolveFlags.Intermediate) == ResolveFlags.Intermediate;
295 if (this is SimpleName)
296 e = ((SimpleName) this).DoResolveAllowStatic (ec, intermediate);
301 ec.DoFlowAnalysis = old_do_flow_analysis;
306 if (e is SimpleName){
307 SimpleName s = (SimpleName) e;
309 if ((flags & ResolveFlags.SimpleName) == 0) {
310 MemberLookupFailed (ec, null, ec.ContainerType, s.Name,
311 ec.DeclSpace.Name, loc);
318 if ((e is TypeExpr) || (e is ComposedCast)) {
319 if ((flags & ResolveFlags.Type) == 0) {
320 e.Error_UnexpectedKind (flags, loc);
329 if ((flags & ResolveFlags.VariableOrValue) == 0) {
330 e.Error_UnexpectedKind (flags, loc);
335 case ExprClass.MethodGroup:
336 if (RootContext.Version == LanguageVersion.ISO_1){
337 if ((flags & ResolveFlags.MethodGroup) == 0) {
338 ((MethodGroupExpr) e).ReportUsageError ();
344 case ExprClass.Value:
345 case ExprClass.Variable:
346 case ExprClass.PropertyAccess:
347 case ExprClass.EventAccess:
348 case ExprClass.IndexerAccess:
349 if ((flags & ResolveFlags.VariableOrValue) == 0) {
350 Console.WriteLine ("I got: {0} and {1}", e.GetType (), e);
351 Console.WriteLine ("I am {0} and {1}", this.GetType (), this);
352 FieldInfo fi = ((FieldExpr) e).FieldInfo;
354 Console.WriteLine ("{0} and {1}", fi.DeclaringType, fi.Name);
355 e.Error_UnexpectedKind (flags, loc);
361 throw new Exception ("Expression " + e.GetType () +
362 " ExprClass is Invalid after resolve");
366 throw new Exception (
367 "Expression " + e.GetType () +
368 " did not set its type after Resolve\n" +
369 "called from: " + this.GetType ());
375 /// Resolves an expression and performs semantic analysis on it.
377 public Expression Resolve (EmitContext ec)
379 return Resolve (ec, ResolveFlags.VariableOrValue);
383 /// Resolves an expression for LValue assignment
387 /// Currently ResolveLValue wraps DoResolveLValue to perform sanity
388 /// checking and assertion checking on what we expect from Resolve
390 public Expression ResolveLValue (EmitContext ec, Expression right_side)
392 Expression e = DoResolveLValue (ec, right_side);
395 if (e is SimpleName){
396 SimpleName s = (SimpleName) e;
397 MemberLookupFailed (ec, null, ec.ContainerType, s.Name,
398 ec.DeclSpace.Name, loc);
402 if (e.eclass == ExprClass.Invalid)
403 throw new Exception ("Expression " + e +
404 " ExprClass is Invalid after resolve");
406 if (e.eclass == ExprClass.MethodGroup) {
407 ((MethodGroupExpr) e).ReportUsageError ();
412 throw new Exception ("Expression " + e +
413 " did not set its type after Resolve");
420 /// Emits the code for the expression
424 /// The Emit method is invoked to generate the code
425 /// for the expression.
427 public abstract void Emit (EmitContext ec);
429 public virtual void EmitBranchable (EmitContext ec, Label target, bool onTrue)
432 ec.ig.Emit (onTrue ? OpCodes.Brtrue : OpCodes.Brfalse, target);
436 /// Protected constructor. Only derivate types should
437 /// be able to be created
440 protected Expression ()
442 eclass = ExprClass.Invalid;
447 /// Returns a literalized version of a literal FieldInfo
451 /// The possible return values are:
452 /// IntConstant, UIntConstant
453 /// LongLiteral, ULongConstant
454 /// FloatConstant, DoubleConstant
457 /// The value returned is already resolved.
459 public static Constant Constantify (object v, Type t)
461 if (t == TypeManager.int32_type)
462 return new IntConstant ((int) v);
463 else if (t == TypeManager.uint32_type)
464 return new UIntConstant ((uint) v);
465 else if (t == TypeManager.int64_type)
466 return new LongConstant ((long) v);
467 else if (t == TypeManager.uint64_type)
468 return new ULongConstant ((ulong) v);
469 else if (t == TypeManager.float_type)
470 return new FloatConstant ((float) v);
471 else if (t == TypeManager.double_type)
472 return new DoubleConstant ((double) v);
473 else if (t == TypeManager.string_type)
474 return new StringConstant ((string) v);
475 else if (t == TypeManager.short_type)
476 return new ShortConstant ((short)v);
477 else if (t == TypeManager.ushort_type)
478 return new UShortConstant ((ushort)v);
479 else if (t == TypeManager.sbyte_type)
480 return new SByteConstant (((sbyte)v));
481 else if (t == TypeManager.byte_type)
482 return new ByteConstant ((byte)v);
483 else if (t == TypeManager.char_type)
484 return new CharConstant ((char)v);
485 else if (t == TypeManager.bool_type)
486 return new BoolConstant ((bool) v);
487 else if (TypeManager.IsEnumType (t)){
488 Type real_type = TypeManager.TypeToCoreType (v.GetType ());
490 real_type = System.Enum.GetUnderlyingType (real_type);
492 Constant e = Constantify (v, real_type);
494 return new EnumConstant (e, t);
496 throw new Exception ("Unknown type for constant (" + t +
501 /// Returns a fully formed expression after a MemberLookup
503 public static Expression ExprClassFromMemberInfo (EmitContext ec, MemberInfo mi, Location loc)
506 return new EventExpr ((EventInfo) mi, loc);
507 else if (mi is FieldInfo)
508 return new FieldExpr ((FieldInfo) mi, loc);
509 else if (mi is PropertyInfo)
510 return new PropertyExpr (ec, (PropertyInfo) mi, loc);
511 else if (mi is Type){
512 return new TypeExpression ((System.Type) mi, loc);
519 private static ArrayList almostMatchedMembers = new ArrayList (4);
522 // FIXME: Probably implement a cache for (t,name,current_access_set)?
524 // This code could use some optimizations, but we need to do some
525 // measurements. For example, we could use a delegate to `flag' when
526 // something can not any longer be a method-group (because it is something
530 // If the return value is an Array, then it is an array of
533 // If the return value is an MemberInfo, it is anything, but a Method
537 // FIXME: When calling MemberLookup inside an `Invocation', we should pass
538 // the arguments here and have MemberLookup return only the methods that
539 // match the argument count/type, unlike we are doing now (we delay this
542 // This is so we can catch correctly attempts to invoke instance methods
543 // from a static body (scan for error 120 in ResolveSimpleName).
546 // FIXME: Potential optimization, have a static ArrayList
549 public static Expression MemberLookup (EmitContext ec, Type queried_type, string name,
550 MemberTypes mt, BindingFlags bf, Location loc)
552 return MemberLookup (ec, ec.ContainerType, null, queried_type, name, mt, bf, loc);
556 // Lookup type `queried_type' for code in class `container_type' with a qualifier of
557 // `qualifier_type' or null to lookup members in the current class.
560 public static Expression MemberLookup (EmitContext ec, Type container_type,
561 Type qualifier_type, Type queried_type,
562 string name, MemberTypes mt,
563 BindingFlags bf, Location loc)
565 almostMatchedMembers.Clear ();
567 MemberInfo [] mi = TypeManager.MemberLookup (container_type, qualifier_type,
568 queried_type, mt, bf, name, almostMatchedMembers);
573 int count = mi.Length;
575 if (mi [0] is MethodBase)
576 return new MethodGroupExpr (mi, loc);
581 return ExprClassFromMemberInfo (ec, mi [0], loc);
584 public const MemberTypes AllMemberTypes =
585 MemberTypes.Constructor |
589 MemberTypes.NestedType |
590 MemberTypes.Property;
592 public const BindingFlags AllBindingFlags =
593 BindingFlags.Public |
594 BindingFlags.Static |
595 BindingFlags.Instance;
597 public static Expression MemberLookup (EmitContext ec, Type queried_type,
598 string name, Location loc)
600 return MemberLookup (ec, ec.ContainerType, null, queried_type, name,
601 AllMemberTypes, AllBindingFlags, loc);
604 public static Expression MemberLookup (EmitContext ec, Type qualifier_type,
605 Type queried_type, string name, Location loc)
607 return MemberLookup (ec, ec.ContainerType, qualifier_type, queried_type,
608 name, AllMemberTypes, AllBindingFlags, loc);
611 public static Expression MethodLookup (EmitContext ec, Type queried_type,
612 string name, Location loc)
614 return MemberLookup (ec, ec.ContainerType, null, queried_type, name,
615 MemberTypes.Method, AllBindingFlags, loc);
619 /// This is a wrapper for MemberLookup that is not used to "probe", but
620 /// to find a final definition. If the final definition is not found, we
621 /// look for private members and display a useful debugging message if we
624 public static Expression MemberLookupFinal (EmitContext ec, Type qualifier_type,
625 Type queried_type, string name, Location loc)
627 return MemberLookupFinal (ec, qualifier_type, queried_type, name,
628 AllMemberTypes, AllBindingFlags, loc);
631 public static Expression MemberLookupFinal (EmitContext ec, Type qualifier_type,
632 Type queried_type, string name,
633 MemberTypes mt, BindingFlags bf,
638 int errors = Report.Errors;
640 e = MemberLookup (ec, ec.ContainerType, qualifier_type, queried_type, name, mt, bf, loc);
642 if (e == null && errors == Report.Errors)
643 // No errors were reported by MemberLookup, but there was an error.
644 MemberLookupFailed (ec, qualifier_type, queried_type, name, null, loc);
649 public static void MemberLookupFailed (EmitContext ec, Type qualifier_type,
650 Type queried_type, string name,
651 string class_name, Location loc)
653 if (almostMatchedMembers.Count != 0) {
654 if (qualifier_type == null) {
655 foreach (MemberInfo m in almostMatchedMembers)
656 Report.Error (38, loc,
657 "Cannot access non-static member `{0}' via nested type `{1}'",
658 TypeManager.GetFullNameSignature (m),
659 TypeManager.CSharpName (ec.ContainerType));
663 if (qualifier_type != ec.ContainerType) {
664 // Although a derived class can access protected members of
665 // its base class it cannot do so through an instance of the
666 // base class (CS1540). If the qualifier_type is a parent of the
667 // ec.ContainerType and the lookup succeeds with the latter one,
668 // then we are in this situation.
669 foreach (MemberInfo m in almostMatchedMembers)
670 Report.Error (1540, loc,
671 "Cannot access protected member `{0}' via a qualifier of type `{1}';"
672 + " the qualifier must be of type `{2}' (or derived from it)",
673 TypeManager.GetFullNameSignature (m),
674 TypeManager.CSharpName (qualifier_type),
675 TypeManager.CSharpName (ec.ContainerType));
678 almostMatchedMembers.Clear ();
681 object lookup = TypeManager.MemberLookup (queried_type, null, queried_type,
682 AllMemberTypes, AllBindingFlags |
683 BindingFlags.NonPublic, name, null);
685 if (lookup == null) {
686 if (class_name != null)
687 Report.Error (103, loc, "The name `" + name + "' could not be " +
688 "found in `" + class_name + "'");
691 117, loc, "`" + queried_type + "' does not contain a " +
692 "definition for `" + name + "'");
696 if (qualifier_type != null)
697 Report.Error (122, loc, "'{0}' is inaccessible due to its protection level", TypeManager.CSharpName (qualifier_type) + "." + name);
698 else if (name == ".ctor") {
699 Report.Error (143, loc, String.Format ("The type {0} has no constructors defined",
700 TypeManager.CSharpName (queried_type)));
702 Report.Error (122, loc, "'{0}' is inaccessible due to its protection level", name);
706 static public MemberInfo GetFieldFromEvent (EventExpr event_expr)
708 EventInfo ei = event_expr.EventInfo;
710 return TypeManager.GetPrivateFieldOfEvent (ei);
714 /// Returns an expression that can be used to invoke operator true
715 /// on the expression if it exists.
717 static public StaticCallExpr GetOperatorTrue (EmitContext ec, Expression e, Location loc)
719 return GetOperatorTrueOrFalse (ec, e, true, loc);
723 /// Returns an expression that can be used to invoke operator false
724 /// on the expression if it exists.
726 static public StaticCallExpr GetOperatorFalse (EmitContext ec, Expression e, Location loc)
728 return GetOperatorTrueOrFalse (ec, e, false, loc);
731 static StaticCallExpr GetOperatorTrueOrFalse (EmitContext ec, Expression e, bool is_true, Location loc)
734 Expression operator_group;
736 operator_group = MethodLookup (ec, e.Type, is_true ? "op_True" : "op_False", loc);
737 if (operator_group == null)
740 ArrayList arguments = new ArrayList ();
741 arguments.Add (new Argument (e, Argument.AType.Expression));
742 method = Invocation.OverloadResolve (
743 ec, (MethodGroupExpr) operator_group, arguments, false, loc);
748 return new StaticCallExpr ((MethodInfo) method, arguments, loc);
752 /// Resolves the expression `e' into a boolean expression: either through
753 /// an implicit conversion, or through an `operator true' invocation
755 public static Expression ResolveBoolean (EmitContext ec, Expression e, Location loc)
761 Expression converted = e;
762 if (e.Type != TypeManager.bool_type)
763 converted = Convert.ImplicitConversion (ec, e, TypeManager.bool_type, new Location (-1));
766 // If no implicit conversion to bool exists, try using `operator true'
768 if (converted == null){
769 Expression operator_true = Expression.GetOperatorTrue (ec, e, loc);
770 if (operator_true == null){
772 31, loc, "Can not convert the expression to a boolean");
782 static string ExprClassName (ExprClass c)
785 case ExprClass.Invalid:
787 case ExprClass.Value:
789 case ExprClass.Variable:
791 case ExprClass.Namespace:
795 case ExprClass.MethodGroup:
796 return "method group";
797 case ExprClass.PropertyAccess:
798 return "property access";
799 case ExprClass.EventAccess:
800 return "event access";
801 case ExprClass.IndexerAccess:
802 return "indexer access";
803 case ExprClass.Nothing:
806 throw new Exception ("Should not happen");
810 /// Reports that we were expecting `expr' to be of class `expected'
812 public void Error_UnexpectedKind (string expected, Location loc)
814 string kind = "Unknown";
816 kind = ExprClassName (eclass);
818 Report.Error (118, loc, "Expression denotes a `" + kind +
819 "' where a `" + expected + "' was expected");
822 public void Error_UnexpectedKind (ResolveFlags flags, Location loc)
824 ArrayList valid = new ArrayList (10);
826 if ((flags & ResolveFlags.VariableOrValue) != 0) {
827 valid.Add ("variable");
831 if ((flags & ResolveFlags.Type) != 0)
834 if ((flags & ResolveFlags.MethodGroup) != 0)
835 valid.Add ("method group");
837 if ((flags & ResolveFlags.SimpleName) != 0)
838 valid.Add ("simple name");
840 if (valid.Count == 0)
841 valid.Add ("unknown");
843 StringBuilder sb = new StringBuilder ();
844 for (int i = 0; i < valid.Count; i++) {
847 else if (i == valid.Count)
849 sb.Append (valid [i]);
852 string kind = ExprClassName (eclass);
854 Error (119, "Expression denotes a `" + kind + "' where " +
855 "a `" + sb.ToString () + "' was expected");
858 static public void Error_ConstantValueCannotBeConverted (Location l, string val, Type t)
860 Report.Error (31, l, "Constant value `" + val + "' cannot be converted to " +
861 TypeManager.CSharpName (t));
864 public static void UnsafeError (Location loc)
866 Report.Error (214, loc, "Pointers may only be used in an unsafe context");
870 /// Converts the IntConstant, UIntConstant, LongConstant or
871 /// ULongConstant into the integral target_type. Notice
872 /// that we do not return an `Expression' we do return
873 /// a boxed integral type.
875 /// FIXME: Since I added the new constants, we need to
876 /// also support conversions from CharConstant, ByteConstant,
877 /// SByteConstant, UShortConstant, ShortConstant
879 /// This is used by the switch statement, so the domain
880 /// of work is restricted to the literals above, and the
881 /// targets are int32, uint32, char, byte, sbyte, ushort,
882 /// short, uint64 and int64
884 public static object ConvertIntLiteral (Constant c, Type target_type, Location loc)
886 if (!Convert.ImplicitStandardConversionExists (c, target_type)){
887 Convert.Error_CannotImplicitConversion (loc, c.Type, target_type);
893 if (c.Type == target_type)
894 return ((Constant) c).GetValue ();
897 // Make into one of the literals we handle, we dont really care
898 // about this value as we will just return a few limited types
900 if (c is EnumConstant)
901 c = ((EnumConstant)c).WidenToCompilerConstant ();
903 if (c is IntConstant){
904 int v = ((IntConstant) c).Value;
906 if (target_type == TypeManager.uint32_type){
909 } else if (target_type == TypeManager.char_type){
910 if (v >= Char.MinValue && v <= Char.MaxValue)
912 } else if (target_type == TypeManager.byte_type){
913 if (v >= Byte.MinValue && v <= Byte.MaxValue)
915 } else if (target_type == TypeManager.sbyte_type){
916 if (v >= SByte.MinValue && v <= SByte.MaxValue)
918 } else if (target_type == TypeManager.short_type){
919 if (v >= Int16.MinValue && v <= UInt16.MaxValue)
921 } else if (target_type == TypeManager.ushort_type){
922 if (v >= UInt16.MinValue && v <= UInt16.MaxValue)
924 } else if (target_type == TypeManager.int64_type)
926 else if (target_type == TypeManager.uint64_type){
932 } else if (c is UIntConstant){
933 uint v = ((UIntConstant) c).Value;
935 if (target_type == TypeManager.int32_type){
936 if (v <= Int32.MaxValue)
938 } else if (target_type == TypeManager.char_type){
939 if (v >= Char.MinValue && v <= Char.MaxValue)
941 } else if (target_type == TypeManager.byte_type){
942 if (v <= Byte.MaxValue)
944 } else if (target_type == TypeManager.sbyte_type){
945 if (v <= SByte.MaxValue)
947 } else if (target_type == TypeManager.short_type){
948 if (v <= UInt16.MaxValue)
950 } else if (target_type == TypeManager.ushort_type){
951 if (v <= UInt16.MaxValue)
953 } else if (target_type == TypeManager.int64_type)
955 else if (target_type == TypeManager.uint64_type)
958 } else if (c is LongConstant){
959 long v = ((LongConstant) c).Value;
961 if (target_type == TypeManager.int32_type){
962 if (v >= UInt32.MinValue && v <= UInt32.MaxValue)
964 } else if (target_type == TypeManager.uint32_type){
965 if (v >= 0 && v <= UInt32.MaxValue)
967 } else if (target_type == TypeManager.char_type){
968 if (v >= Char.MinValue && v <= Char.MaxValue)
970 } else if (target_type == TypeManager.byte_type){
971 if (v >= Byte.MinValue && v <= Byte.MaxValue)
973 } else if (target_type == TypeManager.sbyte_type){
974 if (v >= SByte.MinValue && v <= SByte.MaxValue)
976 } else if (target_type == TypeManager.short_type){
977 if (v >= Int16.MinValue && v <= UInt16.MaxValue)
979 } else if (target_type == TypeManager.ushort_type){
980 if (v >= UInt16.MinValue && v <= UInt16.MaxValue)
982 } else if (target_type == TypeManager.uint64_type){
987 } else if (c is ULongConstant){
988 ulong v = ((ULongConstant) c).Value;
990 if (target_type == TypeManager.int32_type){
991 if (v <= Int32.MaxValue)
993 } else if (target_type == TypeManager.uint32_type){
994 if (v <= UInt32.MaxValue)
996 } else if (target_type == TypeManager.char_type){
997 if (v >= Char.MinValue && v <= Char.MaxValue)
999 } else if (target_type == TypeManager.byte_type){
1000 if (v >= Byte.MinValue && v <= Byte.MaxValue)
1002 } else if (target_type == TypeManager.sbyte_type){
1003 if (v <= (int) SByte.MaxValue)
1005 } else if (target_type == TypeManager.short_type){
1006 if (v <= UInt16.MaxValue)
1008 } else if (target_type == TypeManager.ushort_type){
1009 if (v <= UInt16.MaxValue)
1011 } else if (target_type == TypeManager.int64_type){
1012 if (v <= Int64.MaxValue)
1016 } else if (c is ByteConstant){
1017 byte v = ((ByteConstant) c).Value;
1019 if (target_type == TypeManager.int32_type)
1021 else if (target_type == TypeManager.uint32_type)
1023 else if (target_type == TypeManager.char_type)
1025 else if (target_type == TypeManager.sbyte_type){
1026 if (v <= SByte.MaxValue)
1028 } else if (target_type == TypeManager.short_type)
1030 else if (target_type == TypeManager.ushort_type)
1032 else if (target_type == TypeManager.int64_type)
1034 else if (target_type == TypeManager.uint64_type)
1037 } else if (c is SByteConstant){
1038 sbyte v = ((SByteConstant) c).Value;
1040 if (target_type == TypeManager.int32_type)
1042 else if (target_type == TypeManager.uint32_type){
1045 } else if (target_type == TypeManager.char_type){
1048 } else if (target_type == TypeManager.byte_type){
1051 } else if (target_type == TypeManager.short_type)
1053 else if (target_type == TypeManager.ushort_type){
1056 } else if (target_type == TypeManager.int64_type)
1058 else if (target_type == TypeManager.uint64_type){
1063 } else if (c is ShortConstant){
1064 short v = ((ShortConstant) c).Value;
1066 if (target_type == TypeManager.int32_type){
1068 } else if (target_type == TypeManager.uint32_type){
1071 } else if (target_type == TypeManager.char_type){
1074 } else if (target_type == TypeManager.byte_type){
1075 if (v >= Byte.MinValue && v <= Byte.MaxValue)
1077 } else if (target_type == TypeManager.sbyte_type){
1078 if (v >= SByte.MinValue && v <= SByte.MaxValue)
1080 } else if (target_type == TypeManager.ushort_type){
1083 } else if (target_type == TypeManager.int64_type)
1085 else if (target_type == TypeManager.uint64_type)
1089 } else if (c is UShortConstant){
1090 ushort v = ((UShortConstant) c).Value;
1092 if (target_type == TypeManager.int32_type)
1094 else if (target_type == TypeManager.uint32_type)
1096 else if (target_type == TypeManager.char_type){
1097 if (v >= Char.MinValue && v <= Char.MaxValue)
1099 } else if (target_type == TypeManager.byte_type){
1100 if (v >= Byte.MinValue && v <= Byte.MaxValue)
1102 } else if (target_type == TypeManager.sbyte_type){
1103 if (v <= SByte.MaxValue)
1105 } else if (target_type == TypeManager.short_type){
1106 if (v <= Int16.MaxValue)
1108 } else if (target_type == TypeManager.int64_type)
1110 else if (target_type == TypeManager.uint64_type)
1114 } else if (c is CharConstant){
1115 char v = ((CharConstant) c).Value;
1117 if (target_type == TypeManager.int32_type)
1119 else if (target_type == TypeManager.uint32_type)
1121 else if (target_type == TypeManager.byte_type){
1122 if (v >= Byte.MinValue && v <= Byte.MaxValue)
1124 } else if (target_type == TypeManager.sbyte_type){
1125 if (v <= SByte.MaxValue)
1127 } else if (target_type == TypeManager.short_type){
1128 if (v <= Int16.MaxValue)
1130 } else if (target_type == TypeManager.ushort_type)
1132 else if (target_type == TypeManager.int64_type)
1134 else if (target_type == TypeManager.uint64_type)
1139 Error_ConstantValueCannotBeConverted (loc, s, target_type);
1144 // Load the object from the pointer.
1146 public static void LoadFromPtr (ILGenerator ig, Type t)
1148 if (t == TypeManager.int32_type)
1149 ig.Emit (OpCodes.Ldind_I4);
1150 else if (t == TypeManager.uint32_type)
1151 ig.Emit (OpCodes.Ldind_U4);
1152 else if (t == TypeManager.short_type)
1153 ig.Emit (OpCodes.Ldind_I2);
1154 else if (t == TypeManager.ushort_type)
1155 ig.Emit (OpCodes.Ldind_U2);
1156 else if (t == TypeManager.char_type)
1157 ig.Emit (OpCodes.Ldind_U2);
1158 else if (t == TypeManager.byte_type)
1159 ig.Emit (OpCodes.Ldind_U1);
1160 else if (t == TypeManager.sbyte_type)
1161 ig.Emit (OpCodes.Ldind_I1);
1162 else if (t == TypeManager.uint64_type)
1163 ig.Emit (OpCodes.Ldind_I8);
1164 else if (t == TypeManager.int64_type)
1165 ig.Emit (OpCodes.Ldind_I8);
1166 else if (t == TypeManager.float_type)
1167 ig.Emit (OpCodes.Ldind_R4);
1168 else if (t == TypeManager.double_type)
1169 ig.Emit (OpCodes.Ldind_R8);
1170 else if (t == TypeManager.bool_type)
1171 ig.Emit (OpCodes.Ldind_I1);
1172 else if (t == TypeManager.intptr_type)
1173 ig.Emit (OpCodes.Ldind_I);
1174 else if (TypeManager.IsEnumType (t)) {
1175 if (t == TypeManager.enum_type)
1176 ig.Emit (OpCodes.Ldind_Ref);
1178 LoadFromPtr (ig, TypeManager.EnumToUnderlying (t));
1179 } else if (t.IsValueType)
1180 ig.Emit (OpCodes.Ldobj, t);
1181 else if (t.IsPointer)
1182 ig.Emit (OpCodes.Ldind_I);
1184 ig.Emit (OpCodes.Ldind_Ref);
1188 // The stack contains the pointer and the value of type `type'
1190 public static void StoreFromPtr (ILGenerator ig, Type type)
1192 if (TypeManager.IsEnumType (type))
1193 type = TypeManager.EnumToUnderlying (type);
1194 if (type == TypeManager.int32_type || type == TypeManager.uint32_type)
1195 ig.Emit (OpCodes.Stind_I4);
1196 else if (type == TypeManager.int64_type || type == TypeManager.uint64_type)
1197 ig.Emit (OpCodes.Stind_I8);
1198 else if (type == TypeManager.char_type || type == TypeManager.short_type ||
1199 type == TypeManager.ushort_type)
1200 ig.Emit (OpCodes.Stind_I2);
1201 else if (type == TypeManager.float_type)
1202 ig.Emit (OpCodes.Stind_R4);
1203 else if (type == TypeManager.double_type)
1204 ig.Emit (OpCodes.Stind_R8);
1205 else if (type == TypeManager.byte_type || type == TypeManager.sbyte_type ||
1206 type == TypeManager.bool_type)
1207 ig.Emit (OpCodes.Stind_I1);
1208 else if (type == TypeManager.intptr_type)
1209 ig.Emit (OpCodes.Stind_I);
1210 else if (type.IsValueType)
1211 ig.Emit (OpCodes.Stobj, type);
1213 ig.Emit (OpCodes.Stind_Ref);
1217 // Returns the size of type `t' if known, otherwise, 0
1219 public static int GetTypeSize (Type t)
1221 t = TypeManager.TypeToCoreType (t);
1222 if (t == TypeManager.int32_type ||
1223 t == TypeManager.uint32_type ||
1224 t == TypeManager.float_type)
1226 else if (t == TypeManager.int64_type ||
1227 t == TypeManager.uint64_type ||
1228 t == TypeManager.double_type)
1230 else if (t == TypeManager.byte_type ||
1231 t == TypeManager.sbyte_type ||
1232 t == TypeManager.bool_type)
1234 else if (t == TypeManager.short_type ||
1235 t == TypeManager.char_type ||
1236 t == TypeManager.ushort_type)
1238 else if (t == TypeManager.decimal_type)
1244 public static void Error_NegativeArrayIndex (Location loc)
1246 Report.Error (248, loc, "Cannot create an array with a negative size");
1250 // Converts `source' to an int, uint, long or ulong.
1252 public Expression ExpressionToArrayArgument (EmitContext ec, Expression source, Location loc)
1256 bool old_checked = ec.CheckState;
1257 ec.CheckState = true;
1259 target = Convert.ImplicitConversion (ec, source, TypeManager.int32_type, loc);
1260 if (target == null){
1261 target = Convert.ImplicitConversion (ec, source, TypeManager.uint32_type, loc);
1262 if (target == null){
1263 target = Convert.ImplicitConversion (ec, source, TypeManager.int64_type, loc);
1264 if (target == null){
1265 target = Convert.ImplicitConversion (ec, source, TypeManager.uint64_type, loc);
1267 Convert.Error_CannotImplicitConversion (loc, source.Type, TypeManager.int32_type);
1271 ec.CheckState = old_checked;
1274 // Only positive constants are allowed at compile time
1276 if (target is Constant){
1277 if (target is IntConstant){
1278 if (((IntConstant) target).Value < 0){
1279 Error_NegativeArrayIndex (loc);
1284 if (target is LongConstant){
1285 if (((LongConstant) target).Value < 0){
1286 Error_NegativeArrayIndex (loc);
1299 /// This is just a base class for expressions that can
1300 /// appear on statements (invocations, object creation,
1301 /// assignments, post/pre increment and decrement). The idea
1302 /// being that they would support an extra Emition interface that
1303 /// does not leave a result on the stack.
1305 public abstract class ExpressionStatement : Expression {
1307 public virtual ExpressionStatement ResolveStatement (EmitContext ec)
1309 Expression e = Resolve (ec);
1313 ExpressionStatement es = e as ExpressionStatement;
1315 Error (201, "Only assignment, call, increment, decrement and new object " +
1316 "expressions can be used as a statement");
1322 /// Requests the expression to be emitted in a `statement'
1323 /// context. This means that no new value is left on the
1324 /// stack after invoking this method (constrasted with
1325 /// Emit that will always leave a value on the stack).
1327 public abstract void EmitStatement (EmitContext ec);
1331 /// This kind of cast is used to encapsulate the child
1332 /// whose type is child.Type into an expression that is
1333 /// reported to return "return_type". This is used to encapsulate
1334 /// expressions which have compatible types, but need to be dealt
1335 /// at higher levels with.
1337 /// For example, a "byte" expression could be encapsulated in one
1338 /// of these as an "unsigned int". The type for the expression
1339 /// would be "unsigned int".
1342 public class EmptyCast : Expression {
1343 protected Expression child;
1345 public Expression Child {
1351 public EmptyCast (Expression child, Type return_type)
1353 eclass = child.eclass;
1358 public override Expression DoResolve (EmitContext ec)
1360 // This should never be invoked, we are born in fully
1361 // initialized state.
1366 public override void Emit (EmitContext ec)
1373 // We need to special case this since an empty cast of
1374 // a NullLiteral is still a Constant
1376 public class NullCast : Constant {
1377 protected Expression child;
1379 public NullCast (Expression child, Type return_type)
1381 eclass = child.eclass;
1386 override public string AsString ()
1391 public override object GetValue ()
1396 public override Expression DoResolve (EmitContext ec)
1398 // This should never be invoked, we are born in fully
1399 // initialized state.
1404 public override void Emit (EmitContext ec)
1409 public override bool IsNegative {
1418 /// This class is used to wrap literals which belong inside Enums
1420 public class EnumConstant : Constant {
1421 public Constant Child;
1423 public EnumConstant (Constant child, Type enum_type)
1425 eclass = child.eclass;
1430 public override Expression DoResolve (EmitContext ec)
1432 // This should never be invoked, we are born in fully
1433 // initialized state.
1438 public override void Emit (EmitContext ec)
1443 public override object GetValue ()
1445 return Child.GetValue ();
1448 public object GetValueAsEnumType ()
1450 return System.Enum.ToObject (type, Child.GetValue ());
1454 // Converts from one of the valid underlying types for an enumeration
1455 // (int32, uint32, int64, uint64, short, ushort, byte, sbyte) to
1456 // one of the internal compiler literals: Int/UInt/Long/ULong Literals.
1458 public Constant WidenToCompilerConstant ()
1460 Type t = TypeManager.EnumToUnderlying (Child.Type);
1461 object v = ((Constant) Child).GetValue ();;
1463 if (t == TypeManager.int32_type)
1464 return new IntConstant ((int) v);
1465 if (t == TypeManager.uint32_type)
1466 return new UIntConstant ((uint) v);
1467 if (t == TypeManager.int64_type)
1468 return new LongConstant ((long) v);
1469 if (t == TypeManager.uint64_type)
1470 return new ULongConstant ((ulong) v);
1471 if (t == TypeManager.short_type)
1472 return new ShortConstant ((short) v);
1473 if (t == TypeManager.ushort_type)
1474 return new UShortConstant ((ushort) v);
1475 if (t == TypeManager.byte_type)
1476 return new ByteConstant ((byte) v);
1477 if (t == TypeManager.sbyte_type)
1478 return new SByteConstant ((sbyte) v);
1480 throw new Exception ("Invalid enumeration underlying type: " + t);
1484 // Extracts the value in the enumeration on its native representation
1486 public object GetPlainValue ()
1488 Type t = TypeManager.EnumToUnderlying (Child.Type);
1489 object v = ((Constant) Child).GetValue ();;
1491 if (t == TypeManager.int32_type)
1493 if (t == TypeManager.uint32_type)
1495 if (t == TypeManager.int64_type)
1497 if (t == TypeManager.uint64_type)
1499 if (t == TypeManager.short_type)
1501 if (t == TypeManager.ushort_type)
1503 if (t == TypeManager.byte_type)
1505 if (t == TypeManager.sbyte_type)
1511 public override string AsString ()
1513 return Child.AsString ();
1516 public override DoubleConstant ConvertToDouble ()
1518 return Child.ConvertToDouble ();
1521 public override FloatConstant ConvertToFloat ()
1523 return Child.ConvertToFloat ();
1526 public override ULongConstant ConvertToULong ()
1528 return Child.ConvertToULong ();
1531 public override LongConstant ConvertToLong ()
1533 return Child.ConvertToLong ();
1536 public override UIntConstant ConvertToUInt ()
1538 return Child.ConvertToUInt ();
1541 public override IntConstant ConvertToInt ()
1543 return Child.ConvertToInt ();
1546 public override bool IsZeroInteger {
1547 get { return Child.IsZeroInteger; }
1550 public override bool IsNegative {
1552 return Child.IsNegative;
1558 /// This kind of cast is used to encapsulate Value Types in objects.
1560 /// The effect of it is to box the value type emitted by the previous
1563 public class BoxedCast : EmptyCast {
1565 public BoxedCast (Expression expr)
1566 : base (expr, TypeManager.object_type)
1568 eclass = ExprClass.Value;
1571 public BoxedCast (Expression expr, Type target_type)
1572 : base (expr, target_type)
1574 eclass = ExprClass.Value;
1577 public override Expression DoResolve (EmitContext ec)
1579 // This should never be invoked, we are born in fully
1580 // initialized state.
1585 public override void Emit (EmitContext ec)
1589 ec.ig.Emit (OpCodes.Box, child.Type);
1593 public class UnboxCast : EmptyCast {
1594 public UnboxCast (Expression expr, Type return_type)
1595 : base (expr, return_type)
1599 public override Expression DoResolve (EmitContext ec)
1601 // This should never be invoked, we are born in fully
1602 // initialized state.
1607 public override void Emit (EmitContext ec)
1610 ILGenerator ig = ec.ig;
1613 ig.Emit (OpCodes.Unbox, t);
1615 LoadFromPtr (ig, t);
1620 /// This is used to perform explicit numeric conversions.
1622 /// Explicit numeric conversions might trigger exceptions in a checked
1623 /// context, so they should generate the conv.ovf opcodes instead of
1626 public class ConvCast : EmptyCast {
1627 public enum Mode : byte {
1628 I1_U1, I1_U2, I1_U4, I1_U8, I1_CH,
1630 I2_I1, I2_U1, I2_U2, I2_U4, I2_U8, I2_CH,
1631 U2_I1, U2_U1, U2_I2, U2_CH,
1632 I4_I1, I4_U1, I4_I2, I4_U2, I4_U4, I4_U8, I4_CH,
1633 U4_I1, U4_U1, U4_I2, U4_U2, U4_I4, U4_CH,
1634 I8_I1, I8_U1, I8_I2, I8_U2, I8_I4, I8_U4, I8_U8, I8_CH,
1635 U8_I1, U8_U1, U8_I2, U8_U2, U8_I4, U8_U4, U8_I8, U8_CH,
1636 CH_I1, CH_U1, CH_I2,
1637 R4_I1, R4_U1, R4_I2, R4_U2, R4_I4, R4_U4, R4_I8, R4_U8, R4_CH,
1638 R8_I1, R8_U1, R8_I2, R8_U2, R8_I4, R8_U4, R8_I8, R8_U8, R8_CH, R8_R4
1644 public ConvCast (EmitContext ec, Expression child, Type return_type, Mode m)
1645 : base (child, return_type)
1647 checked_state = ec.CheckState;
1651 public override Expression DoResolve (EmitContext ec)
1653 // This should never be invoked, we are born in fully
1654 // initialized state.
1659 public override string ToString ()
1661 return String.Format ("ConvCast ({0}, {1})", mode, child);
1664 public override void Emit (EmitContext ec)
1666 ILGenerator ig = ec.ig;
1672 case Mode.I1_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1673 case Mode.I1_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1674 case Mode.I1_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1675 case Mode.I1_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1676 case Mode.I1_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1678 case Mode.U1_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1679 case Mode.U1_CH: /* nothing */ break;
1681 case Mode.I2_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1682 case Mode.I2_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1683 case Mode.I2_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1684 case Mode.I2_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1685 case Mode.I2_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1686 case Mode.I2_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1688 case Mode.U2_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1689 case Mode.U2_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
1690 case Mode.U2_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
1691 case Mode.U2_CH: /* nothing */ break;
1693 case Mode.I4_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1694 case Mode.I4_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1695 case Mode.I4_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
1696 case Mode.I4_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1697 case Mode.I4_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1698 case Mode.I4_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1699 case Mode.I4_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1701 case Mode.U4_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1702 case Mode.U4_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
1703 case Mode.U4_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
1704 case Mode.U4_U2: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
1705 case Mode.U4_I4: ig.Emit (OpCodes.Conv_Ovf_I4_Un); break;
1706 case Mode.U4_CH: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
1708 case Mode.I8_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1709 case Mode.I8_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1710 case Mode.I8_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
1711 case Mode.I8_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1712 case Mode.I8_I4: ig.Emit (OpCodes.Conv_Ovf_I4); break;
1713 case Mode.I8_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1714 case Mode.I8_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1715 case Mode.I8_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1717 case Mode.U8_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1718 case Mode.U8_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
1719 case Mode.U8_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
1720 case Mode.U8_U2: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
1721 case Mode.U8_I4: ig.Emit (OpCodes.Conv_Ovf_I4_Un); break;
1722 case Mode.U8_U4: ig.Emit (OpCodes.Conv_Ovf_U4_Un); break;
1723 case Mode.U8_I8: ig.Emit (OpCodes.Conv_Ovf_I8_Un); break;
1724 case Mode.U8_CH: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
1726 case Mode.CH_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1727 case Mode.CH_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
1728 case Mode.CH_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
1730 case Mode.R4_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1731 case Mode.R4_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1732 case Mode.R4_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
1733 case Mode.R4_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1734 case Mode.R4_I4: ig.Emit (OpCodes.Conv_Ovf_I4); break;
1735 case Mode.R4_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1736 case Mode.R4_I8: ig.Emit (OpCodes.Conv_Ovf_I8); break;
1737 case Mode.R4_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1738 case Mode.R4_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1740 case Mode.R8_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1741 case Mode.R8_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1742 case Mode.R8_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
1743 case Mode.R8_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1744 case Mode.R8_I4: ig.Emit (OpCodes.Conv_Ovf_I4); break;
1745 case Mode.R8_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1746 case Mode.R8_I8: ig.Emit (OpCodes.Conv_Ovf_I8); break;
1747 case Mode.R8_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1748 case Mode.R8_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1749 case Mode.R8_R4: ig.Emit (OpCodes.Conv_R4); break;
1753 case Mode.I1_U1: ig.Emit (OpCodes.Conv_U1); break;
1754 case Mode.I1_U2: ig.Emit (OpCodes.Conv_U2); break;
1755 case Mode.I1_U4: ig.Emit (OpCodes.Conv_U4); break;
1756 case Mode.I1_U8: ig.Emit (OpCodes.Conv_I8); break;
1757 case Mode.I1_CH: ig.Emit (OpCodes.Conv_U2); break;
1759 case Mode.U1_I1: ig.Emit (OpCodes.Conv_I1); break;
1760 case Mode.U1_CH: ig.Emit (OpCodes.Conv_U2); break;
1762 case Mode.I2_I1: ig.Emit (OpCodes.Conv_I1); break;
1763 case Mode.I2_U1: ig.Emit (OpCodes.Conv_U1); break;
1764 case Mode.I2_U2: ig.Emit (OpCodes.Conv_U2); break;
1765 case Mode.I2_U4: ig.Emit (OpCodes.Conv_U4); break;
1766 case Mode.I2_U8: ig.Emit (OpCodes.Conv_I8); break;
1767 case Mode.I2_CH: ig.Emit (OpCodes.Conv_U2); break;
1769 case Mode.U2_I1: ig.Emit (OpCodes.Conv_I1); break;
1770 case Mode.U2_U1: ig.Emit (OpCodes.Conv_U1); break;
1771 case Mode.U2_I2: ig.Emit (OpCodes.Conv_I2); break;
1772 case Mode.U2_CH: /* nothing */ break;
1774 case Mode.I4_I1: ig.Emit (OpCodes.Conv_I1); break;
1775 case Mode.I4_U1: ig.Emit (OpCodes.Conv_U1); break;
1776 case Mode.I4_I2: ig.Emit (OpCodes.Conv_I2); break;
1777 case Mode.I4_U4: /* nothing */ break;
1778 case Mode.I4_U2: ig.Emit (OpCodes.Conv_U2); break;
1779 case Mode.I4_U8: ig.Emit (OpCodes.Conv_I8); break;
1780 case Mode.I4_CH: ig.Emit (OpCodes.Conv_U2); break;
1782 case Mode.U4_I1: ig.Emit (OpCodes.Conv_I1); break;
1783 case Mode.U4_U1: ig.Emit (OpCodes.Conv_U1); break;
1784 case Mode.U4_I2: ig.Emit (OpCodes.Conv_I2); break;
1785 case Mode.U4_U2: ig.Emit (OpCodes.Conv_U2); break;
1786 case Mode.U4_I4: /* nothing */ break;
1787 case Mode.U4_CH: ig.Emit (OpCodes.Conv_U2); break;
1789 case Mode.I8_I1: ig.Emit (OpCodes.Conv_I1); break;
1790 case Mode.I8_U1: ig.Emit (OpCodes.Conv_U1); break;
1791 case Mode.I8_I2: ig.Emit (OpCodes.Conv_I2); break;
1792 case Mode.I8_U2: ig.Emit (OpCodes.Conv_U2); break;
1793 case Mode.I8_I4: ig.Emit (OpCodes.Conv_I4); break;
1794 case Mode.I8_U4: ig.Emit (OpCodes.Conv_U4); break;
1795 case Mode.I8_U8: /* nothing */ break;
1796 case Mode.I8_CH: ig.Emit (OpCodes.Conv_U2); break;
1798 case Mode.U8_I1: ig.Emit (OpCodes.Conv_I1); break;
1799 case Mode.U8_U1: ig.Emit (OpCodes.Conv_U1); break;
1800 case Mode.U8_I2: ig.Emit (OpCodes.Conv_I2); break;
1801 case Mode.U8_U2: ig.Emit (OpCodes.Conv_U2); break;
1802 case Mode.U8_I4: ig.Emit (OpCodes.Conv_I4); break;
1803 case Mode.U8_U4: ig.Emit (OpCodes.Conv_U4); break;
1804 case Mode.U8_I8: /* nothing */ break;
1805 case Mode.U8_CH: ig.Emit (OpCodes.Conv_U2); break;
1807 case Mode.CH_I1: ig.Emit (OpCodes.Conv_I1); break;
1808 case Mode.CH_U1: ig.Emit (OpCodes.Conv_U1); break;
1809 case Mode.CH_I2: ig.Emit (OpCodes.Conv_I2); break;
1811 case Mode.R4_I1: ig.Emit (OpCodes.Conv_I1); break;
1812 case Mode.R4_U1: ig.Emit (OpCodes.Conv_U1); break;
1813 case Mode.R4_I2: ig.Emit (OpCodes.Conv_I2); break;
1814 case Mode.R4_U2: ig.Emit (OpCodes.Conv_U2); break;
1815 case Mode.R4_I4: ig.Emit (OpCodes.Conv_I4); break;
1816 case Mode.R4_U4: ig.Emit (OpCodes.Conv_U4); break;
1817 case Mode.R4_I8: ig.Emit (OpCodes.Conv_I8); break;
1818 case Mode.R4_U8: ig.Emit (OpCodes.Conv_U8); break;
1819 case Mode.R4_CH: ig.Emit (OpCodes.Conv_U2); break;
1821 case Mode.R8_I1: ig.Emit (OpCodes.Conv_I1); break;
1822 case Mode.R8_U1: ig.Emit (OpCodes.Conv_U1); break;
1823 case Mode.R8_I2: ig.Emit (OpCodes.Conv_I2); break;
1824 case Mode.R8_U2: ig.Emit (OpCodes.Conv_U2); break;
1825 case Mode.R8_I4: ig.Emit (OpCodes.Conv_I4); break;
1826 case Mode.R8_U4: ig.Emit (OpCodes.Conv_U4); break;
1827 case Mode.R8_I8: ig.Emit (OpCodes.Conv_I8); break;
1828 case Mode.R8_U8: ig.Emit (OpCodes.Conv_U8); break;
1829 case Mode.R8_CH: ig.Emit (OpCodes.Conv_U2); break;
1830 case Mode.R8_R4: ig.Emit (OpCodes.Conv_R4); break;
1836 public class OpcodeCast : EmptyCast {
1840 public OpcodeCast (Expression child, Type return_type, OpCode op)
1841 : base (child, return_type)
1845 second_valid = false;
1848 public OpcodeCast (Expression child, Type return_type, OpCode op, OpCode op2)
1849 : base (child, return_type)
1854 second_valid = true;
1857 public override Expression DoResolve (EmitContext ec)
1859 // This should never be invoked, we are born in fully
1860 // initialized state.
1865 public override void Emit (EmitContext ec)
1876 /// This kind of cast is used to encapsulate a child and cast it
1877 /// to the class requested
1879 public class ClassCast : EmptyCast {
1880 public ClassCast (Expression child, Type return_type)
1881 : base (child, return_type)
1886 public override Expression DoResolve (EmitContext ec)
1888 // This should never be invoked, we are born in fully
1889 // initialized state.
1894 public override void Emit (EmitContext ec)
1898 ec.ig.Emit (OpCodes.Castclass, type);
1904 /// SimpleName expressions are initially formed of a single
1905 /// word and it only happens at the beginning of the expression.
1909 /// The expression will try to be bound to a Field, a Method
1910 /// group or a Property. If those fail we pass the name to our
1911 /// caller and the SimpleName is compounded to perform a type
1912 /// lookup. The idea behind this process is that we want to avoid
1913 /// creating a namespace map from the assemblies, as that requires
1914 /// the GetExportedTypes function to be called and a hashtable to
1915 /// be constructed which reduces startup time. If later we find
1916 /// that this is slower, we should create a `NamespaceExpr' expression
1917 /// that fully participates in the resolution process.
1919 /// For example `System.Console.WriteLine' is decomposed into
1920 /// MemberAccess (MemberAccess (SimpleName ("System"), "Console"), "WriteLine")
1922 /// The first SimpleName wont produce a match on its own, so it will
1924 /// MemberAccess (SimpleName ("System.Console"), "WriteLine").
1926 /// System.Console will produce a TypeExpr match.
1928 /// The downside of this is that we might be hitting `LookupType' too many
1929 /// times with this scheme.
1931 public class SimpleName : Expression {
1935 // If true, then we are a simple name, not composed with a ".
1939 public SimpleName (string a, string b, Location l)
1941 Name = String.Concat (a, ".", b);
1946 public SimpleName (string name, Location l)
1953 public static void Error_ObjectRefRequired (EmitContext ec, Location l, string name)
1955 if (ec.IsFieldInitializer)
1958 "A field initializer cannot reference the non-static field, " +
1959 "method or property `"+name+"'");
1963 "An object reference is required " +
1964 "for the non-static field `"+name+"'");
1968 // Checks whether we are trying to access an instance
1969 // property, method or field from a static body.
1971 Expression MemberStaticCheck (EmitContext ec, Expression e)
1973 if (e is IMemberExpr){
1974 IMemberExpr member = (IMemberExpr) e;
1976 if (!member.IsStatic){
1977 Error_ObjectRefRequired (ec, loc, Name);
1985 public override Expression DoResolve (EmitContext ec)
1987 return SimpleNameResolve (ec, null, false, false);
1990 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
1992 return SimpleNameResolve (ec, right_side, false, false);
1996 public Expression DoResolveAllowStatic (EmitContext ec, bool intermediate)
1998 return SimpleNameResolve (ec, null, true, intermediate);
2001 public override Expression ResolveAsTypeStep (EmitContext ec)
2003 DeclSpace ds = ec.DeclSpace;
2004 NamespaceEntry ns = ds.NamespaceEntry;
2009 // Since we are cheating: we only do the Alias lookup for
2010 // namespaces if the name does not include any dots in it
2012 if (ns != null && is_base)
2013 alias_value = ns.LookupAlias (Name);
2017 if (ec.ResolvingTypeTree){
2018 int errors = Report.Errors;
2019 Type dt = ds.FindType (loc, Name);
2021 if (Report.Errors != errors)
2025 return new TypeExpression (dt, loc);
2027 if (alias_value != null){
2028 if ((t = RootContext.LookupType (ds, alias_value, true, loc)) != null)
2029 return new TypeExpression (t, loc);
2034 // First, the using aliases
2036 if (alias_value != null){
2037 if ((t = RootContext.LookupType (ds, alias_value, true, loc)) != null)
2038 return new TypeExpression (t, loc);
2040 // we have alias value, but it isn't Type, so try if it's namespace
2041 return new SimpleName (alias_value, loc);
2045 // Stage 2: Lookup up if we are an alias to a type
2049 if ((t = RootContext.LookupType (ds, Name, true, loc)) != null)
2050 return new TypeExpression (t, loc);
2052 // No match, maybe our parent can compose us
2053 // into something meaningful.
2057 Expression SimpleNameResolve (EmitContext ec, Expression right_side,
2058 bool allow_static, bool intermediate)
2060 Expression e = DoSimpleNameResolve (ec, right_side, allow_static, intermediate);
2064 Block current_block = ec.CurrentBlock;
2065 if (current_block != null){
2066 //LocalInfo vi = current_block.GetLocalInfo (Name);
2068 current_block.IsVariableNameUsedInChildBlock(Name)) {
2069 Report.Error (135, Location,
2070 "'{0}' has a different meaning in a " +
2071 "child block", Name);
2080 /// 7.5.2: Simple Names.
2082 /// Local Variables and Parameters are handled at
2083 /// parse time, so they never occur as SimpleNames.
2085 /// The `allow_static' flag is used by MemberAccess only
2086 /// and it is used to inform us that it is ok for us to
2087 /// avoid the static check, because MemberAccess might end
2088 /// up resolving the Name as a Type name and the access as
2089 /// a static type access.
2091 /// ie: Type Type; .... { Type.GetType (""); }
2093 /// Type is both an instance variable and a Type; Type.GetType
2094 /// is the static method not an instance method of type.
2096 Expression DoSimpleNameResolve (EmitContext ec, Expression right_side, bool allow_static, bool intermediate)
2098 Expression e = null;
2101 // Stage 1: Performed by the parser (binding to locals or parameters).
2103 Block current_block = ec.CurrentBlock;
2104 if (current_block != null){
2105 LocalInfo vi = current_block.GetLocalInfo (Name);
2109 var = new LocalVariableReference (ec.CurrentBlock, Name, loc);
2111 if (right_side != null)
2112 return var.ResolveLValue (ec, right_side);
2114 return var.Resolve (ec);
2118 Parameter par = null;
2119 Parameters pars = current_block.Parameters;
2121 par = pars.GetParameterByName (Name, out idx);
2124 ParameterReference param;
2126 param = new ParameterReference (pars, current_block, idx, Name, loc);
2128 if (right_side != null)
2129 return param.ResolveLValue (ec, right_side);
2131 return param.Resolve (ec);
2136 // Stage 2: Lookup members
2139 DeclSpace lookup_ds = ec.DeclSpace;
2141 if (lookup_ds.TypeBuilder == null)
2144 e = MemberLookup (ec, lookup_ds.TypeBuilder, Name, loc);
2148 lookup_ds =lookup_ds.Parent;
2149 } while (lookup_ds != null);
2151 if (e == null && ec.ContainerType != null)
2152 e = MemberLookup (ec, ec.ContainerType, Name, loc);
2156 // Since we are cheating (is_base is our hint
2157 // that we are the beginning of the name): we
2158 // only do the Alias lookup for namespaces if
2159 // the name does not include any dots in it
2161 NamespaceEntry ns = ec.DeclSpace.NamespaceEntry;
2162 if (is_base && ns != null){
2163 string alias_value = ns.LookupAlias (Name);
2164 if (alias_value != null){
2168 if ((t = TypeManager.LookupType (Name)) != null)
2169 return new TypeExpression (t, loc);
2171 // No match, maybe our parent can compose us
2172 // into something meaningful.
2177 return ResolveAsTypeStep (ec);
2183 if (e is IMemberExpr) {
2184 e = MemberAccess.ResolveMemberAccess (ec, e, null, loc, this);
2188 IMemberExpr me = e as IMemberExpr;
2192 // This fails if ResolveMemberAccess() was unable to decide whether
2193 // it's a field or a type of the same name.
2195 if (!me.IsStatic && (me.InstanceExpression == null))
2199 TypeManager.IsSubclassOrNestedChildOf (me.InstanceExpression.Type, me.DeclaringType) &&
2200 me.InstanceExpression.Type != me.DeclaringType &&
2201 !me.InstanceExpression.Type.IsSubclassOf (me.DeclaringType) &&
2202 (!intermediate || !MemberAccess.IdenticalNameAndTypeName (ec, this, e, loc))) {
2203 Error (38, "Cannot access nonstatic member `" + me.Name + "' of " +
2204 "outer type `" + me.DeclaringType + "' via nested type `" +
2205 me.InstanceExpression.Type + "'");
2209 return (right_side != null)
2210 ? e.DoResolveLValue (ec, right_side)
2214 if (ec.IsStatic || ec.IsFieldInitializer){
2218 return MemberStaticCheck (ec, e);
2223 public override void Emit (EmitContext ec)
2226 // If this is ever reached, then we failed to
2227 // find the name as a namespace
2230 Error (103, "The name `" + Name +
2231 "' does not exist in the class `" +
2232 ec.DeclSpace.Name + "'");
2235 public override string ToString ()
2242 /// Fully resolved expression that evaluates to a type
2244 public abstract class TypeExpr : Expression {
2245 override public Expression ResolveAsTypeStep (EmitContext ec)
2247 TypeExpr t = DoResolveAsTypeStep (ec);
2251 eclass = ExprClass.Type;
2255 override public Expression DoResolve (EmitContext ec)
2257 return ResolveAsTypeTerminal (ec, true);
2260 override public void Emit (EmitContext ec)
2262 throw new Exception ("Should never be called");
2265 public virtual bool CheckAccessLevel (DeclSpace ds)
2267 return ds.CheckAccessLevel (Type);
2270 public virtual bool AsAccessible (DeclSpace ds, int flags)
2272 return ds.AsAccessible (Type, flags);
2275 public virtual bool IsClass {
2276 get { return Type.IsClass; }
2279 public virtual bool IsValueType {
2280 get { return Type.IsValueType; }
2283 public virtual bool IsInterface {
2284 get { return Type.IsInterface; }
2287 public virtual bool IsSealed {
2288 get { return Type.IsSealed; }
2291 public virtual bool CanInheritFrom ()
2293 if (Type == TypeManager.enum_type ||
2294 (Type == TypeManager.value_type && RootContext.StdLib) ||
2295 Type == TypeManager.multicast_delegate_type ||
2296 Type == TypeManager.delegate_type ||
2297 Type == TypeManager.array_type)
2303 public virtual bool IsAttribute {
2305 return Type == TypeManager.attribute_type ||
2306 Type.IsSubclassOf (TypeManager.attribute_type);
2310 public virtual TypeExpr[] GetInterfaces ()
2312 return TypeManager.GetInterfaces (Type);
2315 public abstract TypeExpr DoResolveAsTypeStep (EmitContext ec);
2317 public virtual Type ResolveType (EmitContext ec)
2319 TypeExpr t = ResolveAsTypeTerminal (ec, false);
2326 public abstract string Name {
2330 public override bool Equals (object obj)
2332 TypeExpr tobj = obj as TypeExpr;
2336 return Type == tobj.Type;
2339 public override int GetHashCode ()
2341 return Type.GetHashCode ();
2344 public override string ToString ()
2350 public class TypeExpression : TypeExpr {
2351 public TypeExpression (Type t, Location l)
2354 eclass = ExprClass.Type;
2358 public override TypeExpr DoResolveAsTypeStep (EmitContext ec)
2363 public override string Name {
2365 return Type.ToString ();
2371 /// Used to create types from a fully qualified name. These are just used
2372 /// by the parser to setup the core types. A TypeLookupExpression is always
2373 /// classified as a type.
2375 public class TypeLookupExpression : TypeExpr {
2378 public TypeLookupExpression (string name)
2383 public override TypeExpr DoResolveAsTypeStep (EmitContext ec)
2386 type = RootContext.LookupType (ec.DeclSpace, name, false, Location.Null);
2390 public override string Name {
2398 /// MethodGroup Expression.
2400 /// This is a fully resolved expression that evaluates to a type
2402 public class MethodGroupExpr : Expression, IMemberExpr {
2403 public MethodBase [] Methods;
2404 Expression instance_expression = null;
2405 bool is_explicit_impl = false;
2406 bool identical_type_name = false;
2409 public MethodGroupExpr (MemberInfo [] mi, Location l)
2411 Methods = new MethodBase [mi.Length];
2412 mi.CopyTo (Methods, 0);
2413 eclass = ExprClass.MethodGroup;
2414 type = TypeManager.object_type;
2418 public MethodGroupExpr (ArrayList list, Location l)
2420 Methods = new MethodBase [list.Count];
2423 list.CopyTo (Methods, 0);
2425 foreach (MemberInfo m in list){
2426 if (!(m is MethodBase)){
2427 Console.WriteLine ("Name " + m.Name);
2428 Console.WriteLine ("Found a: " + m.GetType ().FullName);
2435 eclass = ExprClass.MethodGroup;
2436 type = TypeManager.object_type;
2439 public Type DeclaringType {
2442 // The methods are arranged in this order:
2443 // derived type -> base type
2445 return Methods [0].DeclaringType;
2450 // `A method group may have associated an instance expression'
2452 public Expression InstanceExpression {
2454 return instance_expression;
2458 instance_expression = value;
2462 public bool IsExplicitImpl {
2464 return is_explicit_impl;
2468 is_explicit_impl = value;
2472 public bool IdenticalTypeName {
2474 return identical_type_name;
2478 identical_type_name = value;
2482 public bool IsBase {
2491 public string Name {
2493 return Methods [0].Name;
2497 public bool IsInstance {
2499 foreach (MethodBase mb in Methods)
2507 public bool IsStatic {
2509 foreach (MethodBase mb in Methods)
2517 override public Expression DoResolve (EmitContext ec)
2520 instance_expression = null;
2522 if (instance_expression != null) {
2523 instance_expression = instance_expression.DoResolve (ec);
2524 if (instance_expression == null)
2531 public void ReportUsageError ()
2533 Report.Error (654, loc, "Method `" + DeclaringType + "." +
2534 Name + "()' is referenced without parentheses");
2537 override public void Emit (EmitContext ec)
2539 ReportUsageError ();
2542 bool RemoveMethods (bool keep_static)
2544 ArrayList smethods = new ArrayList ();
2546 foreach (MethodBase mb in Methods){
2547 if (mb.IsStatic == keep_static)
2551 if (smethods.Count == 0)
2554 Methods = new MethodBase [smethods.Count];
2555 smethods.CopyTo (Methods, 0);
2561 /// Removes any instance methods from the MethodGroup, returns
2562 /// false if the resulting set is empty.
2564 public bool RemoveInstanceMethods ()
2566 return RemoveMethods (true);
2570 /// Removes any static methods from the MethodGroup, returns
2571 /// false if the resulting set is empty.
2573 public bool RemoveStaticMethods ()
2575 return RemoveMethods (false);
2580 /// Fully resolved expression that evaluates to a Field
2582 public class FieldExpr : Expression, IAssignMethod, IMemoryLocation, IMemberExpr, IVariable {
2583 public readonly FieldInfo FieldInfo;
2584 Expression instance_expr;
2585 VariableInfo variable_info;
2587 LocalTemporary temp;
2590 public FieldExpr (FieldInfo fi, Location l)
2593 eclass = ExprClass.Variable;
2594 type = fi.FieldType;
2598 public string Name {
2600 return FieldInfo.Name;
2604 public bool IsInstance {
2606 return !FieldInfo.IsStatic;
2610 public bool IsStatic {
2612 return FieldInfo.IsStatic;
2616 public Type DeclaringType {
2618 return FieldInfo.DeclaringType;
2622 public Expression InstanceExpression {
2624 return instance_expr;
2628 instance_expr = value;
2632 public VariableInfo VariableInfo {
2634 return variable_info;
2638 override public Expression DoResolve (EmitContext ec)
2640 if (!FieldInfo.IsStatic){
2641 if (instance_expr == null){
2643 // This can happen when referencing an instance field using
2644 // a fully qualified type expression: TypeName.InstanceField = xxx
2646 SimpleName.Error_ObjectRefRequired (ec, loc, FieldInfo.Name);
2650 // Resolve the field's instance expression while flow analysis is turned
2651 // off: when accessing a field "a.b", we must check whether the field
2652 // "a.b" is initialized, not whether the whole struct "a" is initialized.
2653 instance_expr = instance_expr.Resolve (ec, ResolveFlags.VariableOrValue |
2654 ResolveFlags.DisableFlowAnalysis);
2655 if (instance_expr == null)
2659 ObsoleteAttribute oa;
2660 FieldBase f = TypeManager.GetField (FieldInfo);
2662 oa = f.GetObsoleteAttribute (f.Parent);
2664 AttributeTester.Report_ObsoleteMessage (oa, f.GetSignatureForError (), loc);
2666 // To be sure that type is external because we do not register generated fields
2667 } else if (!(FieldInfo.DeclaringType is TypeBuilder)) {
2668 oa = AttributeTester.GetMemberObsoleteAttribute (FieldInfo);
2670 AttributeTester.Report_ObsoleteMessage (oa, TypeManager.GetFullNameSignature (FieldInfo), loc);
2673 // If the instance expression is a local variable or parameter.
2674 IVariable var = instance_expr as IVariable;
2675 if ((var == null) || (var.VariableInfo == null))
2678 VariableInfo vi = var.VariableInfo;
2679 if (!vi.IsFieldAssigned (ec, FieldInfo.Name, loc))
2682 variable_info = vi.GetSubStruct (FieldInfo.Name);
2686 void Report_AssignToReadonly (bool is_instance)
2691 msg = "Readonly field can not be assigned outside " +
2692 "of constructor or variable initializer";
2694 msg = "A static readonly field can only be assigned in " +
2695 "a static constructor";
2697 Report.Error (is_instance ? 191 : 198, loc, msg);
2700 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
2702 IVariable var = instance_expr as IVariable;
2703 if ((var != null) && (var.VariableInfo != null))
2704 var.VariableInfo.SetFieldAssigned (ec, FieldInfo.Name);
2706 Expression e = DoResolve (ec);
2711 if (!FieldInfo.IsStatic && (instance_expr.Type.IsValueType && !(instance_expr is IMemoryLocation))) {
2712 // FIXME: Provide better error reporting.
2713 Error (1612, "Cannot modify expression because it is not a variable.");
2717 if (!FieldInfo.IsInitOnly)
2720 FieldBase fb = TypeManager.GetField (FieldInfo);
2725 // InitOnly fields can only be assigned in constructors
2728 if (ec.IsConstructor){
2729 if (IsStatic && !ec.IsStatic)
2730 Report_AssignToReadonly (false);
2732 if (ec.ContainerType == FieldInfo.DeclaringType)
2736 Report_AssignToReadonly (!IsStatic);
2741 public bool VerifyFixed (bool is_expression)
2743 IVariable variable = instance_expr as IVariable;
2744 if ((variable == null) || !variable.VerifyFixed (true))
2750 public void Emit (EmitContext ec, bool leave_copy)
2752 ILGenerator ig = ec.ig;
2753 bool is_volatile = false;
2755 if (FieldInfo is FieldBuilder){
2756 FieldBase f = TypeManager.GetField (FieldInfo);
2758 if ((f.ModFlags & Modifiers.VOLATILE) != 0)
2761 f.status |= Field.Status.USED;
2765 if (FieldInfo.IsStatic){
2767 ig.Emit (OpCodes.Volatile);
2769 ig.Emit (OpCodes.Ldsfld, FieldInfo);
2775 ig.Emit (OpCodes.Volatile);
2777 ig.Emit (OpCodes.Ldfld, FieldInfo);
2781 ec.ig.Emit (OpCodes.Dup);
2782 if (!FieldInfo.IsStatic) {
2783 temp = new LocalTemporary (ec, this.Type);
2789 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
2791 FieldAttributes fa = FieldInfo.Attributes;
2792 bool is_static = (fa & FieldAttributes.Static) != 0;
2793 bool is_readonly = (fa & FieldAttributes.InitOnly) != 0;
2794 ILGenerator ig = ec.ig;
2795 prepared = prepare_for_load;
2797 if (is_readonly && !ec.IsConstructor){
2798 Report_AssignToReadonly (!is_static);
2804 if (prepare_for_load)
2805 ig.Emit (OpCodes.Dup);
2810 ec.ig.Emit (OpCodes.Dup);
2811 if (!FieldInfo.IsStatic) {
2812 temp = new LocalTemporary (ec, this.Type);
2817 if (FieldInfo is FieldBuilder){
2818 FieldBase f = TypeManager.GetField (FieldInfo);
2820 if ((f.ModFlags & Modifiers.VOLATILE) != 0)
2821 ig.Emit (OpCodes.Volatile);
2823 f.status |= Field.Status.ASSIGNED;
2828 ig.Emit (OpCodes.Stsfld, FieldInfo);
2830 ig.Emit (OpCodes.Stfld, FieldInfo);
2836 void EmitInstance (EmitContext ec)
2838 if (instance_expr.Type.IsValueType) {
2839 if (instance_expr is IMemoryLocation) {
2840 ((IMemoryLocation) instance_expr).AddressOf (ec, AddressOp.LoadStore);
2842 LocalTemporary t = new LocalTemporary (ec, instance_expr.Type);
2843 instance_expr.Emit (ec);
2845 t.AddressOf (ec, AddressOp.Store);
2848 instance_expr.Emit (ec);
2851 public override void Emit (EmitContext ec)
2856 public void AddressOf (EmitContext ec, AddressOp mode)
2858 ILGenerator ig = ec.ig;
2860 if (FieldInfo is FieldBuilder){
2861 FieldBase f = TypeManager.GetField (FieldInfo);
2863 if ((f.ModFlags & Modifiers.VOLATILE) != 0){
2864 Error (676, "volatile variable: can not take its address, or pass as ref/out parameter");
2868 if ((mode & AddressOp.Store) != 0)
2869 f.status |= Field.Status.ASSIGNED;
2870 if ((mode & AddressOp.Load) != 0)
2871 f.status |= Field.Status.USED;
2876 // Handle initonly fields specially: make a copy and then
2877 // get the address of the copy.
2880 if (FieldInfo.IsInitOnly){
2882 if (ec.IsConstructor){
2883 if (FieldInfo.IsStatic){
2895 local = ig.DeclareLocal (type);
2896 ig.Emit (OpCodes.Stloc, local);
2897 ig.Emit (OpCodes.Ldloca, local);
2902 if (FieldInfo.IsStatic){
2903 ig.Emit (OpCodes.Ldsflda, FieldInfo);
2906 ig.Emit (OpCodes.Ldflda, FieldInfo);
2912 // A FieldExpr whose address can not be taken
2914 public class FieldExprNoAddress : FieldExpr, IMemoryLocation {
2915 public FieldExprNoAddress (FieldInfo fi, Location loc) : base (fi, loc)
2919 public new void AddressOf (EmitContext ec, AddressOp mode)
2921 Report.Error (-215, "Report this: Taking the address of a remapped parameter not supported");
2926 /// Expression that evaluates to a Property. The Assign class
2927 /// might set the `Value' expression if we are in an assignment.
2929 /// This is not an LValue because we need to re-write the expression, we
2930 /// can not take data from the stack and store it.
2932 public class PropertyExpr : ExpressionStatement, IAssignMethod, IMemberExpr {
2933 public readonly PropertyInfo PropertyInfo;
2936 // This is set externally by the `BaseAccess' class
2939 MethodInfo getter, setter;
2941 bool must_do_cs1540_check;
2943 Expression instance_expr;
2944 LocalTemporary temp;
2947 public PropertyExpr (EmitContext ec, PropertyInfo pi, Location l)
2950 eclass = ExprClass.PropertyAccess;
2954 type = TypeManager.TypeToCoreType (pi.PropertyType);
2956 ResolveAccessors (ec);
2959 public string Name {
2961 return PropertyInfo.Name;
2965 public bool IsInstance {
2971 public bool IsStatic {
2977 public Type DeclaringType {
2979 return PropertyInfo.DeclaringType;
2984 // The instance expression associated with this expression
2986 public Expression InstanceExpression {
2988 instance_expr = value;
2992 return instance_expr;
2996 public bool VerifyAssignable ()
2998 if (setter == null) {
2999 Report.Error (200, loc,
3000 "The property `" + PropertyInfo.Name +
3001 "' can not be assigned to, as it has not set accessor");
3008 void FindAccessors (Type invocation_type)
3010 BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic |
3011 BindingFlags.Static | BindingFlags.Instance |
3012 BindingFlags.DeclaredOnly;
3014 Type current = PropertyInfo.DeclaringType;
3015 for (; current != null; current = current.BaseType) {
3016 MemberInfo[] group = TypeManager.MemberLookup (
3017 invocation_type, invocation_type, current,
3018 MemberTypes.Property, flags, PropertyInfo.Name, null);
3023 if (group.Length != 1)
3024 // Oooops, can this ever happen ?
3027 PropertyInfo pi = (PropertyInfo) group [0];
3030 getter = pi.GetGetMethod (true);;
3033 setter = pi.GetSetMethod (true);;
3035 MethodInfo accessor = getter != null ? getter : setter;
3037 if (!accessor.IsVirtual)
3042 bool IsAccessorAccessible (Type invocation_type, MethodInfo mi)
3044 MethodAttributes ma = mi.Attributes & MethodAttributes.MemberAccessMask;
3047 // If only accessible to the current class or children
3049 if (ma == MethodAttributes.Private) {
3050 Type declaring_type = mi.DeclaringType;
3052 if (invocation_type != declaring_type)
3053 return TypeManager.IsSubclassOrNestedChildOf (invocation_type, declaring_type);
3058 // FamAndAssem requires that we not only derivate, but we are on the
3061 if (ma == MethodAttributes.FamANDAssem){
3062 return (mi.DeclaringType.Assembly != invocation_type.Assembly);
3065 // Assembly and FamORAssem succeed if we're in the same assembly.
3066 if ((ma == MethodAttributes.Assembly) || (ma == MethodAttributes.FamORAssem)){
3067 if (mi.DeclaringType.Assembly == invocation_type.Assembly)
3071 // We already know that we aren't in the same assembly.
3072 if (ma == MethodAttributes.Assembly)
3075 // Family and FamANDAssem require that we derive.
3076 if ((ma == MethodAttributes.Family) || (ma == MethodAttributes.FamANDAssem) || (ma == MethodAttributes.FamORAssem)){
3077 if (!TypeManager.IsSubclassOrNestedChildOf (invocation_type, mi.DeclaringType))
3080 if (!TypeManager.IsNestedChildOf (invocation_type, mi.DeclaringType))
3081 must_do_cs1540_check = true;
3090 // We also perform the permission checking here, as the PropertyInfo does not
3091 // hold the information for the accessibility of its setter/getter
3093 void ResolveAccessors (EmitContext ec)
3095 FindAccessors (ec.ContainerType);
3097 if (setter != null && !IsAccessorAccessible (ec.ContainerType, setter) ||
3098 getter != null && !IsAccessorAccessible (ec.ContainerType, getter)) {
3099 Report.Error (122, loc, "'{0}' is inaccessible due to its protection level", PropertyInfo.Name);
3102 is_static = getter != null ? getter.IsStatic : setter.IsStatic;
3105 bool InstanceResolve (EmitContext ec)
3107 if ((instance_expr == null) && ec.IsStatic && !is_static) {
3108 SimpleName.Error_ObjectRefRequired (ec, loc, PropertyInfo.Name);
3112 if (instance_expr != null) {
3113 instance_expr = instance_expr.DoResolve (ec);
3114 if (instance_expr == null)
3118 if (must_do_cs1540_check && (instance_expr != null)) {
3119 if ((instance_expr.Type != ec.ContainerType) &&
3120 ec.ContainerType.IsSubclassOf (instance_expr.Type)) {
3121 Report.Error (1540, loc, "Cannot access protected member `" +
3122 PropertyInfo.DeclaringType + "." + PropertyInfo.Name +
3123 "' via a qualifier of type `" +
3124 TypeManager.CSharpName (instance_expr.Type) +
3125 "'; the qualifier must be of type `" +
3126 TypeManager.CSharpName (ec.ContainerType) +
3127 "' (or derived from it)");
3135 override public Expression DoResolve (EmitContext ec)
3137 if (getter != null){
3138 if (TypeManager.GetArgumentTypes (getter).Length != 0){
3140 117, loc, "`{0}' does not contain a " +
3141 "definition for `{1}'.", getter.DeclaringType,
3147 if (getter == null){
3149 // The following condition happens if the PropertyExpr was
3150 // created, but is invalid (ie, the property is inaccessible),
3151 // and we did not want to embed the knowledge about this in
3152 // the caller routine. This only avoids double error reporting.
3157 Report.Error (154, loc,
3158 "The property `" + PropertyInfo.Name +
3159 "' can not be used in " +
3160 "this context because it lacks a get accessor");
3164 if (!InstanceResolve (ec))
3168 // Only base will allow this invocation to happen.
3170 if (IsBase && getter.IsAbstract){
3171 Report.Error (205, loc, "Cannot call an abstract base property: " +
3172 PropertyInfo.DeclaringType + "." +PropertyInfo.Name);
3179 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
3181 if (setter == null){
3183 // The following condition happens if the PropertyExpr was
3184 // created, but is invalid (ie, the property is inaccessible),
3185 // and we did not want to embed the knowledge about this in
3186 // the caller routine. This only avoids double error reporting.
3191 Report.Error (154, loc,
3192 "The property `" + PropertyInfo.Name +
3193 "' can not be used in " +
3194 "this context because it lacks a set accessor");
3198 if (TypeManager.GetArgumentTypes (setter).Length != 1){
3200 117, loc, "`{0}' does not contain a " +
3201 "definition for `{1}'.", getter.DeclaringType,
3206 if (!InstanceResolve (ec))
3210 // Only base will allow this invocation to happen.
3212 if (IsBase && setter.IsAbstract){
3213 Report.Error (205, loc, "Cannot call an abstract base property: " +
3214 PropertyInfo.DeclaringType + "." +PropertyInfo.Name);
3219 // Check that we are not making changes to a temporary memory location
3221 if (instance_expr != null && instance_expr.Type.IsValueType && !(instance_expr is IMemoryLocation)) {
3222 // FIXME: Provide better error reporting.
3223 Error (1612, "Cannot modify expression because it is not a variable.");
3232 public override void Emit (EmitContext ec)
3237 void EmitInstance (EmitContext ec)
3242 if (instance_expr.Type.IsValueType) {
3243 if (instance_expr is IMemoryLocation) {
3244 ((IMemoryLocation) instance_expr).AddressOf (ec, AddressOp.LoadStore);
3246 LocalTemporary t = new LocalTemporary (ec, instance_expr.Type);
3247 instance_expr.Emit (ec);
3249 t.AddressOf (ec, AddressOp.Store);
3252 instance_expr.Emit (ec);
3255 ec.ig.Emit (OpCodes.Dup);
3259 public void Emit (EmitContext ec, bool leave_copy)
3265 // Special case: length of single dimension array property is turned into ldlen
3267 if ((getter == TypeManager.system_int_array_get_length) ||
3268 (getter == TypeManager.int_array_get_length)){
3269 Type iet = instance_expr.Type;
3272 // System.Array.Length can be called, but the Type does not
3273 // support invoking GetArrayRank, so test for that case first
3275 if (iet != TypeManager.array_type && (iet.GetArrayRank () == 1)) {
3276 ec.ig.Emit (OpCodes.Ldlen);
3277 ec.ig.Emit (OpCodes.Conv_I4);
3282 Invocation.EmitCall (ec, IsBase, IsStatic, new EmptyAddressOf (), getter, null, loc);
3287 ec.ig.Emit (OpCodes.Dup);
3289 temp = new LocalTemporary (ec, this.Type);
3295 // Implements the IAssignMethod interface for assignments
3297 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
3299 prepared = prepare_for_load;
3305 ec.ig.Emit (OpCodes.Dup);
3307 temp = new LocalTemporary (ec, this.Type);
3312 ArrayList args = new ArrayList (1);
3313 args.Add (new Argument (new EmptyAddressOf (), Argument.AType.Expression));
3315 Invocation.EmitCall (ec, IsBase, IsStatic, new EmptyAddressOf (), setter, args, loc);
3321 override public void EmitStatement (EmitContext ec)
3324 ec.ig.Emit (OpCodes.Pop);
3329 /// Fully resolved expression that evaluates to an Event
3331 public class EventExpr : Expression, IMemberExpr {
3332 public readonly EventInfo EventInfo;
3333 Expression instance_expr;
3336 MethodInfo add_accessor, remove_accessor;
3338 public EventExpr (EventInfo ei, Location loc)
3342 eclass = ExprClass.EventAccess;
3344 add_accessor = TypeManager.GetAddMethod (ei);
3345 remove_accessor = TypeManager.GetRemoveMethod (ei);
3347 if (add_accessor.IsStatic || remove_accessor.IsStatic)
3350 if (EventInfo is MyEventBuilder){
3351 MyEventBuilder eb = (MyEventBuilder) EventInfo;
3352 type = eb.EventType;
3355 type = EventInfo.EventHandlerType;
3358 public string Name {
3360 return EventInfo.Name;
3364 public bool IsInstance {
3370 public bool IsStatic {
3376 public Type DeclaringType {
3378 return EventInfo.DeclaringType;
3382 public Expression InstanceExpression {
3384 return instance_expr;
3388 instance_expr = value;
3392 public override Expression DoResolve (EmitContext ec)
3394 if (instance_expr != null) {
3395 instance_expr = instance_expr.DoResolve (ec);
3396 if (instance_expr == null)
3404 public override void Emit (EmitContext ec)
3406 Report.Error (70, loc, "The event `" + Name + "' can only appear on the left hand side of += or -= (except on the defining type)");
3409 public void EmitAddOrRemove (EmitContext ec, Expression source)
3411 BinaryDelegate source_del = (BinaryDelegate) source;
3412 Expression handler = source_del.Right;
3414 Argument arg = new Argument (handler, Argument.AType.Expression);
3415 ArrayList args = new ArrayList ();
3419 if (source_del.IsAddition)
3420 Invocation.EmitCall (
3421 ec, false, IsStatic, instance_expr, add_accessor, args, loc);
3423 Invocation.EmitCall (
3424 ec, false, IsStatic, instance_expr, remove_accessor, args, loc);