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)
258 return ResolveAsTypeStep (ec) as TypeExpr;
262 /// Resolves an expression and performs semantic analysis on it.
266 /// Currently Resolve wraps DoResolve to perform sanity
267 /// checking and assertion checking on what we expect from Resolve.
269 public Expression Resolve (EmitContext ec, ResolveFlags flags)
271 if ((flags & ResolveFlags.MaskExprClass) == ResolveFlags.Type)
272 return ResolveAsTypeStep (ec);
274 bool old_do_flow_analysis = ec.DoFlowAnalysis;
275 if ((flags & ResolveFlags.DisableFlowAnalysis) != 0)
276 ec.DoFlowAnalysis = false;
279 bool intermediate = (flags & ResolveFlags.Intermediate) == ResolveFlags.Intermediate;
280 if (this is SimpleName)
281 e = ((SimpleName) this).DoResolveAllowStatic (ec, intermediate);
286 ec.DoFlowAnalysis = old_do_flow_analysis;
291 if (e is SimpleName){
292 SimpleName s = (SimpleName) e;
294 if ((flags & ResolveFlags.SimpleName) == 0) {
295 MemberLookupFailed (ec, null, ec.ContainerType, s.Name,
296 ec.DeclSpace.Name, loc);
303 if ((e is TypeExpr) || (e is ComposedCast)) {
304 if ((flags & ResolveFlags.Type) == 0) {
305 e.Error_UnexpectedKind (flags);
314 if ((flags & ResolveFlags.VariableOrValue) == 0) {
315 e.Error_UnexpectedKind (flags);
320 case ExprClass.MethodGroup:
321 if (!RootContext.V2){
322 if ((flags & ResolveFlags.MethodGroup) == 0) {
323 ((MethodGroupExpr) e).ReportUsageError ();
329 case ExprClass.Value:
330 case ExprClass.Variable:
331 case ExprClass.PropertyAccess:
332 case ExprClass.EventAccess:
333 case ExprClass.IndexerAccess:
334 if ((flags & ResolveFlags.VariableOrValue) == 0) {
335 Console.WriteLine ("I got: {0} and {1}", e.GetType (), e);
336 Console.WriteLine ("I am {0} and {1}", this.GetType (), this);
337 FieldInfo fi = ((FieldExpr) e).FieldInfo;
339 Console.WriteLine ("{0} and {1}", fi.DeclaringType, fi.Name);
340 e.Error_UnexpectedKind (flags);
346 throw new Exception ("Expression " + e.GetType () +
347 " ExprClass is Invalid after resolve");
351 throw new Exception (
352 "Expression " + e.GetType () +
353 " did not set its type after Resolve\n" +
354 "called from: " + this.GetType ());
360 /// Resolves an expression and performs semantic analysis on it.
362 public Expression Resolve (EmitContext ec)
364 return Resolve (ec, ResolveFlags.VariableOrValue);
368 /// Resolves an expression for LValue assignment
372 /// Currently ResolveLValue wraps DoResolveLValue to perform sanity
373 /// checking and assertion checking on what we expect from Resolve
375 public Expression ResolveLValue (EmitContext ec, Expression right_side)
377 Expression e = DoResolveLValue (ec, right_side);
380 if (e is SimpleName){
381 SimpleName s = (SimpleName) e;
382 MemberLookupFailed (ec, null, ec.ContainerType, s.Name,
383 ec.DeclSpace.Name, loc);
387 if (e.eclass == ExprClass.Invalid)
388 throw new Exception ("Expression " + e +
389 " ExprClass is Invalid after resolve");
391 if (e.eclass == ExprClass.MethodGroup) {
392 ((MethodGroupExpr) e).ReportUsageError ();
397 throw new Exception ("Expression " + e +
398 " did not set its type after Resolve");
405 /// Emits the code for the expression
409 /// The Emit method is invoked to generate the code
410 /// for the expression.
412 public abstract void Emit (EmitContext ec);
414 public virtual void EmitBranchable (EmitContext ec, Label target, bool onTrue)
417 ec.ig.Emit (onTrue ? OpCodes.Brtrue : OpCodes.Brfalse, target);
421 /// Protected constructor. Only derivate types should
422 /// be able to be created
425 protected Expression ()
427 eclass = ExprClass.Invalid;
432 /// Returns a literalized version of a literal FieldInfo
436 /// The possible return values are:
437 /// IntConstant, UIntConstant
438 /// LongLiteral, ULongConstant
439 /// FloatConstant, DoubleConstant
442 /// The value returned is already resolved.
444 public static Constant Constantify (object v, Type t)
446 if (t == TypeManager.int32_type)
447 return new IntConstant ((int) v);
448 else if (t == TypeManager.uint32_type)
449 return new UIntConstant ((uint) v);
450 else if (t == TypeManager.int64_type)
451 return new LongConstant ((long) v);
452 else if (t == TypeManager.uint64_type)
453 return new ULongConstant ((ulong) v);
454 else if (t == TypeManager.float_type)
455 return new FloatConstant ((float) v);
456 else if (t == TypeManager.double_type)
457 return new DoubleConstant ((double) v);
458 else if (t == TypeManager.string_type)
459 return new StringConstant ((string) v);
460 else if (t == TypeManager.short_type)
461 return new ShortConstant ((short)v);
462 else if (t == TypeManager.ushort_type)
463 return new UShortConstant ((ushort)v);
464 else if (t == TypeManager.sbyte_type)
465 return new SByteConstant (((sbyte)v));
466 else if (t == TypeManager.byte_type)
467 return new ByteConstant ((byte)v);
468 else if (t == TypeManager.char_type)
469 return new CharConstant ((char)v);
470 else if (t == TypeManager.bool_type)
471 return new BoolConstant ((bool) v);
472 else if (TypeManager.IsEnumType (t)){
473 Type real_type = TypeManager.TypeToCoreType (v.GetType ());
475 real_type = System.Enum.GetUnderlyingType (real_type);
477 Constant e = Constantify (v, real_type);
479 return new EnumConstant (e, t);
481 throw new Exception ("Unknown type for constant (" + t +
486 /// Returns a fully formed expression after a MemberLookup
488 public static Expression ExprClassFromMemberInfo (EmitContext ec, MemberInfo mi, Location loc)
491 return new EventExpr ((EventInfo) mi, loc);
492 else if (mi is FieldInfo)
493 return new FieldExpr ((FieldInfo) mi, loc);
494 else if (mi is PropertyInfo)
495 return new PropertyExpr (ec, (PropertyInfo) mi, loc);
496 else if (mi is Type){
497 return new TypeExpression ((System.Type) mi, loc);
504 private static ArrayList almostMatchedMembers = new ArrayList (4);
507 // FIXME: Probably implement a cache for (t,name,current_access_set)?
509 // This code could use some optimizations, but we need to do some
510 // measurements. For example, we could use a delegate to `flag' when
511 // something can not any longer be a method-group (because it is something
515 // If the return value is an Array, then it is an array of
518 // If the return value is an MemberInfo, it is anything, but a Method
522 // FIXME: When calling MemberLookup inside an `Invocation', we should pass
523 // the arguments here and have MemberLookup return only the methods that
524 // match the argument count/type, unlike we are doing now (we delay this
527 // This is so we can catch correctly attempts to invoke instance methods
528 // from a static body (scan for error 120 in ResolveSimpleName).
531 // FIXME: Potential optimization, have a static ArrayList
534 public static Expression MemberLookup (EmitContext ec, Type queried_type, string name,
535 MemberTypes mt, BindingFlags bf, Location loc)
537 return MemberLookup (ec, ec.ContainerType, null, queried_type, name, mt, bf, loc);
541 // Lookup type `queried_type' for code in class `container_type' with a qualifier of
542 // `qualifier_type' or null to lookup members in the current class.
545 public static Expression MemberLookup (EmitContext ec, Type container_type,
546 Type qualifier_type, Type queried_type,
547 string name, MemberTypes mt,
548 BindingFlags bf, Location loc)
550 almostMatchedMembers.Clear ();
552 MemberInfo [] mi = TypeManager.MemberLookup (container_type, qualifier_type,
553 queried_type, mt, bf, name, almostMatchedMembers);
558 int count = mi.Length;
560 if (mi [0] is MethodBase)
561 return new MethodGroupExpr (mi, loc);
566 return ExprClassFromMemberInfo (ec, mi [0], loc);
569 public const MemberTypes AllMemberTypes =
570 MemberTypes.Constructor |
574 MemberTypes.NestedType |
575 MemberTypes.Property;
577 public const BindingFlags AllBindingFlags =
578 BindingFlags.Public |
579 BindingFlags.Static |
580 BindingFlags.Instance;
582 public static Expression MemberLookup (EmitContext ec, Type queried_type,
583 string name, Location loc)
585 return MemberLookup (ec, ec.ContainerType, null, queried_type, name,
586 AllMemberTypes, AllBindingFlags, loc);
589 public static Expression MemberLookup (EmitContext ec, Type qualifier_type,
590 Type queried_type, string name, Location loc)
592 return MemberLookup (ec, ec.ContainerType, qualifier_type, queried_type,
593 name, AllMemberTypes, AllBindingFlags, loc);
596 public static Expression MethodLookup (EmitContext ec, Type queried_type,
597 string name, Location loc)
599 return MemberLookup (ec, ec.ContainerType, null, queried_type, name,
600 MemberTypes.Method, AllBindingFlags, loc);
604 /// This is a wrapper for MemberLookup that is not used to "probe", but
605 /// to find a final definition. If the final definition is not found, we
606 /// look for private members and display a useful debugging message if we
609 public static Expression MemberLookupFinal (EmitContext ec, Type qualifier_type,
610 Type queried_type, string name, Location loc)
612 return MemberLookupFinal (ec, qualifier_type, queried_type, name,
613 AllMemberTypes, AllBindingFlags, loc);
616 public static Expression MemberLookupFinal (EmitContext ec, Type qualifier_type,
617 Type queried_type, string name,
618 MemberTypes mt, BindingFlags bf,
623 int errors = Report.Errors;
625 e = MemberLookup (ec, ec.ContainerType, qualifier_type, queried_type, name, mt, bf, loc);
627 if (e == null && errors == Report.Errors)
628 // No errors were reported by MemberLookup, but there was an error.
629 MemberLookupFailed (ec, qualifier_type, queried_type, name, null, loc);
634 public static void MemberLookupFailed (EmitContext ec, Type qualifier_type,
635 Type queried_type, string name,
636 string class_name, Location loc)
638 if (almostMatchedMembers.Count != 0) {
639 if (qualifier_type == null) {
640 foreach (MemberInfo m in almostMatchedMembers)
641 Report.Error (38, loc,
642 "Cannot access non-static member `{0}' via nested type `{1}'",
643 TypeManager.GetFullNameSignature (m),
644 TypeManager.CSharpName (ec.ContainerType));
648 if (qualifier_type != ec.ContainerType) {
649 // Although a derived class can access protected members of
650 // its base class it cannot do so through an instance of the
651 // base class (CS1540). If the qualifier_type is a parent of the
652 // ec.ContainerType and the lookup succeeds with the latter one,
653 // then we are in this situation.
654 foreach (MemberInfo m in almostMatchedMembers)
655 Report.Error (1540, loc,
656 "Cannot access protected member `{0}' via a qualifier of type `{1}';"
657 + " the qualifier must be of type `{2}' (or derived from it)",
658 TypeManager.GetFullNameSignature (m),
659 TypeManager.CSharpName (qualifier_type),
660 TypeManager.CSharpName (ec.ContainerType));
663 almostMatchedMembers.Clear ();
666 object lookup = TypeManager.MemberLookup (queried_type, null, queried_type,
667 AllMemberTypes, AllBindingFlags |
668 BindingFlags.NonPublic, name, null);
670 if (lookup == null) {
671 if (class_name != null)
672 Report.Error (103, loc, "The name `" + name + "' could not be " +
673 "found in `" + class_name + "'");
676 117, loc, "`" + queried_type + "' does not contain a " +
677 "definition for `" + name + "'");
681 if (qualifier_type != null)
682 Report.Error (122, loc, "'{0}' is inaccessible due to its protection level", TypeManager.CSharpName (qualifier_type) + "." + name);
683 else if (name == ".ctor") {
684 Report.Error (143, loc, String.Format ("The type {0} has no constructors defined",
685 TypeManager.CSharpName (queried_type)));
687 Report.Error (122, loc, "'{0}' is inaccessible due to its protection level", name);
691 static public MemberInfo GetFieldFromEvent (EventExpr event_expr)
693 EventInfo ei = event_expr.EventInfo;
695 return TypeManager.GetPrivateFieldOfEvent (ei);
699 /// Returns an expression that can be used to invoke operator true
700 /// on the expression if it exists.
702 static public StaticCallExpr GetOperatorTrue (EmitContext ec, Expression e, Location loc)
704 return GetOperatorTrueOrFalse (ec, e, true, loc);
708 /// Returns an expression that can be used to invoke operator false
709 /// on the expression if it exists.
711 static public StaticCallExpr GetOperatorFalse (EmitContext ec, Expression e, Location loc)
713 return GetOperatorTrueOrFalse (ec, e, false, loc);
716 static StaticCallExpr GetOperatorTrueOrFalse (EmitContext ec, Expression e, bool is_true, Location loc)
719 Expression operator_group;
721 operator_group = MethodLookup (ec, e.Type, is_true ? "op_True" : "op_False", loc);
722 if (operator_group == null)
725 ArrayList arguments = new ArrayList ();
726 arguments.Add (new Argument (e, Argument.AType.Expression));
727 method = Invocation.OverloadResolve (ec, (MethodGroupExpr) operator_group, arguments, loc);
732 return new StaticCallExpr ((MethodInfo) method, arguments, loc);
736 /// Resolves the expression `e' into a boolean expression: either through
737 /// an implicit conversion, or through an `operator true' invocation
739 public static Expression ResolveBoolean (EmitContext ec, Expression e, Location loc)
745 Expression converted = e;
746 if (e.Type != TypeManager.bool_type)
747 converted = Convert.ImplicitConversion (ec, e, TypeManager.bool_type, new Location (-1));
750 // If no implicit conversion to bool exists, try using `operator true'
752 if (converted == null){
753 Expression operator_true = Expression.GetOperatorTrue (ec, e, loc);
754 if (operator_true == null){
756 31, loc, "Can not convert the expression to a boolean");
766 static string ExprClassName (ExprClass c)
769 case ExprClass.Invalid:
771 case ExprClass.Value:
773 case ExprClass.Variable:
775 case ExprClass.Namespace:
779 case ExprClass.MethodGroup:
780 return "method group";
781 case ExprClass.PropertyAccess:
782 return "property access";
783 case ExprClass.EventAccess:
784 return "event access";
785 case ExprClass.IndexerAccess:
786 return "indexer access";
787 case ExprClass.Nothing:
790 throw new Exception ("Should not happen");
794 /// Reports that we were expecting `expr' to be of class `expected'
796 public void Error_UnexpectedKind (string expected)
798 string kind = "Unknown";
800 kind = ExprClassName (eclass);
802 Error (118, "Expression denotes a `" + kind +
803 "' where a `" + expected + "' was expected");
806 public void Error_UnexpectedKind (ResolveFlags flags)
808 ArrayList valid = new ArrayList (10);
810 if ((flags & ResolveFlags.VariableOrValue) != 0) {
811 valid.Add ("variable");
815 if ((flags & ResolveFlags.Type) != 0)
818 if ((flags & ResolveFlags.MethodGroup) != 0)
819 valid.Add ("method group");
821 if ((flags & ResolveFlags.SimpleName) != 0)
822 valid.Add ("simple name");
824 if (valid.Count == 0)
825 valid.Add ("unknown");
827 StringBuilder sb = new StringBuilder ();
828 for (int i = 0; i < valid.Count; i++) {
831 else if (i == valid.Count)
833 sb.Append (valid [i]);
836 string kind = ExprClassName (eclass);
838 Error (119, "Expression denotes a `" + kind + "' where " +
839 "a `" + sb.ToString () + "' was expected");
842 static public void Error_ConstantValueCannotBeConverted (Location l, string val, Type t)
844 Report.Error (31, l, "Constant value `" + val + "' cannot be converted to " +
845 TypeManager.CSharpName (t));
848 public static void UnsafeError (Location loc)
850 Report.Error (214, loc, "Pointers may only be used in an unsafe context");
854 /// Converts the IntConstant, UIntConstant, LongConstant or
855 /// ULongConstant into the integral target_type. Notice
856 /// that we do not return an `Expression' we do return
857 /// a boxed integral type.
859 /// FIXME: Since I added the new constants, we need to
860 /// also support conversions from CharConstant, ByteConstant,
861 /// SByteConstant, UShortConstant, ShortConstant
863 /// This is used by the switch statement, so the domain
864 /// of work is restricted to the literals above, and the
865 /// targets are int32, uint32, char, byte, sbyte, ushort,
866 /// short, uint64 and int64
868 public static object ConvertIntLiteral (Constant c, Type target_type, Location loc)
870 if (!Convert.ImplicitStandardConversionExists (c, target_type)){
871 Convert.Error_CannotImplicitConversion (loc, c.Type, target_type);
877 if (c.Type == target_type)
878 return ((Constant) c).GetValue ();
881 // Make into one of the literals we handle, we dont really care
882 // about this value as we will just return a few limited types
884 if (c is EnumConstant)
885 c = ((EnumConstant)c).WidenToCompilerConstant ();
887 if (c is IntConstant){
888 int v = ((IntConstant) c).Value;
890 if (target_type == TypeManager.uint32_type){
893 } else if (target_type == TypeManager.char_type){
894 if (v >= Char.MinValue && v <= Char.MaxValue)
896 } else if (target_type == TypeManager.byte_type){
897 if (v >= Byte.MinValue && v <= Byte.MaxValue)
899 } else if (target_type == TypeManager.sbyte_type){
900 if (v >= SByte.MinValue && v <= SByte.MaxValue)
902 } else if (target_type == TypeManager.short_type){
903 if (v >= Int16.MinValue && v <= UInt16.MaxValue)
905 } else if (target_type == TypeManager.ushort_type){
906 if (v >= UInt16.MinValue && v <= UInt16.MaxValue)
908 } else if (target_type == TypeManager.int64_type)
910 else if (target_type == TypeManager.uint64_type){
916 } else if (c is UIntConstant){
917 uint v = ((UIntConstant) c).Value;
919 if (target_type == TypeManager.int32_type){
920 if (v <= Int32.MaxValue)
922 } else if (target_type == TypeManager.char_type){
923 if (v >= Char.MinValue && v <= Char.MaxValue)
925 } else if (target_type == TypeManager.byte_type){
926 if (v <= Byte.MaxValue)
928 } else if (target_type == TypeManager.sbyte_type){
929 if (v <= SByte.MaxValue)
931 } else if (target_type == TypeManager.short_type){
932 if (v <= UInt16.MaxValue)
934 } else if (target_type == TypeManager.ushort_type){
935 if (v <= UInt16.MaxValue)
937 } else if (target_type == TypeManager.int64_type)
939 else if (target_type == TypeManager.uint64_type)
942 } else if (c is LongConstant){
943 long v = ((LongConstant) c).Value;
945 if (target_type == TypeManager.int32_type){
946 if (v >= UInt32.MinValue && v <= UInt32.MaxValue)
948 } else if (target_type == TypeManager.uint32_type){
949 if (v >= 0 && v <= UInt32.MaxValue)
951 } else if (target_type == TypeManager.char_type){
952 if (v >= Char.MinValue && v <= Char.MaxValue)
954 } else if (target_type == TypeManager.byte_type){
955 if (v >= Byte.MinValue && v <= Byte.MaxValue)
957 } else if (target_type == TypeManager.sbyte_type){
958 if (v >= SByte.MinValue && v <= SByte.MaxValue)
960 } else if (target_type == TypeManager.short_type){
961 if (v >= Int16.MinValue && v <= UInt16.MaxValue)
963 } else if (target_type == TypeManager.ushort_type){
964 if (v >= UInt16.MinValue && v <= UInt16.MaxValue)
966 } else if (target_type == TypeManager.uint64_type){
971 } else if (c is ULongConstant){
972 ulong v = ((ULongConstant) c).Value;
974 if (target_type == TypeManager.int32_type){
975 if (v <= Int32.MaxValue)
977 } else if (target_type == TypeManager.uint32_type){
978 if (v <= UInt32.MaxValue)
980 } else if (target_type == TypeManager.char_type){
981 if (v >= Char.MinValue && v <= Char.MaxValue)
983 } else if (target_type == TypeManager.byte_type){
984 if (v >= Byte.MinValue && v <= Byte.MaxValue)
986 } else if (target_type == TypeManager.sbyte_type){
987 if (v <= (int) SByte.MaxValue)
989 } else if (target_type == TypeManager.short_type){
990 if (v <= UInt16.MaxValue)
992 } else if (target_type == TypeManager.ushort_type){
993 if (v <= UInt16.MaxValue)
995 } else if (target_type == TypeManager.int64_type){
996 if (v <= Int64.MaxValue)
1000 } else if (c is ByteConstant){
1001 byte v = ((ByteConstant) c).Value;
1003 if (target_type == TypeManager.int32_type)
1005 else if (target_type == TypeManager.uint32_type)
1007 else if (target_type == TypeManager.char_type)
1009 else if (target_type == TypeManager.sbyte_type){
1010 if (v <= SByte.MaxValue)
1012 } else if (target_type == TypeManager.short_type)
1014 else if (target_type == TypeManager.ushort_type)
1016 else if (target_type == TypeManager.int64_type)
1018 else if (target_type == TypeManager.uint64_type)
1021 } else if (c is SByteConstant){
1022 sbyte v = ((SByteConstant) c).Value;
1024 if (target_type == TypeManager.int32_type)
1026 else if (target_type == TypeManager.uint32_type){
1029 } else if (target_type == TypeManager.char_type){
1032 } else if (target_type == TypeManager.byte_type){
1035 } else if (target_type == TypeManager.short_type)
1037 else if (target_type == TypeManager.ushort_type){
1040 } else if (target_type == TypeManager.int64_type)
1042 else if (target_type == TypeManager.uint64_type){
1047 } else if (c is ShortConstant){
1048 short v = ((ShortConstant) c).Value;
1050 if (target_type == TypeManager.int32_type){
1052 } else if (target_type == TypeManager.uint32_type){
1055 } else if (target_type == TypeManager.char_type){
1058 } else if (target_type == TypeManager.byte_type){
1059 if (v >= Byte.MinValue && v <= Byte.MaxValue)
1061 } else if (target_type == TypeManager.sbyte_type){
1062 if (v >= SByte.MinValue && v <= SByte.MaxValue)
1064 } else if (target_type == TypeManager.ushort_type){
1067 } else if (target_type == TypeManager.int64_type)
1069 else if (target_type == TypeManager.uint64_type)
1073 } else if (c is UShortConstant){
1074 ushort v = ((UShortConstant) c).Value;
1076 if (target_type == TypeManager.int32_type)
1078 else if (target_type == TypeManager.uint32_type)
1080 else if (target_type == TypeManager.char_type){
1081 if (v >= Char.MinValue && v <= Char.MaxValue)
1083 } else if (target_type == TypeManager.byte_type){
1084 if (v >= Byte.MinValue && v <= Byte.MaxValue)
1086 } else if (target_type == TypeManager.sbyte_type){
1087 if (v <= SByte.MaxValue)
1089 } else if (target_type == TypeManager.short_type){
1090 if (v <= Int16.MaxValue)
1092 } else if (target_type == TypeManager.int64_type)
1094 else if (target_type == TypeManager.uint64_type)
1098 } else if (c is CharConstant){
1099 char v = ((CharConstant) c).Value;
1101 if (target_type == TypeManager.int32_type)
1103 else if (target_type == TypeManager.uint32_type)
1105 else if (target_type == TypeManager.byte_type){
1106 if (v >= Byte.MinValue && v <= Byte.MaxValue)
1108 } else if (target_type == TypeManager.sbyte_type){
1109 if (v <= SByte.MaxValue)
1111 } else if (target_type == TypeManager.short_type){
1112 if (v <= Int16.MaxValue)
1114 } else if (target_type == TypeManager.ushort_type)
1116 else if (target_type == TypeManager.int64_type)
1118 else if (target_type == TypeManager.uint64_type)
1123 Error_ConstantValueCannotBeConverted (loc, s, target_type);
1128 // Load the object from the pointer.
1130 public static void LoadFromPtr (ILGenerator ig, Type t)
1132 if (t == TypeManager.int32_type)
1133 ig.Emit (OpCodes.Ldind_I4);
1134 else if (t == TypeManager.uint32_type)
1135 ig.Emit (OpCodes.Ldind_U4);
1136 else if (t == TypeManager.short_type)
1137 ig.Emit (OpCodes.Ldind_I2);
1138 else if (t == TypeManager.ushort_type)
1139 ig.Emit (OpCodes.Ldind_U2);
1140 else if (t == TypeManager.char_type)
1141 ig.Emit (OpCodes.Ldind_U2);
1142 else if (t == TypeManager.byte_type)
1143 ig.Emit (OpCodes.Ldind_U1);
1144 else if (t == TypeManager.sbyte_type)
1145 ig.Emit (OpCodes.Ldind_I1);
1146 else if (t == TypeManager.uint64_type)
1147 ig.Emit (OpCodes.Ldind_I8);
1148 else if (t == TypeManager.int64_type)
1149 ig.Emit (OpCodes.Ldind_I8);
1150 else if (t == TypeManager.float_type)
1151 ig.Emit (OpCodes.Ldind_R4);
1152 else if (t == TypeManager.double_type)
1153 ig.Emit (OpCodes.Ldind_R8);
1154 else if (t == TypeManager.bool_type)
1155 ig.Emit (OpCodes.Ldind_I1);
1156 else if (t == TypeManager.intptr_type)
1157 ig.Emit (OpCodes.Ldind_I);
1158 else if (TypeManager.IsEnumType (t)) {
1159 if (t == TypeManager.enum_type)
1160 ig.Emit (OpCodes.Ldind_Ref);
1162 LoadFromPtr (ig, TypeManager.EnumToUnderlying (t));
1163 } else if (t.IsValueType)
1164 ig.Emit (OpCodes.Ldobj, t);
1165 else if (t.IsPointer)
1166 ig.Emit (OpCodes.Ldind_I);
1168 ig.Emit (OpCodes.Ldind_Ref);
1172 // The stack contains the pointer and the value of type `type'
1174 public static void StoreFromPtr (ILGenerator ig, Type type)
1176 if (TypeManager.IsEnumType (type))
1177 type = TypeManager.EnumToUnderlying (type);
1178 if (type == TypeManager.int32_type || type == TypeManager.uint32_type)
1179 ig.Emit (OpCodes.Stind_I4);
1180 else if (type == TypeManager.int64_type || type == TypeManager.uint64_type)
1181 ig.Emit (OpCodes.Stind_I8);
1182 else if (type == TypeManager.char_type || type == TypeManager.short_type ||
1183 type == TypeManager.ushort_type)
1184 ig.Emit (OpCodes.Stind_I2);
1185 else if (type == TypeManager.float_type)
1186 ig.Emit (OpCodes.Stind_R4);
1187 else if (type == TypeManager.double_type)
1188 ig.Emit (OpCodes.Stind_R8);
1189 else if (type == TypeManager.byte_type || type == TypeManager.sbyte_type ||
1190 type == TypeManager.bool_type)
1191 ig.Emit (OpCodes.Stind_I1);
1192 else if (type == TypeManager.intptr_type)
1193 ig.Emit (OpCodes.Stind_I);
1194 else if (type.IsValueType)
1195 ig.Emit (OpCodes.Stobj, type);
1197 ig.Emit (OpCodes.Stind_Ref);
1201 // Returns the size of type `t' if known, otherwise, 0
1203 public static int GetTypeSize (Type t)
1205 t = TypeManager.TypeToCoreType (t);
1206 if (t == TypeManager.int32_type ||
1207 t == TypeManager.uint32_type ||
1208 t == TypeManager.float_type)
1210 else if (t == TypeManager.int64_type ||
1211 t == TypeManager.uint64_type ||
1212 t == TypeManager.double_type)
1214 else if (t == TypeManager.byte_type ||
1215 t == TypeManager.sbyte_type ||
1216 t == TypeManager.bool_type)
1218 else if (t == TypeManager.short_type ||
1219 t == TypeManager.char_type ||
1220 t == TypeManager.ushort_type)
1222 else if (t == TypeManager.decimal_type)
1228 static void Error_NegativeArrayIndex (Location loc)
1230 Report.Error (284, loc, "Can not create array with a negative size");
1234 // Converts `source' to an int, uint, long or ulong.
1236 public Expression ExpressionToArrayArgument (EmitContext ec, Expression source, Location loc)
1240 bool old_checked = ec.CheckState;
1241 ec.CheckState = true;
1243 target = Convert.ImplicitConversion (ec, source, TypeManager.int32_type, loc);
1244 if (target == null){
1245 target = Convert.ImplicitConversion (ec, source, TypeManager.uint32_type, loc);
1246 if (target == null){
1247 target = Convert.ImplicitConversion (ec, source, TypeManager.int64_type, loc);
1248 if (target == null){
1249 target = Convert.ImplicitConversion (ec, source, TypeManager.uint64_type, loc);
1251 Convert.Error_CannotImplicitConversion (loc, source.Type, TypeManager.int32_type);
1255 ec.CheckState = old_checked;
1258 // Only positive constants are allowed at compile time
1260 if (target is Constant){
1261 if (target is IntConstant){
1262 if (((IntConstant) target).Value < 0){
1263 Error_NegativeArrayIndex (loc);
1268 if (target is LongConstant){
1269 if (((LongConstant) target).Value < 0){
1270 Error_NegativeArrayIndex (loc);
1283 /// This is just a base class for expressions that can
1284 /// appear on statements (invocations, object creation,
1285 /// assignments, post/pre increment and decrement). The idea
1286 /// being that they would support an extra Emition interface that
1287 /// does not leave a result on the stack.
1289 public abstract class ExpressionStatement : Expression {
1291 public virtual ExpressionStatement ResolveStatement (EmitContext ec)
1293 Expression e = Resolve (ec);
1297 ExpressionStatement es = e as ExpressionStatement;
1299 Error (201, "Only assignment, call, increment, decrement and new object " +
1300 "expressions can be used as a statement");
1306 /// Requests the expression to be emitted in a `statement'
1307 /// context. This means that no new value is left on the
1308 /// stack after invoking this method (constrasted with
1309 /// Emit that will always leave a value on the stack).
1311 public abstract void EmitStatement (EmitContext ec);
1315 /// This kind of cast is used to encapsulate the child
1316 /// whose type is child.Type into an expression that is
1317 /// reported to return "return_type". This is used to encapsulate
1318 /// expressions which have compatible types, but need to be dealt
1319 /// at higher levels with.
1321 /// For example, a "byte" expression could be encapsulated in one
1322 /// of these as an "unsigned int". The type for the expression
1323 /// would be "unsigned int".
1326 public class EmptyCast : Expression {
1327 protected Expression child;
1329 public Expression Child {
1335 public EmptyCast (Expression child, Type return_type)
1337 eclass = child.eclass;
1342 public override Expression DoResolve (EmitContext ec)
1344 // This should never be invoked, we are born in fully
1345 // initialized state.
1350 public override void Emit (EmitContext ec)
1357 // We need to special case this since an empty cast of
1358 // a NullLiteral is still a Constant
1360 public class NullCast : Constant {
1361 protected Expression child;
1363 public NullCast (Expression child, Type return_type)
1365 eclass = child.eclass;
1370 override public string AsString ()
1375 public override object GetValue ()
1380 public override Expression DoResolve (EmitContext ec)
1382 // This should never be invoked, we are born in fully
1383 // initialized state.
1388 public override void Emit (EmitContext ec)
1396 /// This class is used to wrap literals which belong inside Enums
1398 public class EnumConstant : Constant {
1399 public Constant Child;
1401 public EnumConstant (Constant child, Type enum_type)
1403 eclass = child.eclass;
1408 public override Expression DoResolve (EmitContext ec)
1410 // This should never be invoked, we are born in fully
1411 // initialized state.
1416 public override void Emit (EmitContext ec)
1421 public override object GetValue ()
1423 return Child.GetValue ();
1427 // Converts from one of the valid underlying types for an enumeration
1428 // (int32, uint32, int64, uint64, short, ushort, byte, sbyte) to
1429 // one of the internal compiler literals: Int/UInt/Long/ULong Literals.
1431 public Constant WidenToCompilerConstant ()
1433 Type t = TypeManager.EnumToUnderlying (Child.Type);
1434 object v = ((Constant) Child).GetValue ();;
1436 if (t == TypeManager.int32_type)
1437 return new IntConstant ((int) v);
1438 if (t == TypeManager.uint32_type)
1439 return new UIntConstant ((uint) v);
1440 if (t == TypeManager.int64_type)
1441 return new LongConstant ((long) v);
1442 if (t == TypeManager.uint64_type)
1443 return new ULongConstant ((ulong) v);
1444 if (t == TypeManager.short_type)
1445 return new ShortConstant ((short) v);
1446 if (t == TypeManager.ushort_type)
1447 return new UShortConstant ((ushort) v);
1448 if (t == TypeManager.byte_type)
1449 return new ByteConstant ((byte) v);
1450 if (t == TypeManager.sbyte_type)
1451 return new SByteConstant ((sbyte) v);
1453 throw new Exception ("Invalid enumeration underlying type: " + t);
1457 // Extracts the value in the enumeration on its native representation
1459 public object GetPlainValue ()
1461 Type t = TypeManager.EnumToUnderlying (Child.Type);
1462 object v = ((Constant) Child).GetValue ();;
1464 if (t == TypeManager.int32_type)
1466 if (t == TypeManager.uint32_type)
1468 if (t == TypeManager.int64_type)
1470 if (t == TypeManager.uint64_type)
1472 if (t == TypeManager.short_type)
1474 if (t == TypeManager.ushort_type)
1476 if (t == TypeManager.byte_type)
1478 if (t == TypeManager.sbyte_type)
1484 public override string AsString ()
1486 return Child.AsString ();
1489 public override DoubleConstant ConvertToDouble ()
1491 return Child.ConvertToDouble ();
1494 public override FloatConstant ConvertToFloat ()
1496 return Child.ConvertToFloat ();
1499 public override ULongConstant ConvertToULong ()
1501 return Child.ConvertToULong ();
1504 public override LongConstant ConvertToLong ()
1506 return Child.ConvertToLong ();
1509 public override UIntConstant ConvertToUInt ()
1511 return Child.ConvertToUInt ();
1514 public override IntConstant ConvertToInt ()
1516 return Child.ConvertToInt ();
1519 public override bool IsZeroInteger {
1520 get { return Child.IsZeroInteger; }
1525 /// This kind of cast is used to encapsulate Value Types in objects.
1527 /// The effect of it is to box the value type emitted by the previous
1530 public class BoxedCast : EmptyCast {
1532 public BoxedCast (Expression expr)
1533 : base (expr, TypeManager.object_type)
1535 eclass = ExprClass.Value;
1538 public BoxedCast (Expression expr, Type target_type)
1539 : base (expr, target_type)
1541 eclass = ExprClass.Value;
1544 public override Expression DoResolve (EmitContext ec)
1546 // This should never be invoked, we are born in fully
1547 // initialized state.
1552 public override void Emit (EmitContext ec)
1556 ec.ig.Emit (OpCodes.Box, child.Type);
1560 public class UnboxCast : EmptyCast {
1561 public UnboxCast (Expression expr, Type return_type)
1562 : base (expr, return_type)
1566 public override Expression DoResolve (EmitContext ec)
1568 // This should never be invoked, we are born in fully
1569 // initialized state.
1574 public override void Emit (EmitContext ec)
1577 ILGenerator ig = ec.ig;
1580 ig.Emit (OpCodes.Unbox, t);
1582 LoadFromPtr (ig, t);
1587 /// This is used to perform explicit numeric conversions.
1589 /// Explicit numeric conversions might trigger exceptions in a checked
1590 /// context, so they should generate the conv.ovf opcodes instead of
1593 public class ConvCast : EmptyCast {
1594 public enum Mode : byte {
1595 I1_U1, I1_U2, I1_U4, I1_U8, I1_CH,
1597 I2_I1, I2_U1, I2_U2, I2_U4, I2_U8, I2_CH,
1598 U2_I1, U2_U1, U2_I2, U2_CH,
1599 I4_I1, I4_U1, I4_I2, I4_U2, I4_U4, I4_U8, I4_CH,
1600 U4_I1, U4_U1, U4_I2, U4_U2, U4_I4, U4_CH,
1601 I8_I1, I8_U1, I8_I2, I8_U2, I8_I4, I8_U4, I8_U8, I8_CH,
1602 U8_I1, U8_U1, U8_I2, U8_U2, U8_I4, U8_U4, U8_I8, U8_CH,
1603 CH_I1, CH_U1, CH_I2,
1604 R4_I1, R4_U1, R4_I2, R4_U2, R4_I4, R4_U4, R4_I8, R4_U8, R4_CH,
1605 R8_I1, R8_U1, R8_I2, R8_U2, R8_I4, R8_U4, R8_I8, R8_U8, R8_CH, R8_R4
1611 public ConvCast (EmitContext ec, Expression child, Type return_type, Mode m)
1612 : base (child, return_type)
1614 checked_state = ec.CheckState;
1618 public override Expression DoResolve (EmitContext ec)
1620 // This should never be invoked, we are born in fully
1621 // initialized state.
1626 public override string ToString ()
1628 return String.Format ("ConvCast ({0}, {1})", mode, child);
1631 public override void Emit (EmitContext ec)
1633 ILGenerator ig = ec.ig;
1639 case Mode.I1_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1640 case Mode.I1_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1641 case Mode.I1_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1642 case Mode.I1_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1643 case Mode.I1_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1645 case Mode.U1_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1646 case Mode.U1_CH: /* nothing */ break;
1648 case Mode.I2_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1649 case Mode.I2_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1650 case Mode.I2_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1651 case Mode.I2_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1652 case Mode.I2_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1653 case Mode.I2_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1655 case Mode.U2_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1656 case Mode.U2_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
1657 case Mode.U2_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
1658 case Mode.U2_CH: /* nothing */ break;
1660 case Mode.I4_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1661 case Mode.I4_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1662 case Mode.I4_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
1663 case Mode.I4_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1664 case Mode.I4_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1665 case Mode.I4_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1666 case Mode.I4_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1668 case Mode.U4_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1669 case Mode.U4_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
1670 case Mode.U4_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
1671 case Mode.U4_U2: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
1672 case Mode.U4_I4: ig.Emit (OpCodes.Conv_Ovf_I4_Un); break;
1673 case Mode.U4_CH: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
1675 case Mode.I8_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1676 case Mode.I8_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1677 case Mode.I8_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
1678 case Mode.I8_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1679 case Mode.I8_I4: ig.Emit (OpCodes.Conv_Ovf_I4); break;
1680 case Mode.I8_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1681 case Mode.I8_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1682 case Mode.I8_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1684 case Mode.U8_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1685 case Mode.U8_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
1686 case Mode.U8_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
1687 case Mode.U8_U2: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
1688 case Mode.U8_I4: ig.Emit (OpCodes.Conv_Ovf_I4_Un); break;
1689 case Mode.U8_U4: ig.Emit (OpCodes.Conv_Ovf_U4_Un); break;
1690 case Mode.U8_I8: ig.Emit (OpCodes.Conv_Ovf_I8_Un); break;
1691 case Mode.U8_CH: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
1693 case Mode.CH_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1694 case Mode.CH_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
1695 case Mode.CH_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
1697 case Mode.R4_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1698 case Mode.R4_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1699 case Mode.R4_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
1700 case Mode.R4_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1701 case Mode.R4_I4: ig.Emit (OpCodes.Conv_Ovf_I4); break;
1702 case Mode.R4_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1703 case Mode.R4_I8: ig.Emit (OpCodes.Conv_Ovf_I8); break;
1704 case Mode.R4_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1705 case Mode.R4_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1707 case Mode.R8_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1708 case Mode.R8_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1709 case Mode.R8_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
1710 case Mode.R8_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1711 case Mode.R8_I4: ig.Emit (OpCodes.Conv_Ovf_I4); break;
1712 case Mode.R8_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1713 case Mode.R8_I8: ig.Emit (OpCodes.Conv_Ovf_I8); break;
1714 case Mode.R8_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1715 case Mode.R8_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1716 case Mode.R8_R4: ig.Emit (OpCodes.Conv_R4); break;
1720 case Mode.I1_U1: ig.Emit (OpCodes.Conv_U1); break;
1721 case Mode.I1_U2: ig.Emit (OpCodes.Conv_U2); break;
1722 case Mode.I1_U4: ig.Emit (OpCodes.Conv_U4); break;
1723 case Mode.I1_U8: ig.Emit (OpCodes.Conv_I8); break;
1724 case Mode.I1_CH: ig.Emit (OpCodes.Conv_U2); break;
1726 case Mode.U1_I1: ig.Emit (OpCodes.Conv_I1); break;
1727 case Mode.U1_CH: ig.Emit (OpCodes.Conv_U2); break;
1729 case Mode.I2_I1: ig.Emit (OpCodes.Conv_I1); break;
1730 case Mode.I2_U1: ig.Emit (OpCodes.Conv_U1); break;
1731 case Mode.I2_U2: ig.Emit (OpCodes.Conv_U2); break;
1732 case Mode.I2_U4: ig.Emit (OpCodes.Conv_U4); break;
1733 case Mode.I2_U8: ig.Emit (OpCodes.Conv_I8); break;
1734 case Mode.I2_CH: ig.Emit (OpCodes.Conv_U2); break;
1736 case Mode.U2_I1: ig.Emit (OpCodes.Conv_I1); break;
1737 case Mode.U2_U1: ig.Emit (OpCodes.Conv_U1); break;
1738 case Mode.U2_I2: ig.Emit (OpCodes.Conv_I2); break;
1739 case Mode.U2_CH: /* nothing */ break;
1741 case Mode.I4_I1: ig.Emit (OpCodes.Conv_I1); break;
1742 case Mode.I4_U1: ig.Emit (OpCodes.Conv_U1); break;
1743 case Mode.I4_I2: ig.Emit (OpCodes.Conv_I2); break;
1744 case Mode.I4_U4: /* nothing */ break;
1745 case Mode.I4_U2: ig.Emit (OpCodes.Conv_U2); break;
1746 case Mode.I4_U8: ig.Emit (OpCodes.Conv_I8); break;
1747 case Mode.I4_CH: ig.Emit (OpCodes.Conv_U2); break;
1749 case Mode.U4_I1: ig.Emit (OpCodes.Conv_I1); break;
1750 case Mode.U4_U1: ig.Emit (OpCodes.Conv_U1); break;
1751 case Mode.U4_I2: ig.Emit (OpCodes.Conv_I2); break;
1752 case Mode.U4_U2: ig.Emit (OpCodes.Conv_U2); break;
1753 case Mode.U4_I4: /* nothing */ break;
1754 case Mode.U4_CH: ig.Emit (OpCodes.Conv_U2); break;
1756 case Mode.I8_I1: ig.Emit (OpCodes.Conv_I1); break;
1757 case Mode.I8_U1: ig.Emit (OpCodes.Conv_U1); break;
1758 case Mode.I8_I2: ig.Emit (OpCodes.Conv_I2); break;
1759 case Mode.I8_U2: ig.Emit (OpCodes.Conv_U2); break;
1760 case Mode.I8_I4: ig.Emit (OpCodes.Conv_I4); break;
1761 case Mode.I8_U4: ig.Emit (OpCodes.Conv_U4); break;
1762 case Mode.I8_U8: /* nothing */ break;
1763 case Mode.I8_CH: ig.Emit (OpCodes.Conv_U2); break;
1765 case Mode.U8_I1: ig.Emit (OpCodes.Conv_I1); break;
1766 case Mode.U8_U1: ig.Emit (OpCodes.Conv_U1); break;
1767 case Mode.U8_I2: ig.Emit (OpCodes.Conv_I2); break;
1768 case Mode.U8_U2: ig.Emit (OpCodes.Conv_U2); break;
1769 case Mode.U8_I4: ig.Emit (OpCodes.Conv_I4); break;
1770 case Mode.U8_U4: ig.Emit (OpCodes.Conv_U4); break;
1771 case Mode.U8_I8: /* nothing */ break;
1772 case Mode.U8_CH: ig.Emit (OpCodes.Conv_U2); break;
1774 case Mode.CH_I1: ig.Emit (OpCodes.Conv_I1); break;
1775 case Mode.CH_U1: ig.Emit (OpCodes.Conv_U1); break;
1776 case Mode.CH_I2: ig.Emit (OpCodes.Conv_I2); break;
1778 case Mode.R4_I1: ig.Emit (OpCodes.Conv_I1); break;
1779 case Mode.R4_U1: ig.Emit (OpCodes.Conv_U1); break;
1780 case Mode.R4_I2: ig.Emit (OpCodes.Conv_I2); break;
1781 case Mode.R4_U2: ig.Emit (OpCodes.Conv_U2); break;
1782 case Mode.R4_I4: ig.Emit (OpCodes.Conv_I4); break;
1783 case Mode.R4_U4: ig.Emit (OpCodes.Conv_U4); break;
1784 case Mode.R4_I8: ig.Emit (OpCodes.Conv_I8); break;
1785 case Mode.R4_U8: ig.Emit (OpCodes.Conv_U8); break;
1786 case Mode.R4_CH: ig.Emit (OpCodes.Conv_U2); break;
1788 case Mode.R8_I1: ig.Emit (OpCodes.Conv_I1); break;
1789 case Mode.R8_U1: ig.Emit (OpCodes.Conv_U1); break;
1790 case Mode.R8_I2: ig.Emit (OpCodes.Conv_I2); break;
1791 case Mode.R8_U2: ig.Emit (OpCodes.Conv_U2); break;
1792 case Mode.R8_I4: ig.Emit (OpCodes.Conv_I4); break;
1793 case Mode.R8_U4: ig.Emit (OpCodes.Conv_U4); break;
1794 case Mode.R8_I8: ig.Emit (OpCodes.Conv_I8); break;
1795 case Mode.R8_U8: ig.Emit (OpCodes.Conv_U8); break;
1796 case Mode.R8_CH: ig.Emit (OpCodes.Conv_U2); break;
1797 case Mode.R8_R4: ig.Emit (OpCodes.Conv_R4); break;
1803 public class OpcodeCast : EmptyCast {
1807 public OpcodeCast (Expression child, Type return_type, OpCode op)
1808 : base (child, return_type)
1812 second_valid = false;
1815 public OpcodeCast (Expression child, Type return_type, OpCode op, OpCode op2)
1816 : base (child, return_type)
1821 second_valid = true;
1824 public override Expression DoResolve (EmitContext ec)
1826 // This should never be invoked, we are born in fully
1827 // initialized state.
1832 public override void Emit (EmitContext ec)
1843 /// This kind of cast is used to encapsulate a child and cast it
1844 /// to the class requested
1846 public class ClassCast : EmptyCast {
1847 public ClassCast (Expression child, Type return_type)
1848 : base (child, return_type)
1853 public override Expression DoResolve (EmitContext ec)
1855 // This should never be invoked, we are born in fully
1856 // initialized state.
1861 public override void Emit (EmitContext ec)
1865 ec.ig.Emit (OpCodes.Castclass, type);
1871 /// SimpleName expressions are initially formed of a single
1872 /// word and it only happens at the beginning of the expression.
1876 /// The expression will try to be bound to a Field, a Method
1877 /// group or a Property. If those fail we pass the name to our
1878 /// caller and the SimpleName is compounded to perform a type
1879 /// lookup. The idea behind this process is that we want to avoid
1880 /// creating a namespace map from the assemblies, as that requires
1881 /// the GetExportedTypes function to be called and a hashtable to
1882 /// be constructed which reduces startup time. If later we find
1883 /// that this is slower, we should create a `NamespaceExpr' expression
1884 /// that fully participates in the resolution process.
1886 /// For example `System.Console.WriteLine' is decomposed into
1887 /// MemberAccess (MemberAccess (SimpleName ("System"), "Console"), "WriteLine")
1889 /// The first SimpleName wont produce a match on its own, so it will
1891 /// MemberAccess (SimpleName ("System.Console"), "WriteLine").
1893 /// System.Console will produce a TypeExpr match.
1895 /// The downside of this is that we might be hitting `LookupType' too many
1896 /// times with this scheme.
1898 public class SimpleName : Expression {
1902 // If true, then we are a simple name, not composed with a ".
1906 public SimpleName (string a, string b, Location l)
1908 Name = String.Concat (a, ".", b);
1913 public SimpleName (string name, Location l)
1920 public static void Error_ObjectRefRequired (EmitContext ec, Location l, string name)
1922 if (ec.IsFieldInitializer)
1925 "A field initializer cannot reference the non-static field, " +
1926 "method or property `"+name+"'");
1930 "An object reference is required " +
1931 "for the non-static field `"+name+"'");
1935 // Checks whether we are trying to access an instance
1936 // property, method or field from a static body.
1938 Expression MemberStaticCheck (EmitContext ec, Expression e)
1940 if (e is IMemberExpr){
1941 IMemberExpr member = (IMemberExpr) e;
1943 if (!member.IsStatic){
1944 Error_ObjectRefRequired (ec, loc, Name);
1952 public override Expression DoResolve (EmitContext ec)
1954 return SimpleNameResolve (ec, null, false, false);
1957 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
1959 return SimpleNameResolve (ec, right_side, false, false);
1963 public Expression DoResolveAllowStatic (EmitContext ec, bool intermediate)
1965 return SimpleNameResolve (ec, null, true, intermediate);
1968 public override Expression ResolveAsTypeStep (EmitContext ec)
1970 DeclSpace ds = ec.DeclSpace;
1971 NamespaceEntry ns = ds.NamespaceEntry;
1976 // Since we are cheating: we only do the Alias lookup for
1977 // namespaces if the name does not include any dots in it
1979 if (ns != null && is_base)
1980 alias_value = ns.LookupAlias (Name);
1984 if (ec.ResolvingTypeTree){
1985 int errors = Report.Errors;
1986 Type dt = ds.FindType (loc, Name);
1988 if (Report.Errors != errors)
1992 return new TypeExpression (dt, loc);
1994 if (alias_value != null){
1995 if ((t = RootContext.LookupType (ds, alias_value, true, loc)) != null)
1996 return new TypeExpression (t, loc);
2001 // First, the using aliases
2003 if (alias_value != null){
2004 if ((t = RootContext.LookupType (ds, alias_value, true, loc)) != null)
2005 return new TypeExpression (t, loc);
2007 // we have alias value, but it isn't Type, so try if it's namespace
2008 return new SimpleName (alias_value, loc);
2012 // Stage 2: Lookup up if we are an alias to a type
2016 if ((t = RootContext.LookupType (ds, Name, true, loc)) != null)
2017 return new TypeExpression (t, loc);
2019 // No match, maybe our parent can compose us
2020 // into something meaningful.
2024 Expression SimpleNameResolve (EmitContext ec, Expression right_side,
2025 bool allow_static, bool intermediate)
2027 Expression e = DoSimpleNameResolve (ec, right_side, allow_static, intermediate);
2031 Block current_block = ec.CurrentBlock;
2032 if (current_block != null){
2033 LocalInfo vi = current_block.GetLocalInfo (Name);
2035 current_block.IsVariableNameUsedInChildBlock(Name)) {
2036 Report.Error (135, Location,
2037 "'{0}' has a different meaning in a " +
2038 "child block", Name);
2047 /// 7.5.2: Simple Names.
2049 /// Local Variables and Parameters are handled at
2050 /// parse time, so they never occur as SimpleNames.
2052 /// The `allow_static' flag is used by MemberAccess only
2053 /// and it is used to inform us that it is ok for us to
2054 /// avoid the static check, because MemberAccess might end
2055 /// up resolving the Name as a Type name and the access as
2056 /// a static type access.
2058 /// ie: Type Type; .... { Type.GetType (""); }
2060 /// Type is both an instance variable and a Type; Type.GetType
2061 /// is the static method not an instance method of type.
2063 Expression DoSimpleNameResolve (EmitContext ec, Expression right_side, bool allow_static, bool intermediate)
2065 Expression e = null;
2068 // Stage 1: Performed by the parser (binding to locals or parameters).
2070 Block current_block = ec.CurrentBlock;
2071 if (current_block != null){
2072 LocalInfo vi = current_block.GetLocalInfo (Name);
2076 var = new LocalVariableReference (ec.CurrentBlock, Name, loc);
2078 if (right_side != null)
2079 return var.ResolveLValue (ec, right_side);
2081 return var.Resolve (ec);
2085 Parameter par = null;
2086 Parameters pars = current_block.Parameters;
2088 par = pars.GetParameterByName (Name, out idx);
2091 ParameterReference param;
2093 param = new ParameterReference (pars, current_block, idx, Name, loc);
2095 if (right_side != null)
2096 return param.ResolveLValue (ec, right_side);
2098 return param.Resolve (ec);
2103 // Stage 2: Lookup members
2106 DeclSpace lookup_ds = ec.DeclSpace;
2108 if (lookup_ds.TypeBuilder == null)
2111 e = MemberLookup (ec, lookup_ds.TypeBuilder, Name, loc);
2115 lookup_ds =lookup_ds.Parent;
2116 } while (lookup_ds != null);
2118 if (e == null && ec.ContainerType != null)
2119 e = MemberLookup (ec, ec.ContainerType, Name, loc);
2123 // Since we are cheating (is_base is our hint
2124 // that we are the beginning of the name): we
2125 // only do the Alias lookup for namespaces if
2126 // the name does not include any dots in it
2128 NamespaceEntry ns = ec.DeclSpace.NamespaceEntry;
2129 if (is_base && ns != null){
2130 string alias_value = ns.LookupAlias (Name);
2131 if (alias_value != null){
2135 if ((t = TypeManager.LookupType (Name)) != null)
2136 return new TypeExpression (t, loc);
2138 // No match, maybe our parent can compose us
2139 // into something meaningful.
2144 return ResolveAsTypeStep (ec);
2150 if (e is IMemberExpr) {
2151 e = MemberAccess.ResolveMemberAccess (ec, e, null, loc, this);
2155 IMemberExpr me = e as IMemberExpr;
2159 // This fails if ResolveMemberAccess() was unable to decide whether
2160 // it's a field or a type of the same name.
2162 if (!me.IsStatic && (me.InstanceExpression == null))
2166 TypeManager.IsSubclassOrNestedChildOf (me.InstanceExpression.Type, me.DeclaringType) &&
2167 me.InstanceExpression.Type != me.DeclaringType &&
2168 !me.InstanceExpression.Type.IsSubclassOf (me.DeclaringType) &&
2169 (!intermediate || !MemberAccess.IdenticalNameAndTypeName (ec, this, e, loc))) {
2170 Error (38, "Cannot access nonstatic member `" + me.Name + "' of " +
2171 "outer type `" + me.DeclaringType + "' via nested type `" +
2172 me.InstanceExpression.Type + "'");
2176 return (right_side != null)
2177 ? e.DoResolveLValue (ec, right_side)
2181 if (ec.IsStatic || ec.IsFieldInitializer){
2185 return MemberStaticCheck (ec, e);
2190 public override void Emit (EmitContext ec)
2193 // If this is ever reached, then we failed to
2194 // find the name as a namespace
2197 Error (103, "The name `" + Name +
2198 "' does not exist in the class `" +
2199 ec.DeclSpace.Name + "'");
2202 public override string ToString ()
2209 /// Fully resolved expression that evaluates to a type
2211 public abstract class TypeExpr : Expression {
2212 override public Expression ResolveAsTypeStep (EmitContext ec)
2214 TypeExpr t = DoResolveAsTypeStep (ec);
2218 eclass = ExprClass.Type;
2222 override public Expression DoResolve (EmitContext ec)
2224 return ResolveAsTypeTerminal (ec);
2227 override public void Emit (EmitContext ec)
2229 throw new Exception ("Should never be called");
2232 public virtual bool CheckAccessLevel (DeclSpace ds)
2234 return ds.CheckAccessLevel (Type);
2237 public virtual bool AsAccessible (DeclSpace ds, int flags)
2239 return ds.AsAccessible (Type, flags);
2242 public virtual bool IsClass {
2243 get { return Type.IsClass; }
2246 public virtual bool IsValueType {
2247 get { return Type.IsValueType; }
2250 public virtual bool IsInterface {
2251 get { return Type.IsInterface; }
2254 public virtual bool IsSealed {
2255 get { return Type.IsSealed; }
2258 public virtual bool CanInheritFrom ()
2260 if (Type == TypeManager.enum_type ||
2261 (Type == TypeManager.value_type && RootContext.StdLib) ||
2262 Type == TypeManager.multicast_delegate_type ||
2263 Type == TypeManager.delegate_type ||
2264 Type == TypeManager.array_type)
2270 public virtual bool IsAttribute {
2272 return Type == TypeManager.attribute_type ||
2273 Type.IsSubclassOf (TypeManager.attribute_type);
2277 public virtual TypeExpr[] GetInterfaces ()
2279 return TypeManager.GetInterfaces (Type);
2282 public abstract TypeExpr DoResolveAsTypeStep (EmitContext ec);
2284 public virtual Type ResolveType (EmitContext ec)
2286 TypeExpr t = ResolveAsTypeTerminal (ec);
2293 public abstract string Name {
2297 public override bool Equals (object obj)
2299 TypeExpr tobj = obj as TypeExpr;
2303 return Type == tobj.Type;
2306 public override int GetHashCode ()
2308 return Type.GetHashCode ();
2311 public override string ToString ()
2317 public class TypeExpression : TypeExpr {
2318 public TypeExpression (Type t, Location l)
2321 eclass = ExprClass.Type;
2325 public override TypeExpr DoResolveAsTypeStep (EmitContext ec)
2330 public override string Name {
2332 return Type.ToString ();
2338 /// Used to create types from a fully qualified name. These are just used
2339 /// by the parser to setup the core types. A TypeLookupExpression is always
2340 /// classified as a type.
2342 public class TypeLookupExpression : TypeExpr {
2345 public TypeLookupExpression (string name)
2350 public override TypeExpr DoResolveAsTypeStep (EmitContext ec)
2353 type = RootContext.LookupType (ec.DeclSpace, name, false, Location.Null);
2357 public override string Name {
2365 /// MethodGroup Expression.
2367 /// This is a fully resolved expression that evaluates to a type
2369 public class MethodGroupExpr : Expression, IMemberExpr {
2370 public MethodBase [] Methods;
2371 Expression instance_expression = null;
2372 bool is_explicit_impl = false;
2373 bool identical_type_name = false;
2376 public MethodGroupExpr (MemberInfo [] mi, Location l)
2378 Methods = new MethodBase [mi.Length];
2379 mi.CopyTo (Methods, 0);
2380 eclass = ExprClass.MethodGroup;
2381 type = TypeManager.object_type;
2385 public MethodGroupExpr (ArrayList list, Location l)
2387 Methods = new MethodBase [list.Count];
2390 list.CopyTo (Methods, 0);
2392 foreach (MemberInfo m in list){
2393 if (!(m is MethodBase)){
2394 Console.WriteLine ("Name " + m.Name);
2395 Console.WriteLine ("Found a: " + m.GetType ().FullName);
2402 eclass = ExprClass.MethodGroup;
2403 type = TypeManager.object_type;
2406 public Type DeclaringType {
2409 // The methods are arranged in this order:
2410 // derived type -> base type
2412 return Methods [0].DeclaringType;
2417 // `A method group may have associated an instance expression'
2419 public Expression InstanceExpression {
2421 return instance_expression;
2425 instance_expression = value;
2429 public bool IsExplicitImpl {
2431 return is_explicit_impl;
2435 is_explicit_impl = value;
2439 public bool IdenticalTypeName {
2441 return identical_type_name;
2445 identical_type_name = value;
2449 public bool IsBase {
2458 public string Name {
2460 return Methods [0].Name;
2464 public bool IsInstance {
2466 foreach (MethodBase mb in Methods)
2474 public bool IsStatic {
2476 foreach (MethodBase mb in Methods)
2484 override public Expression DoResolve (EmitContext ec)
2487 instance_expression = null;
2489 if (instance_expression != null) {
2490 instance_expression = instance_expression.DoResolve (ec);
2491 if (instance_expression == null)
2498 public void ReportUsageError ()
2500 Report.Error (654, loc, "Method `" + DeclaringType + "." +
2501 Name + "()' is referenced without parentheses");
2504 override public void Emit (EmitContext ec)
2506 ReportUsageError ();
2509 bool RemoveMethods (bool keep_static)
2511 ArrayList smethods = new ArrayList ();
2513 foreach (MethodBase mb in Methods){
2514 if (mb.IsStatic == keep_static)
2518 if (smethods.Count == 0)
2521 Methods = new MethodBase [smethods.Count];
2522 smethods.CopyTo (Methods, 0);
2528 /// Removes any instance methods from the MethodGroup, returns
2529 /// false if the resulting set is empty.
2531 public bool RemoveInstanceMethods ()
2533 return RemoveMethods (true);
2537 /// Removes any static methods from the MethodGroup, returns
2538 /// false if the resulting set is empty.
2540 public bool RemoveStaticMethods ()
2542 return RemoveMethods (false);
2547 /// Fully resolved expression that evaluates to a Field
2549 public class FieldExpr : Expression, IAssignMethod, IMemoryLocation, IMemberExpr, IVariable {
2550 public readonly FieldInfo FieldInfo;
2551 Expression instance_expr;
2552 VariableInfo variable_info;
2554 LocalTemporary temp;
2557 public FieldExpr (FieldInfo fi, Location l)
2560 eclass = ExprClass.Variable;
2561 type = fi.FieldType;
2565 public string Name {
2567 return FieldInfo.Name;
2571 public bool IsInstance {
2573 return !FieldInfo.IsStatic;
2577 public bool IsStatic {
2579 return FieldInfo.IsStatic;
2583 public Type DeclaringType {
2585 return FieldInfo.DeclaringType;
2589 public Expression InstanceExpression {
2591 return instance_expr;
2595 instance_expr = value;
2599 public VariableInfo VariableInfo {
2601 return variable_info;
2605 override public Expression DoResolve (EmitContext ec)
2607 if (!FieldInfo.IsStatic){
2608 if (instance_expr == null){
2610 // This can happen when referencing an instance field using
2611 // a fully qualified type expression: TypeName.InstanceField = xxx
2613 SimpleName.Error_ObjectRefRequired (ec, loc, FieldInfo.Name);
2617 // Resolve the field's instance expression while flow analysis is turned
2618 // off: when accessing a field "a.b", we must check whether the field
2619 // "a.b" is initialized, not whether the whole struct "a" is initialized.
2620 instance_expr = instance_expr.Resolve (ec, ResolveFlags.VariableOrValue |
2621 ResolveFlags.DisableFlowAnalysis);
2622 if (instance_expr == null)
2626 ObsoleteAttribute oa;
2627 FieldBase f = TypeManager.GetField (FieldInfo);
2629 oa = f.GetObsoleteAttribute (ec.DeclSpace);
2631 AttributeTester.Report_ObsoleteMessage (oa, f.GetSignatureForError (), loc);
2633 // To be sure that type is external because we do not register generated fields
2634 } else if (!(FieldInfo.DeclaringType is TypeBuilder)) {
2635 oa = AttributeTester.GetMemberObsoleteAttribute (FieldInfo);
2637 AttributeTester.Report_ObsoleteMessage (oa, TypeManager.GetFullNameSignature (FieldInfo), loc);
2640 // If the instance expression is a local variable or parameter.
2641 IVariable var = instance_expr as IVariable;
2642 if ((var == null) || (var.VariableInfo == null))
2645 VariableInfo vi = var.VariableInfo;
2646 if (!vi.IsFieldAssigned (ec, FieldInfo.Name, loc))
2649 variable_info = vi.GetSubStruct (FieldInfo.Name);
2653 void Report_AssignToReadonly (bool is_instance)
2658 msg = "Readonly field can not be assigned outside " +
2659 "of constructor or variable initializer";
2661 msg = "A static readonly field can only be assigned in " +
2662 "a static constructor";
2664 Report.Error (is_instance ? 191 : 198, loc, msg);
2667 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
2669 IVariable var = instance_expr as IVariable;
2670 if ((var != null) && (var.VariableInfo != null))
2671 var.VariableInfo.SetFieldAssigned (ec, FieldInfo.Name);
2673 Expression e = DoResolve (ec);
2678 if (!FieldInfo.IsStatic && (instance_expr.Type.IsValueType && !(instance_expr is IMemoryLocation))) {
2679 // FIXME: Provide better error reporting.
2680 Error (1612, "Cannot modify expression because it is not a variable.");
2684 if (!FieldInfo.IsInitOnly)
2687 FieldBase fb = TypeManager.GetField (FieldInfo);
2692 // InitOnly fields can only be assigned in constructors
2695 if (ec.IsConstructor){
2696 if (IsStatic && !ec.IsStatic)
2697 Report_AssignToReadonly (false);
2699 if (ec.ContainerType == FieldInfo.DeclaringType)
2703 Report_AssignToReadonly (true);
2708 public bool VerifyFixed (bool is_expression)
2710 IVariable variable = instance_expr as IVariable;
2711 if ((variable == null) || !variable.VerifyFixed (true))
2717 public void Emit (EmitContext ec, bool leave_copy)
2719 ILGenerator ig = ec.ig;
2720 bool is_volatile = false;
2722 if (FieldInfo is FieldBuilder){
2723 FieldBase f = TypeManager.GetField (FieldInfo);
2725 if ((f.ModFlags & Modifiers.VOLATILE) != 0)
2728 f.status |= Field.Status.USED;
2732 if (FieldInfo.IsStatic){
2734 ig.Emit (OpCodes.Volatile);
2736 ig.Emit (OpCodes.Ldsfld, FieldInfo);
2742 ig.Emit (OpCodes.Volatile);
2744 ig.Emit (OpCodes.Ldfld, FieldInfo);
2748 ec.ig.Emit (OpCodes.Dup);
2749 if (!FieldInfo.IsStatic) {
2750 temp = new LocalTemporary (ec, this.Type);
2756 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
2758 FieldAttributes fa = FieldInfo.Attributes;
2759 bool is_static = (fa & FieldAttributes.Static) != 0;
2760 bool is_readonly = (fa & FieldAttributes.InitOnly) != 0;
2761 ILGenerator ig = ec.ig;
2762 prepared = prepare_for_load;
2764 if (is_readonly && !ec.IsConstructor){
2765 Report_AssignToReadonly (!is_static);
2771 if (prepare_for_load)
2772 ig.Emit (OpCodes.Dup);
2777 ec.ig.Emit (OpCodes.Dup);
2778 if (!FieldInfo.IsStatic) {
2779 temp = new LocalTemporary (ec, this.Type);
2784 if (FieldInfo is FieldBuilder){
2785 FieldBase f = TypeManager.GetField (FieldInfo);
2787 if ((f.ModFlags & Modifiers.VOLATILE) != 0)
2788 ig.Emit (OpCodes.Volatile);
2790 f.status |= Field.Status.ASSIGNED;
2795 ig.Emit (OpCodes.Stsfld, FieldInfo);
2797 ig.Emit (OpCodes.Stfld, FieldInfo);
2803 void EmitInstance (EmitContext ec)
2805 if (instance_expr.Type.IsValueType) {
2806 if (instance_expr is IMemoryLocation) {
2807 ((IMemoryLocation) instance_expr).AddressOf (ec, AddressOp.LoadStore);
2809 LocalTemporary t = new LocalTemporary (ec, instance_expr.Type);
2810 instance_expr.Emit (ec);
2812 t.AddressOf (ec, AddressOp.Store);
2815 instance_expr.Emit (ec);
2818 public override void Emit (EmitContext ec)
2823 public void AddressOf (EmitContext ec, AddressOp mode)
2825 ILGenerator ig = ec.ig;
2827 if (FieldInfo is FieldBuilder){
2828 FieldBase f = TypeManager.GetField (FieldInfo);
2830 if ((f.ModFlags & Modifiers.VOLATILE) != 0){
2831 Error (676, "volatile variable: can not take its address, or pass as ref/out parameter");
2835 if ((mode & AddressOp.Store) != 0)
2836 f.status |= Field.Status.ASSIGNED;
2837 if ((mode & AddressOp.Load) != 0)
2838 f.status |= Field.Status.USED;
2843 // Handle initonly fields specially: make a copy and then
2844 // get the address of the copy.
2847 if (FieldInfo.IsInitOnly){
2849 if (ec.IsConstructor){
2850 if (FieldInfo.IsStatic){
2862 local = ig.DeclareLocal (type);
2863 ig.Emit (OpCodes.Stloc, local);
2864 ig.Emit (OpCodes.Ldloca, local);
2869 if (FieldInfo.IsStatic){
2870 ig.Emit (OpCodes.Ldsflda, FieldInfo);
2873 ig.Emit (OpCodes.Ldflda, FieldInfo);
2879 // A FieldExpr whose address can not be taken
2881 public class FieldExprNoAddress : FieldExpr, IMemoryLocation {
2882 public FieldExprNoAddress (FieldInfo fi, Location loc) : base (fi, loc)
2886 public new void AddressOf (EmitContext ec, AddressOp mode)
2888 Report.Error (-215, "Report this: Taking the address of a remapped parameter not supported");
2893 /// Expression that evaluates to a Property. The Assign class
2894 /// might set the `Value' expression if we are in an assignment.
2896 /// This is not an LValue because we need to re-write the expression, we
2897 /// can not take data from the stack and store it.
2899 public class PropertyExpr : ExpressionStatement, IAssignMethod, IMemberExpr {
2900 public readonly PropertyInfo PropertyInfo;
2903 // This is set externally by the `BaseAccess' class
2906 MethodInfo getter, setter;
2908 bool must_do_cs1540_check;
2910 Expression instance_expr;
2911 LocalTemporary temp;
2914 public PropertyExpr (EmitContext ec, PropertyInfo pi, Location l)
2917 eclass = ExprClass.PropertyAccess;
2921 type = TypeManager.TypeToCoreType (pi.PropertyType);
2923 ResolveAccessors (ec);
2926 public string Name {
2928 return PropertyInfo.Name;
2932 public bool IsInstance {
2938 public bool IsStatic {
2944 public Type DeclaringType {
2946 return PropertyInfo.DeclaringType;
2951 // The instance expression associated with this expression
2953 public Expression InstanceExpression {
2955 instance_expr = value;
2959 return instance_expr;
2963 public bool VerifyAssignable ()
2965 if (setter == null) {
2966 Report.Error (200, loc,
2967 "The property `" + PropertyInfo.Name +
2968 "' can not be assigned to, as it has not set accessor");
2975 MethodInfo FindAccessor (Type invocation_type, bool is_set)
2977 BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic |
2978 BindingFlags.Static | BindingFlags.Instance |
2979 BindingFlags.DeclaredOnly;
2981 Type current = PropertyInfo.DeclaringType;
2982 for (; current != null; current = current.BaseType) {
2983 MemberInfo[] group = TypeManager.MemberLookup (
2984 invocation_type, invocation_type, current,
2985 MemberTypes.Property, flags, PropertyInfo.Name, null);
2990 if (group.Length != 1)
2991 // Oooops, can this ever happen ?
2994 PropertyInfo pi = (PropertyInfo) group [0];
2996 MethodInfo get = pi.GetGetMethod (true);
2997 MethodInfo set = pi.GetSetMethod (true);
3007 MethodInfo accessor = get != null ? get : set;
3008 if (accessor == null)
3010 if ((accessor.Attributes & MethodAttributes.NewSlot) != 0)
3017 MethodInfo GetAccessor (Type invocation_type, bool is_set)
3019 MethodInfo mi = FindAccessor (invocation_type, is_set);
3023 MethodAttributes ma = mi.Attributes & MethodAttributes.MemberAccessMask;
3026 // If only accessible to the current class or children
3028 if (ma == MethodAttributes.Private) {
3029 Type declaring_type = mi.DeclaringType;
3031 if (invocation_type != declaring_type){
3032 if (TypeManager.IsSubclassOrNestedChildOf (invocation_type, mi.DeclaringType))
3040 // FamAndAssem requires that we not only derivate, but we are on the
3043 if (ma == MethodAttributes.FamANDAssem){
3044 if (mi.DeclaringType.Assembly != invocation_type.Assembly)
3050 // Assembly and FamORAssem succeed if we're in the same assembly.
3051 if ((ma == MethodAttributes.Assembly) || (ma == MethodAttributes.FamORAssem)){
3052 if (mi.DeclaringType.Assembly == invocation_type.Assembly)
3056 // We already know that we aren't in the same assembly.
3057 if (ma == MethodAttributes.Assembly)
3060 // Family and FamANDAssem require that we derive.
3061 if ((ma == MethodAttributes.Family) || (ma == MethodAttributes.FamANDAssem) || (ma == MethodAttributes.FamORAssem)){
3062 if (!TypeManager.IsSubclassOrNestedChildOf (invocation_type, mi.DeclaringType))
3065 if (!TypeManager.IsNestedChildOf (invocation_type, mi.DeclaringType))
3066 must_do_cs1540_check = true;
3076 // We also perform the permission checking here, as the PropertyInfo does not
3077 // hold the information for the accessibility of its setter/getter
3079 void ResolveAccessors (EmitContext ec)
3081 getter = GetAccessor (ec.ContainerType, false);
3082 if ((getter != null) && getter.IsStatic)
3085 setter = GetAccessor (ec.ContainerType, true);
3086 if ((setter != null) && setter.IsStatic)
3089 if (setter == null && getter == null){
3090 Report.Error (122, loc, "'{0}' is inaccessible due to its protection level", PropertyInfo.Name);
3094 bool InstanceResolve (EmitContext ec)
3096 if ((instance_expr == null) && ec.IsStatic && !is_static) {
3097 SimpleName.Error_ObjectRefRequired (ec, loc, PropertyInfo.Name);
3101 if (instance_expr != null) {
3102 instance_expr = instance_expr.DoResolve (ec);
3103 if (instance_expr == null)
3107 if (must_do_cs1540_check && (instance_expr != null)) {
3108 if ((instance_expr.Type != ec.ContainerType) &&
3109 ec.ContainerType.IsSubclassOf (instance_expr.Type)) {
3110 Report.Error (1540, loc, "Cannot access protected member `" +
3111 PropertyInfo.DeclaringType + "." + PropertyInfo.Name +
3112 "' via a qualifier of type `" +
3113 TypeManager.CSharpName (instance_expr.Type) +
3114 "'; the qualifier must be of type `" +
3115 TypeManager.CSharpName (ec.ContainerType) +
3116 "' (or derived from it)");
3124 override public Expression DoResolve (EmitContext ec)
3126 if (getter != null){
3127 if (TypeManager.GetArgumentTypes (getter).Length != 0){
3129 117, loc, "`{0}' does not contain a " +
3130 "definition for `{1}'.", getter.DeclaringType,
3136 if (getter == null){
3138 // The following condition happens if the PropertyExpr was
3139 // created, but is invalid (ie, the property is inaccessible),
3140 // and we did not want to embed the knowledge about this in
3141 // the caller routine. This only avoids double error reporting.
3146 Report.Error (154, loc,
3147 "The property `" + PropertyInfo.Name +
3148 "' can not be used in " +
3149 "this context because it lacks a get accessor");
3153 if (!InstanceResolve (ec))
3157 // Only base will allow this invocation to happen.
3159 if (IsBase && getter.IsAbstract){
3160 Report.Error (205, loc, "Cannot call an abstract base property: " +
3161 PropertyInfo.DeclaringType + "." +PropertyInfo.Name);
3168 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
3170 if (setter == null){
3172 // The following condition happens if the PropertyExpr was
3173 // created, but is invalid (ie, the property is inaccessible),
3174 // and we did not want to embed the knowledge about this in
3175 // the caller routine. This only avoids double error reporting.
3180 Report.Error (154, loc,
3181 "The property `" + PropertyInfo.Name +
3182 "' can not be used in " +
3183 "this context because it lacks a set accessor");
3187 if (TypeManager.GetArgumentTypes (setter).Length != 1){
3189 117, loc, "`{0}' does not contain a " +
3190 "definition for `{1}'.", getter.DeclaringType,
3195 if (!InstanceResolve (ec))
3199 // Only base will allow this invocation to happen.
3201 if (IsBase && setter.IsAbstract){
3202 Report.Error (205, loc, "Cannot call an abstract base property: " +
3203 PropertyInfo.DeclaringType + "." +PropertyInfo.Name);
3208 // Check that we are not making changes to a temporary memory location
3210 if (instance_expr != null && instance_expr.Type.IsValueType && !(instance_expr is IMemoryLocation)) {
3211 // FIXME: Provide better error reporting.
3212 Error (1612, "Cannot modify expression because it is not a variable.");
3221 public override void Emit (EmitContext ec)
3226 void EmitInstance (EmitContext ec)
3231 if (instance_expr.Type.IsValueType) {
3232 if (instance_expr is IMemoryLocation) {
3233 ((IMemoryLocation) instance_expr).AddressOf (ec, AddressOp.LoadStore);
3235 LocalTemporary t = new LocalTemporary (ec, instance_expr.Type);
3236 instance_expr.Emit (ec);
3238 t.AddressOf (ec, AddressOp.Store);
3241 instance_expr.Emit (ec);
3244 ec.ig.Emit (OpCodes.Dup);
3248 public void Emit (EmitContext ec, bool leave_copy)
3254 // Special case: length of single dimension array property is turned into ldlen
3256 if ((getter == TypeManager.system_int_array_get_length) ||
3257 (getter == TypeManager.int_array_get_length)){
3258 Type iet = instance_expr.Type;
3261 // System.Array.Length can be called, but the Type does not
3262 // support invoking GetArrayRank, so test for that case first
3264 if (iet != TypeManager.array_type && (iet.GetArrayRank () == 1)) {
3265 ec.ig.Emit (OpCodes.Ldlen);
3266 ec.ig.Emit (OpCodes.Conv_I4);
3271 Invocation.EmitCall (ec, IsBase, IsStatic, new EmptyAddressOf (), getter, null, loc);
3276 ec.ig.Emit (OpCodes.Dup);
3278 temp = new LocalTemporary (ec, this.Type);
3284 // Implements the IAssignMethod interface for assignments
3286 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
3288 prepared = prepare_for_load;
3294 ec.ig.Emit (OpCodes.Dup);
3296 temp = new LocalTemporary (ec, this.Type);
3301 ArrayList args = new ArrayList (1);
3302 args.Add (new Argument (new EmptyAddressOf (), Argument.AType.Expression));
3304 Invocation.EmitCall (ec, IsBase, IsStatic, new EmptyAddressOf (), setter, args, loc);
3310 override public void EmitStatement (EmitContext ec)
3313 ec.ig.Emit (OpCodes.Pop);
3318 /// Fully resolved expression that evaluates to an Event
3320 public class EventExpr : Expression, IMemberExpr {
3321 public readonly EventInfo EventInfo;
3322 Expression instance_expr;
3325 MethodInfo add_accessor, remove_accessor;
3327 public EventExpr (EventInfo ei, Location loc)
3331 eclass = ExprClass.EventAccess;
3333 add_accessor = TypeManager.GetAddMethod (ei);
3334 remove_accessor = TypeManager.GetRemoveMethod (ei);
3336 if (add_accessor.IsStatic || remove_accessor.IsStatic)
3339 if (EventInfo is MyEventBuilder){
3340 MyEventBuilder eb = (MyEventBuilder) EventInfo;
3341 type = eb.EventType;
3344 type = EventInfo.EventHandlerType;
3347 public string Name {
3349 return EventInfo.Name;
3353 public bool IsInstance {
3359 public bool IsStatic {
3365 public Type DeclaringType {
3367 return EventInfo.DeclaringType;
3371 public Expression InstanceExpression {
3373 return instance_expr;
3377 instance_expr = value;
3381 public override Expression DoResolve (EmitContext ec)
3383 if (instance_expr != null) {
3384 instance_expr = instance_expr.DoResolve (ec);
3385 if (instance_expr == null)
3393 public override void Emit (EmitContext ec)
3395 Report.Error (70, loc, "The event `" + Name + "' can only appear on the left hand side of += or -= (except on the defining type)");
3398 public void EmitAddOrRemove (EmitContext ec, Expression source)
3400 BinaryDelegate source_del = (BinaryDelegate) source;
3401 Expression handler = source_del.Right;
3403 Argument arg = new Argument (handler, Argument.AType.Expression);
3404 ArrayList args = new ArrayList ();
3408 if (source_del.IsAddition)
3409 Invocation.EmitCall (
3410 ec, false, IsStatic, instance_expr, add_accessor, args, loc);
3412 Invocation.EmitCall (
3413 ec, false, IsStatic, instance_expr, remove_accessor, args, loc);