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
68 // This is just as a hint to AddressOf of what will be done with the
71 public enum AddressOp {
78 /// This interface is implemented by variables
80 public interface IMemoryLocation {
82 /// The AddressOf method should generate code that loads
83 /// the address of the object and leaves it on the stack.
85 /// The `mode' argument is used to notify the expression
86 /// of whether this will be used to read from the address or
87 /// write to the address.
89 /// This is just a hint that can be used to provide good error
90 /// reporting, and should have no other side effects.
92 void AddressOf (EmitContext ec, AddressOp mode);
96 /// This interface is implemented by variables
98 public interface IVariable {
99 VariableInfo VariableInfo {
103 bool VerifyFixed (bool is_expression);
107 /// This interface denotes an expression which evaluates to a member
108 /// of a struct or a class.
110 public interface IMemberExpr
113 /// The name of this member.
120 /// Whether this is an instance member.
127 /// Whether this is a static member.
134 /// The type which declares this member.
141 /// The instance expression associated with this member, if it's a
142 /// non-static member.
144 Expression InstanceExpression {
150 /// Base class for expressions
152 public abstract class Expression {
153 public ExprClass eclass;
155 protected Location loc;
167 public Location Location {
174 /// Utility wrapper routine for Error, just to beautify the code
176 public void Error (int error, string s)
178 if (!Location.IsNull (loc))
179 Report.Error (error, loc, s);
181 Report.Error (error, s);
185 /// Utility wrapper routine for Warning, just to beautify the code
187 public void Warning (int warning, string s)
189 if (!Location.IsNull (loc))
190 Report.Warning (warning, loc, s);
192 Report.Warning (warning, s);
196 /// Utility wrapper routine for Warning, only prints the warning if
197 /// warnings of level `level' are enabled.
199 public void Warning (int warning, int level, string s)
201 if (level <= RootContext.WarningLevel)
202 Warning (warning, s);
206 /// Tests presence of ObsoleteAttribute and report proper error
208 protected void CheckObsoleteAttribute (Type type)
210 ObsoleteAttribute obsolete_attr = AttributeTester.GetObsoleteAttribute (type);
211 if (obsolete_attr == null)
214 AttributeTester.Report_ObsoleteMessage (obsolete_attr, type.FullName, loc);
218 /// Performs semantic analysis on the Expression
222 /// The Resolve method is invoked to perform the semantic analysis
225 /// The return value is an expression (it can be the
226 /// same expression in some cases) or a new
227 /// expression that better represents this node.
229 /// For example, optimizations of Unary (LiteralInt)
230 /// would return a new LiteralInt with a negated
233 /// If there is an error during semantic analysis,
234 /// then an error should be reported (using Report)
235 /// and a null value should be returned.
237 /// There are two side effects expected from calling
238 /// Resolve(): the the field variable "eclass" should
239 /// be set to any value of the enumeration
240 /// `ExprClass' and the type variable should be set
241 /// to a valid type (this is the type of the
244 public abstract Expression DoResolve (EmitContext ec);
246 public virtual Expression DoResolveLValue (EmitContext ec, Expression right_side)
248 return DoResolve (ec);
252 // This is used if the expression should be resolved as a type.
253 // the default implementation fails. Use this method in
254 // those participants in the SimpleName chain system.
256 public virtual Expression ResolveAsTypeStep (EmitContext ec)
262 // This is used to resolve the expression as a type, a null
263 // value will be returned if the expression is not a type
266 public TypeExpr ResolveAsTypeTerminal (EmitContext ec)
268 return ResolveAsTypeStep (ec) as TypeExpr;
272 /// Resolves an expression and performs semantic analysis on it.
276 /// Currently Resolve wraps DoResolve to perform sanity
277 /// checking and assertion checking on what we expect from Resolve.
279 public Expression Resolve (EmitContext ec, ResolveFlags flags)
281 if ((flags & ResolveFlags.MaskExprClass) == ResolveFlags.Type)
282 return ResolveAsTypeStep (ec);
284 bool old_do_flow_analysis = ec.DoFlowAnalysis;
285 if ((flags & ResolveFlags.DisableFlowAnalysis) != 0)
286 ec.DoFlowAnalysis = false;
289 if (this is SimpleName)
290 e = ((SimpleName) this).DoResolveAllowStatic (ec);
294 ec.DoFlowAnalysis = old_do_flow_analysis;
299 if (e is SimpleName){
300 SimpleName s = (SimpleName) e;
302 if ((flags & ResolveFlags.SimpleName) == 0) {
303 MemberLookupFailed (ec, null, ec.ContainerType, s.Name,
304 ec.DeclSpace.Name, loc);
311 if ((e is TypeExpr) || (e is ComposedCast)) {
312 if ((flags & ResolveFlags.Type) == 0) {
313 e.Error_UnexpectedKind (flags);
322 if ((flags & ResolveFlags.VariableOrValue) == 0) {
323 e.Error_UnexpectedKind (flags);
328 case ExprClass.MethodGroup:
329 if (!RootContext.V2){
330 if ((flags & ResolveFlags.MethodGroup) == 0) {
331 ((MethodGroupExpr) e).ReportUsageError ();
337 case ExprClass.Value:
338 case ExprClass.Variable:
339 case ExprClass.PropertyAccess:
340 case ExprClass.EventAccess:
341 case ExprClass.IndexerAccess:
342 if ((flags & ResolveFlags.VariableOrValue) == 0) {
343 Console.WriteLine ("I got: {0} and {1}", e.GetType (), e);
344 Console.WriteLine ("I am {0} and {1}", this.GetType (), this);
345 FieldInfo fi = ((FieldExpr) e).FieldInfo;
347 Console.WriteLine ("{0} and {1}", fi.DeclaringType, fi.Name);
348 e.Error_UnexpectedKind (flags);
354 throw new Exception ("Expression " + e.GetType () +
355 " ExprClass is Invalid after resolve");
359 throw new Exception (
360 "Expression " + e.GetType () +
361 " did not set its type after Resolve\n" +
362 "called from: " + this.GetType ());
368 /// Resolves an expression and performs semantic analysis on it.
370 public Expression Resolve (EmitContext ec)
372 return Resolve (ec, ResolveFlags.VariableOrValue);
376 /// Resolves an expression for LValue assignment
380 /// Currently ResolveLValue wraps DoResolveLValue to perform sanity
381 /// checking and assertion checking on what we expect from Resolve
383 public Expression ResolveLValue (EmitContext ec, Expression right_side)
385 Expression e = DoResolveLValue (ec, right_side);
388 if (e is SimpleName){
389 SimpleName s = (SimpleName) e;
390 MemberLookupFailed (ec, null, ec.ContainerType, s.Name,
391 ec.DeclSpace.Name, loc);
395 if (e.eclass == ExprClass.Invalid)
396 throw new Exception ("Expression " + e +
397 " ExprClass is Invalid after resolve");
399 if (e.eclass == ExprClass.MethodGroup) {
400 ((MethodGroupExpr) e).ReportUsageError ();
405 throw new Exception ("Expression " + e +
406 " did not set its type after Resolve");
413 /// Emits the code for the expression
417 /// The Emit method is invoked to generate the code
418 /// for the expression.
420 public abstract void Emit (EmitContext ec);
422 public virtual void EmitBranchable (EmitContext ec, Label target, bool onTrue)
425 ec.ig.Emit (onTrue ? OpCodes.Brtrue : OpCodes.Brfalse, target);
429 /// Protected constructor. Only derivate types should
430 /// be able to be created
433 protected Expression ()
435 eclass = ExprClass.Invalid;
440 /// Returns a literalized version of a literal FieldInfo
444 /// The possible return values are:
445 /// IntConstant, UIntConstant
446 /// LongLiteral, ULongConstant
447 /// FloatConstant, DoubleConstant
450 /// The value returned is already resolved.
452 public static Constant Constantify (object v, Type t)
454 if (t == TypeManager.int32_type)
455 return new IntConstant ((int) v);
456 else if (t == TypeManager.uint32_type)
457 return new UIntConstant ((uint) v);
458 else if (t == TypeManager.int64_type)
459 return new LongConstant ((long) v);
460 else if (t == TypeManager.uint64_type)
461 return new ULongConstant ((ulong) v);
462 else if (t == TypeManager.float_type)
463 return new FloatConstant ((float) v);
464 else if (t == TypeManager.double_type)
465 return new DoubleConstant ((double) v);
466 else if (t == TypeManager.string_type)
467 return new StringConstant ((string) v);
468 else if (t == TypeManager.short_type)
469 return new ShortConstant ((short)v);
470 else if (t == TypeManager.ushort_type)
471 return new UShortConstant ((ushort)v);
472 else if (t == TypeManager.sbyte_type)
473 return new SByteConstant (((sbyte)v));
474 else if (t == TypeManager.byte_type)
475 return new ByteConstant ((byte)v);
476 else if (t == TypeManager.char_type)
477 return new CharConstant ((char)v);
478 else if (t == TypeManager.bool_type)
479 return new BoolConstant ((bool) v);
480 else if (TypeManager.IsEnumType (t)){
481 Type real_type = TypeManager.TypeToCoreType (v.GetType ());
483 real_type = real_type.UnderlyingSystemType;
485 Constant e = Constantify (v, real_type);
487 return new EnumConstant (e, t);
489 throw new Exception ("Unknown type for constant (" + t +
494 /// Returns a fully formed expression after a MemberLookup
496 public static Expression ExprClassFromMemberInfo (EmitContext ec, MemberInfo mi, Location loc)
499 return new EventExpr ((EventInfo) mi, loc);
500 else if (mi is FieldInfo)
501 return new FieldExpr ((FieldInfo) mi, loc);
502 else if (mi is PropertyInfo)
503 return new PropertyExpr (ec, (PropertyInfo) mi, loc);
504 else if (mi is Type){
505 return new TypeExpression ((System.Type) mi, loc);
512 private static ArrayList almostMatchedMembers = new ArrayList (4);
515 // FIXME: Probably implement a cache for (t,name,current_access_set)?
517 // This code could use some optimizations, but we need to do some
518 // measurements. For example, we could use a delegate to `flag' when
519 // something can not any longer be a method-group (because it is something
523 // If the return value is an Array, then it is an array of
526 // If the return value is an MemberInfo, it is anything, but a Method
530 // FIXME: When calling MemberLookup inside an `Invocation', we should pass
531 // the arguments here and have MemberLookup return only the methods that
532 // match the argument count/type, unlike we are doing now (we delay this
535 // This is so we can catch correctly attempts to invoke instance methods
536 // from a static body (scan for error 120 in ResolveSimpleName).
539 // FIXME: Potential optimization, have a static ArrayList
542 public static Expression MemberLookup (EmitContext ec, Type queried_type, string name,
543 MemberTypes mt, BindingFlags bf, Location loc)
545 return MemberLookup (ec, ec.ContainerType, null, queried_type, name, mt, bf, loc);
549 // Lookup type `queried_type' for code in class `container_type' with a qualifier of
550 // `qualifier_type' or null to lookup members in the current class.
553 public static Expression MemberLookup (EmitContext ec, Type container_type,
554 Type qualifier_type, Type queried_type,
555 string name, MemberTypes mt,
556 BindingFlags bf, Location loc)
558 almostMatchedMembers.Clear ();
560 MemberInfo [] mi = TypeManager.MemberLookup (container_type, qualifier_type,
561 queried_type, mt, bf, name, almostMatchedMembers);
566 int count = mi.Length;
568 if (mi [0] is MethodBase)
569 return new MethodGroupExpr (mi, loc);
574 return ExprClassFromMemberInfo (ec, mi [0], loc);
577 public const MemberTypes AllMemberTypes =
578 MemberTypes.Constructor |
582 MemberTypes.NestedType |
583 MemberTypes.Property;
585 public const BindingFlags AllBindingFlags =
586 BindingFlags.Public |
587 BindingFlags.Static |
588 BindingFlags.Instance;
590 public static Expression MemberLookup (EmitContext ec, Type queried_type,
591 string name, Location loc)
593 return MemberLookup (ec, ec.ContainerType, null, queried_type, name,
594 AllMemberTypes, AllBindingFlags, loc);
597 public static Expression MemberLookup (EmitContext ec, Type qualifier_type,
598 Type queried_type, string name, Location loc)
600 return MemberLookup (ec, ec.ContainerType, qualifier_type, queried_type,
601 name, AllMemberTypes, AllBindingFlags, loc);
604 public static Expression MethodLookup (EmitContext ec, Type queried_type,
605 string name, Location loc)
607 return MemberLookup (ec, ec.ContainerType, null, queried_type, name,
608 MemberTypes.Method, AllBindingFlags, loc);
612 /// This is a wrapper for MemberLookup that is not used to "probe", but
613 /// to find a final definition. If the final definition is not found, we
614 /// look for private members and display a useful debugging message if we
617 public static Expression MemberLookupFinal (EmitContext ec, Type qualifier_type,
618 Type queried_type, string name, Location loc)
620 return MemberLookupFinal (ec, qualifier_type, queried_type, name,
621 AllMemberTypes, AllBindingFlags, loc);
624 public static Expression MemberLookupFinal (EmitContext ec, Type qualifier_type,
625 Type queried_type, string name,
626 MemberTypes mt, BindingFlags bf,
631 int errors = Report.Errors;
633 e = MemberLookup (ec, ec.ContainerType, qualifier_type, queried_type, name, mt, bf, loc);
635 if (e == null && errors == Report.Errors)
636 // No errors were reported by MemberLookup, but there was an error.
637 MemberLookupFailed (ec, qualifier_type, queried_type, name, null, loc);
642 public static void MemberLookupFailed (EmitContext ec, Type qualifier_type,
643 Type queried_type, string name,
644 string class_name, Location loc)
646 if (almostMatchedMembers.Count != 0) {
647 if (qualifier_type == null) {
648 foreach (MemberInfo m in almostMatchedMembers)
649 Report.Error (38, loc,
650 "Cannot access non-static member `{0}' via nested type `{1}'",
651 TypeManager.GetFullNameSignature (m),
652 TypeManager.CSharpName (ec.ContainerType));
656 if (qualifier_type != ec.ContainerType) {
657 // Although a derived class can access protected members of
658 // its base class it cannot do so through an instance of the
659 // base class (CS1540). If the qualifier_type is a parent of the
660 // ec.ContainerType and the lookup succeeds with the latter one,
661 // then we are in this situation.
662 foreach (MemberInfo m in almostMatchedMembers)
663 Report.Error (1540, loc,
664 "Cannot access protected member `{0}' via a qualifier of type `{1}';"
665 + " the qualifier must be of type `{2}' (or derived from it)",
666 TypeManager.GetFullNameSignature (m),
667 TypeManager.CSharpName (qualifier_type),
668 TypeManager.CSharpName (ec.ContainerType));
671 almostMatchedMembers.Clear ();
674 object lookup = TypeManager.MemberLookup (queried_type, null, queried_type,
675 AllMemberTypes, AllBindingFlags |
676 BindingFlags.NonPublic, name, null);
678 if (lookup == null) {
679 if (class_name != null)
680 Report.Error (103, loc, "The name `" + name + "' could not be " +
681 "found in `" + class_name + "'");
684 117, loc, "`" + queried_type + "' does not contain a " +
685 "definition for `" + name + "'");
689 if (qualifier_type != null)
690 Report.Error_T (122, loc, TypeManager.CSharpName (qualifier_type) + "." + name);
691 else if (name == ".ctor") {
692 Report.Error (143, loc, String.Format ("The type {0} has no constructors defined",
693 TypeManager.CSharpName (queried_type)));
695 Report.Error_T (122, loc, name);
699 static public MemberInfo GetFieldFromEvent (EventExpr event_expr)
701 EventInfo ei = event_expr.EventInfo;
703 return TypeManager.GetPrivateFieldOfEvent (ei);
707 /// Returns an expression that can be used to invoke operator true
708 /// on the expression if it exists.
710 static public StaticCallExpr GetOperatorTrue (EmitContext ec, Expression e, Location loc)
712 return GetOperatorTrueOrFalse (ec, e, true, loc);
716 /// Returns an expression that can be used to invoke operator false
717 /// on the expression if it exists.
719 static public StaticCallExpr GetOperatorFalse (EmitContext ec, Expression e, Location loc)
721 return GetOperatorTrueOrFalse (ec, e, false, loc);
724 static StaticCallExpr GetOperatorTrueOrFalse (EmitContext ec, Expression e, bool is_true, Location loc)
727 Expression operator_group;
729 operator_group = MethodLookup (ec, e.Type, is_true ? "op_True" : "op_False", loc);
730 if (operator_group == null)
733 ArrayList arguments = new ArrayList ();
734 arguments.Add (new Argument (e, Argument.AType.Expression));
735 method = Invocation.OverloadResolve (ec, (MethodGroupExpr) operator_group, arguments, loc);
740 return new StaticCallExpr ((MethodInfo) method, arguments, loc);
744 /// Resolves the expression `e' into a boolean expression: either through
745 /// an implicit conversion, or through an `operator true' invocation
747 public static Expression ResolveBoolean (EmitContext ec, Expression e, Location loc)
753 Expression converted = e;
754 if (e.Type != TypeManager.bool_type)
755 converted = Convert.ImplicitConversion (ec, e, TypeManager.bool_type, new Location (-1));
758 // If no implicit conversion to bool exists, try using `operator true'
760 if (converted == null){
761 Expression operator_true = Expression.GetOperatorTrue (ec, e, loc);
762 if (operator_true == null){
764 31, loc, "Can not convert the expression to a boolean");
774 static string ExprClassName (ExprClass c)
777 case ExprClass.Invalid:
779 case ExprClass.Value:
781 case ExprClass.Variable:
783 case ExprClass.Namespace:
787 case ExprClass.MethodGroup:
788 return "method group";
789 case ExprClass.PropertyAccess:
790 return "property access";
791 case ExprClass.EventAccess:
792 return "event access";
793 case ExprClass.IndexerAccess:
794 return "indexer access";
795 case ExprClass.Nothing:
798 throw new Exception ("Should not happen");
802 /// Reports that we were expecting `expr' to be of class `expected'
804 public void Error_UnexpectedKind (string expected)
806 string kind = "Unknown";
808 kind = ExprClassName (eclass);
810 Error (118, "Expression denotes a `" + kind +
811 "' where a `" + expected + "' was expected");
814 public void Error_UnexpectedKind (ResolveFlags flags)
816 ArrayList valid = new ArrayList (10);
818 if ((flags & ResolveFlags.VariableOrValue) != 0) {
819 valid.Add ("variable");
823 if ((flags & ResolveFlags.Type) != 0)
826 if ((flags & ResolveFlags.MethodGroup) != 0)
827 valid.Add ("method group");
829 if ((flags & ResolveFlags.SimpleName) != 0)
830 valid.Add ("simple name");
832 if (valid.Count == 0)
833 valid.Add ("unknown");
835 StringBuilder sb = new StringBuilder ();
836 for (int i = 0; i < valid.Count; i++) {
839 else if (i == valid.Count)
841 sb.Append (valid [i]);
844 string kind = ExprClassName (eclass);
846 Error (119, "Expression denotes a `" + kind + "' where " +
847 "a `" + sb.ToString () + "' was expected");
850 static public void Error_ConstantValueCannotBeConverted (Location l, string val, Type t)
852 Report.Error (31, l, "Constant value `" + val + "' cannot be converted to " +
853 TypeManager.CSharpName (t));
856 public static void UnsafeError (Location loc)
858 Report.Error (214, loc, "Pointers may only be used in an unsafe context");
862 /// Converts the IntConstant, UIntConstant, LongConstant or
863 /// ULongConstant into the integral target_type. Notice
864 /// that we do not return an `Expression' we do return
865 /// a boxed integral type.
867 /// FIXME: Since I added the new constants, we need to
868 /// also support conversions from CharConstant, ByteConstant,
869 /// SByteConstant, UShortConstant, ShortConstant
871 /// This is used by the switch statement, so the domain
872 /// of work is restricted to the literals above, and the
873 /// targets are int32, uint32, char, byte, sbyte, ushort,
874 /// short, uint64 and int64
876 public static object ConvertIntLiteral (Constant c, Type target_type, Location loc)
878 if (!Convert.ImplicitStandardConversionExists (c, target_type)){
879 Convert.Error_CannotImplicitConversion (loc, c.Type, target_type);
885 if (c.Type == target_type)
886 return ((Constant) c).GetValue ();
889 // Make into one of the literals we handle, we dont really care
890 // about this value as we will just return a few limited types
892 if (c is EnumConstant)
893 c = ((EnumConstant)c).WidenToCompilerConstant ();
895 if (c is IntConstant){
896 int v = ((IntConstant) c).Value;
898 if (target_type == TypeManager.uint32_type){
901 } else if (target_type == TypeManager.char_type){
902 if (v >= Char.MinValue && v <= Char.MaxValue)
904 } else if (target_type == TypeManager.byte_type){
905 if (v >= Byte.MinValue && v <= Byte.MaxValue)
907 } else if (target_type == TypeManager.sbyte_type){
908 if (v >= SByte.MinValue && v <= SByte.MaxValue)
910 } else if (target_type == TypeManager.short_type){
911 if (v >= Int16.MinValue && v <= UInt16.MaxValue)
913 } else if (target_type == TypeManager.ushort_type){
914 if (v >= UInt16.MinValue && v <= UInt16.MaxValue)
916 } else if (target_type == TypeManager.int64_type)
918 else if (target_type == TypeManager.uint64_type){
924 } else if (c is UIntConstant){
925 uint v = ((UIntConstant) c).Value;
927 if (target_type == TypeManager.int32_type){
928 if (v <= Int32.MaxValue)
930 } else if (target_type == TypeManager.char_type){
931 if (v >= Char.MinValue && v <= Char.MaxValue)
933 } else if (target_type == TypeManager.byte_type){
934 if (v <= Byte.MaxValue)
936 } else if (target_type == TypeManager.sbyte_type){
937 if (v <= SByte.MaxValue)
939 } else if (target_type == TypeManager.short_type){
940 if (v <= UInt16.MaxValue)
942 } else if (target_type == TypeManager.ushort_type){
943 if (v <= UInt16.MaxValue)
945 } else if (target_type == TypeManager.int64_type)
947 else if (target_type == TypeManager.uint64_type)
950 } else if (c is LongConstant){
951 long v = ((LongConstant) c).Value;
953 if (target_type == TypeManager.int32_type){
954 if (v >= UInt32.MinValue && v <= UInt32.MaxValue)
956 } else if (target_type == TypeManager.uint32_type){
957 if (v >= 0 && v <= UInt32.MaxValue)
959 } else if (target_type == TypeManager.char_type){
960 if (v >= Char.MinValue && v <= Char.MaxValue)
962 } else if (target_type == TypeManager.byte_type){
963 if (v >= Byte.MinValue && v <= Byte.MaxValue)
965 } else if (target_type == TypeManager.sbyte_type){
966 if (v >= SByte.MinValue && v <= SByte.MaxValue)
968 } else if (target_type == TypeManager.short_type){
969 if (v >= Int16.MinValue && v <= UInt16.MaxValue)
971 } else if (target_type == TypeManager.ushort_type){
972 if (v >= UInt16.MinValue && v <= UInt16.MaxValue)
974 } else if (target_type == TypeManager.uint64_type){
979 } else if (c is ULongConstant){
980 ulong v = ((ULongConstant) c).Value;
982 if (target_type == TypeManager.int32_type){
983 if (v <= Int32.MaxValue)
985 } else if (target_type == TypeManager.uint32_type){
986 if (v <= UInt32.MaxValue)
988 } else if (target_type == TypeManager.char_type){
989 if (v >= Char.MinValue && v <= Char.MaxValue)
991 } else if (target_type == TypeManager.byte_type){
992 if (v >= Byte.MinValue && v <= Byte.MaxValue)
994 } else if (target_type == TypeManager.sbyte_type){
995 if (v <= (int) SByte.MaxValue)
997 } else if (target_type == TypeManager.short_type){
998 if (v <= UInt16.MaxValue)
1000 } else if (target_type == TypeManager.ushort_type){
1001 if (v <= UInt16.MaxValue)
1003 } else if (target_type == TypeManager.int64_type){
1004 if (v <= Int64.MaxValue)
1008 } else if (c is ByteConstant){
1009 byte v = ((ByteConstant) c).Value;
1011 if (target_type == TypeManager.int32_type)
1013 else if (target_type == TypeManager.uint32_type)
1015 else if (target_type == TypeManager.char_type)
1017 else if (target_type == TypeManager.sbyte_type){
1018 if (v <= SByte.MaxValue)
1020 } else if (target_type == TypeManager.short_type)
1022 else if (target_type == TypeManager.ushort_type)
1024 else if (target_type == TypeManager.int64_type)
1026 else if (target_type == TypeManager.uint64_type)
1029 } else if (c is SByteConstant){
1030 sbyte v = ((SByteConstant) c).Value;
1032 if (target_type == TypeManager.int32_type)
1034 else if (target_type == TypeManager.uint32_type){
1037 } else if (target_type == TypeManager.char_type){
1040 } else if (target_type == TypeManager.byte_type){
1043 } else if (target_type == TypeManager.short_type)
1045 else if (target_type == TypeManager.ushort_type){
1048 } else if (target_type == TypeManager.int64_type)
1050 else if (target_type == TypeManager.uint64_type){
1055 } else if (c is ShortConstant){
1056 short v = ((ShortConstant) c).Value;
1058 if (target_type == TypeManager.int32_type){
1060 } else if (target_type == TypeManager.uint32_type){
1063 } else if (target_type == TypeManager.char_type){
1066 } else if (target_type == TypeManager.byte_type){
1067 if (v >= Byte.MinValue && v <= Byte.MaxValue)
1069 } else if (target_type == TypeManager.sbyte_type){
1070 if (v >= SByte.MinValue && v <= SByte.MaxValue)
1072 } else if (target_type == TypeManager.ushort_type){
1075 } else if (target_type == TypeManager.int64_type)
1077 else if (target_type == TypeManager.uint64_type)
1081 } else if (c is UShortConstant){
1082 ushort v = ((UShortConstant) c).Value;
1084 if (target_type == TypeManager.int32_type)
1086 else if (target_type == TypeManager.uint32_type)
1088 else if (target_type == TypeManager.char_type){
1089 if (v >= Char.MinValue && v <= Char.MaxValue)
1091 } else if (target_type == TypeManager.byte_type){
1092 if (v >= Byte.MinValue && v <= Byte.MaxValue)
1094 } else if (target_type == TypeManager.sbyte_type){
1095 if (v <= SByte.MaxValue)
1097 } else if (target_type == TypeManager.short_type){
1098 if (v <= Int16.MaxValue)
1100 } else if (target_type == TypeManager.int64_type)
1102 else if (target_type == TypeManager.uint64_type)
1106 } else if (c is CharConstant){
1107 char v = ((CharConstant) c).Value;
1109 if (target_type == TypeManager.int32_type)
1111 else if (target_type == TypeManager.uint32_type)
1113 else if (target_type == TypeManager.byte_type){
1114 if (v >= Byte.MinValue && v <= Byte.MaxValue)
1116 } else if (target_type == TypeManager.sbyte_type){
1117 if (v <= SByte.MaxValue)
1119 } else if (target_type == TypeManager.short_type){
1120 if (v <= Int16.MaxValue)
1122 } else if (target_type == TypeManager.ushort_type)
1124 else if (target_type == TypeManager.int64_type)
1126 else if (target_type == TypeManager.uint64_type)
1131 Error_ConstantValueCannotBeConverted (loc, s, target_type);
1136 // Load the object from the pointer.
1138 public static void LoadFromPtr (ILGenerator ig, Type t)
1140 if (t == TypeManager.int32_type)
1141 ig.Emit (OpCodes.Ldind_I4);
1142 else if (t == TypeManager.uint32_type)
1143 ig.Emit (OpCodes.Ldind_U4);
1144 else if (t == TypeManager.short_type)
1145 ig.Emit (OpCodes.Ldind_I2);
1146 else if (t == TypeManager.ushort_type)
1147 ig.Emit (OpCodes.Ldind_U2);
1148 else if (t == TypeManager.char_type)
1149 ig.Emit (OpCodes.Ldind_U2);
1150 else if (t == TypeManager.byte_type)
1151 ig.Emit (OpCodes.Ldind_U1);
1152 else if (t == TypeManager.sbyte_type)
1153 ig.Emit (OpCodes.Ldind_I1);
1154 else if (t == TypeManager.uint64_type)
1155 ig.Emit (OpCodes.Ldind_I8);
1156 else if (t == TypeManager.int64_type)
1157 ig.Emit (OpCodes.Ldind_I8);
1158 else if (t == TypeManager.float_type)
1159 ig.Emit (OpCodes.Ldind_R4);
1160 else if (t == TypeManager.double_type)
1161 ig.Emit (OpCodes.Ldind_R8);
1162 else if (t == TypeManager.bool_type)
1163 ig.Emit (OpCodes.Ldind_I1);
1164 else if (t == TypeManager.intptr_type)
1165 ig.Emit (OpCodes.Ldind_I);
1166 else if (TypeManager.IsEnumType (t)) {
1167 if (t == TypeManager.enum_type)
1168 ig.Emit (OpCodes.Ldind_Ref);
1170 LoadFromPtr (ig, TypeManager.EnumToUnderlying (t));
1171 } else if (t.IsValueType)
1172 ig.Emit (OpCodes.Ldobj, t);
1173 else if (t.IsPointer)
1174 ig.Emit (OpCodes.Ldind_I);
1176 ig.Emit (OpCodes.Ldind_Ref);
1180 // The stack contains the pointer and the value of type `type'
1182 public static void StoreFromPtr (ILGenerator ig, Type type)
1184 if (TypeManager.IsEnumType (type))
1185 type = TypeManager.EnumToUnderlying (type);
1186 if (type == TypeManager.int32_type || type == TypeManager.uint32_type)
1187 ig.Emit (OpCodes.Stind_I4);
1188 else if (type == TypeManager.int64_type || type == TypeManager.uint64_type)
1189 ig.Emit (OpCodes.Stind_I8);
1190 else if (type == TypeManager.char_type || type == TypeManager.short_type ||
1191 type == TypeManager.ushort_type)
1192 ig.Emit (OpCodes.Stind_I2);
1193 else if (type == TypeManager.float_type)
1194 ig.Emit (OpCodes.Stind_R4);
1195 else if (type == TypeManager.double_type)
1196 ig.Emit (OpCodes.Stind_R8);
1197 else if (type == TypeManager.byte_type || type == TypeManager.sbyte_type ||
1198 type == TypeManager.bool_type)
1199 ig.Emit (OpCodes.Stind_I1);
1200 else if (type == TypeManager.intptr_type)
1201 ig.Emit (OpCodes.Stind_I);
1202 else if (type.IsValueType)
1203 ig.Emit (OpCodes.Stobj, type);
1205 ig.Emit (OpCodes.Stind_Ref);
1209 // Returns the size of type `t' if known, otherwise, 0
1211 public static int GetTypeSize (Type t)
1213 t = TypeManager.TypeToCoreType (t);
1214 if (t == TypeManager.int32_type ||
1215 t == TypeManager.uint32_type ||
1216 t == TypeManager.float_type)
1218 else if (t == TypeManager.int64_type ||
1219 t == TypeManager.uint64_type ||
1220 t == TypeManager.double_type)
1222 else if (t == TypeManager.byte_type ||
1223 t == TypeManager.sbyte_type ||
1224 t == TypeManager.bool_type)
1226 else if (t == TypeManager.short_type ||
1227 t == TypeManager.char_type ||
1228 t == TypeManager.ushort_type)
1230 else if (t == TypeManager.decimal_type)
1237 // Default implementation of IAssignMethod.CacheTemporaries
1239 public virtual void CacheTemporaries (EmitContext ec)
1243 static void Error_NegativeArrayIndex (Location loc)
1245 Report.Error (284, loc, "Can not create array with a negative size");
1249 // Converts `source' to an int, uint, long or ulong.
1251 public Expression ExpressionToArrayArgument (EmitContext ec, Expression source, Location loc)
1255 bool old_checked = ec.CheckState;
1256 ec.CheckState = true;
1258 target = Convert.ImplicitConversion (ec, source, TypeManager.int32_type, loc);
1259 if (target == null){
1260 target = Convert.ImplicitConversion (ec, source, TypeManager.uint32_type, loc);
1261 if (target == null){
1262 target = Convert.ImplicitConversion (ec, source, TypeManager.int64_type, loc);
1263 if (target == null){
1264 target = Convert.ImplicitConversion (ec, source, TypeManager.uint64_type, loc);
1266 Convert.Error_CannotImplicitConversion (loc, source.Type, TypeManager.int32_type);
1270 ec.CheckState = old_checked;
1273 // Only positive constants are allowed at compile time
1275 if (target is Constant){
1276 if (target is IntConstant){
1277 if (((IntConstant) target).Value < 0){
1278 Error_NegativeArrayIndex (loc);
1283 if (target is LongConstant){
1284 if (((LongConstant) target).Value < 0){
1285 Error_NegativeArrayIndex (loc);
1298 /// This is just a base class for expressions that can
1299 /// appear on statements (invocations, object creation,
1300 /// assignments, post/pre increment and decrement). The idea
1301 /// being that they would support an extra Emition interface that
1302 /// does not leave a result on the stack.
1304 public abstract class ExpressionStatement : Expression {
1306 public virtual ExpressionStatement ResolveStatement (EmitContext ec)
1308 Expression e = Resolve (ec);
1312 ExpressionStatement es = e as ExpressionStatement;
1314 Error (201, "Only assignment, call, increment, decrement and new object " +
1315 "expressions can be used as a statement");
1321 /// Requests the expression to be emitted in a `statement'
1322 /// context. This means that no new value is left on the
1323 /// stack after invoking this method (constrasted with
1324 /// Emit that will always leave a value on the stack).
1326 public abstract void EmitStatement (EmitContext ec);
1330 /// This kind of cast is used to encapsulate the child
1331 /// whose type is child.Type into an expression that is
1332 /// reported to return "return_type". This is used to encapsulate
1333 /// expressions which have compatible types, but need to be dealt
1334 /// at higher levels with.
1336 /// For example, a "byte" expression could be encapsulated in one
1337 /// of these as an "unsigned int". The type for the expression
1338 /// would be "unsigned int".
1341 public class EmptyCast : Expression {
1342 protected Expression child;
1344 public Expression Child {
1350 public EmptyCast (Expression child, Type return_type)
1352 eclass = child.eclass;
1357 public override Expression DoResolve (EmitContext ec)
1359 // This should never be invoked, we are born in fully
1360 // initialized state.
1365 public override void Emit (EmitContext ec)
1372 // We need to special case this since an empty cast of
1373 // a NullLiteral is still a Constant
1375 public class NullCast : Constant {
1376 protected Expression child;
1378 public NullCast (Expression child, Type return_type)
1380 eclass = child.eclass;
1385 override public string AsString ()
1390 public override object GetValue ()
1395 public override Expression DoResolve (EmitContext ec)
1397 // This should never be invoked, we are born in fully
1398 // initialized state.
1403 public override void Emit (EmitContext ec)
1411 /// This class is used to wrap literals which belong inside Enums
1413 public class EnumConstant : Constant {
1414 public Constant Child;
1416 public EnumConstant (Constant child, Type enum_type)
1418 eclass = child.eclass;
1423 public override Expression DoResolve (EmitContext ec)
1425 // This should never be invoked, we are born in fully
1426 // initialized state.
1431 public override void Emit (EmitContext ec)
1436 public override object GetValue ()
1438 return Child.GetValue ();
1442 // Converts from one of the valid underlying types for an enumeration
1443 // (int32, uint32, int64, uint64, short, ushort, byte, sbyte) to
1444 // one of the internal compiler literals: Int/UInt/Long/ULong Literals.
1446 public Constant WidenToCompilerConstant ()
1448 Type t = TypeManager.EnumToUnderlying (Child.Type);
1449 object v = ((Constant) Child).GetValue ();;
1451 if (t == TypeManager.int32_type)
1452 return new IntConstant ((int) v);
1453 if (t == TypeManager.uint32_type)
1454 return new UIntConstant ((uint) v);
1455 if (t == TypeManager.int64_type)
1456 return new LongConstant ((long) v);
1457 if (t == TypeManager.uint64_type)
1458 return new ULongConstant ((ulong) v);
1459 if (t == TypeManager.short_type)
1460 return new ShortConstant ((short) v);
1461 if (t == TypeManager.ushort_type)
1462 return new UShortConstant ((ushort) v);
1463 if (t == TypeManager.byte_type)
1464 return new ByteConstant ((byte) v);
1465 if (t == TypeManager.sbyte_type)
1466 return new SByteConstant ((sbyte) v);
1468 throw new Exception ("Invalid enumeration underlying type: " + t);
1472 // Extracts the value in the enumeration on its native representation
1474 public object GetPlainValue ()
1476 Type t = TypeManager.EnumToUnderlying (Child.Type);
1477 object v = ((Constant) Child).GetValue ();;
1479 if (t == TypeManager.int32_type)
1481 if (t == TypeManager.uint32_type)
1483 if (t == TypeManager.int64_type)
1485 if (t == TypeManager.uint64_type)
1487 if (t == TypeManager.short_type)
1489 if (t == TypeManager.ushort_type)
1491 if (t == TypeManager.byte_type)
1493 if (t == TypeManager.sbyte_type)
1499 public override string AsString ()
1501 return Child.AsString ();
1504 public override DoubleConstant ConvertToDouble ()
1506 return Child.ConvertToDouble ();
1509 public override FloatConstant ConvertToFloat ()
1511 return Child.ConvertToFloat ();
1514 public override ULongConstant ConvertToULong ()
1516 return Child.ConvertToULong ();
1519 public override LongConstant ConvertToLong ()
1521 return Child.ConvertToLong ();
1524 public override UIntConstant ConvertToUInt ()
1526 return Child.ConvertToUInt ();
1529 public override IntConstant ConvertToInt ()
1531 return Child.ConvertToInt ();
1534 public override bool IsZeroInteger {
1535 get { return Child.IsZeroInteger; }
1540 /// This kind of cast is used to encapsulate Value Types in objects.
1542 /// The effect of it is to box the value type emitted by the previous
1545 public class BoxedCast : EmptyCast {
1547 public BoxedCast (Expression expr)
1548 : base (expr, TypeManager.object_type)
1550 eclass = ExprClass.Value;
1553 public BoxedCast (Expression expr, Type target_type)
1554 : base (expr, target_type)
1556 eclass = ExprClass.Value;
1559 public override Expression DoResolve (EmitContext ec)
1561 // This should never be invoked, we are born in fully
1562 // initialized state.
1567 public override void Emit (EmitContext ec)
1571 ec.ig.Emit (OpCodes.Box, child.Type);
1575 public class UnboxCast : EmptyCast {
1576 public UnboxCast (Expression expr, Type return_type)
1577 : base (expr, return_type)
1581 public override Expression DoResolve (EmitContext ec)
1583 // This should never be invoked, we are born in fully
1584 // initialized state.
1589 public override void Emit (EmitContext ec)
1592 ILGenerator ig = ec.ig;
1595 ig.Emit (OpCodes.Unbox, t);
1597 LoadFromPtr (ig, t);
1602 /// This is used to perform explicit numeric conversions.
1604 /// Explicit numeric conversions might trigger exceptions in a checked
1605 /// context, so they should generate the conv.ovf opcodes instead of
1608 public class ConvCast : EmptyCast {
1609 public enum Mode : byte {
1610 I1_U1, I1_U2, I1_U4, I1_U8, I1_CH,
1612 I2_I1, I2_U1, I2_U2, I2_U4, I2_U8, I2_CH,
1613 U2_I1, U2_U1, U2_I2, U2_CH,
1614 I4_I1, I4_U1, I4_I2, I4_U2, I4_U4, I4_U8, I4_CH,
1615 U4_I1, U4_U1, U4_I2, U4_U2, U4_I4, U4_CH,
1616 I8_I1, I8_U1, I8_I2, I8_U2, I8_I4, I8_U4, I8_U8, I8_CH,
1617 U8_I1, U8_U1, U8_I2, U8_U2, U8_I4, U8_U4, U8_I8, U8_CH,
1618 CH_I1, CH_U1, CH_I2,
1619 R4_I1, R4_U1, R4_I2, R4_U2, R4_I4, R4_U4, R4_I8, R4_U8, R4_CH,
1620 R8_I1, R8_U1, R8_I2, R8_U2, R8_I4, R8_U4, R8_I8, R8_U8, R8_CH, R8_R4
1626 public ConvCast (EmitContext ec, Expression child, Type return_type, Mode m)
1627 : base (child, return_type)
1629 checked_state = ec.CheckState;
1633 public override Expression DoResolve (EmitContext ec)
1635 // This should never be invoked, we are born in fully
1636 // initialized state.
1641 public override string ToString ()
1643 return String.Format ("ConvCast ({0}, {1})", mode, child);
1646 public override void Emit (EmitContext ec)
1648 ILGenerator ig = ec.ig;
1654 case Mode.I1_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1655 case Mode.I1_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1656 case Mode.I1_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1657 case Mode.I1_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1658 case Mode.I1_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1660 case Mode.U1_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1661 case Mode.U1_CH: /* nothing */ break;
1663 case Mode.I2_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1664 case Mode.I2_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1665 case Mode.I2_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1666 case Mode.I2_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1667 case Mode.I2_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1668 case Mode.I2_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1670 case Mode.U2_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1671 case Mode.U2_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
1672 case Mode.U2_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
1673 case Mode.U2_CH: /* nothing */ break;
1675 case Mode.I4_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1676 case Mode.I4_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1677 case Mode.I4_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
1678 case Mode.I4_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1679 case Mode.I4_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1680 case Mode.I4_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1681 case Mode.I4_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1683 case Mode.U4_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1684 case Mode.U4_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
1685 case Mode.U4_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
1686 case Mode.U4_U2: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
1687 case Mode.U4_I4: ig.Emit (OpCodes.Conv_Ovf_I4_Un); break;
1688 case Mode.U4_CH: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
1690 case Mode.I8_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1691 case Mode.I8_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1692 case Mode.I8_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
1693 case Mode.I8_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1694 case Mode.I8_I4: ig.Emit (OpCodes.Conv_Ovf_I4); break;
1695 case Mode.I8_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1696 case Mode.I8_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1697 case Mode.I8_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1699 case Mode.U8_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1700 case Mode.U8_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
1701 case Mode.U8_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
1702 case Mode.U8_U2: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
1703 case Mode.U8_I4: ig.Emit (OpCodes.Conv_Ovf_I4_Un); break;
1704 case Mode.U8_U4: ig.Emit (OpCodes.Conv_Ovf_U4_Un); break;
1705 case Mode.U8_I8: ig.Emit (OpCodes.Conv_Ovf_I8_Un); break;
1706 case Mode.U8_CH: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
1708 case Mode.CH_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1709 case Mode.CH_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
1710 case Mode.CH_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
1712 case Mode.R4_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1713 case Mode.R4_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1714 case Mode.R4_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
1715 case Mode.R4_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1716 case Mode.R4_I4: ig.Emit (OpCodes.Conv_Ovf_I4); break;
1717 case Mode.R4_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1718 case Mode.R4_I8: ig.Emit (OpCodes.Conv_Ovf_I8); break;
1719 case Mode.R4_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1720 case Mode.R4_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1722 case Mode.R8_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1723 case Mode.R8_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1724 case Mode.R8_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
1725 case Mode.R8_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1726 case Mode.R8_I4: ig.Emit (OpCodes.Conv_Ovf_I4); break;
1727 case Mode.R8_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1728 case Mode.R8_I8: ig.Emit (OpCodes.Conv_Ovf_I8); break;
1729 case Mode.R8_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1730 case Mode.R8_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1731 case Mode.R8_R4: ig.Emit (OpCodes.Conv_R4); break;
1735 case Mode.I1_U1: ig.Emit (OpCodes.Conv_U1); break;
1736 case Mode.I1_U2: ig.Emit (OpCodes.Conv_U2); break;
1737 case Mode.I1_U4: ig.Emit (OpCodes.Conv_U4); break;
1738 case Mode.I1_U8: ig.Emit (OpCodes.Conv_I8); break;
1739 case Mode.I1_CH: ig.Emit (OpCodes.Conv_U2); break;
1741 case Mode.U1_I1: ig.Emit (OpCodes.Conv_I1); break;
1742 case Mode.U1_CH: ig.Emit (OpCodes.Conv_U2); break;
1744 case Mode.I2_I1: ig.Emit (OpCodes.Conv_I1); break;
1745 case Mode.I2_U1: ig.Emit (OpCodes.Conv_U1); break;
1746 case Mode.I2_U2: ig.Emit (OpCodes.Conv_U2); break;
1747 case Mode.I2_U4: ig.Emit (OpCodes.Conv_U4); break;
1748 case Mode.I2_U8: ig.Emit (OpCodes.Conv_I8); break;
1749 case Mode.I2_CH: ig.Emit (OpCodes.Conv_U2); break;
1751 case Mode.U2_I1: ig.Emit (OpCodes.Conv_I1); break;
1752 case Mode.U2_U1: ig.Emit (OpCodes.Conv_U1); break;
1753 case Mode.U2_I2: ig.Emit (OpCodes.Conv_I2); break;
1754 case Mode.U2_CH: /* nothing */ break;
1756 case Mode.I4_I1: ig.Emit (OpCodes.Conv_I1); break;
1757 case Mode.I4_U1: ig.Emit (OpCodes.Conv_U1); break;
1758 case Mode.I4_I2: ig.Emit (OpCodes.Conv_I2); break;
1759 case Mode.I4_U4: /* nothing */ break;
1760 case Mode.I4_U2: ig.Emit (OpCodes.Conv_U2); break;
1761 case Mode.I4_U8: ig.Emit (OpCodes.Conv_I8); break;
1762 case Mode.I4_CH: ig.Emit (OpCodes.Conv_U2); break;
1764 case Mode.U4_I1: ig.Emit (OpCodes.Conv_I1); break;
1765 case Mode.U4_U1: ig.Emit (OpCodes.Conv_U1); break;
1766 case Mode.U4_I2: ig.Emit (OpCodes.Conv_I2); break;
1767 case Mode.U4_U2: ig.Emit (OpCodes.Conv_U2); break;
1768 case Mode.U4_I4: /* nothing */ break;
1769 case Mode.U4_CH: ig.Emit (OpCodes.Conv_U2); break;
1771 case Mode.I8_I1: ig.Emit (OpCodes.Conv_I1); break;
1772 case Mode.I8_U1: ig.Emit (OpCodes.Conv_U1); break;
1773 case Mode.I8_I2: ig.Emit (OpCodes.Conv_I2); break;
1774 case Mode.I8_U2: ig.Emit (OpCodes.Conv_U2); break;
1775 case Mode.I8_I4: ig.Emit (OpCodes.Conv_I4); break;
1776 case Mode.I8_U4: ig.Emit (OpCodes.Conv_U4); break;
1777 case Mode.I8_U8: /* nothing */ break;
1778 case Mode.I8_CH: ig.Emit (OpCodes.Conv_U2); break;
1780 case Mode.U8_I1: ig.Emit (OpCodes.Conv_I1); break;
1781 case Mode.U8_U1: ig.Emit (OpCodes.Conv_U1); break;
1782 case Mode.U8_I2: ig.Emit (OpCodes.Conv_I2); break;
1783 case Mode.U8_U2: ig.Emit (OpCodes.Conv_U2); break;
1784 case Mode.U8_I4: ig.Emit (OpCodes.Conv_I4); break;
1785 case Mode.U8_U4: ig.Emit (OpCodes.Conv_U4); break;
1786 case Mode.U8_I8: /* nothing */ break;
1787 case Mode.U8_CH: ig.Emit (OpCodes.Conv_U2); break;
1789 case Mode.CH_I1: ig.Emit (OpCodes.Conv_I1); break;
1790 case Mode.CH_U1: ig.Emit (OpCodes.Conv_U1); break;
1791 case Mode.CH_I2: ig.Emit (OpCodes.Conv_I2); break;
1793 case Mode.R4_I1: ig.Emit (OpCodes.Conv_I1); break;
1794 case Mode.R4_U1: ig.Emit (OpCodes.Conv_U1); break;
1795 case Mode.R4_I2: ig.Emit (OpCodes.Conv_I2); break;
1796 case Mode.R4_U2: ig.Emit (OpCodes.Conv_U2); break;
1797 case Mode.R4_I4: ig.Emit (OpCodes.Conv_I4); break;
1798 case Mode.R4_U4: ig.Emit (OpCodes.Conv_U4); break;
1799 case Mode.R4_I8: ig.Emit (OpCodes.Conv_I8); break;
1800 case Mode.R4_U8: ig.Emit (OpCodes.Conv_U8); break;
1801 case Mode.R4_CH: ig.Emit (OpCodes.Conv_U2); break;
1803 case Mode.R8_I1: ig.Emit (OpCodes.Conv_I1); break;
1804 case Mode.R8_U1: ig.Emit (OpCodes.Conv_U1); break;
1805 case Mode.R8_I2: ig.Emit (OpCodes.Conv_I2); break;
1806 case Mode.R8_U2: ig.Emit (OpCodes.Conv_U2); break;
1807 case Mode.R8_I4: ig.Emit (OpCodes.Conv_I4); break;
1808 case Mode.R8_U4: ig.Emit (OpCodes.Conv_U4); break;
1809 case Mode.R8_I8: ig.Emit (OpCodes.Conv_I8); break;
1810 case Mode.R8_U8: ig.Emit (OpCodes.Conv_U8); break;
1811 case Mode.R8_CH: ig.Emit (OpCodes.Conv_U2); break;
1812 case Mode.R8_R4: ig.Emit (OpCodes.Conv_R4); break;
1818 public class OpcodeCast : EmptyCast {
1822 public OpcodeCast (Expression child, Type return_type, OpCode op)
1823 : base (child, return_type)
1827 second_valid = false;
1830 public OpcodeCast (Expression child, Type return_type, OpCode op, OpCode op2)
1831 : base (child, return_type)
1836 second_valid = true;
1839 public override Expression DoResolve (EmitContext ec)
1841 // This should never be invoked, we are born in fully
1842 // initialized state.
1847 public override void Emit (EmitContext ec)
1858 /// This kind of cast is used to encapsulate a child and cast it
1859 /// to the class requested
1861 public class ClassCast : EmptyCast {
1862 public ClassCast (Expression child, Type return_type)
1863 : base (child, return_type)
1868 public override Expression DoResolve (EmitContext ec)
1870 // This should never be invoked, we are born in fully
1871 // initialized state.
1876 public override void Emit (EmitContext ec)
1880 ec.ig.Emit (OpCodes.Castclass, type);
1886 /// SimpleName expressions are initially formed of a single
1887 /// word and it only happens at the beginning of the expression.
1891 /// The expression will try to be bound to a Field, a Method
1892 /// group or a Property. If those fail we pass the name to our
1893 /// caller and the SimpleName is compounded to perform a type
1894 /// lookup. The idea behind this process is that we want to avoid
1895 /// creating a namespace map from the assemblies, as that requires
1896 /// the GetExportedTypes function to be called and a hashtable to
1897 /// be constructed which reduces startup time. If later we find
1898 /// that this is slower, we should create a `NamespaceExpr' expression
1899 /// that fully participates in the resolution process.
1901 /// For example `System.Console.WriteLine' is decomposed into
1902 /// MemberAccess (MemberAccess (SimpleName ("System"), "Console"), "WriteLine")
1904 /// The first SimpleName wont produce a match on its own, so it will
1906 /// MemberAccess (SimpleName ("System.Console"), "WriteLine").
1908 /// System.Console will produce a TypeExpr match.
1910 /// The downside of this is that we might be hitting `LookupType' too many
1911 /// times with this scheme.
1913 public class SimpleName : Expression {
1917 // If true, then we are a simple name, not composed with a ".
1921 public SimpleName (string a, string b, Location l)
1923 Name = String.Concat (a, ".", b);
1928 public SimpleName (string name, Location l)
1935 public static void Error_ObjectRefRequired (EmitContext ec, Location l, string name)
1937 if (ec.IsFieldInitializer)
1940 "A field initializer cannot reference the non-static field, " +
1941 "method or property `"+name+"'");
1945 "An object reference is required " +
1946 "for the non-static field `"+name+"'");
1950 // Checks whether we are trying to access an instance
1951 // property, method or field from a static body.
1953 Expression MemberStaticCheck (EmitContext ec, Expression e)
1955 if (e is IMemberExpr){
1956 IMemberExpr member = (IMemberExpr) e;
1958 if (!member.IsStatic){
1959 Error_ObjectRefRequired (ec, loc, Name);
1967 public override Expression DoResolve (EmitContext ec)
1969 return SimpleNameResolve (ec, null, false);
1972 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
1974 return SimpleNameResolve (ec, right_side, false);
1978 public Expression DoResolveAllowStatic (EmitContext ec)
1980 return SimpleNameResolve (ec, null, true);
1983 public override Expression ResolveAsTypeStep (EmitContext ec)
1985 DeclSpace ds = ec.DeclSpace;
1986 NamespaceEntry ns = ds.NamespaceEntry;
1991 // Since we are cheating: we only do the Alias lookup for
1992 // namespaces if the name does not include any dots in it
1994 if (ns != null && is_base)
1995 alias_value = ns.LookupAlias (Name);
1999 if (ec.ResolvingTypeTree){
2000 int errors = Report.Errors;
2001 Type dt = ds.FindType (loc, Name);
2003 if (Report.Errors != errors)
2007 return new TypeExpression (dt, loc);
2009 if (alias_value != null){
2010 if ((t = RootContext.LookupType (ds, alias_value, true, loc)) != null)
2011 return new TypeExpression (t, loc);
2016 // First, the using aliases
2018 if (alias_value != null){
2019 if ((t = RootContext.LookupType (ds, alias_value, true, loc)) != null)
2020 return new TypeExpression (t, loc);
2022 // we have alias value, but it isn't Type, so try if it's namespace
2023 return new SimpleName (alias_value, loc);
2027 // Stage 2: Lookup up if we are an alias to a type
2031 if ((t = RootContext.LookupType (ds, Name, true, loc)) != null)
2032 return new TypeExpression (t, loc);
2034 // No match, maybe our parent can compose us
2035 // into something meaningful.
2039 Expression SimpleNameResolve (EmitContext ec, Expression right_side,
2042 Expression e = DoSimpleNameResolve (ec, right_side, allow_static);
2046 Block current_block = ec.CurrentBlock;
2047 if (current_block != null){
2048 LocalInfo vi = current_block.GetLocalInfo (Name);
2050 current_block.IsVariableNameUsedInChildBlock(Name)) {
2051 Report.Error (135, Location,
2052 "'{0}' has a different meaning in a " +
2053 "child block", Name);
2062 /// 7.5.2: Simple Names.
2064 /// Local Variables and Parameters are handled at
2065 /// parse time, so they never occur as SimpleNames.
2067 /// The `allow_static' flag is used by MemberAccess only
2068 /// and it is used to inform us that it is ok for us to
2069 /// avoid the static check, because MemberAccess might end
2070 /// up resolving the Name as a Type name and the access as
2071 /// a static type access.
2073 /// ie: Type Type; .... { Type.GetType (""); }
2075 /// Type is both an instance variable and a Type; Type.GetType
2076 /// is the static method not an instance method of type.
2078 Expression DoSimpleNameResolve (EmitContext ec, Expression right_side, bool allow_static)
2080 Expression e = null;
2083 // Stage 1: Performed by the parser (binding to locals or parameters).
2085 Block current_block = ec.CurrentBlock;
2086 if (current_block != null){
2087 LocalInfo vi = current_block.GetLocalInfo (Name);
2091 var = new LocalVariableReference (ec.CurrentBlock, Name, loc);
2093 if (right_side != null)
2094 return var.ResolveLValue (ec, right_side);
2096 return var.Resolve (ec);
2100 Parameter par = null;
2101 Parameters pars = current_block.Parameters;
2103 par = pars.GetParameterByName (Name, out idx);
2106 ParameterReference param;
2108 param = new ParameterReference (pars, current_block, idx, Name, loc);
2110 if (right_side != null)
2111 return param.ResolveLValue (ec, right_side);
2113 return param.Resolve (ec);
2118 // Stage 2: Lookup members
2121 DeclSpace lookup_ds = ec.DeclSpace;
2123 if (lookup_ds.TypeBuilder == null)
2126 e = MemberLookup (ec, lookup_ds.TypeBuilder, Name, loc);
2130 lookup_ds =lookup_ds.Parent;
2131 } while (lookup_ds != null);
2133 if (e == null && ec.ContainerType != null)
2134 e = MemberLookup (ec, ec.ContainerType, Name, loc);
2138 // Since we are cheating (is_base is our hint
2139 // that we are the beginning of the name): we
2140 // only do the Alias lookup for namespaces if
2141 // the name does not include any dots in it
2143 NamespaceEntry ns = ec.DeclSpace.NamespaceEntry;
2144 if (is_base && ns != null){
2145 string alias_value = ns.LookupAlias (Name);
2146 if (alias_value != null){
2150 if ((t = TypeManager.LookupType (Name)) != null)
2151 return new TypeExpression (t, loc);
2153 // No match, maybe our parent can compose us
2154 // into something meaningful.
2159 return ResolveAsTypeStep (ec);
2165 if (e is IMemberExpr) {
2166 e = MemberAccess.ResolveMemberAccess (ec, e, null, loc, this);
2170 IMemberExpr me = e as IMemberExpr;
2174 // This fails if ResolveMemberAccess() was unable to decide whether
2175 // it's a field or a type of the same name.
2176 if (!me.IsStatic && (me.InstanceExpression == null))
2180 TypeManager.IsNestedChildOf (me.InstanceExpression.Type, me.DeclaringType) &&
2181 !me.InstanceExpression.Type.IsSubclassOf (me.DeclaringType)) {
2182 Error (38, "Cannot access nonstatic member `" + me.Name + "' of " +
2183 "outer type `" + me.DeclaringType + "' via nested type `" +
2184 me.InstanceExpression.Type + "'");
2188 if (right_side != null)
2189 e = e.DoResolveLValue (ec, right_side);
2191 e = e.DoResolve (ec);
2196 if (ec.IsStatic || ec.IsFieldInitializer){
2200 return MemberStaticCheck (ec, e);
2205 public override void Emit (EmitContext ec)
2208 // If this is ever reached, then we failed to
2209 // find the name as a namespace
2212 Error (103, "The name `" + Name +
2213 "' does not exist in the class `" +
2214 ec.DeclSpace.Name + "'");
2217 public override string ToString ()
2224 /// Fully resolved expression that evaluates to a type
2226 public abstract class TypeExpr : Expression {
2227 override public Expression ResolveAsTypeStep (EmitContext ec)
2229 TypeExpr t = DoResolveAsTypeStep (ec);
2233 eclass = ExprClass.Type;
2237 override public Expression DoResolve (EmitContext ec)
2239 return ResolveAsTypeTerminal (ec);
2242 override public void Emit (EmitContext ec)
2244 throw new Exception ("Should never be called");
2247 public virtual bool CheckAccessLevel (DeclSpace ds)
2249 return ds.CheckAccessLevel (Type);
2252 public virtual bool AsAccessible (DeclSpace ds, int flags)
2254 return ds.AsAccessible (Type, flags);
2257 public virtual bool IsClass {
2258 get { return Type.IsClass; }
2261 public virtual bool IsValueType {
2262 get { return Type.IsValueType; }
2265 public virtual bool IsInterface {
2266 get { return Type.IsInterface; }
2269 public virtual bool IsSealed {
2270 get { return Type.IsSealed; }
2273 public virtual bool CanInheritFrom ()
2275 if (Type == TypeManager.enum_type ||
2276 (Type == TypeManager.value_type && RootContext.StdLib) ||
2277 Type == TypeManager.multicast_delegate_type ||
2278 Type == TypeManager.delegate_type ||
2279 Type == TypeManager.array_type)
2285 public virtual bool IsAttribute {
2287 return Type == TypeManager.attribute_type ||
2288 Type.IsSubclassOf (TypeManager.attribute_type);
2292 public virtual TypeExpr[] GetInterfaces ()
2294 return TypeManager.GetInterfaces (Type);
2297 public abstract TypeExpr DoResolveAsTypeStep (EmitContext ec);
2299 public virtual Type ResolveType (EmitContext ec)
2301 TypeExpr t = ResolveAsTypeTerminal (ec);
2308 public abstract string Name {
2312 public override bool Equals (object obj)
2314 TypeExpr tobj = obj as TypeExpr;
2318 return Type == tobj.Type;
2321 public override int GetHashCode ()
2323 return Type.GetHashCode ();
2326 public override string ToString ()
2332 public class TypeExpression : TypeExpr {
2333 public TypeExpression (Type t, Location l)
2336 eclass = ExprClass.Type;
2340 public override TypeExpr DoResolveAsTypeStep (EmitContext ec)
2345 public override string Name {
2347 return Type.ToString ();
2353 /// Used to create types from a fully qualified name. These are just used
2354 /// by the parser to setup the core types. A TypeLookupExpression is always
2355 /// classified as a type.
2357 public class TypeLookupExpression : TypeExpr {
2360 public TypeLookupExpression (string name)
2365 public override TypeExpr DoResolveAsTypeStep (EmitContext ec)
2368 type = RootContext.LookupType (ec.DeclSpace, name, false, Location.Null);
2372 public override string Name {
2380 /// MethodGroup Expression.
2382 /// This is a fully resolved expression that evaluates to a type
2384 public class MethodGroupExpr : Expression, IMemberExpr {
2385 public MethodBase [] Methods;
2386 Expression instance_expression = null;
2387 bool is_explicit_impl = false;
2388 bool identical_type_name = false;
2390 public MethodGroupExpr (MemberInfo [] mi, Location l)
2392 Methods = new MethodBase [mi.Length];
2393 mi.CopyTo (Methods, 0);
2394 eclass = ExprClass.MethodGroup;
2395 type = TypeManager.object_type;
2399 public MethodGroupExpr (ArrayList list, Location l)
2401 Methods = new MethodBase [list.Count];
2404 list.CopyTo (Methods, 0);
2406 foreach (MemberInfo m in list){
2407 if (!(m is MethodBase)){
2408 Console.WriteLine ("Name " + m.Name);
2409 Console.WriteLine ("Found a: " + m.GetType ().FullName);
2416 eclass = ExprClass.MethodGroup;
2417 type = TypeManager.object_type;
2420 public Type DeclaringType {
2423 // The methods are arranged in this order:
2424 // derived type -> base type
2426 return Methods [0].DeclaringType;
2431 // `A method group may have associated an instance expression'
2433 public Expression InstanceExpression {
2435 return instance_expression;
2439 instance_expression = value;
2443 public bool IsExplicitImpl {
2445 return is_explicit_impl;
2449 is_explicit_impl = value;
2453 public bool IdenticalTypeName {
2455 return identical_type_name;
2459 identical_type_name = value;
2463 public string Name {
2465 return Methods [0].Name;
2469 public bool IsInstance {
2471 foreach (MethodBase mb in Methods)
2479 public bool IsStatic {
2481 foreach (MethodBase mb in Methods)
2489 override public Expression DoResolve (EmitContext ec)
2492 instance_expression = null;
2494 if (instance_expression != null) {
2495 instance_expression = instance_expression.DoResolve (ec);
2496 if (instance_expression == null)
2503 public void ReportUsageError ()
2505 Report.Error (654, loc, "Method `" + DeclaringType + "." +
2506 Name + "()' is referenced without parentheses");
2509 override public void Emit (EmitContext ec)
2511 ReportUsageError ();
2514 bool RemoveMethods (bool keep_static)
2516 ArrayList smethods = new ArrayList ();
2518 foreach (MethodBase mb in Methods){
2519 if (mb.IsStatic == keep_static)
2523 if (smethods.Count == 0)
2526 Methods = new MethodBase [smethods.Count];
2527 smethods.CopyTo (Methods, 0);
2533 /// Removes any instance methods from the MethodGroup, returns
2534 /// false if the resulting set is empty.
2536 public bool RemoveInstanceMethods ()
2538 return RemoveMethods (true);
2542 /// Removes any static methods from the MethodGroup, returns
2543 /// false if the resulting set is empty.
2545 public bool RemoveStaticMethods ()
2547 return RemoveMethods (false);
2552 /// Fully resolved expression that evaluates to a Field
2554 public class FieldExpr : Expression, IAssignMethod, IMemoryLocation, IMemberExpr, IVariable {
2555 public readonly FieldInfo FieldInfo;
2556 Expression instance_expr;
2557 VariableInfo variable_info;
2559 LocalTemporary temporary;
2560 IMemoryLocation instance_ml;
2561 bool have_temporary;
2563 public FieldExpr (FieldInfo fi, Location l)
2566 eclass = ExprClass.Variable;
2567 type = fi.FieldType;
2571 public string Name {
2573 return FieldInfo.Name;
2577 public bool IsInstance {
2579 return !FieldInfo.IsStatic;
2583 public bool IsStatic {
2585 return FieldInfo.IsStatic;
2589 public Type DeclaringType {
2591 return FieldInfo.DeclaringType;
2595 public Expression InstanceExpression {
2597 return instance_expr;
2601 instance_expr = value;
2605 public VariableInfo VariableInfo {
2607 return variable_info;
2611 override public Expression DoResolve (EmitContext ec)
2613 if (!FieldInfo.IsStatic){
2614 if (instance_expr == null){
2616 // This can happen when referencing an instance field using
2617 // a fully qualified type expression: TypeName.InstanceField = xxx
2619 SimpleName.Error_ObjectRefRequired (ec, loc, FieldInfo.Name);
2623 // Resolve the field's instance expression while flow analysis is turned
2624 // off: when accessing a field "a.b", we must check whether the field
2625 // "a.b" is initialized, not whether the whole struct "a" is initialized.
2626 instance_expr = instance_expr.Resolve (ec, ResolveFlags.VariableOrValue |
2627 ResolveFlags.DisableFlowAnalysis);
2628 if (instance_expr == null)
2632 ObsoleteAttribute oa;
2633 FieldBase f = TypeManager.GetField (FieldInfo);
2635 oa = f.GetObsoleteAttribute (ec.DeclSpace);
2637 AttributeTester.Report_ObsoleteMessage (oa, f.GetSignatureForError (), loc);
2639 // To be sure that type is external because we do not register generated fields
2640 } else if (!(FieldInfo.DeclaringType is TypeBuilder)) {
2641 oa = AttributeTester.GetMemberObsoleteAttribute (FieldInfo);
2643 AttributeTester.Report_ObsoleteMessage (oa, TypeManager.GetFullNameSignature (FieldInfo), loc);
2646 // If the instance expression is a local variable or parameter.
2647 IVariable var = instance_expr as IVariable;
2648 if ((var == null) || (var.VariableInfo == null))
2651 VariableInfo vi = var.VariableInfo;
2652 if (!vi.IsFieldAssigned (ec, FieldInfo.Name, loc))
2655 variable_info = vi.GetSubStruct (FieldInfo.Name);
2659 void Report_AssignToReadonly (bool is_instance)
2664 msg = "Readonly field can not be assigned outside " +
2665 "of constructor or variable initializer";
2667 msg = "A static readonly field can only be assigned in " +
2668 "a static constructor";
2670 Report.Error (is_instance ? 191 : 198, loc, msg);
2673 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
2675 IVariable var = instance_expr as IVariable;
2676 if ((var != null) && (var.VariableInfo != null))
2677 var.VariableInfo.SetFieldAssigned (ec, FieldInfo.Name);
2679 Expression e = DoResolve (ec);
2684 if (!FieldInfo.IsStatic && (instance_expr.Type.IsValueType && !(instance_expr is IMemoryLocation))) {
2685 // FIXME: Provide better error reporting.
2686 Error (1612, "Cannot modify expression because it is not a variable.");
2690 if (!FieldInfo.IsInitOnly)
2693 FieldBase fb = TypeManager.GetField (FieldInfo);
2698 // InitOnly fields can only be assigned in constructors
2701 if (ec.IsConstructor){
2702 if (IsStatic && !ec.IsStatic)
2703 Report_AssignToReadonly (false);
2705 if (ec.ContainerType == FieldInfo.DeclaringType)
2709 Report_AssignToReadonly (true);
2714 public bool VerifyFixed (bool is_expression)
2716 IVariable variable = instance_expr as IVariable;
2717 if ((variable == null) || !variable.VerifyFixed (true))
2723 public override void CacheTemporaries (EmitContext ec)
2725 if (!FieldInfo.IsStatic && (temporary == null))
2726 temporary = new LocalTemporary (ec, instance_expr.Type);
2729 void EmitInstance (EmitContext ec)
2731 if (instance_expr.Type.IsValueType)
2732 CacheTemporaries (ec);
2734 if ((temporary == null) || have_temporary)
2737 if (instance_expr.Type.IsValueType) {
2738 instance_ml = instance_expr as IMemoryLocation;
2739 if (instance_ml == null) {
2740 instance_expr.Emit (ec);
2741 temporary.Store (ec);
2742 instance_ml = temporary;
2745 instance_expr.Emit (ec);
2746 temporary.Store (ec);
2749 have_temporary = true;
2752 override public void Emit (EmitContext ec)
2754 ILGenerator ig = ec.ig;
2755 bool is_volatile = false;
2757 if (FieldInfo is FieldBuilder){
2758 FieldBase f = TypeManager.GetField (FieldInfo);
2760 if ((f.ModFlags & Modifiers.VOLATILE) != 0)
2763 f.status |= Field.Status.USED;
2767 if (FieldInfo.IsStatic){
2769 ig.Emit (OpCodes.Volatile);
2771 ig.Emit (OpCodes.Ldsfld, FieldInfo);
2776 if (instance_ml != null)
2777 instance_ml.AddressOf (ec, AddressOp.Load);
2778 else if (temporary != null)
2779 temporary.Emit (ec);
2781 instance_expr.Emit (ec);
2784 ig.Emit (OpCodes.Volatile);
2786 ig.Emit (OpCodes.Ldfld, FieldInfo);
2789 public void EmitAssign (EmitContext ec, Expression source)
2791 FieldAttributes fa = FieldInfo.Attributes;
2792 bool is_static = (fa & FieldAttributes.Static) != 0;
2793 bool is_readonly = (fa & FieldAttributes.InitOnly) != 0;
2794 ILGenerator ig = ec.ig;
2796 if (is_readonly && !ec.IsConstructor){
2797 Report_AssignToReadonly (!is_static);
2803 if (instance_ml != null)
2804 instance_ml.AddressOf (ec, AddressOp.Store);
2805 else if (temporary != null)
2806 temporary.Emit (ec);
2808 instance_expr.Emit (ec);
2813 if (FieldInfo is FieldBuilder){
2814 FieldBase f = TypeManager.GetField (FieldInfo);
2816 if ((f.ModFlags & Modifiers.VOLATILE) != 0)
2817 ig.Emit (OpCodes.Volatile);
2819 f.status |= Field.Status.ASSIGNED;
2824 ig.Emit (OpCodes.Stsfld, FieldInfo);
2826 ig.Emit (OpCodes.Stfld, FieldInfo);
2829 public void AddressOf (EmitContext ec, AddressOp mode)
2831 ILGenerator ig = ec.ig;
2833 if (FieldInfo is FieldBuilder){
2834 FieldBase f = TypeManager.GetField (FieldInfo);
2836 if ((f.ModFlags & Modifiers.VOLATILE) != 0){
2837 Error (676, "volatile variable: can not take its address, or pass as ref/out parameter");
2841 if ((mode & AddressOp.Store) != 0)
2842 f.status |= Field.Status.ASSIGNED;
2843 if ((mode & AddressOp.Load) != 0)
2844 f.status |= Field.Status.USED;
2849 // Handle initonly fields specially: make a copy and then
2850 // get the address of the copy.
2853 if (FieldInfo.IsInitOnly){
2855 if (ec.IsConstructor){
2856 if (FieldInfo.IsStatic){
2868 local = ig.DeclareLocal (type);
2869 ig.Emit (OpCodes.Stloc, local);
2870 ig.Emit (OpCodes.Ldloca, local);
2875 if (FieldInfo.IsStatic){
2876 ig.Emit (OpCodes.Ldsflda, FieldInfo);
2879 // In the case of `This', we call the AddressOf method, which will
2880 // only load the pointer, and not perform an Ldobj immediately after
2881 // the value has been loaded into the stack.
2884 if (instance_ml != null)
2885 instance_ml.AddressOf (ec, AddressOp.LoadStore);
2886 else if (temporary != null)
2887 temporary.Emit (ec);
2888 else if (instance_expr is This)
2889 ((This)instance_expr).AddressOf (ec, AddressOp.LoadStore);
2891 instance_expr.Emit (ec);
2892 ig.Emit (OpCodes.Ldflda, FieldInfo);
2898 // A FieldExpr whose address can not be taken
2900 public class FieldExprNoAddress : FieldExpr, IMemoryLocation {
2901 public FieldExprNoAddress (FieldInfo fi, Location loc) : base (fi, loc)
2905 public new void AddressOf (EmitContext ec, AddressOp mode)
2907 Report.Error (-215, "Report this: Taking the address of a remapped parameter not supported");
2912 /// Expression that evaluates to a Property. The Assign class
2913 /// might set the `Value' expression if we are in an assignment.
2915 /// This is not an LValue because we need to re-write the expression, we
2916 /// can not take data from the stack and store it.
2918 public class PropertyExpr : ExpressionStatement, IAssignMethod, IMemberExpr {
2919 public readonly PropertyInfo PropertyInfo;
2922 // This is set externally by the `BaseAccess' class
2925 MethodInfo getter, setter;
2927 bool must_do_cs1540_check;
2929 Expression instance_expr;
2930 LocalTemporary temporary;
2931 bool have_temporary;
2933 public PropertyExpr (EmitContext ec, PropertyInfo pi, Location l)
2936 eclass = ExprClass.PropertyAccess;
2940 type = TypeManager.TypeToCoreType (pi.PropertyType);
2942 ResolveAccessors (ec);
2945 public string Name {
2947 return PropertyInfo.Name;
2951 public bool IsInstance {
2957 public bool IsStatic {
2963 public Type DeclaringType {
2965 return PropertyInfo.DeclaringType;
2970 // The instance expression associated with this expression
2972 public Expression InstanceExpression {
2974 instance_expr = value;
2978 return instance_expr;
2982 public bool VerifyAssignable ()
2984 if (setter == null) {
2985 Report.Error (200, loc,
2986 "The property `" + PropertyInfo.Name +
2987 "' can not be assigned to, as it has not set accessor");
2994 MethodInfo FindAccessor (Type invocation_type, bool is_set)
2996 BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic |
2997 BindingFlags.Static | BindingFlags.Instance |
2998 BindingFlags.DeclaredOnly;
3000 Type current = PropertyInfo.DeclaringType;
3001 for (; current != null; current = current.BaseType) {
3002 MemberInfo[] group = TypeManager.MemberLookup (
3003 invocation_type, invocation_type, current,
3004 MemberTypes.Property, flags, PropertyInfo.Name, null);
3009 if (group.Length != 1)
3010 // Oooops, can this ever happen ?
3013 PropertyInfo pi = (PropertyInfo) group [0];
3015 MethodInfo get = pi.GetGetMethod (true);
3016 MethodInfo set = pi.GetSetMethod (true);
3026 MethodInfo accessor = get != null ? get : set;
3027 if (accessor == null)
3029 if ((accessor.Attributes & MethodAttributes.NewSlot) != 0)
3036 MethodInfo GetAccessor (Type invocation_type, bool is_set)
3038 MethodInfo mi = FindAccessor (invocation_type, is_set);
3042 MethodAttributes ma = mi.Attributes & MethodAttributes.MemberAccessMask;
3045 // If only accessible to the current class or children
3047 if (ma == MethodAttributes.Private) {
3048 Type declaring_type = mi.DeclaringType;
3050 if (invocation_type != declaring_type){
3051 if (TypeManager.IsSubclassOrNestedChildOf (invocation_type, mi.DeclaringType))
3059 // FamAndAssem requires that we not only derivate, but we are on the
3062 if (ma == MethodAttributes.FamANDAssem){
3063 if (mi.DeclaringType.Assembly != invocation_type.Assembly)
3069 // Assembly and FamORAssem succeed if we're in the same assembly.
3070 if ((ma == MethodAttributes.Assembly) || (ma == MethodAttributes.FamORAssem)){
3071 if (mi.DeclaringType.Assembly == invocation_type.Assembly)
3075 // We already know that we aren't in the same assembly.
3076 if (ma == MethodAttributes.Assembly)
3079 // Family and FamANDAssem require that we derive.
3080 if ((ma == MethodAttributes.Family) || (ma == MethodAttributes.FamANDAssem) || (ma == MethodAttributes.FamORAssem)){
3081 if (!TypeManager.IsSubclassOrNestedChildOf (invocation_type, mi.DeclaringType))
3084 if (!TypeManager.IsNestedChildOf (invocation_type, mi.DeclaringType))
3085 must_do_cs1540_check = true;
3095 // We also perform the permission checking here, as the PropertyInfo does not
3096 // hold the information for the accessibility of its setter/getter
3098 void ResolveAccessors (EmitContext ec)
3100 getter = GetAccessor (ec.ContainerType, false);
3101 if ((getter != null) && getter.IsStatic)
3104 setter = GetAccessor (ec.ContainerType, true);
3105 if ((setter != null) && setter.IsStatic)
3108 if (setter == null && getter == null){
3109 Report.Error_T (122, loc, PropertyInfo.Name);
3113 bool InstanceResolve (EmitContext ec)
3115 if ((instance_expr == null) && ec.IsStatic && !is_static) {
3116 SimpleName.Error_ObjectRefRequired (ec, loc, PropertyInfo.Name);
3120 if (instance_expr != null) {
3121 instance_expr = instance_expr.DoResolve (ec);
3122 if (instance_expr == null)
3126 if (must_do_cs1540_check && (instance_expr != null)) {
3127 if ((instance_expr.Type != ec.ContainerType) &&
3128 ec.ContainerType.IsSubclassOf (instance_expr.Type)) {
3129 Report.Error (1540, loc, "Cannot access protected member `" +
3130 PropertyInfo.DeclaringType + "." + PropertyInfo.Name +
3131 "' via a qualifier of type `" +
3132 TypeManager.CSharpName (instance_expr.Type) +
3133 "'; the qualifier must be of type `" +
3134 TypeManager.CSharpName (ec.ContainerType) +
3135 "' (or derived from it)");
3143 override public Expression DoResolve (EmitContext ec)
3145 if (getter != null){
3146 if (TypeManager.GetArgumentTypes (getter).Length != 0){
3148 117, loc, "`{0}' does not contain a " +
3149 "definition for `{1}'.", getter.DeclaringType,
3155 if (getter == null){
3157 // The following condition happens if the PropertyExpr was
3158 // created, but is invalid (ie, the property is inaccessible),
3159 // and we did not want to embed the knowledge about this in
3160 // the caller routine. This only avoids double error reporting.
3165 Report.Error (154, loc,
3166 "The property `" + PropertyInfo.Name +
3167 "' can not be used in " +
3168 "this context because it lacks a get accessor");
3172 if (!InstanceResolve (ec))
3176 // Only base will allow this invocation to happen.
3178 if (IsBase && getter.IsAbstract){
3179 Report.Error (205, loc, "Cannot call an abstract base property: " +
3180 PropertyInfo.DeclaringType + "." +PropertyInfo.Name);
3187 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
3189 if (setter == null){
3191 // The following condition happens if the PropertyExpr was
3192 // created, but is invalid (ie, the property is inaccessible),
3193 // and we did not want to embed the knowledge about this in
3194 // the caller routine. This only avoids double error reporting.
3199 Report.Error (154, loc,
3200 "The property `" + PropertyInfo.Name +
3201 "' can not be used in " +
3202 "this context because it lacks a set accessor");
3206 if (TypeManager.GetArgumentTypes (setter).Length != 1){
3208 117, loc, "`{0}' does not contain a " +
3209 "definition for `{1}'.", getter.DeclaringType,
3214 if (!InstanceResolve (ec))
3218 // Only base will allow this invocation to happen.
3220 if (IsBase && setter.IsAbstract){
3221 Report.Error (205, loc, "Cannot call an abstract base property: " +
3222 PropertyInfo.DeclaringType + "." +PropertyInfo.Name);
3228 public override void CacheTemporaries (EmitContext ec)
3231 temporary = new LocalTemporary (ec, instance_expr.Type);
3234 Expression EmitInstance (EmitContext ec)
3236 if (temporary != null){
3237 if (!have_temporary){
3238 instance_expr.Emit (ec);
3239 temporary.Store (ec);
3240 have_temporary = true;
3244 return instance_expr;
3247 override public void Emit (EmitContext ec)
3249 Expression expr = EmitInstance (ec);
3252 // Special case: length of single dimension array property is turned into ldlen
3254 if ((getter == TypeManager.system_int_array_get_length) ||
3255 (getter == TypeManager.int_array_get_length)){
3256 Type iet = instance_expr.Type;
3259 // System.Array.Length can be called, but the Type does not
3260 // support invoking GetArrayRank, so test for that case first
3262 if (iet != TypeManager.array_type && (iet.GetArrayRank () == 1)){
3264 ec.ig.Emit (OpCodes.Ldlen);
3265 ec.ig.Emit (OpCodes.Conv_I4);
3270 Invocation.EmitCall (ec, IsBase, IsStatic, expr, getter, null, loc);
3275 // Implements the IAssignMethod interface for assignments
3277 public void EmitAssign (EmitContext ec, Expression source)
3279 Expression expr = EmitInstance (ec);
3281 Argument arg = new Argument (source, Argument.AType.Expression);
3282 ArrayList args = new ArrayList ();
3285 Invocation.EmitCall (ec, IsBase, IsStatic, expr, setter, args, loc);
3288 override public void EmitStatement (EmitContext ec)
3291 ec.ig.Emit (OpCodes.Pop);
3296 /// Fully resolved expression that evaluates to an Event
3298 public class EventExpr : Expression, IMemberExpr {
3299 public readonly EventInfo EventInfo;
3300 Expression instance_expr;
3303 MethodInfo add_accessor, remove_accessor;
3305 public EventExpr (EventInfo ei, Location loc)
3309 eclass = ExprClass.EventAccess;
3311 add_accessor = TypeManager.GetAddMethod (ei);
3312 remove_accessor = TypeManager.GetRemoveMethod (ei);
3314 if (add_accessor.IsStatic || remove_accessor.IsStatic)
3317 if (EventInfo is MyEventBuilder){
3318 MyEventBuilder eb = (MyEventBuilder) EventInfo;
3319 type = eb.EventType;
3322 type = EventInfo.EventHandlerType;
3325 public string Name {
3327 return EventInfo.Name;
3331 public bool IsInstance {
3337 public bool IsStatic {
3343 public Type DeclaringType {
3345 return EventInfo.DeclaringType;
3349 public Expression InstanceExpression {
3351 return instance_expr;
3355 instance_expr = value;
3359 public override Expression DoResolve (EmitContext ec)
3361 if (instance_expr != null) {
3362 instance_expr = instance_expr.DoResolve (ec);
3363 if (instance_expr == null)
3371 public override void Emit (EmitContext ec)
3373 Report.Error (70, loc, "The event `" + Name + "' can only appear on the left hand side of += or -= (except on the defining type)");
3376 public void EmitAddOrRemove (EmitContext ec, Expression source)
3378 BinaryDelegate source_del = (BinaryDelegate) source;
3379 Expression handler = source_del.Right;
3381 Argument arg = new Argument (handler, Argument.AType.Expression);
3382 ArrayList args = new ArrayList ();
3386 if (source_del.IsAddition)
3387 Invocation.EmitCall (
3388 ec, false, IsStatic, instance_expr, add_accessor, args, loc);
3390 Invocation.EmitCall (
3391 ec, false, IsStatic, instance_expr, remove_accessor, args, loc);