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);
195 // Not nice but we have broken hierarchy
196 public virtual void CheckMarshallByRefAccess (Type container) {}
199 /// Tests presence of ObsoleteAttribute and report proper error
201 protected void CheckObsoleteAttribute (Type type)
203 ObsoleteAttribute obsolete_attr = AttributeTester.GetObsoleteAttribute (type);
204 if (obsolete_attr == null)
207 AttributeTester.Report_ObsoleteMessage (obsolete_attr, type.FullName, loc);
210 public static bool IsAccessorAccessible (Type invocation_type, MethodInfo mi, out bool must_do_cs1540_check)
212 MethodAttributes ma = mi.Attributes & MethodAttributes.MemberAccessMask;
214 must_do_cs1540_check = false; // by default we do not check for this
217 // If only accessible to the current class or children
219 if (ma == MethodAttributes.Private) {
220 Type declaring_type = mi.DeclaringType;
222 if (invocation_type != declaring_type)
223 return TypeManager.IsSubclassOrNestedChildOf (invocation_type, declaring_type);
228 // FamAndAssem requires that we not only derivate, but we are on the
231 if (ma == MethodAttributes.FamANDAssem){
232 return (mi.DeclaringType.Assembly != invocation_type.Assembly);
235 // Assembly and FamORAssem succeed if we're in the same assembly.
236 if ((ma == MethodAttributes.Assembly) || (ma == MethodAttributes.FamORAssem)){
237 if (mi.DeclaringType.Assembly == invocation_type.Assembly)
241 // We already know that we aren't in the same assembly.
242 if (ma == MethodAttributes.Assembly)
245 // Family and FamANDAssem require that we derive.
246 if ((ma == MethodAttributes.Family) || (ma == MethodAttributes.FamANDAssem) || (ma == MethodAttributes.FamORAssem)){
247 if (!TypeManager.IsSubclassOrNestedChildOf (invocation_type, mi.DeclaringType))
250 if (!TypeManager.IsNestedChildOf (invocation_type, mi.DeclaringType))
251 must_do_cs1540_check = true;
260 /// Performs semantic analysis on the Expression
264 /// The Resolve method is invoked to perform the semantic analysis
267 /// The return value is an expression (it can be the
268 /// same expression in some cases) or a new
269 /// expression that better represents this node.
271 /// For example, optimizations of Unary (LiteralInt)
272 /// would return a new LiteralInt with a negated
275 /// If there is an error during semantic analysis,
276 /// then an error should be reported (using Report)
277 /// and a null value should be returned.
279 /// There are two side effects expected from calling
280 /// Resolve(): the the field variable "eclass" should
281 /// be set to any value of the enumeration
282 /// `ExprClass' and the type variable should be set
283 /// to a valid type (this is the type of the
286 public abstract Expression DoResolve (EmitContext ec);
288 public virtual Expression DoResolveLValue (EmitContext ec, Expression right_side)
290 return DoResolve (ec);
294 // This is used if the expression should be resolved as a type.
295 // the default implementation fails. Use this method in
296 // those participants in the SimpleName chain system.
298 public virtual Expression ResolveAsTypeStep (EmitContext ec)
304 // This is used to resolve the expression as a type, a null
305 // value will be returned if the expression is not a type
308 public TypeExpr ResolveAsTypeTerminal (EmitContext ec, bool silent)
310 int errors = Report.Errors;
312 TypeExpr te = ResolveAsTypeStep (ec) as TypeExpr;
314 if (te == null || te.eclass != ExprClass.Type) {
315 if (!silent && errors == Report.Errors)
316 Report.Error (246, Location, "Cannot find type '{0}'", ToString ());
320 if (!te.CheckAccessLevel (ec.DeclSpace)) {
321 Report.Error (122, Location, "'{0}' is inaccessible due to its protection level", te.Name);
329 /// Resolves an expression and performs semantic analysis on it.
333 /// Currently Resolve wraps DoResolve to perform sanity
334 /// checking and assertion checking on what we expect from Resolve.
336 public Expression Resolve (EmitContext ec, ResolveFlags flags)
338 if ((flags & ResolveFlags.MaskExprClass) == ResolveFlags.Type)
339 return ResolveAsTypeStep (ec);
341 bool old_do_flow_analysis = ec.DoFlowAnalysis;
342 if ((flags & ResolveFlags.DisableFlowAnalysis) != 0)
343 ec.DoFlowAnalysis = false;
346 bool intermediate = (flags & ResolveFlags.Intermediate) == ResolveFlags.Intermediate;
347 if (this is SimpleName)
348 e = ((SimpleName) this).DoResolveAllowStatic (ec, intermediate);
353 ec.DoFlowAnalysis = old_do_flow_analysis;
358 if (e is SimpleName){
359 SimpleName s = (SimpleName) e;
361 if ((flags & ResolveFlags.SimpleName) == 0) {
362 MemberLookupFailed (ec, null, ec.ContainerType, s.Name,
363 ec.DeclSpace.Name, loc);
370 if ((e is TypeExpr) || (e is ComposedCast)) {
371 if ((flags & ResolveFlags.Type) == 0) {
372 e.Error_UnexpectedKind (flags, loc);
381 if ((flags & ResolveFlags.VariableOrValue) == 0) {
382 e.Error_UnexpectedKind (flags, loc);
387 case ExprClass.MethodGroup:
388 if (RootContext.Version == LanguageVersion.ISO_1){
389 if ((flags & ResolveFlags.MethodGroup) == 0) {
390 ((MethodGroupExpr) e).ReportUsageError ();
396 case ExprClass.Value:
397 case ExprClass.Variable:
398 case ExprClass.PropertyAccess:
399 case ExprClass.EventAccess:
400 case ExprClass.IndexerAccess:
401 if ((flags & ResolveFlags.VariableOrValue) == 0) {
402 Console.WriteLine ("I got: {0} and {1}", e.GetType (), e);
403 Console.WriteLine ("I am {0} and {1}", this.GetType (), this);
404 FieldInfo fi = ((FieldExpr) e).FieldInfo;
406 Console.WriteLine ("{0} and {1}", fi.DeclaringType, fi.Name);
407 e.Error_UnexpectedKind (flags, loc);
413 throw new Exception ("Expression " + e.GetType () +
414 " ExprClass is Invalid after resolve");
418 throw new Exception (
419 "Expression " + e.GetType () +
420 " did not set its type after Resolve\n" +
421 "called from: " + this.GetType ());
427 /// Resolves an expression and performs semantic analysis on it.
429 public Expression Resolve (EmitContext ec)
431 return Resolve (ec, ResolveFlags.VariableOrValue);
435 /// Resolves an expression for LValue assignment
439 /// Currently ResolveLValue wraps DoResolveLValue to perform sanity
440 /// checking and assertion checking on what we expect from Resolve
442 public Expression ResolveLValue (EmitContext ec, Expression right_side)
444 Expression e = DoResolveLValue (ec, right_side);
447 if (e is SimpleName){
448 SimpleName s = (SimpleName) e;
449 MemberLookupFailed (ec, null, ec.ContainerType, s.Name,
450 ec.DeclSpace.Name, loc);
454 if (e.eclass == ExprClass.Invalid)
455 throw new Exception ("Expression " + e +
456 " ExprClass is Invalid after resolve");
458 if (e.eclass == ExprClass.MethodGroup) {
459 ((MethodGroupExpr) e).ReportUsageError ();
464 throw new Exception ("Expression " + e +
465 " did not set its type after Resolve");
472 /// Emits the code for the expression
476 /// The Emit method is invoked to generate the code
477 /// for the expression.
479 public abstract void Emit (EmitContext ec);
481 public virtual void EmitBranchable (EmitContext ec, Label target, bool onTrue)
484 ec.ig.Emit (onTrue ? OpCodes.Brtrue : OpCodes.Brfalse, target);
488 /// Protected constructor. Only derivate types should
489 /// be able to be created
492 protected Expression ()
494 eclass = ExprClass.Invalid;
499 /// Returns a literalized version of a literal FieldInfo
503 /// The possible return values are:
504 /// IntConstant, UIntConstant
505 /// LongLiteral, ULongConstant
506 /// FloatConstant, DoubleConstant
509 /// The value returned is already resolved.
511 public static Constant Constantify (object v, Type t)
513 if (t == TypeManager.int32_type)
514 return new IntConstant ((int) v);
515 else if (t == TypeManager.uint32_type)
516 return new UIntConstant ((uint) v);
517 else if (t == TypeManager.int64_type)
518 return new LongConstant ((long) v);
519 else if (t == TypeManager.uint64_type)
520 return new ULongConstant ((ulong) v);
521 else if (t == TypeManager.float_type)
522 return new FloatConstant ((float) v);
523 else if (t == TypeManager.double_type)
524 return new DoubleConstant ((double) v);
525 else if (t == TypeManager.string_type)
526 return new StringConstant ((string) v);
527 else if (t == TypeManager.short_type)
528 return new ShortConstant ((short)v);
529 else if (t == TypeManager.ushort_type)
530 return new UShortConstant ((ushort)v);
531 else if (t == TypeManager.sbyte_type)
532 return new SByteConstant (((sbyte)v));
533 else if (t == TypeManager.byte_type)
534 return new ByteConstant ((byte)v);
535 else if (t == TypeManager.char_type)
536 return new CharConstant ((char)v);
537 else if (t == TypeManager.bool_type)
538 return new BoolConstant ((bool) v);
539 else if (t == TypeManager.decimal_type)
540 return new DecimalConstant ((decimal) v);
541 else if (TypeManager.IsEnumType (t)){
542 Type real_type = TypeManager.TypeToCoreType (v.GetType ());
544 real_type = System.Enum.GetUnderlyingType (real_type);
546 Constant e = Constantify (v, real_type);
548 return new EnumConstant (e, t);
549 } else if (v == null && !TypeManager.IsValueType (t))
550 return NullLiteral.Null;
552 throw new Exception ("Unknown type for constant (" + t +
557 /// Returns a fully formed expression after a MemberLookup
559 public static Expression ExprClassFromMemberInfo (EmitContext ec, MemberInfo mi, Location loc)
562 return new EventExpr ((EventInfo) mi, loc);
563 else if (mi is FieldInfo)
564 return new FieldExpr ((FieldInfo) mi, loc);
565 else if (mi is PropertyInfo)
566 return new PropertyExpr (ec, (PropertyInfo) mi, loc);
567 else if (mi is Type){
568 return new TypeExpression ((System.Type) mi, loc);
575 private static ArrayList almostMatchedMembers = new ArrayList (4);
578 // FIXME: Probably implement a cache for (t,name,current_access_set)?
580 // This code could use some optimizations, but we need to do some
581 // measurements. For example, we could use a delegate to `flag' when
582 // something can not any longer be a method-group (because it is something
586 // If the return value is an Array, then it is an array of
589 // If the return value is an MemberInfo, it is anything, but a Method
593 // FIXME: When calling MemberLookup inside an `Invocation', we should pass
594 // the arguments here and have MemberLookup return only the methods that
595 // match the argument count/type, unlike we are doing now (we delay this
598 // This is so we can catch correctly attempts to invoke instance methods
599 // from a static body (scan for error 120 in ResolveSimpleName).
602 // FIXME: Potential optimization, have a static ArrayList
605 public static Expression MemberLookup (EmitContext ec, Type queried_type, string name,
606 MemberTypes mt, BindingFlags bf, Location loc)
608 return MemberLookup (ec, ec.ContainerType, null, queried_type, name, mt, bf, loc);
612 // Lookup type `queried_type' for code in class `container_type' with a qualifier of
613 // `qualifier_type' or null to lookup members in the current class.
616 public static Expression MemberLookup (EmitContext ec, Type container_type,
617 Type qualifier_type, Type queried_type,
618 string name, MemberTypes mt,
619 BindingFlags bf, Location loc)
621 almostMatchedMembers.Clear ();
623 MemberInfo [] mi = TypeManager.MemberLookup (container_type, qualifier_type,
624 queried_type, mt, bf, name, almostMatchedMembers);
629 int count = mi.Length;
631 if (mi [0] is MethodBase)
632 return new MethodGroupExpr (mi, loc);
637 return ExprClassFromMemberInfo (ec, mi [0], loc);
640 public const MemberTypes AllMemberTypes =
641 MemberTypes.Constructor |
645 MemberTypes.NestedType |
646 MemberTypes.Property;
648 public const BindingFlags AllBindingFlags =
649 BindingFlags.Public |
650 BindingFlags.Static |
651 BindingFlags.Instance;
653 public static Expression MemberLookup (EmitContext ec, Type queried_type,
654 string name, Location loc)
656 return MemberLookup (ec, ec.ContainerType, null, queried_type, name,
657 AllMemberTypes, AllBindingFlags, loc);
660 public static Expression MemberLookup (EmitContext ec, Type qualifier_type,
661 Type queried_type, string name, Location loc)
663 return MemberLookup (ec, ec.ContainerType, qualifier_type, queried_type,
664 name, AllMemberTypes, AllBindingFlags, loc);
667 public static Expression MethodLookup (EmitContext ec, Type queried_type,
668 string name, Location loc)
670 return MemberLookup (ec, ec.ContainerType, null, queried_type, name,
671 MemberTypes.Method, AllBindingFlags, loc);
675 /// This is a wrapper for MemberLookup that is not used to "probe", but
676 /// to find a final definition. If the final definition is not found, we
677 /// look for private members and display a useful debugging message if we
680 public static Expression MemberLookupFinal (EmitContext ec, Type qualifier_type,
681 Type queried_type, string name, Location loc)
683 return MemberLookupFinal (ec, qualifier_type, queried_type, name,
684 AllMemberTypes, AllBindingFlags, loc);
687 public static Expression MemberLookupFinal (EmitContext ec, Type qualifier_type,
688 Type queried_type, string name,
689 MemberTypes mt, BindingFlags bf,
694 int errors = Report.Errors;
696 e = MemberLookup (ec, ec.ContainerType, qualifier_type, queried_type, name, mt, bf, loc);
698 if (e == null && errors == Report.Errors)
699 // No errors were reported by MemberLookup, but there was an error.
700 MemberLookupFailed (ec, qualifier_type, queried_type, name, null, loc);
705 public static void MemberLookupFailed (EmitContext ec, Type qualifier_type,
706 Type queried_type, string name,
707 string class_name, Location loc)
709 if (almostMatchedMembers.Count != 0) {
710 if (qualifier_type == null) {
711 foreach (MemberInfo m in almostMatchedMembers)
712 Report.Error (38, loc,
713 "Cannot access non-static member `{0}' via nested type `{1}'",
714 TypeManager.GetFullNameSignature (m),
715 TypeManager.CSharpName (ec.ContainerType));
719 if (qualifier_type != ec.ContainerType) {
720 // Although a derived class can access protected members of
721 // its base class it cannot do so through an instance of the
722 // base class (CS1540). If the qualifier_type is a parent of the
723 // ec.ContainerType and the lookup succeeds with the latter one,
724 // then we are in this situation.
725 foreach (MemberInfo m in almostMatchedMembers)
726 Report.Error (1540, loc,
727 "Cannot access protected member `{0}' via a qualifier of type `{1}';"
728 + " the qualifier must be of type `{2}' (or derived from it)",
729 TypeManager.GetFullNameSignature (m),
730 TypeManager.CSharpName (qualifier_type),
731 TypeManager.CSharpName (ec.ContainerType));
734 almostMatchedMembers.Clear ();
737 object lookup = TypeManager.MemberLookup (queried_type, null, queried_type,
738 AllMemberTypes, AllBindingFlags |
739 BindingFlags.NonPublic, name, null);
741 if (lookup == null) {
742 if (class_name != null)
743 Report.Error (103, loc, "The name `" + name + "' could not be " +
744 "found in `" + class_name + "'");
747 117, loc, "`" + queried_type + "' does not contain a " +
748 "definition for `" + name + "'");
752 if (qualifier_type != null)
753 Report.Error (122, loc, "'{0}' is inaccessible due to its protection level", TypeManager.CSharpName (qualifier_type) + "." + name);
754 else if (name == ".ctor") {
755 Report.Error (143, loc, String.Format ("The type {0} has no constructors defined",
756 TypeManager.CSharpName (queried_type)));
758 Report.Error (122, loc, "'{0}' is inaccessible due to its protection level", name);
762 static public MemberInfo GetFieldFromEvent (EventExpr event_expr)
764 EventInfo ei = event_expr.EventInfo;
766 return TypeManager.GetPrivateFieldOfEvent (ei);
770 /// Returns an expression that can be used to invoke operator true
771 /// on the expression if it exists.
773 static public StaticCallExpr GetOperatorTrue (EmitContext ec, Expression e, Location loc)
775 return GetOperatorTrueOrFalse (ec, e, true, loc);
779 /// Returns an expression that can be used to invoke operator false
780 /// on the expression if it exists.
782 static public StaticCallExpr GetOperatorFalse (EmitContext ec, Expression e, Location loc)
784 return GetOperatorTrueOrFalse (ec, e, false, loc);
787 static StaticCallExpr GetOperatorTrueOrFalse (EmitContext ec, Expression e, bool is_true, Location loc)
790 Expression operator_group;
792 operator_group = MethodLookup (ec, e.Type, is_true ? "op_True" : "op_False", loc);
793 if (operator_group == null)
796 ArrayList arguments = new ArrayList ();
797 arguments.Add (new Argument (e, Argument.AType.Expression));
798 method = Invocation.OverloadResolve (
799 ec, (MethodGroupExpr) operator_group, arguments, false, loc);
804 return new StaticCallExpr ((MethodInfo) method, arguments, loc);
808 /// Resolves the expression `e' into a boolean expression: either through
809 /// an implicit conversion, or through an `operator true' invocation
811 public static Expression ResolveBoolean (EmitContext ec, Expression e, Location loc)
817 if (e.Type == TypeManager.bool_type)
820 Expression converted = Convert.ImplicitConversion (ec, e, TypeManager.bool_type, new Location (-1));
822 if (converted != null)
826 // If no implicit conversion to bool exists, try using `operator true'
828 Expression operator_true = Expression.GetOperatorTrue (ec, e, loc);
829 if (operator_true == null){
830 Report.Error (31, loc, "Can not convert the expression to a boolean");
833 return operator_true;
836 static string ExprClassName (ExprClass c)
839 case ExprClass.Invalid:
841 case ExprClass.Value:
843 case ExprClass.Variable:
845 case ExprClass.Namespace:
849 case ExprClass.MethodGroup:
850 return "method group";
851 case ExprClass.PropertyAccess:
852 return "property access";
853 case ExprClass.EventAccess:
854 return "event access";
855 case ExprClass.IndexerAccess:
856 return "indexer access";
857 case ExprClass.Nothing:
860 throw new Exception ("Should not happen");
864 /// Reports that we were expecting `expr' to be of class `expected'
866 public void Error_UnexpectedKind (string expected, Location loc)
868 string kind = "Unknown";
870 kind = ExprClassName (eclass);
872 Report.Error (118, loc, "Expression denotes a `" + kind +
873 "' where a `" + expected + "' was expected");
876 public void Error_UnexpectedKind (ResolveFlags flags, Location loc)
878 ArrayList valid = new ArrayList (10);
880 if ((flags & ResolveFlags.VariableOrValue) != 0) {
881 valid.Add ("variable");
885 if ((flags & ResolveFlags.Type) != 0)
888 if ((flags & ResolveFlags.MethodGroup) != 0)
889 valid.Add ("method group");
891 if ((flags & ResolveFlags.SimpleName) != 0)
892 valid.Add ("simple name");
894 if (valid.Count == 0)
895 valid.Add ("unknown");
897 StringBuilder sb = new StringBuilder ();
898 for (int i = 0; i < valid.Count; i++) {
901 else if (i == valid.Count)
903 sb.Append (valid [i]);
906 string kind = ExprClassName (eclass);
908 Error (119, "Expression denotes a `" + kind + "' where " +
909 "a `" + sb.ToString () + "' was expected");
912 static public void Error_ConstantValueCannotBeConverted (Location l, string val, Type t)
914 Report.Error (31, l, "Constant value `" + val + "' cannot be converted to " +
915 TypeManager.CSharpName (t));
918 public static void UnsafeError (Location loc)
920 Report.Error (214, loc, "Pointers may only be used in an unsafe context");
924 /// Converts the IntConstant, UIntConstant, LongConstant or
925 /// ULongConstant into the integral target_type. Notice
926 /// that we do not return an `Expression' we do return
927 /// a boxed integral type.
929 /// FIXME: Since I added the new constants, we need to
930 /// also support conversions from CharConstant, ByteConstant,
931 /// SByteConstant, UShortConstant, ShortConstant
933 /// This is used by the switch statement, so the domain
934 /// of work is restricted to the literals above, and the
935 /// targets are int32, uint32, char, byte, sbyte, ushort,
936 /// short, uint64 and int64
938 public static object ConvertIntLiteral (Constant c, Type target_type, Location loc)
940 if (!Convert.ImplicitStandardConversionExists (Convert.ConstantEC, c, target_type)){
941 Convert.Error_CannotImplicitConversion (loc, c.Type, target_type);
947 if (c.Type == target_type)
948 return ((Constant) c).GetValue ();
951 // Make into one of the literals we handle, we dont really care
952 // about this value as we will just return a few limited types
954 if (c is EnumConstant)
955 c = ((EnumConstant)c).WidenToCompilerConstant ();
957 if (c is IntConstant){
958 int v = ((IntConstant) c).Value;
960 if (target_type == TypeManager.uint32_type){
963 } else if (target_type == TypeManager.char_type){
964 if (v >= Char.MinValue && v <= Char.MaxValue)
966 } else if (target_type == TypeManager.byte_type){
967 if (v >= Byte.MinValue && v <= Byte.MaxValue)
969 } else if (target_type == TypeManager.sbyte_type){
970 if (v >= SByte.MinValue && v <= SByte.MaxValue)
972 } else if (target_type == TypeManager.short_type){
973 if (v >= Int16.MinValue && v <= UInt16.MaxValue)
975 } else if (target_type == TypeManager.ushort_type){
976 if (v >= UInt16.MinValue && v <= UInt16.MaxValue)
978 } else if (target_type == TypeManager.int64_type)
980 else if (target_type == TypeManager.uint64_type){
986 } else if (c is UIntConstant){
987 uint v = ((UIntConstant) c).Value;
989 if (target_type == TypeManager.int32_type){
990 if (v <= Int32.MaxValue)
992 } else if (target_type == TypeManager.char_type){
993 if (v >= Char.MinValue && v <= Char.MaxValue)
995 } else if (target_type == TypeManager.byte_type){
996 if (v <= Byte.MaxValue)
998 } else if (target_type == TypeManager.sbyte_type){
999 if (v <= SByte.MaxValue)
1001 } else if (target_type == TypeManager.short_type){
1002 if (v <= UInt16.MaxValue)
1004 } else if (target_type == TypeManager.ushort_type){
1005 if (v <= UInt16.MaxValue)
1007 } else if (target_type == TypeManager.int64_type)
1009 else if (target_type == TypeManager.uint64_type)
1012 } else if (c is LongConstant){
1013 long v = ((LongConstant) c).Value;
1015 if (target_type == TypeManager.int32_type){
1016 if (v >= UInt32.MinValue && v <= UInt32.MaxValue)
1018 } else if (target_type == TypeManager.uint32_type){
1019 if (v >= 0 && v <= UInt32.MaxValue)
1021 } else if (target_type == TypeManager.char_type){
1022 if (v >= Char.MinValue && v <= Char.MaxValue)
1024 } else if (target_type == TypeManager.byte_type){
1025 if (v >= Byte.MinValue && v <= Byte.MaxValue)
1027 } else if (target_type == TypeManager.sbyte_type){
1028 if (v >= SByte.MinValue && v <= SByte.MaxValue)
1030 } else if (target_type == TypeManager.short_type){
1031 if (v >= Int16.MinValue && v <= UInt16.MaxValue)
1033 } else if (target_type == TypeManager.ushort_type){
1034 if (v >= UInt16.MinValue && v <= UInt16.MaxValue)
1036 } else if (target_type == TypeManager.uint64_type){
1041 } else if (c is ULongConstant){
1042 ulong v = ((ULongConstant) c).Value;
1044 if (target_type == TypeManager.int32_type){
1045 if (v <= Int32.MaxValue)
1047 } else if (target_type == TypeManager.uint32_type){
1048 if (v <= UInt32.MaxValue)
1050 } else if (target_type == TypeManager.char_type){
1051 if (v >= Char.MinValue && v <= Char.MaxValue)
1053 } else if (target_type == TypeManager.byte_type){
1054 if (v >= Byte.MinValue && v <= Byte.MaxValue)
1056 } else if (target_type == TypeManager.sbyte_type){
1057 if (v <= (int) SByte.MaxValue)
1059 } else if (target_type == TypeManager.short_type){
1060 if (v <= UInt16.MaxValue)
1062 } else if (target_type == TypeManager.ushort_type){
1063 if (v <= UInt16.MaxValue)
1065 } else if (target_type == TypeManager.int64_type){
1066 if (v <= Int64.MaxValue)
1070 } else if (c is ByteConstant){
1071 byte v = ((ByteConstant) c).Value;
1073 if (target_type == TypeManager.int32_type)
1075 else if (target_type == TypeManager.uint32_type)
1077 else if (target_type == TypeManager.char_type)
1079 else if (target_type == TypeManager.sbyte_type){
1080 if (v <= SByte.MaxValue)
1082 } else if (target_type == TypeManager.short_type)
1084 else if (target_type == TypeManager.ushort_type)
1086 else if (target_type == TypeManager.int64_type)
1088 else if (target_type == TypeManager.uint64_type)
1091 } else if (c is SByteConstant){
1092 sbyte v = ((SByteConstant) c).Value;
1094 if (target_type == TypeManager.int32_type)
1096 else if (target_type == TypeManager.uint32_type){
1099 } else if (target_type == TypeManager.char_type){
1102 } else if (target_type == TypeManager.byte_type){
1105 } else if (target_type == TypeManager.short_type)
1107 else if (target_type == TypeManager.ushort_type){
1110 } else if (target_type == TypeManager.int64_type)
1112 else if (target_type == TypeManager.uint64_type){
1117 } else if (c is ShortConstant){
1118 short v = ((ShortConstant) c).Value;
1120 if (target_type == TypeManager.int32_type){
1122 } else if (target_type == TypeManager.uint32_type){
1125 } else if (target_type == TypeManager.char_type){
1128 } else if (target_type == TypeManager.byte_type){
1129 if (v >= Byte.MinValue && v <= Byte.MaxValue)
1131 } else if (target_type == TypeManager.sbyte_type){
1132 if (v >= SByte.MinValue && v <= SByte.MaxValue)
1134 } else if (target_type == TypeManager.ushort_type){
1137 } else if (target_type == TypeManager.int64_type)
1139 else if (target_type == TypeManager.uint64_type)
1143 } else if (c is UShortConstant){
1144 ushort v = ((UShortConstant) c).Value;
1146 if (target_type == TypeManager.int32_type)
1148 else if (target_type == TypeManager.uint32_type)
1150 else if (target_type == TypeManager.char_type){
1151 if (v >= Char.MinValue && v <= Char.MaxValue)
1153 } else if (target_type == TypeManager.byte_type){
1154 if (v >= Byte.MinValue && v <= Byte.MaxValue)
1156 } else if (target_type == TypeManager.sbyte_type){
1157 if (v <= SByte.MaxValue)
1159 } else if (target_type == TypeManager.short_type){
1160 if (v <= Int16.MaxValue)
1162 } else if (target_type == TypeManager.int64_type)
1164 else if (target_type == TypeManager.uint64_type)
1168 } else if (c is CharConstant){
1169 char v = ((CharConstant) c).Value;
1171 if (target_type == TypeManager.int32_type)
1173 else if (target_type == TypeManager.uint32_type)
1175 else if (target_type == TypeManager.byte_type){
1176 if (v >= Byte.MinValue && v <= Byte.MaxValue)
1178 } else if (target_type == TypeManager.sbyte_type){
1179 if (v <= SByte.MaxValue)
1181 } else if (target_type == TypeManager.short_type){
1182 if (v <= Int16.MaxValue)
1184 } else if (target_type == TypeManager.ushort_type)
1186 else if (target_type == TypeManager.int64_type)
1188 else if (target_type == TypeManager.uint64_type)
1193 Error_ConstantValueCannotBeConverted (loc, s, target_type);
1198 // Load the object from the pointer.
1200 public static void LoadFromPtr (ILGenerator ig, Type t)
1202 if (t == TypeManager.int32_type)
1203 ig.Emit (OpCodes.Ldind_I4);
1204 else if (t == TypeManager.uint32_type)
1205 ig.Emit (OpCodes.Ldind_U4);
1206 else if (t == TypeManager.short_type)
1207 ig.Emit (OpCodes.Ldind_I2);
1208 else if (t == TypeManager.ushort_type)
1209 ig.Emit (OpCodes.Ldind_U2);
1210 else if (t == TypeManager.char_type)
1211 ig.Emit (OpCodes.Ldind_U2);
1212 else if (t == TypeManager.byte_type)
1213 ig.Emit (OpCodes.Ldind_U1);
1214 else if (t == TypeManager.sbyte_type)
1215 ig.Emit (OpCodes.Ldind_I1);
1216 else if (t == TypeManager.uint64_type)
1217 ig.Emit (OpCodes.Ldind_I8);
1218 else if (t == TypeManager.int64_type)
1219 ig.Emit (OpCodes.Ldind_I8);
1220 else if (t == TypeManager.float_type)
1221 ig.Emit (OpCodes.Ldind_R4);
1222 else if (t == TypeManager.double_type)
1223 ig.Emit (OpCodes.Ldind_R8);
1224 else if (t == TypeManager.bool_type)
1225 ig.Emit (OpCodes.Ldind_I1);
1226 else if (t == TypeManager.intptr_type)
1227 ig.Emit (OpCodes.Ldind_I);
1228 else if (TypeManager.IsEnumType (t)) {
1229 if (t == TypeManager.enum_type)
1230 ig.Emit (OpCodes.Ldind_Ref);
1232 LoadFromPtr (ig, TypeManager.EnumToUnderlying (t));
1233 } else if (t.IsValueType)
1234 ig.Emit (OpCodes.Ldobj, t);
1235 else if (t.IsPointer)
1236 ig.Emit (OpCodes.Ldind_I);
1238 ig.Emit (OpCodes.Ldind_Ref);
1242 // The stack contains the pointer and the value of type `type'
1244 public static void StoreFromPtr (ILGenerator ig, Type type)
1246 if (TypeManager.IsEnumType (type))
1247 type = TypeManager.EnumToUnderlying (type);
1248 if (type == TypeManager.int32_type || type == TypeManager.uint32_type)
1249 ig.Emit (OpCodes.Stind_I4);
1250 else if (type == TypeManager.int64_type || type == TypeManager.uint64_type)
1251 ig.Emit (OpCodes.Stind_I8);
1252 else if (type == TypeManager.char_type || type == TypeManager.short_type ||
1253 type == TypeManager.ushort_type)
1254 ig.Emit (OpCodes.Stind_I2);
1255 else if (type == TypeManager.float_type)
1256 ig.Emit (OpCodes.Stind_R4);
1257 else if (type == TypeManager.double_type)
1258 ig.Emit (OpCodes.Stind_R8);
1259 else if (type == TypeManager.byte_type || type == TypeManager.sbyte_type ||
1260 type == TypeManager.bool_type)
1261 ig.Emit (OpCodes.Stind_I1);
1262 else if (type == TypeManager.intptr_type)
1263 ig.Emit (OpCodes.Stind_I);
1264 else if (type.IsValueType)
1265 ig.Emit (OpCodes.Stobj, type);
1267 ig.Emit (OpCodes.Stind_Ref);
1271 // Returns the size of type `t' if known, otherwise, 0
1273 public static int GetTypeSize (Type t)
1275 t = TypeManager.TypeToCoreType (t);
1276 if (t == TypeManager.int32_type ||
1277 t == TypeManager.uint32_type ||
1278 t == TypeManager.float_type)
1280 else if (t == TypeManager.int64_type ||
1281 t == TypeManager.uint64_type ||
1282 t == TypeManager.double_type)
1284 else if (t == TypeManager.byte_type ||
1285 t == TypeManager.sbyte_type ||
1286 t == TypeManager.bool_type)
1288 else if (t == TypeManager.short_type ||
1289 t == TypeManager.char_type ||
1290 t == TypeManager.ushort_type)
1292 else if (t == TypeManager.decimal_type)
1298 public static void Error_NegativeArrayIndex (Location loc)
1300 Report.Error (248, loc, "Cannot create an array with a negative size");
1304 // Converts `source' to an int, uint, long or ulong.
1306 public Expression ExpressionToArrayArgument (EmitContext ec, Expression source, Location loc)
1310 bool old_checked = ec.CheckState;
1311 ec.CheckState = true;
1313 target = Convert.ImplicitConversion (ec, source, TypeManager.int32_type, loc);
1314 if (target == null){
1315 target = Convert.ImplicitConversion (ec, source, TypeManager.uint32_type, loc);
1316 if (target == null){
1317 target = Convert.ImplicitConversion (ec, source, TypeManager.int64_type, loc);
1318 if (target == null){
1319 target = Convert.ImplicitConversion (ec, source, TypeManager.uint64_type, loc);
1321 Convert.Error_CannotImplicitConversion (loc, source.Type, TypeManager.int32_type);
1325 ec.CheckState = old_checked;
1328 // Only positive constants are allowed at compile time
1330 if (target is Constant){
1331 if (target is IntConstant){
1332 if (((IntConstant) target).Value < 0){
1333 Error_NegativeArrayIndex (loc);
1338 if (target is LongConstant){
1339 if (((LongConstant) target).Value < 0){
1340 Error_NegativeArrayIndex (loc);
1353 /// This is just a base class for expressions that can
1354 /// appear on statements (invocations, object creation,
1355 /// assignments, post/pre increment and decrement). The idea
1356 /// being that they would support an extra Emition interface that
1357 /// does not leave a result on the stack.
1359 public abstract class ExpressionStatement : Expression {
1361 public virtual ExpressionStatement ResolveStatement (EmitContext ec)
1363 Expression e = Resolve (ec);
1367 ExpressionStatement es = e as ExpressionStatement;
1369 Error (201, "Only assignment, call, increment, decrement and new object " +
1370 "expressions can be used as a statement");
1376 /// Requests the expression to be emitted in a `statement'
1377 /// context. This means that no new value is left on the
1378 /// stack after invoking this method (constrasted with
1379 /// Emit that will always leave a value on the stack).
1381 public abstract void EmitStatement (EmitContext ec);
1385 /// This kind of cast is used to encapsulate the child
1386 /// whose type is child.Type into an expression that is
1387 /// reported to return "return_type". This is used to encapsulate
1388 /// expressions which have compatible types, but need to be dealt
1389 /// at higher levels with.
1391 /// For example, a "byte" expression could be encapsulated in one
1392 /// of these as an "unsigned int". The type for the expression
1393 /// would be "unsigned int".
1396 public class EmptyCast : Expression {
1397 protected Expression child;
1399 public Expression Child {
1405 public EmptyCast (Expression child, Type return_type)
1407 eclass = child.eclass;
1412 public override Expression DoResolve (EmitContext ec)
1414 // This should never be invoked, we are born in fully
1415 // initialized state.
1420 public override void Emit (EmitContext ec)
1427 // We need to special case this since an empty cast of
1428 // a NullLiteral is still a Constant
1430 public class NullCast : Constant {
1431 protected Expression child;
1433 public NullCast (Expression child, Type return_type)
1435 eclass = child.eclass;
1440 override public string AsString ()
1445 public override object GetValue ()
1450 public override Expression DoResolve (EmitContext ec)
1452 // This should never be invoked, we are born in fully
1453 // initialized state.
1458 public override void Emit (EmitContext ec)
1463 public override bool IsNegative {
1472 /// This class is used to wrap literals which belong inside Enums
1474 public class EnumConstant : Constant {
1475 public Constant Child;
1477 public EnumConstant (Constant child, Type enum_type)
1479 eclass = child.eclass;
1484 public override Expression DoResolve (EmitContext ec)
1486 // This should never be invoked, we are born in fully
1487 // initialized state.
1492 public override void Emit (EmitContext ec)
1497 public override object GetValue ()
1499 return Child.GetValue ();
1502 public object GetValueAsEnumType ()
1504 return System.Enum.ToObject (type, Child.GetValue ());
1508 // Converts from one of the valid underlying types for an enumeration
1509 // (int32, uint32, int64, uint64, short, ushort, byte, sbyte) to
1510 // one of the internal compiler literals: Int/UInt/Long/ULong Literals.
1512 public Constant WidenToCompilerConstant ()
1514 Type t = TypeManager.EnumToUnderlying (Child.Type);
1515 object v = ((Constant) Child).GetValue ();;
1517 if (t == TypeManager.int32_type)
1518 return new IntConstant ((int) v);
1519 if (t == TypeManager.uint32_type)
1520 return new UIntConstant ((uint) v);
1521 if (t == TypeManager.int64_type)
1522 return new LongConstant ((long) v);
1523 if (t == TypeManager.uint64_type)
1524 return new ULongConstant ((ulong) v);
1525 if (t == TypeManager.short_type)
1526 return new ShortConstant ((short) v);
1527 if (t == TypeManager.ushort_type)
1528 return new UShortConstant ((ushort) v);
1529 if (t == TypeManager.byte_type)
1530 return new ByteConstant ((byte) v);
1531 if (t == TypeManager.sbyte_type)
1532 return new SByteConstant ((sbyte) v);
1534 throw new Exception ("Invalid enumeration underlying type: " + t);
1538 // Extracts the value in the enumeration on its native representation
1540 public object GetPlainValue ()
1542 Type t = TypeManager.EnumToUnderlying (Child.Type);
1543 object v = ((Constant) Child).GetValue ();;
1545 if (t == TypeManager.int32_type)
1547 if (t == TypeManager.uint32_type)
1549 if (t == TypeManager.int64_type)
1551 if (t == TypeManager.uint64_type)
1553 if (t == TypeManager.short_type)
1555 if (t == TypeManager.ushort_type)
1557 if (t == TypeManager.byte_type)
1559 if (t == TypeManager.sbyte_type)
1565 public override string AsString ()
1567 return Child.AsString ();
1570 public override DoubleConstant ConvertToDouble ()
1572 return Child.ConvertToDouble ();
1575 public override FloatConstant ConvertToFloat ()
1577 return Child.ConvertToFloat ();
1580 public override ULongConstant ConvertToULong ()
1582 return Child.ConvertToULong ();
1585 public override LongConstant ConvertToLong ()
1587 return Child.ConvertToLong ();
1590 public override UIntConstant ConvertToUInt ()
1592 return Child.ConvertToUInt ();
1595 public override IntConstant ConvertToInt ()
1597 return Child.ConvertToInt ();
1600 public override bool IsZeroInteger {
1601 get { return Child.IsZeroInteger; }
1604 public override bool IsNegative {
1606 return Child.IsNegative;
1612 /// This kind of cast is used to encapsulate Value Types in objects.
1614 /// The effect of it is to box the value type emitted by the previous
1617 public class BoxedCast : EmptyCast {
1619 public BoxedCast (Expression expr)
1620 : base (expr, TypeManager.object_type)
1622 eclass = ExprClass.Value;
1625 public BoxedCast (Expression expr, Type target_type)
1626 : base (expr, target_type)
1628 eclass = ExprClass.Value;
1631 public override Expression DoResolve (EmitContext ec)
1633 // This should never be invoked, we are born in fully
1634 // initialized state.
1639 public override void Emit (EmitContext ec)
1643 ec.ig.Emit (OpCodes.Box, child.Type);
1647 public class UnboxCast : EmptyCast {
1648 public UnboxCast (Expression expr, Type return_type)
1649 : base (expr, return_type)
1653 public override Expression DoResolve (EmitContext ec)
1655 // This should never be invoked, we are born in fully
1656 // initialized state.
1661 public override void Emit (EmitContext ec)
1664 ILGenerator ig = ec.ig;
1667 ig.Emit (OpCodes.Unbox, t);
1669 LoadFromPtr (ig, t);
1674 /// This is used to perform explicit numeric conversions.
1676 /// Explicit numeric conversions might trigger exceptions in a checked
1677 /// context, so they should generate the conv.ovf opcodes instead of
1680 public class ConvCast : EmptyCast {
1681 public enum Mode : byte {
1682 I1_U1, I1_U2, I1_U4, I1_U8, I1_CH,
1684 I2_I1, I2_U1, I2_U2, I2_U4, I2_U8, I2_CH,
1685 U2_I1, U2_U1, U2_I2, U2_CH,
1686 I4_I1, I4_U1, I4_I2, I4_U2, I4_U4, I4_U8, I4_CH,
1687 U4_I1, U4_U1, U4_I2, U4_U2, U4_I4, U4_CH,
1688 I8_I1, I8_U1, I8_I2, I8_U2, I8_I4, I8_U4, I8_U8, I8_CH,
1689 U8_I1, U8_U1, U8_I2, U8_U2, U8_I4, U8_U4, U8_I8, U8_CH,
1690 CH_I1, CH_U1, CH_I2,
1691 R4_I1, R4_U1, R4_I2, R4_U2, R4_I4, R4_U4, R4_I8, R4_U8, R4_CH,
1692 R8_I1, R8_U1, R8_I2, R8_U2, R8_I4, R8_U4, R8_I8, R8_U8, R8_CH, R8_R4
1698 public ConvCast (EmitContext ec, Expression child, Type return_type, Mode m)
1699 : base (child, return_type)
1701 checked_state = ec.CheckState;
1705 public override Expression DoResolve (EmitContext ec)
1707 // This should never be invoked, we are born in fully
1708 // initialized state.
1713 public override string ToString ()
1715 return String.Format ("ConvCast ({0}, {1})", mode, child);
1718 public override void Emit (EmitContext ec)
1720 ILGenerator ig = ec.ig;
1726 case Mode.I1_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1727 case Mode.I1_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1728 case Mode.I1_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1729 case Mode.I1_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1730 case Mode.I1_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1732 case Mode.U1_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1733 case Mode.U1_CH: /* nothing */ break;
1735 case Mode.I2_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1736 case Mode.I2_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1737 case Mode.I2_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1738 case Mode.I2_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1739 case Mode.I2_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1740 case Mode.I2_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1742 case Mode.U2_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1743 case Mode.U2_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
1744 case Mode.U2_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
1745 case Mode.U2_CH: /* nothing */ break;
1747 case Mode.I4_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1748 case Mode.I4_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1749 case Mode.I4_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
1750 case Mode.I4_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1751 case Mode.I4_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1752 case Mode.I4_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1753 case Mode.I4_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1755 case Mode.U4_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1756 case Mode.U4_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
1757 case Mode.U4_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
1758 case Mode.U4_U2: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
1759 case Mode.U4_I4: ig.Emit (OpCodes.Conv_Ovf_I4_Un); break;
1760 case Mode.U4_CH: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
1762 case Mode.I8_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1763 case Mode.I8_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1764 case Mode.I8_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
1765 case Mode.I8_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1766 case Mode.I8_I4: ig.Emit (OpCodes.Conv_Ovf_I4); break;
1767 case Mode.I8_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1768 case Mode.I8_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1769 case Mode.I8_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1771 case Mode.U8_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1772 case Mode.U8_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
1773 case Mode.U8_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
1774 case Mode.U8_U2: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
1775 case Mode.U8_I4: ig.Emit (OpCodes.Conv_Ovf_I4_Un); break;
1776 case Mode.U8_U4: ig.Emit (OpCodes.Conv_Ovf_U4_Un); break;
1777 case Mode.U8_I8: ig.Emit (OpCodes.Conv_Ovf_I8_Un); break;
1778 case Mode.U8_CH: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
1780 case Mode.CH_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1781 case Mode.CH_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
1782 case Mode.CH_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
1784 case Mode.R4_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1785 case Mode.R4_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1786 case Mode.R4_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
1787 case Mode.R4_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1788 case Mode.R4_I4: ig.Emit (OpCodes.Conv_Ovf_I4); break;
1789 case Mode.R4_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1790 case Mode.R4_I8: ig.Emit (OpCodes.Conv_Ovf_I8); break;
1791 case Mode.R4_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1792 case Mode.R4_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1794 case Mode.R8_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1795 case Mode.R8_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1796 case Mode.R8_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
1797 case Mode.R8_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1798 case Mode.R8_I4: ig.Emit (OpCodes.Conv_Ovf_I4); break;
1799 case Mode.R8_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1800 case Mode.R8_I8: ig.Emit (OpCodes.Conv_Ovf_I8); break;
1801 case Mode.R8_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1802 case Mode.R8_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1803 case Mode.R8_R4: ig.Emit (OpCodes.Conv_R4); break;
1807 case Mode.I1_U1: ig.Emit (OpCodes.Conv_U1); break;
1808 case Mode.I1_U2: ig.Emit (OpCodes.Conv_U2); break;
1809 case Mode.I1_U4: ig.Emit (OpCodes.Conv_U4); break;
1810 case Mode.I1_U8: ig.Emit (OpCodes.Conv_I8); break;
1811 case Mode.I1_CH: ig.Emit (OpCodes.Conv_U2); break;
1813 case Mode.U1_I1: ig.Emit (OpCodes.Conv_I1); break;
1814 case Mode.U1_CH: ig.Emit (OpCodes.Conv_U2); break;
1816 case Mode.I2_I1: ig.Emit (OpCodes.Conv_I1); break;
1817 case Mode.I2_U1: ig.Emit (OpCodes.Conv_U1); break;
1818 case Mode.I2_U2: ig.Emit (OpCodes.Conv_U2); break;
1819 case Mode.I2_U4: ig.Emit (OpCodes.Conv_U4); break;
1820 case Mode.I2_U8: ig.Emit (OpCodes.Conv_I8); break;
1821 case Mode.I2_CH: ig.Emit (OpCodes.Conv_U2); break;
1823 case Mode.U2_I1: ig.Emit (OpCodes.Conv_I1); break;
1824 case Mode.U2_U1: ig.Emit (OpCodes.Conv_U1); break;
1825 case Mode.U2_I2: ig.Emit (OpCodes.Conv_I2); break;
1826 case Mode.U2_CH: /* nothing */ break;
1828 case Mode.I4_I1: ig.Emit (OpCodes.Conv_I1); break;
1829 case Mode.I4_U1: ig.Emit (OpCodes.Conv_U1); break;
1830 case Mode.I4_I2: ig.Emit (OpCodes.Conv_I2); break;
1831 case Mode.I4_U4: /* nothing */ break;
1832 case Mode.I4_U2: ig.Emit (OpCodes.Conv_U2); break;
1833 case Mode.I4_U8: ig.Emit (OpCodes.Conv_I8); break;
1834 case Mode.I4_CH: ig.Emit (OpCodes.Conv_U2); break;
1836 case Mode.U4_I1: ig.Emit (OpCodes.Conv_I1); break;
1837 case Mode.U4_U1: ig.Emit (OpCodes.Conv_U1); break;
1838 case Mode.U4_I2: ig.Emit (OpCodes.Conv_I2); break;
1839 case Mode.U4_U2: ig.Emit (OpCodes.Conv_U2); break;
1840 case Mode.U4_I4: /* nothing */ break;
1841 case Mode.U4_CH: ig.Emit (OpCodes.Conv_U2); break;
1843 case Mode.I8_I1: ig.Emit (OpCodes.Conv_I1); break;
1844 case Mode.I8_U1: ig.Emit (OpCodes.Conv_U1); break;
1845 case Mode.I8_I2: ig.Emit (OpCodes.Conv_I2); break;
1846 case Mode.I8_U2: ig.Emit (OpCodes.Conv_U2); break;
1847 case Mode.I8_I4: ig.Emit (OpCodes.Conv_I4); break;
1848 case Mode.I8_U4: ig.Emit (OpCodes.Conv_U4); break;
1849 case Mode.I8_U8: /* nothing */ break;
1850 case Mode.I8_CH: ig.Emit (OpCodes.Conv_U2); break;
1852 case Mode.U8_I1: ig.Emit (OpCodes.Conv_I1); break;
1853 case Mode.U8_U1: ig.Emit (OpCodes.Conv_U1); break;
1854 case Mode.U8_I2: ig.Emit (OpCodes.Conv_I2); break;
1855 case Mode.U8_U2: ig.Emit (OpCodes.Conv_U2); break;
1856 case Mode.U8_I4: ig.Emit (OpCodes.Conv_I4); break;
1857 case Mode.U8_U4: ig.Emit (OpCodes.Conv_U4); break;
1858 case Mode.U8_I8: /* nothing */ break;
1859 case Mode.U8_CH: ig.Emit (OpCodes.Conv_U2); break;
1861 case Mode.CH_I1: ig.Emit (OpCodes.Conv_I1); break;
1862 case Mode.CH_U1: ig.Emit (OpCodes.Conv_U1); break;
1863 case Mode.CH_I2: ig.Emit (OpCodes.Conv_I2); break;
1865 case Mode.R4_I1: ig.Emit (OpCodes.Conv_I1); break;
1866 case Mode.R4_U1: ig.Emit (OpCodes.Conv_U1); break;
1867 case Mode.R4_I2: ig.Emit (OpCodes.Conv_I2); break;
1868 case Mode.R4_U2: ig.Emit (OpCodes.Conv_U2); break;
1869 case Mode.R4_I4: ig.Emit (OpCodes.Conv_I4); break;
1870 case Mode.R4_U4: ig.Emit (OpCodes.Conv_U4); break;
1871 case Mode.R4_I8: ig.Emit (OpCodes.Conv_I8); break;
1872 case Mode.R4_U8: ig.Emit (OpCodes.Conv_U8); break;
1873 case Mode.R4_CH: ig.Emit (OpCodes.Conv_U2); break;
1875 case Mode.R8_I1: ig.Emit (OpCodes.Conv_I1); break;
1876 case Mode.R8_U1: ig.Emit (OpCodes.Conv_U1); break;
1877 case Mode.R8_I2: ig.Emit (OpCodes.Conv_I2); break;
1878 case Mode.R8_U2: ig.Emit (OpCodes.Conv_U2); break;
1879 case Mode.R8_I4: ig.Emit (OpCodes.Conv_I4); break;
1880 case Mode.R8_U4: ig.Emit (OpCodes.Conv_U4); break;
1881 case Mode.R8_I8: ig.Emit (OpCodes.Conv_I8); break;
1882 case Mode.R8_U8: ig.Emit (OpCodes.Conv_U8); break;
1883 case Mode.R8_CH: ig.Emit (OpCodes.Conv_U2); break;
1884 case Mode.R8_R4: ig.Emit (OpCodes.Conv_R4); break;
1890 public class OpcodeCast : EmptyCast {
1894 public OpcodeCast (Expression child, Type return_type, OpCode op)
1895 : base (child, return_type)
1899 second_valid = false;
1902 public OpcodeCast (Expression child, Type return_type, OpCode op, OpCode op2)
1903 : base (child, return_type)
1908 second_valid = true;
1911 public override Expression DoResolve (EmitContext ec)
1913 // This should never be invoked, we are born in fully
1914 // initialized state.
1919 public override void Emit (EmitContext ec)
1930 /// This kind of cast is used to encapsulate a child and cast it
1931 /// to the class requested
1933 public class ClassCast : EmptyCast {
1934 public ClassCast (Expression child, Type return_type)
1935 : base (child, return_type)
1940 public override Expression DoResolve (EmitContext ec)
1942 // This should never be invoked, we are born in fully
1943 // initialized state.
1948 public override void Emit (EmitContext ec)
1952 ec.ig.Emit (OpCodes.Castclass, type);
1958 /// SimpleName expressions are initially formed of a single
1959 /// word and it only happens at the beginning of the expression.
1963 /// The expression will try to be bound to a Field, a Method
1964 /// group or a Property. If those fail we pass the name to our
1965 /// caller and the SimpleName is compounded to perform a type
1966 /// lookup. The idea behind this process is that we want to avoid
1967 /// creating a namespace map from the assemblies, as that requires
1968 /// the GetExportedTypes function to be called and a hashtable to
1969 /// be constructed which reduces startup time. If later we find
1970 /// that this is slower, we should create a `NamespaceExpr' expression
1971 /// that fully participates in the resolution process.
1973 /// For example `System.Console.WriteLine' is decomposed into
1974 /// MemberAccess (MemberAccess (SimpleName ("System"), "Console"), "WriteLine")
1976 /// The first SimpleName wont produce a match on its own, so it will
1978 /// MemberAccess (SimpleName ("System.Console"), "WriteLine").
1980 /// System.Console will produce a TypeExpr match.
1982 /// The downside of this is that we might be hitting `LookupType' too many
1983 /// times with this scheme.
1985 public class SimpleName : Expression {
1989 // If true, then we are a simple name, not composed with a ".
1993 public SimpleName (string a, string b, Location l)
1995 Name = String.Concat (a, ".", b);
2000 public SimpleName (string name, Location l)
2007 public static void Error_ObjectRefRequired (EmitContext ec, Location l, string name)
2009 if (ec.IsFieldInitializer)
2012 "A field initializer cannot reference the non-static field, " +
2013 "method or property `"+name+"'");
2017 "An object reference is required " +
2018 "for the non-static field `"+name+"'");
2022 // Checks whether we are trying to access an instance
2023 // property, method or field from a static body.
2025 Expression MemberStaticCheck (EmitContext ec, Expression e)
2027 if (e is IMemberExpr){
2028 IMemberExpr member = (IMemberExpr) e;
2030 if (!member.IsStatic){
2031 Error_ObjectRefRequired (ec, loc, Name);
2039 public override Expression DoResolve (EmitContext ec)
2041 return SimpleNameResolve (ec, null, false, false);
2044 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
2046 return SimpleNameResolve (ec, right_side, false, false);
2050 public Expression DoResolveAllowStatic (EmitContext ec, bool intermediate)
2052 return SimpleNameResolve (ec, null, true, intermediate);
2055 public override Expression ResolveAsTypeStep (EmitContext ec)
2057 DeclSpace ds = ec.DeclSpace;
2058 NamespaceEntry ns = ds.NamespaceEntry;
2063 // Since we are cheating: we only do the Alias lookup for
2064 // namespaces if the name does not include any dots in it
2066 if (ns != null && is_base)
2067 alias_value = ns.LookupAlias (Name);
2071 if (ec.ResolvingTypeTree){
2072 int errors = Report.Errors;
2073 Type dt = ds.FindType (loc, Name);
2075 if (Report.Errors != errors)
2079 return new TypeExpression (dt, loc);
2081 if (alias_value != null){
2082 if ((t = RootContext.LookupType (ds, alias_value, true, loc)) != null)
2083 return new TypeExpression (t, loc);
2087 if ((t = RootContext.LookupType (ds, Name, true, loc)) != null)
2088 return new TypeExpression (t, loc);
2090 if (alias_value != null) {
2091 if ((t = RootContext.LookupType (ds, alias_value, true, loc)) != null)
2092 return new TypeExpression (t, loc);
2094 // we have alias value, but it isn't Type, so try if it's namespace
2095 return new SimpleName (alias_value, loc);
2098 // No match, maybe our parent can compose us
2099 // into something meaningful.
2103 Expression SimpleNameResolve (EmitContext ec, Expression right_side,
2104 bool allow_static, bool intermediate)
2106 Expression e = DoSimpleNameResolve (ec, right_side, allow_static, intermediate);
2110 Block current_block = ec.CurrentBlock;
2111 if (current_block != null){
2112 //LocalInfo vi = current_block.GetLocalInfo (Name);
2114 current_block.IsVariableNameUsedInChildBlock(Name)) {
2115 Report.Error (135, Location,
2116 "'{0}' has a different meaning in a " +
2117 "child block", Name);
2126 /// 7.5.2: Simple Names.
2128 /// Local Variables and Parameters are handled at
2129 /// parse time, so they never occur as SimpleNames.
2131 /// The `allow_static' flag is used by MemberAccess only
2132 /// and it is used to inform us that it is ok for us to
2133 /// avoid the static check, because MemberAccess might end
2134 /// up resolving the Name as a Type name and the access as
2135 /// a static type access.
2137 /// ie: Type Type; .... { Type.GetType (""); }
2139 /// Type is both an instance variable and a Type; Type.GetType
2140 /// is the static method not an instance method of type.
2142 Expression DoSimpleNameResolve (EmitContext ec, Expression right_side, bool allow_static, bool intermediate)
2144 Expression e = null;
2147 // Stage 1: Performed by the parser (binding to locals or parameters).
2149 Block current_block = ec.CurrentBlock;
2150 if (current_block != null){
2151 LocalInfo vi = current_block.GetLocalInfo (Name);
2155 var = new LocalVariableReference (ec.CurrentBlock, Name, loc);
2157 if (right_side != null)
2158 return var.ResolveLValue (ec, right_side);
2160 return var.Resolve (ec);
2163 ParameterReference pref = current_block.GetParameterReference (Name, loc);
2165 if (right_side != null)
2166 return pref.ResolveLValue (ec, right_side);
2168 return pref.Resolve (ec);
2173 // Stage 2: Lookup members
2176 DeclSpace lookup_ds = ec.DeclSpace;
2178 if (lookup_ds.TypeBuilder == null)
2181 e = MemberLookup (ec, lookup_ds.TypeBuilder, Name, loc);
2185 lookup_ds =lookup_ds.Parent;
2186 } while (lookup_ds != null);
2188 if (e == null && ec.ContainerType != null)
2189 e = MemberLookup (ec, ec.ContainerType, Name, loc);
2193 // Since we are cheating (is_base is our hint
2194 // that we are the beginning of the name): we
2195 // only do the Alias lookup for namespaces if
2196 // the name does not include any dots in it
2198 NamespaceEntry ns = ec.DeclSpace.NamespaceEntry;
2199 if (is_base && ns != null){
2200 string alias_value = ns.LookupAlias (Name);
2201 if (alias_value != null){
2205 if ((t = TypeManager.LookupType (Name)) != null)
2206 return new TypeExpression (t, loc);
2208 // No match, maybe our parent can compose us
2209 // into something meaningful.
2214 return ResolveAsTypeStep (ec);
2220 if (e is IMemberExpr) {
2221 e = MemberAccess.ResolveMemberAccess (ec, e, null, loc, this);
2225 IMemberExpr me = e as IMemberExpr;
2229 // This fails if ResolveMemberAccess() was unable to decide whether
2230 // it's a field or a type of the same name.
2232 if (!me.IsStatic && (me.InstanceExpression == null))
2236 TypeManager.IsSubclassOrNestedChildOf (me.InstanceExpression.Type, me.DeclaringType) &&
2237 me.InstanceExpression.Type != me.DeclaringType &&
2238 !me.InstanceExpression.Type.IsSubclassOf (me.DeclaringType) &&
2239 (!intermediate || !MemberAccess.IdenticalNameAndTypeName (ec, this, e, loc))) {
2240 Error (38, "Cannot access nonstatic member `" + me.Name + "' of " +
2241 "outer type `" + me.DeclaringType + "' via nested type `" +
2242 me.InstanceExpression.Type + "'");
2246 return (right_side != null)
2247 ? e.DoResolveLValue (ec, right_side)
2251 if (ec.IsStatic || ec.IsFieldInitializer){
2255 return MemberStaticCheck (ec, e);
2260 public override void Emit (EmitContext ec)
2263 // If this is ever reached, then we failed to
2264 // find the name as a namespace
2267 Error (103, "The name `" + Name +
2268 "' does not exist in the class `" +
2269 ec.DeclSpace.Name + "'");
2272 public override string ToString ()
2279 /// Fully resolved expression that evaluates to a type
2281 public abstract class TypeExpr : Expression {
2282 override public Expression ResolveAsTypeStep (EmitContext ec)
2284 TypeExpr t = DoResolveAsTypeStep (ec);
2288 eclass = ExprClass.Type;
2292 override public Expression DoResolve (EmitContext ec)
2294 return ResolveAsTypeTerminal (ec, false);
2297 override public void Emit (EmitContext ec)
2299 throw new Exception ("Should never be called");
2302 public virtual bool CheckAccessLevel (DeclSpace ds)
2304 return ds.CheckAccessLevel (Type);
2307 public virtual bool AsAccessible (DeclSpace ds, int flags)
2309 return ds.AsAccessible (Type, flags);
2312 public virtual bool IsClass {
2313 get { return Type.IsClass; }
2316 public virtual bool IsValueType {
2317 get { return Type.IsValueType; }
2320 public virtual bool IsInterface {
2321 get { return Type.IsInterface; }
2324 public virtual bool IsSealed {
2325 get { return Type.IsSealed; }
2328 public virtual bool CanInheritFrom ()
2330 if (Type == TypeManager.enum_type ||
2331 (Type == TypeManager.value_type && RootContext.StdLib) ||
2332 Type == TypeManager.multicast_delegate_type ||
2333 Type == TypeManager.delegate_type ||
2334 Type == TypeManager.array_type)
2340 public virtual bool IsAttribute {
2342 return Type == TypeManager.attribute_type ||
2343 Type.IsSubclassOf (TypeManager.attribute_type);
2347 public abstract TypeExpr DoResolveAsTypeStep (EmitContext ec);
2349 public virtual Type ResolveType (EmitContext ec)
2351 TypeExpr t = ResolveAsTypeTerminal (ec, false);
2358 public abstract string Name {
2362 public override bool Equals (object obj)
2364 TypeExpr tobj = obj as TypeExpr;
2368 return Type == tobj.Type;
2371 public override int GetHashCode ()
2373 return Type.GetHashCode ();
2376 public override string ToString ()
2382 public class TypeExpression : TypeExpr {
2383 public TypeExpression (Type t, Location l)
2386 eclass = ExprClass.Type;
2390 public override TypeExpr DoResolveAsTypeStep (EmitContext ec)
2395 public override string Name {
2397 return Type.ToString ();
2403 /// Used to create types from a fully qualified name. These are just used
2404 /// by the parser to setup the core types. A TypeLookupExpression is always
2405 /// classified as a type.
2407 public class TypeLookupExpression : TypeExpr {
2410 public TypeLookupExpression (string name)
2415 public override TypeExpr DoResolveAsTypeStep (EmitContext ec)
2418 type = RootContext.LookupType (ec.DeclSpace, name, false, Location.Null);
2422 public override string Name {
2430 /// MethodGroup Expression.
2432 /// This is a fully resolved expression that evaluates to a type
2434 public class MethodGroupExpr : Expression, IMemberExpr {
2435 public MethodBase [] Methods;
2436 Expression instance_expression = null;
2437 bool is_explicit_impl = false;
2438 bool identical_type_name = false;
2441 public MethodGroupExpr (MemberInfo [] mi, Location l)
2443 Methods = new MethodBase [mi.Length];
2444 mi.CopyTo (Methods, 0);
2445 eclass = ExprClass.MethodGroup;
2446 type = TypeManager.object_type;
2450 public MethodGroupExpr (ArrayList list, Location l)
2452 Methods = new MethodBase [list.Count];
2455 list.CopyTo (Methods, 0);
2457 foreach (MemberInfo m in list){
2458 if (!(m is MethodBase)){
2459 Console.WriteLine ("Name " + m.Name);
2460 Console.WriteLine ("Found a: " + m.GetType ().FullName);
2467 eclass = ExprClass.MethodGroup;
2468 type = TypeManager.object_type;
2471 public Type DeclaringType {
2474 // The methods are arranged in this order:
2475 // derived type -> base type
2477 return Methods [0].DeclaringType;
2482 // `A method group may have associated an instance expression'
2484 public Expression InstanceExpression {
2486 return instance_expression;
2490 instance_expression = value;
2494 public bool IsExplicitImpl {
2496 return is_explicit_impl;
2500 is_explicit_impl = value;
2504 public bool IdenticalTypeName {
2506 return identical_type_name;
2510 identical_type_name = value;
2514 public bool IsBase {
2523 public string Name {
2525 return Methods [0].Name;
2529 public bool IsInstance {
2531 foreach (MethodBase mb in Methods)
2539 public bool IsStatic {
2541 foreach (MethodBase mb in Methods)
2549 override public Expression DoResolve (EmitContext ec)
2552 instance_expression = null;
2554 if (instance_expression != null) {
2555 instance_expression = instance_expression.DoResolve (ec);
2556 if (instance_expression == null)
2563 public void ReportUsageError ()
2565 Report.Error (654, loc, "Method `" + DeclaringType + "." +
2566 Name + "()' is referenced without parentheses");
2569 override public void Emit (EmitContext ec)
2571 ReportUsageError ();
2574 bool RemoveMethods (bool keep_static)
2576 ArrayList smethods = new ArrayList ();
2578 foreach (MethodBase mb in Methods){
2579 if (mb.IsStatic == keep_static)
2583 if (smethods.Count == 0)
2586 Methods = new MethodBase [smethods.Count];
2587 smethods.CopyTo (Methods, 0);
2593 /// Removes any instance methods from the MethodGroup, returns
2594 /// false if the resulting set is empty.
2596 public bool RemoveInstanceMethods ()
2598 return RemoveMethods (true);
2602 /// Removes any static methods from the MethodGroup, returns
2603 /// false if the resulting set is empty.
2605 public bool RemoveStaticMethods ()
2607 return RemoveMethods (false);
2612 /// Fully resolved expression that evaluates to a Field
2614 public class FieldExpr : Expression, IAssignMethod, IMemoryLocation, IMemberExpr, IVariable {
2615 public readonly FieldInfo FieldInfo;
2616 Expression instance_expr;
2617 VariableInfo variable_info;
2619 LocalTemporary temp;
2622 public FieldExpr (FieldInfo fi, Location l)
2625 eclass = ExprClass.Variable;
2626 type = fi.FieldType;
2630 public string Name {
2632 return FieldInfo.Name;
2636 public bool IsInstance {
2638 return !FieldInfo.IsStatic;
2642 public bool IsStatic {
2644 return FieldInfo.IsStatic;
2648 public Type DeclaringType {
2650 return FieldInfo.DeclaringType;
2654 public Expression InstanceExpression {
2656 return instance_expr;
2660 instance_expr = value;
2664 public VariableInfo VariableInfo {
2666 return variable_info;
2670 override public Expression DoResolve (EmitContext ec)
2672 if (!FieldInfo.IsStatic){
2673 if (instance_expr == null){
2675 // This can happen when referencing an instance field using
2676 // a fully qualified type expression: TypeName.InstanceField = xxx
2678 SimpleName.Error_ObjectRefRequired (ec, loc, FieldInfo.Name);
2682 // Resolve the field's instance expression while flow analysis is turned
2683 // off: when accessing a field "a.b", we must check whether the field
2684 // "a.b" is initialized, not whether the whole struct "a" is initialized.
2685 instance_expr = instance_expr.Resolve (ec, ResolveFlags.VariableOrValue |
2686 ResolveFlags.DisableFlowAnalysis);
2687 if (instance_expr == null)
2691 ObsoleteAttribute oa;
2692 FieldBase f = TypeManager.GetField (FieldInfo);
2694 oa = f.GetObsoleteAttribute (f.Parent);
2696 AttributeTester.Report_ObsoleteMessage (oa, f.GetSignatureForError (), loc);
2698 // To be sure that type is external because we do not register generated fields
2699 } else if (!(FieldInfo.DeclaringType is TypeBuilder)) {
2700 oa = AttributeTester.GetMemberObsoleteAttribute (FieldInfo);
2702 AttributeTester.Report_ObsoleteMessage (oa, TypeManager.GetFullNameSignature (FieldInfo), loc);
2705 if (ec.CurrentAnonymousMethod != null){
2706 if (!FieldInfo.IsStatic){
2707 if (ec.TypeContainer is Struct){
2708 Report.Error (1673, loc, "Can not reference instance variables in anonymous methods hosted in structs");
2711 ec.CaptureField (this);
2715 // If the instance expression is a local variable or parameter.
2716 IVariable var = instance_expr as IVariable;
2717 if ((var == null) || (var.VariableInfo == null))
2720 VariableInfo vi = var.VariableInfo;
2721 if (!vi.IsFieldAssigned (ec, FieldInfo.Name, loc))
2724 variable_info = vi.GetSubStruct (FieldInfo.Name);
2728 void Report_AssignToReadonly (bool is_instance)
2733 msg = "Readonly field can not be assigned outside " +
2734 "of constructor or variable initializer";
2736 msg = "A static readonly field can only be assigned in " +
2737 "a static constructor";
2739 Report.Error (is_instance ? 191 : 198, loc, msg);
2742 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
2744 IVariable var = instance_expr as IVariable;
2745 if ((var != null) && (var.VariableInfo != null))
2746 var.VariableInfo.SetFieldAssigned (ec, FieldInfo.Name);
2748 Expression e = DoResolve (ec);
2753 if (!FieldInfo.IsStatic && (instance_expr.Type.IsValueType && !(instance_expr is IMemoryLocation))) {
2754 // FIXME: Provide better error reporting.
2755 Error (1612, "Cannot modify expression because it is not a variable.");
2759 if (!FieldInfo.IsInitOnly)
2762 FieldBase fb = TypeManager.GetField (FieldInfo);
2767 // InitOnly fields can only be assigned in constructors
2770 if (ec.IsConstructor){
2771 if (IsStatic && !ec.IsStatic)
2772 Report_AssignToReadonly (false);
2774 if (ec.ContainerType == FieldInfo.DeclaringType)
2778 Report_AssignToReadonly (!IsStatic);
2783 public override void CheckMarshallByRefAccess (Type container)
2785 if (!IsStatic && Type.IsValueType && !container.IsSubclassOf (TypeManager.mbr_type) && DeclaringType.IsSubclassOf (TypeManager.mbr_type)) {
2786 Report.SymbolRelatedToPreviousError (DeclaringType);
2787 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);
2791 public bool VerifyFixed (bool is_expression)
2793 IVariable variable = instance_expr as IVariable;
2794 if ((variable == null) || !variable.VerifyFixed (true))
2800 public void Emit (EmitContext ec, bool leave_copy)
2802 ILGenerator ig = ec.ig;
2803 bool is_volatile = false;
2805 if (FieldInfo is FieldBuilder){
2806 FieldBase f = TypeManager.GetField (FieldInfo);
2808 if ((f.ModFlags & Modifiers.VOLATILE) != 0)
2811 f.status |= Field.Status.USED;
2815 if (FieldInfo.IsStatic){
2817 ig.Emit (OpCodes.Volatile);
2819 ig.Emit (OpCodes.Ldsfld, FieldInfo);
2825 ig.Emit (OpCodes.Volatile);
2827 ig.Emit (OpCodes.Ldfld, FieldInfo);
2831 ec.ig.Emit (OpCodes.Dup);
2832 if (!FieldInfo.IsStatic) {
2833 temp = new LocalTemporary (ec, this.Type);
2839 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
2841 FieldAttributes fa = FieldInfo.Attributes;
2842 bool is_static = (fa & FieldAttributes.Static) != 0;
2843 bool is_readonly = (fa & FieldAttributes.InitOnly) != 0;
2844 ILGenerator ig = ec.ig;
2845 prepared = prepare_for_load;
2847 if (is_readonly && !ec.IsConstructor){
2848 Report_AssignToReadonly (!is_static);
2854 if (prepare_for_load)
2855 ig.Emit (OpCodes.Dup);
2860 ec.ig.Emit (OpCodes.Dup);
2861 if (!FieldInfo.IsStatic) {
2862 temp = new LocalTemporary (ec, this.Type);
2867 if (FieldInfo is FieldBuilder){
2868 FieldBase f = TypeManager.GetField (FieldInfo);
2870 if ((f.ModFlags & Modifiers.VOLATILE) != 0)
2871 ig.Emit (OpCodes.Volatile);
2873 f.status |= Field.Status.ASSIGNED;
2878 ig.Emit (OpCodes.Stsfld, FieldInfo);
2880 ig.Emit (OpCodes.Stfld, FieldInfo);
2886 void EmitInstance (EmitContext ec)
2888 if (instance_expr.Type.IsValueType) {
2889 if (instance_expr is IMemoryLocation) {
2890 ((IMemoryLocation) instance_expr).AddressOf (ec, AddressOp.LoadStore);
2892 LocalTemporary t = new LocalTemporary (ec, instance_expr.Type);
2893 instance_expr.Emit (ec);
2895 t.AddressOf (ec, AddressOp.Store);
2898 instance_expr.Emit (ec);
2901 public override void Emit (EmitContext ec)
2906 public void AddressOf (EmitContext ec, AddressOp mode)
2908 ILGenerator ig = ec.ig;
2910 if (FieldInfo is FieldBuilder){
2911 FieldBase f = TypeManager.GetField (FieldInfo);
2913 if ((f.ModFlags & Modifiers.VOLATILE) != 0){
2914 Error (676, "volatile variable: can not take its address, or pass as ref/out parameter");
2918 if ((mode & AddressOp.Store) != 0)
2919 f.status |= Field.Status.ASSIGNED;
2920 if ((mode & AddressOp.Load) != 0)
2921 f.status |= Field.Status.USED;
2926 // Handle initonly fields specially: make a copy and then
2927 // get the address of the copy.
2930 if (FieldInfo.IsInitOnly){
2932 if (ec.IsConstructor){
2933 if (FieldInfo.IsStatic){
2945 local = ig.DeclareLocal (type);
2946 ig.Emit (OpCodes.Stloc, local);
2947 ig.Emit (OpCodes.Ldloca, local);
2952 if (FieldInfo.IsStatic){
2953 ig.Emit (OpCodes.Ldsflda, FieldInfo);
2956 ig.Emit (OpCodes.Ldflda, FieldInfo);
2962 // A FieldExpr whose address can not be taken
2964 public class FieldExprNoAddress : FieldExpr, IMemoryLocation {
2965 public FieldExprNoAddress (FieldInfo fi, Location loc) : base (fi, loc)
2969 public new void AddressOf (EmitContext ec, AddressOp mode)
2971 Report.Error (-215, "Report this: Taking the address of a remapped parameter not supported");
2976 /// Expression that evaluates to a Property. The Assign class
2977 /// might set the `Value' expression if we are in an assignment.
2979 /// This is not an LValue because we need to re-write the expression, we
2980 /// can not take data from the stack and store it.
2982 public class PropertyExpr : ExpressionStatement, IAssignMethod, IMemberExpr {
2983 public readonly PropertyInfo PropertyInfo;
2986 // This is set externally by the `BaseAccess' class
2989 MethodInfo getter, setter;
2992 Expression instance_expr;
2993 LocalTemporary temp;
2996 public PropertyExpr (EmitContext ec, PropertyInfo pi, Location l)
2999 eclass = ExprClass.PropertyAccess;
3003 type = TypeManager.TypeToCoreType (pi.PropertyType);
3005 ResolveAccessors (ec);
3008 public string Name {
3010 return PropertyInfo.Name;
3014 public bool IsInstance {
3020 public bool IsStatic {
3026 public Type DeclaringType {
3028 return PropertyInfo.DeclaringType;
3033 // The instance expression associated with this expression
3035 public Expression InstanceExpression {
3037 instance_expr = value;
3041 return instance_expr;
3045 public bool VerifyAssignable ()
3047 if (setter == null) {
3048 Report.Error (200, loc,
3049 "The property `" + PropertyInfo.Name +
3050 "' can not be assigned to, as it has not set accessor");
3057 void FindAccessors (Type invocation_type)
3059 BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic |
3060 BindingFlags.Static | BindingFlags.Instance |
3061 BindingFlags.DeclaredOnly;
3063 Type current = PropertyInfo.DeclaringType;
3064 for (; current != null; current = current.BaseType) {
3065 MemberInfo[] group = TypeManager.MemberLookup (
3066 invocation_type, invocation_type, current,
3067 MemberTypes.Property, flags, PropertyInfo.Name, null);
3072 if (group.Length != 1)
3073 // Oooops, can this ever happen ?
3076 PropertyInfo pi = (PropertyInfo) group [0];
3079 getter = pi.GetGetMethod (true);;
3082 setter = pi.GetSetMethod (true);;
3084 MethodInfo accessor = getter != null ? getter : setter;
3086 if (!accessor.IsVirtual)
3092 // We also perform the permission checking here, as the PropertyInfo does not
3093 // hold the information for the accessibility of its setter/getter
3095 void ResolveAccessors (EmitContext ec)
3097 FindAccessors (ec.ContainerType);
3099 is_static = getter != null ? getter.IsStatic : setter.IsStatic;
3102 bool InstanceResolve (EmitContext ec, bool must_do_cs1540_check)
3104 if ((instance_expr == null) && ec.IsStatic && !is_static) {
3105 SimpleName.Error_ObjectRefRequired (ec, loc, PropertyInfo.Name);
3109 if (instance_expr != null) {
3110 instance_expr = instance_expr.DoResolve (ec);
3111 if (instance_expr == null)
3114 instance_expr.CheckMarshallByRefAccess (ec.ContainerType);
3117 if (must_do_cs1540_check && (instance_expr != null)) {
3118 if ((instance_expr.Type != ec.ContainerType) &&
3119 ec.ContainerType.IsSubclassOf (instance_expr.Type)) {
3120 Report.Error (1540, loc, "Cannot access protected member `" +
3121 PropertyInfo.DeclaringType + "." + PropertyInfo.Name +
3122 "' via a qualifier of type `" +
3123 TypeManager.CSharpName (instance_expr.Type) +
3124 "'; the qualifier must be of type `" +
3125 TypeManager.CSharpName (ec.ContainerType) +
3126 "' (or derived from it)");
3134 override public Expression DoResolve (EmitContext ec)
3136 if (getter != null){
3137 if (TypeManager.GetArgumentTypes (getter).Length != 0){
3139 117, loc, "`{0}' does not contain a " +
3140 "definition for `{1}'.", getter.DeclaringType,
3146 if (getter == null){
3148 // The following condition happens if the PropertyExpr was
3149 // created, but is invalid (ie, the property is inaccessible),
3150 // and we did not want to embed the knowledge about this in
3151 // the caller routine. This only avoids double error reporting.
3156 Report.Error (154, loc,
3157 "The property `" + PropertyInfo.Name +
3158 "' can not be used in " +
3159 "this context because it lacks a get accessor");
3163 bool must_do_cs1540_check;
3164 if (!IsAccessorAccessible (ec.ContainerType, getter, out must_do_cs1540_check)) {
3165 Report.Error (122, loc, "'{0}.get' is inaccessible due to its protection level", PropertyInfo.Name);
3169 if (!InstanceResolve (ec, must_do_cs1540_check))
3173 // Only base will allow this invocation to happen.
3175 if (IsBase && getter.IsAbstract){
3176 Report.Error (205, loc, "Cannot call an abstract base property: " +
3177 PropertyInfo.DeclaringType + "." +PropertyInfo.Name);
3184 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
3186 if (setter == null){
3188 // The following condition happens if the PropertyExpr was
3189 // created, but is invalid (ie, the property is inaccessible),
3190 // and we did not want to embed the knowledge about this in
3191 // the caller routine. This only avoids double error reporting.
3196 Report.Error (154, loc,
3197 "The property `" + PropertyInfo.Name +
3198 "' can not be used in " +
3199 "this context because it lacks a set accessor");
3203 if (TypeManager.GetArgumentTypes (setter).Length != 1){
3205 117, loc, "`{0}' does not contain a " +
3206 "definition for `{1}'.", getter.DeclaringType,
3211 bool must_do_cs1540_check;
3212 if (!IsAccessorAccessible (ec.ContainerType, setter, out must_do_cs1540_check)) {
3213 Report.Error (122, loc, "'{0}.set' is inaccessible due to its protection level", PropertyInfo.Name);
3217 if (!InstanceResolve (ec, must_do_cs1540_check))
3221 // Only base will allow this invocation to happen.
3223 if (IsBase && setter.IsAbstract){
3224 Report.Error (205, loc, "Cannot call an abstract base property: " +
3225 PropertyInfo.DeclaringType + "." +PropertyInfo.Name);
3230 // Check that we are not making changes to a temporary memory location
3232 if (instance_expr != null && instance_expr.Type.IsValueType && !(instance_expr is IMemoryLocation)) {
3233 // FIXME: Provide better error reporting.
3234 Error (1612, "Cannot modify expression because it is not a variable.");
3243 public override void Emit (EmitContext ec)
3248 void EmitInstance (EmitContext ec)
3253 if (instance_expr.Type.IsValueType) {
3254 if (instance_expr is IMemoryLocation) {
3255 ((IMemoryLocation) instance_expr).AddressOf (ec, AddressOp.LoadStore);
3257 LocalTemporary t = new LocalTemporary (ec, instance_expr.Type);
3258 instance_expr.Emit (ec);
3260 t.AddressOf (ec, AddressOp.Store);
3263 instance_expr.Emit (ec);
3266 ec.ig.Emit (OpCodes.Dup);
3270 public void Emit (EmitContext ec, bool leave_copy)
3276 // Special case: length of single dimension array property is turned into ldlen
3278 if ((getter == TypeManager.system_int_array_get_length) ||
3279 (getter == TypeManager.int_array_get_length)){
3280 Type iet = instance_expr.Type;
3283 // System.Array.Length can be called, but the Type does not
3284 // support invoking GetArrayRank, so test for that case first
3286 if (iet != TypeManager.array_type && (iet.GetArrayRank () == 1)) {
3287 ec.ig.Emit (OpCodes.Ldlen);
3288 ec.ig.Emit (OpCodes.Conv_I4);
3293 Invocation.EmitCall (ec, IsBase, IsStatic, new EmptyAddressOf (), getter, null, loc);
3298 ec.ig.Emit (OpCodes.Dup);
3300 temp = new LocalTemporary (ec, this.Type);
3306 // Implements the IAssignMethod interface for assignments
3308 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
3310 prepared = prepare_for_load;
3316 ec.ig.Emit (OpCodes.Dup);
3318 temp = new LocalTemporary (ec, this.Type);
3323 ArrayList args = new ArrayList (1);
3324 args.Add (new Argument (new EmptyAddressOf (), Argument.AType.Expression));
3326 Invocation.EmitCall (ec, IsBase, IsStatic, new EmptyAddressOf (), setter, args, loc);
3332 override public void EmitStatement (EmitContext ec)
3335 ec.ig.Emit (OpCodes.Pop);
3340 /// Fully resolved expression that evaluates to an Event
3342 public class EventExpr : Expression, IMemberExpr {
3343 public readonly EventInfo EventInfo;
3344 Expression instance_expr;
3347 MethodInfo add_accessor, remove_accessor;
3349 public EventExpr (EventInfo ei, Location loc)
3353 eclass = ExprClass.EventAccess;
3355 add_accessor = TypeManager.GetAddMethod (ei);
3356 remove_accessor = TypeManager.GetRemoveMethod (ei);
3358 if (add_accessor.IsStatic || remove_accessor.IsStatic)
3361 if (EventInfo is MyEventBuilder){
3362 MyEventBuilder eb = (MyEventBuilder) EventInfo;
3363 type = eb.EventType;
3366 type = EventInfo.EventHandlerType;
3369 public string Name {
3371 return EventInfo.Name;
3375 public bool IsInstance {
3381 public bool IsStatic {
3387 public Type DeclaringType {
3389 return EventInfo.DeclaringType;
3393 public Expression InstanceExpression {
3395 return instance_expr;
3399 instance_expr = value;
3403 bool InstanceResolve (EmitContext ec, bool must_do_cs1540_check)
3405 if ((instance_expr == null) && ec.IsStatic && !is_static) {
3406 SimpleName.Error_ObjectRefRequired (ec, loc, EventInfo.Name);
3410 if (instance_expr != null) {
3411 instance_expr = instance_expr.DoResolve (ec);
3412 if (instance_expr == null)
3417 // This is using the same mechanism as the CS1540 check in PropertyExpr.
3418 // However, in the Event case, we reported a CS0122 instead.
3420 if (must_do_cs1540_check && (instance_expr != null)) {
3421 if ((instance_expr.Type != ec.ContainerType) &&
3422 ec.ContainerType.IsSubclassOf (instance_expr.Type)) {
3423 Report.Error (122, loc, "'{0}' is inaccessible due to its protection level",
3424 DeclaringType.Name + "." + EventInfo.Name);
3433 public override Expression DoResolve (EmitContext ec)
3435 if (instance_expr != null) {
3436 instance_expr = instance_expr.DoResolve (ec);
3437 if (instance_expr == null)
3441 bool must_do_cs1540_check;
3442 if (!(IsAccessorAccessible (ec.ContainerType, add_accessor, out must_do_cs1540_check)
3443 && IsAccessorAccessible (ec.ContainerType, remove_accessor, out must_do_cs1540_check))) {
3445 Report.Error (122, loc, "'{0}' is inaccessible due to its protection level",
3446 DeclaringType.Name + "." + EventInfo.Name);
3450 if (!InstanceResolve (ec, must_do_cs1540_check))
3456 public override void Emit (EmitContext ec)
3458 if (instance_expr is This)
3459 Report.Error (79, loc, "The event `{0}' can only appear on the left hand side of += or -=, try calling the actual delegate");
3461 Report.Error (70, loc, "The event `{0}' can only appear on the left hand side of += or -= "+
3462 "(except on the defining type)", Name);
3465 public void EmitAddOrRemove (EmitContext ec, Expression source)
3467 BinaryDelegate source_del = (BinaryDelegate) source;
3468 Expression handler = source_del.Right;
3470 Argument arg = new Argument (handler, Argument.AType.Expression);
3471 ArrayList args = new ArrayList ();
3475 if (source_del.IsAddition)
3476 Invocation.EmitCall (
3477 ec, false, IsStatic, instance_expr, add_accessor, args, loc);
3479 Invocation.EmitCall (
3480 ec, false, IsStatic, instance_expr, remove_accessor, args, loc);