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 warning, string s)
192 if (!Location.IsNull (loc))
193 Report.Warning (warning, loc, s);
195 Report.Warning (warning, s);
199 /// Utility wrapper routine for Warning, only prints the warning if
200 /// warnings of level `level' are enabled.
202 public void Warning (int warning, int level, string s)
204 if (level <= RootContext.WarningLevel)
205 Warning (warning, s);
209 /// Tests presence of ObsoleteAttribute and report proper error
211 protected void CheckObsoleteAttribute (Type type)
213 ObsoleteAttribute obsolete_attr = AttributeTester.GetObsoleteAttribute (type);
214 if (obsolete_attr == null)
217 AttributeTester.Report_ObsoleteMessage (obsolete_attr, type.FullName, loc);
221 /// Performs semantic analysis on the Expression
225 /// The Resolve method is invoked to perform the semantic analysis
228 /// The return value is an expression (it can be the
229 /// same expression in some cases) or a new
230 /// expression that better represents this node.
232 /// For example, optimizations of Unary (LiteralInt)
233 /// would return a new LiteralInt with a negated
236 /// If there is an error during semantic analysis,
237 /// then an error should be reported (using Report)
238 /// and a null value should be returned.
240 /// There are two side effects expected from calling
241 /// Resolve(): the the field variable "eclass" should
242 /// be set to any value of the enumeration
243 /// `ExprClass' and the type variable should be set
244 /// to a valid type (this is the type of the
247 public abstract Expression DoResolve (EmitContext ec);
249 public virtual Expression DoResolveLValue (EmitContext ec, Expression right_side)
251 return DoResolve (ec);
255 // This is used if the expression should be resolved as a type.
256 // the default implementation fails. Use this method in
257 // those participants in the SimpleName chain system.
259 public virtual Expression ResolveAsTypeStep (EmitContext ec)
265 // This is used to resolve the expression as a type, a null
266 // value will be returned if the expression is not a type
269 public TypeExpr ResolveAsTypeTerminal (EmitContext ec)
271 return ResolveAsTypeStep (ec) as TypeExpr;
275 /// Resolves an expression and performs semantic analysis on it.
279 /// Currently Resolve wraps DoResolve to perform sanity
280 /// checking and assertion checking on what we expect from Resolve.
282 public Expression Resolve (EmitContext ec, ResolveFlags flags)
284 if ((flags & ResolveFlags.MaskExprClass) == ResolveFlags.Type)
285 return ResolveAsTypeStep (ec);
287 bool old_do_flow_analysis = ec.DoFlowAnalysis;
288 if ((flags & ResolveFlags.DisableFlowAnalysis) != 0)
289 ec.DoFlowAnalysis = false;
292 bool intermediate = (flags & ResolveFlags.Intermediate) == ResolveFlags.Intermediate;
293 if (this is SimpleName)
294 e = ((SimpleName) this).DoResolveAllowStatic (ec, intermediate);
299 ec.DoFlowAnalysis = old_do_flow_analysis;
304 if (e is SimpleName){
305 SimpleName s = (SimpleName) e;
307 if ((flags & ResolveFlags.SimpleName) == 0) {
308 MemberLookupFailed (ec, null, ec.ContainerType, s.Name,
309 ec.DeclSpace.Name, loc);
316 if ((e is TypeExpr) || (e is ComposedCast)) {
317 if ((flags & ResolveFlags.Type) == 0) {
318 e.Error_UnexpectedKind (flags);
327 if ((flags & ResolveFlags.VariableOrValue) == 0) {
328 e.Error_UnexpectedKind (flags);
333 case ExprClass.MethodGroup:
334 if (!RootContext.V2){
335 if ((flags & ResolveFlags.MethodGroup) == 0) {
336 ((MethodGroupExpr) e).ReportUsageError ();
342 case ExprClass.Value:
343 case ExprClass.Variable:
344 case ExprClass.PropertyAccess:
345 case ExprClass.EventAccess:
346 case ExprClass.IndexerAccess:
347 if ((flags & ResolveFlags.VariableOrValue) == 0) {
348 Console.WriteLine ("I got: {0} and {1}", e.GetType (), e);
349 Console.WriteLine ("I am {0} and {1}", this.GetType (), this);
350 FieldInfo fi = ((FieldExpr) e).FieldInfo;
352 Console.WriteLine ("{0} and {1}", fi.DeclaringType, fi.Name);
353 e.Error_UnexpectedKind (flags);
359 throw new Exception ("Expression " + e.GetType () +
360 " ExprClass is Invalid after resolve");
364 throw new Exception (
365 "Expression " + e.GetType () +
366 " did not set its type after Resolve\n" +
367 "called from: " + this.GetType ());
373 /// Resolves an expression and performs semantic analysis on it.
375 public Expression Resolve (EmitContext ec)
377 return Resolve (ec, ResolveFlags.VariableOrValue);
381 /// Resolves an expression for LValue assignment
385 /// Currently ResolveLValue wraps DoResolveLValue to perform sanity
386 /// checking and assertion checking on what we expect from Resolve
388 public Expression ResolveLValue (EmitContext ec, Expression right_side)
390 Expression e = DoResolveLValue (ec, right_side);
393 if (e is SimpleName){
394 SimpleName s = (SimpleName) e;
395 MemberLookupFailed (ec, null, ec.ContainerType, s.Name,
396 ec.DeclSpace.Name, loc);
400 if (e.eclass == ExprClass.Invalid)
401 throw new Exception ("Expression " + e +
402 " ExprClass is Invalid after resolve");
404 if (e.eclass == ExprClass.MethodGroup) {
405 ((MethodGroupExpr) e).ReportUsageError ();
410 throw new Exception ("Expression " + e +
411 " did not set its type after Resolve");
418 /// Emits the code for the expression
422 /// The Emit method is invoked to generate the code
423 /// for the expression.
425 public abstract void Emit (EmitContext ec);
427 public virtual void EmitBranchable (EmitContext ec, Label target, bool onTrue)
430 ec.ig.Emit (onTrue ? OpCodes.Brtrue : OpCodes.Brfalse, target);
434 /// Protected constructor. Only derivate types should
435 /// be able to be created
438 protected Expression ()
440 eclass = ExprClass.Invalid;
445 /// Returns a literalized version of a literal FieldInfo
449 /// The possible return values are:
450 /// IntConstant, UIntConstant
451 /// LongLiteral, ULongConstant
452 /// FloatConstant, DoubleConstant
455 /// The value returned is already resolved.
457 public static Constant Constantify (object v, Type t)
459 if (t == TypeManager.int32_type)
460 return new IntConstant ((int) v);
461 else if (t == TypeManager.uint32_type)
462 return new UIntConstant ((uint) v);
463 else if (t == TypeManager.int64_type)
464 return new LongConstant ((long) v);
465 else if (t == TypeManager.uint64_type)
466 return new ULongConstant ((ulong) v);
467 else if (t == TypeManager.float_type)
468 return new FloatConstant ((float) v);
469 else if (t == TypeManager.double_type)
470 return new DoubleConstant ((double) v);
471 else if (t == TypeManager.string_type)
472 return new StringConstant ((string) v);
473 else if (t == TypeManager.short_type)
474 return new ShortConstant ((short)v);
475 else if (t == TypeManager.ushort_type)
476 return new UShortConstant ((ushort)v);
477 else if (t == TypeManager.sbyte_type)
478 return new SByteConstant (((sbyte)v));
479 else if (t == TypeManager.byte_type)
480 return new ByteConstant ((byte)v);
481 else if (t == TypeManager.char_type)
482 return new CharConstant ((char)v);
483 else if (t == TypeManager.bool_type)
484 return new BoolConstant ((bool) v);
485 else if (TypeManager.IsEnumType (t)){
486 Type real_type = TypeManager.TypeToCoreType (v.GetType ());
488 real_type = real_type.UnderlyingSystemType;
490 Constant e = Constantify (v, real_type);
492 return new EnumConstant (e, t);
494 throw new Exception ("Unknown type for constant (" + t +
499 /// Returns a fully formed expression after a MemberLookup
501 public static Expression ExprClassFromMemberInfo (EmitContext ec, MemberInfo mi, Location loc)
504 return new EventExpr ((EventInfo) mi, loc);
505 else if (mi is FieldInfo)
506 return new FieldExpr ((FieldInfo) mi, loc);
507 else if (mi is PropertyInfo)
508 return new PropertyExpr (ec, (PropertyInfo) mi, loc);
509 else if (mi is Type){
510 return new TypeExpression ((System.Type) mi, loc);
517 private static ArrayList almostMatchedMembers = new ArrayList (4);
520 // FIXME: Probably implement a cache for (t,name,current_access_set)?
522 // This code could use some optimizations, but we need to do some
523 // measurements. For example, we could use a delegate to `flag' when
524 // something can not any longer be a method-group (because it is something
528 // If the return value is an Array, then it is an array of
531 // If the return value is an MemberInfo, it is anything, but a Method
535 // FIXME: When calling MemberLookup inside an `Invocation', we should pass
536 // the arguments here and have MemberLookup return only the methods that
537 // match the argument count/type, unlike we are doing now (we delay this
540 // This is so we can catch correctly attempts to invoke instance methods
541 // from a static body (scan for error 120 in ResolveSimpleName).
544 // FIXME: Potential optimization, have a static ArrayList
547 public static Expression MemberLookup (EmitContext ec, Type queried_type, string name,
548 MemberTypes mt, BindingFlags bf, Location loc)
550 return MemberLookup (ec, ec.ContainerType, null, queried_type, name, mt, bf, loc);
554 // Lookup type `queried_type' for code in class `container_type' with a qualifier of
555 // `qualifier_type' or null to lookup members in the current class.
558 public static Expression MemberLookup (EmitContext ec, Type container_type,
559 Type qualifier_type, Type queried_type,
560 string name, MemberTypes mt,
561 BindingFlags bf, Location loc)
563 almostMatchedMembers.Clear ();
565 MemberInfo [] mi = TypeManager.MemberLookup (container_type, qualifier_type,
566 queried_type, mt, bf, name, almostMatchedMembers);
571 int count = mi.Length;
573 if (mi [0] is MethodBase)
574 return new MethodGroupExpr (mi, loc);
579 return ExprClassFromMemberInfo (ec, mi [0], loc);
582 public const MemberTypes AllMemberTypes =
583 MemberTypes.Constructor |
587 MemberTypes.NestedType |
588 MemberTypes.Property;
590 public const BindingFlags AllBindingFlags =
591 BindingFlags.Public |
592 BindingFlags.Static |
593 BindingFlags.Instance;
595 public static Expression MemberLookup (EmitContext ec, Type queried_type,
596 string name, Location loc)
598 return MemberLookup (ec, ec.ContainerType, null, queried_type, name,
599 AllMemberTypes, AllBindingFlags, loc);
602 public static Expression MemberLookup (EmitContext ec, Type qualifier_type,
603 Type queried_type, string name, Location loc)
605 return MemberLookup (ec, ec.ContainerType, qualifier_type, queried_type,
606 name, AllMemberTypes, AllBindingFlags, loc);
609 public static Expression MethodLookup (EmitContext ec, Type queried_type,
610 string name, Location loc)
612 return MemberLookup (ec, ec.ContainerType, null, queried_type, name,
613 MemberTypes.Method, AllBindingFlags, loc);
617 /// This is a wrapper for MemberLookup that is not used to "probe", but
618 /// to find a final definition. If the final definition is not found, we
619 /// look for private members and display a useful debugging message if we
622 public static Expression MemberLookupFinal (EmitContext ec, Type qualifier_type,
623 Type queried_type, string name, Location loc)
625 return MemberLookupFinal (ec, qualifier_type, queried_type, name,
626 AllMemberTypes, AllBindingFlags, loc);
629 public static Expression MemberLookupFinal (EmitContext ec, Type qualifier_type,
630 Type queried_type, string name,
631 MemberTypes mt, BindingFlags bf,
636 int errors = Report.Errors;
638 e = MemberLookup (ec, ec.ContainerType, qualifier_type, queried_type, name, mt, bf, loc);
640 if (e == null && errors == Report.Errors)
641 // No errors were reported by MemberLookup, but there was an error.
642 MemberLookupFailed (ec, qualifier_type, queried_type, name, null, loc);
647 public static void MemberLookupFailed (EmitContext ec, Type qualifier_type,
648 Type queried_type, string name,
649 string class_name, Location loc)
651 if (almostMatchedMembers.Count != 0) {
652 if (qualifier_type == null) {
653 foreach (MemberInfo m in almostMatchedMembers)
654 Report.Error (38, loc,
655 "Cannot access non-static member `{0}' via nested type `{1}'",
656 TypeManager.GetFullNameSignature (m),
657 TypeManager.CSharpName (ec.ContainerType));
661 if (qualifier_type != ec.ContainerType) {
662 // Although a derived class can access protected members of
663 // its base class it cannot do so through an instance of the
664 // base class (CS1540). If the qualifier_type is a parent of the
665 // ec.ContainerType and the lookup succeeds with the latter one,
666 // then we are in this situation.
667 foreach (MemberInfo m in almostMatchedMembers)
668 Report.Error (1540, loc,
669 "Cannot access protected member `{0}' via a qualifier of type `{1}';"
670 + " the qualifier must be of type `{2}' (or derived from it)",
671 TypeManager.GetFullNameSignature (m),
672 TypeManager.CSharpName (qualifier_type),
673 TypeManager.CSharpName (ec.ContainerType));
676 almostMatchedMembers.Clear ();
679 object lookup = TypeManager.MemberLookup (queried_type, null, queried_type,
680 AllMemberTypes, AllBindingFlags |
681 BindingFlags.NonPublic, name, null);
683 if (lookup == null) {
684 if (class_name != null)
685 Report.Error (103, loc, "The name `" + name + "' could not be " +
686 "found in `" + class_name + "'");
689 117, loc, "`" + queried_type + "' does not contain a " +
690 "definition for `" + name + "'");
694 if (qualifier_type != null)
695 Report.Error_T (122, loc, TypeManager.CSharpName (qualifier_type) + "." + name);
696 else if (name == ".ctor") {
697 Report.Error (143, loc, String.Format ("The type {0} has no constructors defined",
698 TypeManager.CSharpName (queried_type)));
700 Report.Error_T (122, loc, name);
704 static public MemberInfo GetFieldFromEvent (EventExpr event_expr)
706 EventInfo ei = event_expr.EventInfo;
708 return TypeManager.GetPrivateFieldOfEvent (ei);
712 /// Returns an expression that can be used to invoke operator true
713 /// on the expression if it exists.
715 static public StaticCallExpr GetOperatorTrue (EmitContext ec, Expression e, Location loc)
717 return GetOperatorTrueOrFalse (ec, e, true, loc);
721 /// Returns an expression that can be used to invoke operator false
722 /// on the expression if it exists.
724 static public StaticCallExpr GetOperatorFalse (EmitContext ec, Expression e, Location loc)
726 return GetOperatorTrueOrFalse (ec, e, false, loc);
729 static StaticCallExpr GetOperatorTrueOrFalse (EmitContext ec, Expression e, bool is_true, Location loc)
732 Expression operator_group;
734 operator_group = MethodLookup (ec, e.Type, is_true ? "op_True" : "op_False", loc);
735 if (operator_group == null)
738 ArrayList arguments = new ArrayList ();
739 arguments.Add (new Argument (e, Argument.AType.Expression));
740 method = Invocation.OverloadResolve (ec, (MethodGroupExpr) operator_group, arguments, loc);
745 return new StaticCallExpr ((MethodInfo) method, arguments, loc);
749 /// Resolves the expression `e' into a boolean expression: either through
750 /// an implicit conversion, or through an `operator true' invocation
752 public static Expression ResolveBoolean (EmitContext ec, Expression e, Location loc)
758 Expression converted = e;
759 if (e.Type != TypeManager.bool_type)
760 converted = Convert.ImplicitConversion (ec, e, TypeManager.bool_type, new Location (-1));
763 // If no implicit conversion to bool exists, try using `operator true'
765 if (converted == null){
766 Expression operator_true = Expression.GetOperatorTrue (ec, e, loc);
767 if (operator_true == null){
769 31, loc, "Can not convert the expression to a boolean");
779 static string ExprClassName (ExprClass c)
782 case ExprClass.Invalid:
784 case ExprClass.Value:
786 case ExprClass.Variable:
788 case ExprClass.Namespace:
792 case ExprClass.MethodGroup:
793 return "method group";
794 case ExprClass.PropertyAccess:
795 return "property access";
796 case ExprClass.EventAccess:
797 return "event access";
798 case ExprClass.IndexerAccess:
799 return "indexer access";
800 case ExprClass.Nothing:
803 throw new Exception ("Should not happen");
807 /// Reports that we were expecting `expr' to be of class `expected'
809 public void Error_UnexpectedKind (string expected)
811 string kind = "Unknown";
813 kind = ExprClassName (eclass);
815 Error (118, "Expression denotes a `" + kind +
816 "' where a `" + expected + "' was expected");
819 public void Error_UnexpectedKind (ResolveFlags flags)
821 ArrayList valid = new ArrayList (10);
823 if ((flags & ResolveFlags.VariableOrValue) != 0) {
824 valid.Add ("variable");
828 if ((flags & ResolveFlags.Type) != 0)
831 if ((flags & ResolveFlags.MethodGroup) != 0)
832 valid.Add ("method group");
834 if ((flags & ResolveFlags.SimpleName) != 0)
835 valid.Add ("simple name");
837 if (valid.Count == 0)
838 valid.Add ("unknown");
840 StringBuilder sb = new StringBuilder ();
841 for (int i = 0; i < valid.Count; i++) {
844 else if (i == valid.Count)
846 sb.Append (valid [i]);
849 string kind = ExprClassName (eclass);
851 Error (119, "Expression denotes a `" + kind + "' where " +
852 "a `" + sb.ToString () + "' was expected");
855 static public void Error_ConstantValueCannotBeConverted (Location l, string val, Type t)
857 Report.Error (31, l, "Constant value `" + val + "' cannot be converted to " +
858 TypeManager.CSharpName (t));
861 public static void UnsafeError (Location loc)
863 Report.Error (214, loc, "Pointers may only be used in an unsafe context");
867 /// Converts the IntConstant, UIntConstant, LongConstant or
868 /// ULongConstant into the integral target_type. Notice
869 /// that we do not return an `Expression' we do return
870 /// a boxed integral type.
872 /// FIXME: Since I added the new constants, we need to
873 /// also support conversions from CharConstant, ByteConstant,
874 /// SByteConstant, UShortConstant, ShortConstant
876 /// This is used by the switch statement, so the domain
877 /// of work is restricted to the literals above, and the
878 /// targets are int32, uint32, char, byte, sbyte, ushort,
879 /// short, uint64 and int64
881 public static object ConvertIntLiteral (Constant c, Type target_type, Location loc)
883 if (!Convert.ImplicitStandardConversionExists (c, target_type)){
884 Convert.Error_CannotImplicitConversion (loc, c.Type, target_type);
890 if (c.Type == target_type)
891 return ((Constant) c).GetValue ();
894 // Make into one of the literals we handle, we dont really care
895 // about this value as we will just return a few limited types
897 if (c is EnumConstant)
898 c = ((EnumConstant)c).WidenToCompilerConstant ();
900 if (c is IntConstant){
901 int v = ((IntConstant) c).Value;
903 if (target_type == TypeManager.uint32_type){
906 } else if (target_type == TypeManager.char_type){
907 if (v >= Char.MinValue && v <= Char.MaxValue)
909 } else if (target_type == TypeManager.byte_type){
910 if (v >= Byte.MinValue && v <= Byte.MaxValue)
912 } else if (target_type == TypeManager.sbyte_type){
913 if (v >= SByte.MinValue && v <= SByte.MaxValue)
915 } else if (target_type == TypeManager.short_type){
916 if (v >= Int16.MinValue && v <= UInt16.MaxValue)
918 } else if (target_type == TypeManager.ushort_type){
919 if (v >= UInt16.MinValue && v <= UInt16.MaxValue)
921 } else if (target_type == TypeManager.int64_type)
923 else if (target_type == TypeManager.uint64_type){
929 } else if (c is UIntConstant){
930 uint v = ((UIntConstant) c).Value;
932 if (target_type == TypeManager.int32_type){
933 if (v <= Int32.MaxValue)
935 } else if (target_type == TypeManager.char_type){
936 if (v >= Char.MinValue && v <= Char.MaxValue)
938 } else if (target_type == TypeManager.byte_type){
939 if (v <= Byte.MaxValue)
941 } else if (target_type == TypeManager.sbyte_type){
942 if (v <= SByte.MaxValue)
944 } else if (target_type == TypeManager.short_type){
945 if (v <= UInt16.MaxValue)
947 } else if (target_type == TypeManager.ushort_type){
948 if (v <= UInt16.MaxValue)
950 } else if (target_type == TypeManager.int64_type)
952 else if (target_type == TypeManager.uint64_type)
955 } else if (c is LongConstant){
956 long v = ((LongConstant) c).Value;
958 if (target_type == TypeManager.int32_type){
959 if (v >= UInt32.MinValue && v <= UInt32.MaxValue)
961 } else if (target_type == TypeManager.uint32_type){
962 if (v >= 0 && v <= UInt32.MaxValue)
964 } else if (target_type == TypeManager.char_type){
965 if (v >= Char.MinValue && v <= Char.MaxValue)
967 } else if (target_type == TypeManager.byte_type){
968 if (v >= Byte.MinValue && v <= Byte.MaxValue)
970 } else if (target_type == TypeManager.sbyte_type){
971 if (v >= SByte.MinValue && v <= SByte.MaxValue)
973 } else if (target_type == TypeManager.short_type){
974 if (v >= Int16.MinValue && v <= UInt16.MaxValue)
976 } else if (target_type == TypeManager.ushort_type){
977 if (v >= UInt16.MinValue && v <= UInt16.MaxValue)
979 } else if (target_type == TypeManager.uint64_type){
984 } else if (c is ULongConstant){
985 ulong v = ((ULongConstant) c).Value;
987 if (target_type == TypeManager.int32_type){
988 if (v <= Int32.MaxValue)
990 } else if (target_type == TypeManager.uint32_type){
991 if (v <= UInt32.MaxValue)
993 } else if (target_type == TypeManager.char_type){
994 if (v >= Char.MinValue && v <= Char.MaxValue)
996 } else if (target_type == TypeManager.byte_type){
997 if (v >= Byte.MinValue && v <= Byte.MaxValue)
999 } else if (target_type == TypeManager.sbyte_type){
1000 if (v <= (int) SByte.MaxValue)
1002 } else if (target_type == TypeManager.short_type){
1003 if (v <= UInt16.MaxValue)
1005 } else if (target_type == TypeManager.ushort_type){
1006 if (v <= UInt16.MaxValue)
1008 } else if (target_type == TypeManager.int64_type){
1009 if (v <= Int64.MaxValue)
1013 } else if (c is ByteConstant){
1014 byte v = ((ByteConstant) c).Value;
1016 if (target_type == TypeManager.int32_type)
1018 else if (target_type == TypeManager.uint32_type)
1020 else if (target_type == TypeManager.char_type)
1022 else if (target_type == TypeManager.sbyte_type){
1023 if (v <= SByte.MaxValue)
1025 } else if (target_type == TypeManager.short_type)
1027 else if (target_type == TypeManager.ushort_type)
1029 else if (target_type == TypeManager.int64_type)
1031 else if (target_type == TypeManager.uint64_type)
1034 } else if (c is SByteConstant){
1035 sbyte v = ((SByteConstant) c).Value;
1037 if (target_type == TypeManager.int32_type)
1039 else if (target_type == TypeManager.uint32_type){
1042 } else if (target_type == TypeManager.char_type){
1045 } else if (target_type == TypeManager.byte_type){
1048 } else if (target_type == TypeManager.short_type)
1050 else if (target_type == TypeManager.ushort_type){
1053 } else if (target_type == TypeManager.int64_type)
1055 else if (target_type == TypeManager.uint64_type){
1060 } else if (c is ShortConstant){
1061 short v = ((ShortConstant) c).Value;
1063 if (target_type == TypeManager.int32_type){
1065 } else if (target_type == TypeManager.uint32_type){
1068 } else if (target_type == TypeManager.char_type){
1071 } else if (target_type == TypeManager.byte_type){
1072 if (v >= Byte.MinValue && v <= Byte.MaxValue)
1074 } else if (target_type == TypeManager.sbyte_type){
1075 if (v >= SByte.MinValue && v <= SByte.MaxValue)
1077 } else if (target_type == TypeManager.ushort_type){
1080 } else if (target_type == TypeManager.int64_type)
1082 else if (target_type == TypeManager.uint64_type)
1086 } else if (c is UShortConstant){
1087 ushort v = ((UShortConstant) c).Value;
1089 if (target_type == TypeManager.int32_type)
1091 else if (target_type == TypeManager.uint32_type)
1093 else if (target_type == TypeManager.char_type){
1094 if (v >= Char.MinValue && v <= Char.MaxValue)
1096 } else if (target_type == TypeManager.byte_type){
1097 if (v >= Byte.MinValue && v <= Byte.MaxValue)
1099 } else if (target_type == TypeManager.sbyte_type){
1100 if (v <= SByte.MaxValue)
1102 } else if (target_type == TypeManager.short_type){
1103 if (v <= Int16.MaxValue)
1105 } else if (target_type == TypeManager.int64_type)
1107 else if (target_type == TypeManager.uint64_type)
1111 } else if (c is CharConstant){
1112 char v = ((CharConstant) c).Value;
1114 if (target_type == TypeManager.int32_type)
1116 else if (target_type == TypeManager.uint32_type)
1118 else if (target_type == TypeManager.byte_type){
1119 if (v >= Byte.MinValue && v <= Byte.MaxValue)
1121 } else if (target_type == TypeManager.sbyte_type){
1122 if (v <= SByte.MaxValue)
1124 } else if (target_type == TypeManager.short_type){
1125 if (v <= Int16.MaxValue)
1127 } else if (target_type == TypeManager.ushort_type)
1129 else if (target_type == TypeManager.int64_type)
1131 else if (target_type == TypeManager.uint64_type)
1136 Error_ConstantValueCannotBeConverted (loc, s, target_type);
1141 // Load the object from the pointer.
1143 public static void LoadFromPtr (ILGenerator ig, Type t)
1145 if (t == TypeManager.int32_type)
1146 ig.Emit (OpCodes.Ldind_I4);
1147 else if (t == TypeManager.uint32_type)
1148 ig.Emit (OpCodes.Ldind_U4);
1149 else if (t == TypeManager.short_type)
1150 ig.Emit (OpCodes.Ldind_I2);
1151 else if (t == TypeManager.ushort_type)
1152 ig.Emit (OpCodes.Ldind_U2);
1153 else if (t == TypeManager.char_type)
1154 ig.Emit (OpCodes.Ldind_U2);
1155 else if (t == TypeManager.byte_type)
1156 ig.Emit (OpCodes.Ldind_U1);
1157 else if (t == TypeManager.sbyte_type)
1158 ig.Emit (OpCodes.Ldind_I1);
1159 else if (t == TypeManager.uint64_type)
1160 ig.Emit (OpCodes.Ldind_I8);
1161 else if (t == TypeManager.int64_type)
1162 ig.Emit (OpCodes.Ldind_I8);
1163 else if (t == TypeManager.float_type)
1164 ig.Emit (OpCodes.Ldind_R4);
1165 else if (t == TypeManager.double_type)
1166 ig.Emit (OpCodes.Ldind_R8);
1167 else if (t == TypeManager.bool_type)
1168 ig.Emit (OpCodes.Ldind_I1);
1169 else if (t == TypeManager.intptr_type)
1170 ig.Emit (OpCodes.Ldind_I);
1171 else if (TypeManager.IsEnumType (t)) {
1172 if (t == TypeManager.enum_type)
1173 ig.Emit (OpCodes.Ldind_Ref);
1175 LoadFromPtr (ig, TypeManager.EnumToUnderlying (t));
1176 } else if (t.IsValueType)
1177 ig.Emit (OpCodes.Ldobj, t);
1178 else if (t.IsPointer)
1179 ig.Emit (OpCodes.Ldind_I);
1181 ig.Emit (OpCodes.Ldind_Ref);
1185 // The stack contains the pointer and the value of type `type'
1187 public static void StoreFromPtr (ILGenerator ig, Type type)
1189 if (TypeManager.IsEnumType (type))
1190 type = TypeManager.EnumToUnderlying (type);
1191 if (type == TypeManager.int32_type || type == TypeManager.uint32_type)
1192 ig.Emit (OpCodes.Stind_I4);
1193 else if (type == TypeManager.int64_type || type == TypeManager.uint64_type)
1194 ig.Emit (OpCodes.Stind_I8);
1195 else if (type == TypeManager.char_type || type == TypeManager.short_type ||
1196 type == TypeManager.ushort_type)
1197 ig.Emit (OpCodes.Stind_I2);
1198 else if (type == TypeManager.float_type)
1199 ig.Emit (OpCodes.Stind_R4);
1200 else if (type == TypeManager.double_type)
1201 ig.Emit (OpCodes.Stind_R8);
1202 else if (type == TypeManager.byte_type || type == TypeManager.sbyte_type ||
1203 type == TypeManager.bool_type)
1204 ig.Emit (OpCodes.Stind_I1);
1205 else if (type == TypeManager.intptr_type)
1206 ig.Emit (OpCodes.Stind_I);
1207 else if (type.IsValueType)
1208 ig.Emit (OpCodes.Stobj, type);
1210 ig.Emit (OpCodes.Stind_Ref);
1214 // Returns the size of type `t' if known, otherwise, 0
1216 public static int GetTypeSize (Type t)
1218 t = TypeManager.TypeToCoreType (t);
1219 if (t == TypeManager.int32_type ||
1220 t == TypeManager.uint32_type ||
1221 t == TypeManager.float_type)
1223 else if (t == TypeManager.int64_type ||
1224 t == TypeManager.uint64_type ||
1225 t == TypeManager.double_type)
1227 else if (t == TypeManager.byte_type ||
1228 t == TypeManager.sbyte_type ||
1229 t == TypeManager.bool_type)
1231 else if (t == TypeManager.short_type ||
1232 t == TypeManager.char_type ||
1233 t == TypeManager.ushort_type)
1235 else if (t == TypeManager.decimal_type)
1241 static void Error_NegativeArrayIndex (Location loc)
1243 Report.Error (284, loc, "Can not create array with a negative size");
1247 // Converts `source' to an int, uint, long or ulong.
1249 public Expression ExpressionToArrayArgument (EmitContext ec, Expression source, Location loc)
1253 bool old_checked = ec.CheckState;
1254 ec.CheckState = true;
1256 target = Convert.ImplicitConversion (ec, source, TypeManager.int32_type, loc);
1257 if (target == null){
1258 target = Convert.ImplicitConversion (ec, source, TypeManager.uint32_type, loc);
1259 if (target == null){
1260 target = Convert.ImplicitConversion (ec, source, TypeManager.int64_type, loc);
1261 if (target == null){
1262 target = Convert.ImplicitConversion (ec, source, TypeManager.uint64_type, loc);
1264 Convert.Error_CannotImplicitConversion (loc, source.Type, TypeManager.int32_type);
1268 ec.CheckState = old_checked;
1271 // Only positive constants are allowed at compile time
1273 if (target is Constant){
1274 if (target is IntConstant){
1275 if (((IntConstant) target).Value < 0){
1276 Error_NegativeArrayIndex (loc);
1281 if (target is LongConstant){
1282 if (((LongConstant) target).Value < 0){
1283 Error_NegativeArrayIndex (loc);
1296 /// This is just a base class for expressions that can
1297 /// appear on statements (invocations, object creation,
1298 /// assignments, post/pre increment and decrement). The idea
1299 /// being that they would support an extra Emition interface that
1300 /// does not leave a result on the stack.
1302 public abstract class ExpressionStatement : Expression {
1304 public virtual ExpressionStatement ResolveStatement (EmitContext ec)
1306 Expression e = Resolve (ec);
1310 ExpressionStatement es = e as ExpressionStatement;
1312 Error (201, "Only assignment, call, increment, decrement and new object " +
1313 "expressions can be used as a statement");
1319 /// Requests the expression to be emitted in a `statement'
1320 /// context. This means that no new value is left on the
1321 /// stack after invoking this method (constrasted with
1322 /// Emit that will always leave a value on the stack).
1324 public abstract void EmitStatement (EmitContext ec);
1328 /// This kind of cast is used to encapsulate the child
1329 /// whose type is child.Type into an expression that is
1330 /// reported to return "return_type". This is used to encapsulate
1331 /// expressions which have compatible types, but need to be dealt
1332 /// at higher levels with.
1334 /// For example, a "byte" expression could be encapsulated in one
1335 /// of these as an "unsigned int". The type for the expression
1336 /// would be "unsigned int".
1339 public class EmptyCast : Expression {
1340 protected Expression child;
1342 public Expression Child {
1348 public EmptyCast (Expression child, Type return_type)
1350 eclass = child.eclass;
1355 public override Expression DoResolve (EmitContext ec)
1357 // This should never be invoked, we are born in fully
1358 // initialized state.
1363 public override void Emit (EmitContext ec)
1370 // We need to special case this since an empty cast of
1371 // a NullLiteral is still a Constant
1373 public class NullCast : Constant {
1374 protected Expression child;
1376 public NullCast (Expression child, Type return_type)
1378 eclass = child.eclass;
1383 override public string AsString ()
1388 public override object GetValue ()
1393 public override Expression DoResolve (EmitContext ec)
1395 // This should never be invoked, we are born in fully
1396 // initialized state.
1401 public override void Emit (EmitContext ec)
1409 /// This class is used to wrap literals which belong inside Enums
1411 public class EnumConstant : Constant {
1412 public Constant Child;
1414 public EnumConstant (Constant child, Type enum_type)
1416 eclass = child.eclass;
1421 public override Expression DoResolve (EmitContext ec)
1423 // This should never be invoked, we are born in fully
1424 // initialized state.
1429 public override void Emit (EmitContext ec)
1434 public override object GetValue ()
1436 return Child.GetValue ();
1440 // Converts from one of the valid underlying types for an enumeration
1441 // (int32, uint32, int64, uint64, short, ushort, byte, sbyte) to
1442 // one of the internal compiler literals: Int/UInt/Long/ULong Literals.
1444 public Constant WidenToCompilerConstant ()
1446 Type t = TypeManager.EnumToUnderlying (Child.Type);
1447 object v = ((Constant) Child).GetValue ();;
1449 if (t == TypeManager.int32_type)
1450 return new IntConstant ((int) v);
1451 if (t == TypeManager.uint32_type)
1452 return new UIntConstant ((uint) v);
1453 if (t == TypeManager.int64_type)
1454 return new LongConstant ((long) v);
1455 if (t == TypeManager.uint64_type)
1456 return new ULongConstant ((ulong) v);
1457 if (t == TypeManager.short_type)
1458 return new ShortConstant ((short) v);
1459 if (t == TypeManager.ushort_type)
1460 return new UShortConstant ((ushort) v);
1461 if (t == TypeManager.byte_type)
1462 return new ByteConstant ((byte) v);
1463 if (t == TypeManager.sbyte_type)
1464 return new SByteConstant ((sbyte) v);
1466 throw new Exception ("Invalid enumeration underlying type: " + t);
1470 // Extracts the value in the enumeration on its native representation
1472 public object GetPlainValue ()
1474 Type t = TypeManager.EnumToUnderlying (Child.Type);
1475 object v = ((Constant) Child).GetValue ();;
1477 if (t == TypeManager.int32_type)
1479 if (t == TypeManager.uint32_type)
1481 if (t == TypeManager.int64_type)
1483 if (t == TypeManager.uint64_type)
1485 if (t == TypeManager.short_type)
1487 if (t == TypeManager.ushort_type)
1489 if (t == TypeManager.byte_type)
1491 if (t == TypeManager.sbyte_type)
1497 public override string AsString ()
1499 return Child.AsString ();
1502 public override DoubleConstant ConvertToDouble ()
1504 return Child.ConvertToDouble ();
1507 public override FloatConstant ConvertToFloat ()
1509 return Child.ConvertToFloat ();
1512 public override ULongConstant ConvertToULong ()
1514 return Child.ConvertToULong ();
1517 public override LongConstant ConvertToLong ()
1519 return Child.ConvertToLong ();
1522 public override UIntConstant ConvertToUInt ()
1524 return Child.ConvertToUInt ();
1527 public override IntConstant ConvertToInt ()
1529 return Child.ConvertToInt ();
1532 public override bool IsZeroInteger {
1533 get { return Child.IsZeroInteger; }
1538 /// This kind of cast is used to encapsulate Value Types in objects.
1540 /// The effect of it is to box the value type emitted by the previous
1543 public class BoxedCast : EmptyCast {
1545 public BoxedCast (Expression expr)
1546 : base (expr, TypeManager.object_type)
1548 eclass = ExprClass.Value;
1551 public BoxedCast (Expression expr, Type target_type)
1552 : base (expr, target_type)
1554 eclass = ExprClass.Value;
1557 public override Expression DoResolve (EmitContext ec)
1559 // This should never be invoked, we are born in fully
1560 // initialized state.
1565 public override void Emit (EmitContext ec)
1569 ec.ig.Emit (OpCodes.Box, child.Type);
1573 public class UnboxCast : EmptyCast {
1574 public UnboxCast (Expression expr, Type return_type)
1575 : base (expr, return_type)
1579 public override Expression DoResolve (EmitContext ec)
1581 // This should never be invoked, we are born in fully
1582 // initialized state.
1587 public override void Emit (EmitContext ec)
1590 ILGenerator ig = ec.ig;
1593 ig.Emit (OpCodes.Unbox, t);
1595 LoadFromPtr (ig, t);
1600 /// This is used to perform explicit numeric conversions.
1602 /// Explicit numeric conversions might trigger exceptions in a checked
1603 /// context, so they should generate the conv.ovf opcodes instead of
1606 public class ConvCast : EmptyCast {
1607 public enum Mode : byte {
1608 I1_U1, I1_U2, I1_U4, I1_U8, I1_CH,
1610 I2_I1, I2_U1, I2_U2, I2_U4, I2_U8, I2_CH,
1611 U2_I1, U2_U1, U2_I2, U2_CH,
1612 I4_I1, I4_U1, I4_I2, I4_U2, I4_U4, I4_U8, I4_CH,
1613 U4_I1, U4_U1, U4_I2, U4_U2, U4_I4, U4_CH,
1614 I8_I1, I8_U1, I8_I2, I8_U2, I8_I4, I8_U4, I8_U8, I8_CH,
1615 U8_I1, U8_U1, U8_I2, U8_U2, U8_I4, U8_U4, U8_I8, U8_CH,
1616 CH_I1, CH_U1, CH_I2,
1617 R4_I1, R4_U1, R4_I2, R4_U2, R4_I4, R4_U4, R4_I8, R4_U8, R4_CH,
1618 R8_I1, R8_U1, R8_I2, R8_U2, R8_I4, R8_U4, R8_I8, R8_U8, R8_CH, R8_R4
1624 public ConvCast (EmitContext ec, Expression child, Type return_type, Mode m)
1625 : base (child, return_type)
1627 checked_state = ec.CheckState;
1631 public override Expression DoResolve (EmitContext ec)
1633 // This should never be invoked, we are born in fully
1634 // initialized state.
1639 public override string ToString ()
1641 return String.Format ("ConvCast ({0}, {1})", mode, child);
1644 public override void Emit (EmitContext ec)
1646 ILGenerator ig = ec.ig;
1652 case Mode.I1_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1653 case Mode.I1_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1654 case Mode.I1_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1655 case Mode.I1_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1656 case Mode.I1_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1658 case Mode.U1_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1659 case Mode.U1_CH: /* nothing */ break;
1661 case Mode.I2_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1662 case Mode.I2_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1663 case Mode.I2_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1664 case Mode.I2_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1665 case Mode.I2_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1666 case Mode.I2_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1668 case Mode.U2_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1669 case Mode.U2_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
1670 case Mode.U2_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
1671 case Mode.U2_CH: /* nothing */ break;
1673 case Mode.I4_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1674 case Mode.I4_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1675 case Mode.I4_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
1676 case Mode.I4_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1677 case Mode.I4_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1678 case Mode.I4_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1679 case Mode.I4_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1681 case Mode.U4_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1682 case Mode.U4_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
1683 case Mode.U4_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
1684 case Mode.U4_U2: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
1685 case Mode.U4_I4: ig.Emit (OpCodes.Conv_Ovf_I4_Un); break;
1686 case Mode.U4_CH: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
1688 case Mode.I8_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1689 case Mode.I8_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1690 case Mode.I8_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
1691 case Mode.I8_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1692 case Mode.I8_I4: ig.Emit (OpCodes.Conv_Ovf_I4); break;
1693 case Mode.I8_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1694 case Mode.I8_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1695 case Mode.I8_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1697 case Mode.U8_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1698 case Mode.U8_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
1699 case Mode.U8_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
1700 case Mode.U8_U2: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
1701 case Mode.U8_I4: ig.Emit (OpCodes.Conv_Ovf_I4_Un); break;
1702 case Mode.U8_U4: ig.Emit (OpCodes.Conv_Ovf_U4_Un); break;
1703 case Mode.U8_I8: ig.Emit (OpCodes.Conv_Ovf_I8_Un); break;
1704 case Mode.U8_CH: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
1706 case Mode.CH_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1707 case Mode.CH_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
1708 case Mode.CH_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
1710 case Mode.R4_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1711 case Mode.R4_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1712 case Mode.R4_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
1713 case Mode.R4_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1714 case Mode.R4_I4: ig.Emit (OpCodes.Conv_Ovf_I4); break;
1715 case Mode.R4_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1716 case Mode.R4_I8: ig.Emit (OpCodes.Conv_Ovf_I8); break;
1717 case Mode.R4_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1718 case Mode.R4_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1720 case Mode.R8_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1721 case Mode.R8_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1722 case Mode.R8_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
1723 case Mode.R8_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1724 case Mode.R8_I4: ig.Emit (OpCodes.Conv_Ovf_I4); break;
1725 case Mode.R8_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1726 case Mode.R8_I8: ig.Emit (OpCodes.Conv_Ovf_I8); break;
1727 case Mode.R8_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1728 case Mode.R8_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1729 case Mode.R8_R4: ig.Emit (OpCodes.Conv_R4); break;
1733 case Mode.I1_U1: ig.Emit (OpCodes.Conv_U1); break;
1734 case Mode.I1_U2: ig.Emit (OpCodes.Conv_U2); break;
1735 case Mode.I1_U4: ig.Emit (OpCodes.Conv_U4); break;
1736 case Mode.I1_U8: ig.Emit (OpCodes.Conv_I8); break;
1737 case Mode.I1_CH: ig.Emit (OpCodes.Conv_U2); break;
1739 case Mode.U1_I1: ig.Emit (OpCodes.Conv_I1); break;
1740 case Mode.U1_CH: ig.Emit (OpCodes.Conv_U2); break;
1742 case Mode.I2_I1: ig.Emit (OpCodes.Conv_I1); break;
1743 case Mode.I2_U1: ig.Emit (OpCodes.Conv_U1); break;
1744 case Mode.I2_U2: ig.Emit (OpCodes.Conv_U2); break;
1745 case Mode.I2_U4: ig.Emit (OpCodes.Conv_U4); break;
1746 case Mode.I2_U8: ig.Emit (OpCodes.Conv_I8); break;
1747 case Mode.I2_CH: ig.Emit (OpCodes.Conv_U2); break;
1749 case Mode.U2_I1: ig.Emit (OpCodes.Conv_I1); break;
1750 case Mode.U2_U1: ig.Emit (OpCodes.Conv_U1); break;
1751 case Mode.U2_I2: ig.Emit (OpCodes.Conv_I2); break;
1752 case Mode.U2_CH: /* nothing */ break;
1754 case Mode.I4_I1: ig.Emit (OpCodes.Conv_I1); break;
1755 case Mode.I4_U1: ig.Emit (OpCodes.Conv_U1); break;
1756 case Mode.I4_I2: ig.Emit (OpCodes.Conv_I2); break;
1757 case Mode.I4_U4: /* nothing */ break;
1758 case Mode.I4_U2: ig.Emit (OpCodes.Conv_U2); break;
1759 case Mode.I4_U8: ig.Emit (OpCodes.Conv_I8); break;
1760 case Mode.I4_CH: ig.Emit (OpCodes.Conv_U2); break;
1762 case Mode.U4_I1: ig.Emit (OpCodes.Conv_I1); break;
1763 case Mode.U4_U1: ig.Emit (OpCodes.Conv_U1); break;
1764 case Mode.U4_I2: ig.Emit (OpCodes.Conv_I2); break;
1765 case Mode.U4_U2: ig.Emit (OpCodes.Conv_U2); break;
1766 case Mode.U4_I4: /* nothing */ break;
1767 case Mode.U4_CH: ig.Emit (OpCodes.Conv_U2); break;
1769 case Mode.I8_I1: ig.Emit (OpCodes.Conv_I1); break;
1770 case Mode.I8_U1: ig.Emit (OpCodes.Conv_U1); break;
1771 case Mode.I8_I2: ig.Emit (OpCodes.Conv_I2); break;
1772 case Mode.I8_U2: ig.Emit (OpCodes.Conv_U2); break;
1773 case Mode.I8_I4: ig.Emit (OpCodes.Conv_I4); break;
1774 case Mode.I8_U4: ig.Emit (OpCodes.Conv_U4); break;
1775 case Mode.I8_U8: /* nothing */ break;
1776 case Mode.I8_CH: ig.Emit (OpCodes.Conv_U2); break;
1778 case Mode.U8_I1: ig.Emit (OpCodes.Conv_I1); break;
1779 case Mode.U8_U1: ig.Emit (OpCodes.Conv_U1); break;
1780 case Mode.U8_I2: ig.Emit (OpCodes.Conv_I2); break;
1781 case Mode.U8_U2: ig.Emit (OpCodes.Conv_U2); break;
1782 case Mode.U8_I4: ig.Emit (OpCodes.Conv_I4); break;
1783 case Mode.U8_U4: ig.Emit (OpCodes.Conv_U4); break;
1784 case Mode.U8_I8: /* nothing */ break;
1785 case Mode.U8_CH: ig.Emit (OpCodes.Conv_U2); break;
1787 case Mode.CH_I1: ig.Emit (OpCodes.Conv_I1); break;
1788 case Mode.CH_U1: ig.Emit (OpCodes.Conv_U1); break;
1789 case Mode.CH_I2: ig.Emit (OpCodes.Conv_I2); break;
1791 case Mode.R4_I1: ig.Emit (OpCodes.Conv_I1); break;
1792 case Mode.R4_U1: ig.Emit (OpCodes.Conv_U1); break;
1793 case Mode.R4_I2: ig.Emit (OpCodes.Conv_I2); break;
1794 case Mode.R4_U2: ig.Emit (OpCodes.Conv_U2); break;
1795 case Mode.R4_I4: ig.Emit (OpCodes.Conv_I4); break;
1796 case Mode.R4_U4: ig.Emit (OpCodes.Conv_U4); break;
1797 case Mode.R4_I8: ig.Emit (OpCodes.Conv_I8); break;
1798 case Mode.R4_U8: ig.Emit (OpCodes.Conv_U8); break;
1799 case Mode.R4_CH: ig.Emit (OpCodes.Conv_U2); break;
1801 case Mode.R8_I1: ig.Emit (OpCodes.Conv_I1); break;
1802 case Mode.R8_U1: ig.Emit (OpCodes.Conv_U1); break;
1803 case Mode.R8_I2: ig.Emit (OpCodes.Conv_I2); break;
1804 case Mode.R8_U2: ig.Emit (OpCodes.Conv_U2); break;
1805 case Mode.R8_I4: ig.Emit (OpCodes.Conv_I4); break;
1806 case Mode.R8_U4: ig.Emit (OpCodes.Conv_U4); break;
1807 case Mode.R8_I8: ig.Emit (OpCodes.Conv_I8); break;
1808 case Mode.R8_U8: ig.Emit (OpCodes.Conv_U8); break;
1809 case Mode.R8_CH: ig.Emit (OpCodes.Conv_U2); break;
1810 case Mode.R8_R4: ig.Emit (OpCodes.Conv_R4); break;
1816 public class OpcodeCast : EmptyCast {
1820 public OpcodeCast (Expression child, Type return_type, OpCode op)
1821 : base (child, return_type)
1825 second_valid = false;
1828 public OpcodeCast (Expression child, Type return_type, OpCode op, OpCode op2)
1829 : base (child, return_type)
1834 second_valid = true;
1837 public override Expression DoResolve (EmitContext ec)
1839 // This should never be invoked, we are born in fully
1840 // initialized state.
1845 public override void Emit (EmitContext ec)
1856 /// This kind of cast is used to encapsulate a child and cast it
1857 /// to the class requested
1859 public class ClassCast : EmptyCast {
1860 public ClassCast (Expression child, Type return_type)
1861 : base (child, return_type)
1866 public override Expression DoResolve (EmitContext ec)
1868 // This should never be invoked, we are born in fully
1869 // initialized state.
1874 public override void Emit (EmitContext ec)
1878 ec.ig.Emit (OpCodes.Castclass, type);
1884 /// SimpleName expressions are initially formed of a single
1885 /// word and it only happens at the beginning of the expression.
1889 /// The expression will try to be bound to a Field, a Method
1890 /// group or a Property. If those fail we pass the name to our
1891 /// caller and the SimpleName is compounded to perform a type
1892 /// lookup. The idea behind this process is that we want to avoid
1893 /// creating a namespace map from the assemblies, as that requires
1894 /// the GetExportedTypes function to be called and a hashtable to
1895 /// be constructed which reduces startup time. If later we find
1896 /// that this is slower, we should create a `NamespaceExpr' expression
1897 /// that fully participates in the resolution process.
1899 /// For example `System.Console.WriteLine' is decomposed into
1900 /// MemberAccess (MemberAccess (SimpleName ("System"), "Console"), "WriteLine")
1902 /// The first SimpleName wont produce a match on its own, so it will
1904 /// MemberAccess (SimpleName ("System.Console"), "WriteLine").
1906 /// System.Console will produce a TypeExpr match.
1908 /// The downside of this is that we might be hitting `LookupType' too many
1909 /// times with this scheme.
1911 public class SimpleName : Expression {
1915 // If true, then we are a simple name, not composed with a ".
1919 public SimpleName (string a, string b, Location l)
1921 Name = String.Concat (a, ".", b);
1926 public SimpleName (string name, Location l)
1933 public static void Error_ObjectRefRequired (EmitContext ec, Location l, string name)
1935 if (ec.IsFieldInitializer)
1938 "A field initializer cannot reference the non-static field, " +
1939 "method or property `"+name+"'");
1943 "An object reference is required " +
1944 "for the non-static field `"+name+"'");
1948 // Checks whether we are trying to access an instance
1949 // property, method or field from a static body.
1951 Expression MemberStaticCheck (EmitContext ec, Expression e)
1953 if (e is IMemberExpr){
1954 IMemberExpr member = (IMemberExpr) e;
1956 if (!member.IsStatic){
1957 Error_ObjectRefRequired (ec, loc, Name);
1965 public override Expression DoResolve (EmitContext ec)
1967 return SimpleNameResolve (ec, null, false, false);
1970 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
1972 return SimpleNameResolve (ec, right_side, false, false);
1976 public Expression DoResolveAllowStatic (EmitContext ec, bool intermediate)
1978 return SimpleNameResolve (ec, null, true, intermediate);
1981 public override Expression ResolveAsTypeStep (EmitContext ec)
1983 DeclSpace ds = ec.DeclSpace;
1984 NamespaceEntry ns = ds.NamespaceEntry;
1989 // Since we are cheating: we only do the Alias lookup for
1990 // namespaces if the name does not include any dots in it
1992 if (ns != null && is_base)
1993 alias_value = ns.LookupAlias (Name);
1997 if (ec.ResolvingTypeTree){
1998 int errors = Report.Errors;
1999 Type dt = ds.FindType (loc, Name);
2001 if (Report.Errors != errors)
2005 return new TypeExpression (dt, loc);
2007 if (alias_value != null){
2008 if ((t = RootContext.LookupType (ds, alias_value, true, loc)) != null)
2009 return new TypeExpression (t, loc);
2014 // First, the using aliases
2016 if (alias_value != null){
2017 if ((t = RootContext.LookupType (ds, alias_value, true, loc)) != null)
2018 return new TypeExpression (t, loc);
2020 // we have alias value, but it isn't Type, so try if it's namespace
2021 return new SimpleName (alias_value, loc);
2025 // Stage 2: Lookup up if we are an alias to a type
2029 if ((t = RootContext.LookupType (ds, Name, true, loc)) != null)
2030 return new TypeExpression (t, loc);
2032 // No match, maybe our parent can compose us
2033 // into something meaningful.
2037 Expression SimpleNameResolve (EmitContext ec, Expression right_side,
2038 bool allow_static, bool intermediate)
2040 Expression e = DoSimpleNameResolve (ec, right_side, allow_static, intermediate);
2044 Block current_block = ec.CurrentBlock;
2045 if (current_block != null){
2046 LocalInfo vi = current_block.GetLocalInfo (Name);
2048 current_block.IsVariableNameUsedInChildBlock(Name)) {
2049 Report.Error (135, Location,
2050 "'{0}' has a different meaning in a " +
2051 "child block", Name);
2060 /// 7.5.2: Simple Names.
2062 /// Local Variables and Parameters are handled at
2063 /// parse time, so they never occur as SimpleNames.
2065 /// The `allow_static' flag is used by MemberAccess only
2066 /// and it is used to inform us that it is ok for us to
2067 /// avoid the static check, because MemberAccess might end
2068 /// up resolving the Name as a Type name and the access as
2069 /// a static type access.
2071 /// ie: Type Type; .... { Type.GetType (""); }
2073 /// Type is both an instance variable and a Type; Type.GetType
2074 /// is the static method not an instance method of type.
2076 Expression DoSimpleNameResolve (EmitContext ec, Expression right_side, bool allow_static, bool intermediate)
2078 Expression e = null;
2081 // Stage 1: Performed by the parser (binding to locals or parameters).
2083 Block current_block = ec.CurrentBlock;
2084 if (current_block != null){
2085 LocalInfo vi = current_block.GetLocalInfo (Name);
2089 var = new LocalVariableReference (ec.CurrentBlock, Name, loc);
2091 if (right_side != null)
2092 return var.ResolveLValue (ec, right_side);
2094 return var.Resolve (ec);
2098 Parameter par = null;
2099 Parameters pars = current_block.Parameters;
2101 par = pars.GetParameterByName (Name, out idx);
2104 ParameterReference param;
2106 param = new ParameterReference (pars, current_block, idx, Name, loc);
2108 if (right_side != null)
2109 return param.ResolveLValue (ec, right_side);
2111 return param.Resolve (ec);
2116 // Stage 2: Lookup members
2119 DeclSpace lookup_ds = ec.DeclSpace;
2121 if (lookup_ds.TypeBuilder == null)
2124 e = MemberLookup (ec, lookup_ds.TypeBuilder, Name, loc);
2128 lookup_ds =lookup_ds.Parent;
2129 } while (lookup_ds != null);
2131 if (e == null && ec.ContainerType != null)
2132 e = MemberLookup (ec, ec.ContainerType, Name, loc);
2136 // Since we are cheating (is_base is our hint
2137 // that we are the beginning of the name): we
2138 // only do the Alias lookup for namespaces if
2139 // the name does not include any dots in it
2141 NamespaceEntry ns = ec.DeclSpace.NamespaceEntry;
2142 if (is_base && ns != null){
2143 string alias_value = ns.LookupAlias (Name);
2144 if (alias_value != null){
2148 if ((t = TypeManager.LookupType (Name)) != null)
2149 return new TypeExpression (t, loc);
2151 // No match, maybe our parent can compose us
2152 // into something meaningful.
2157 return ResolveAsTypeStep (ec);
2163 if (e is IMemberExpr) {
2164 e = MemberAccess.ResolveMemberAccess (ec, e, null, loc, this);
2168 IMemberExpr me = e as IMemberExpr;
2172 // This fails if ResolveMemberAccess() was unable to decide whether
2173 // it's a field or a type of the same name.
2175 if (!me.IsStatic && (me.InstanceExpression == null))
2179 TypeManager.IsSubclassOrNestedChildOf (me.InstanceExpression.Type, me.DeclaringType) &&
2180 me.InstanceExpression.Type != me.DeclaringType &&
2181 !me.InstanceExpression.Type.IsSubclassOf (me.DeclaringType) &&
2182 (!intermediate || !MemberAccess.IdenticalNameAndTypeName (ec, this, e, loc))) {
2183 Error (38, "Cannot access nonstatic member `" + me.Name + "' of " +
2184 "outer type `" + me.DeclaringType + "' via nested type `" +
2185 me.InstanceExpression.Type + "'");
2189 return (right_side != null)
2190 ? e.DoResolveLValue (ec, right_side)
2194 if (ec.IsStatic || ec.IsFieldInitializer){
2198 return MemberStaticCheck (ec, e);
2203 public override void Emit (EmitContext ec)
2206 // If this is ever reached, then we failed to
2207 // find the name as a namespace
2210 Error (103, "The name `" + Name +
2211 "' does not exist in the class `" +
2212 ec.DeclSpace.Name + "'");
2215 public override string ToString ()
2222 /// Fully resolved expression that evaluates to a type
2224 public abstract class TypeExpr : Expression {
2225 override public Expression ResolveAsTypeStep (EmitContext ec)
2227 TypeExpr t = DoResolveAsTypeStep (ec);
2231 eclass = ExprClass.Type;
2235 override public Expression DoResolve (EmitContext ec)
2237 return ResolveAsTypeTerminal (ec);
2240 override public void Emit (EmitContext ec)
2242 throw new Exception ("Should never be called");
2245 public virtual bool CheckAccessLevel (DeclSpace ds)
2247 return ds.CheckAccessLevel (Type);
2250 public virtual bool AsAccessible (DeclSpace ds, int flags)
2252 return ds.AsAccessible (Type, flags);
2255 public virtual bool IsClass {
2256 get { return Type.IsClass; }
2259 public virtual bool IsValueType {
2260 get { return Type.IsValueType; }
2263 public virtual bool IsInterface {
2264 get { return Type.IsInterface; }
2267 public virtual bool IsSealed {
2268 get { return Type.IsSealed; }
2271 public virtual bool CanInheritFrom ()
2273 if (Type == TypeManager.enum_type ||
2274 (Type == TypeManager.value_type && RootContext.StdLib) ||
2275 Type == TypeManager.multicast_delegate_type ||
2276 Type == TypeManager.delegate_type ||
2277 Type == TypeManager.array_type)
2283 public virtual bool IsAttribute {
2285 return Type == TypeManager.attribute_type ||
2286 Type.IsSubclassOf (TypeManager.attribute_type);
2290 public virtual TypeExpr[] GetInterfaces ()
2292 return TypeManager.GetInterfaces (Type);
2295 public abstract TypeExpr DoResolveAsTypeStep (EmitContext ec);
2297 public virtual Type ResolveType (EmitContext ec)
2299 TypeExpr t = ResolveAsTypeTerminal (ec);
2306 public abstract string Name {
2310 public override bool Equals (object obj)
2312 TypeExpr tobj = obj as TypeExpr;
2316 return Type == tobj.Type;
2319 public override int GetHashCode ()
2321 return Type.GetHashCode ();
2324 public override string ToString ()
2330 public class TypeExpression : TypeExpr {
2331 public TypeExpression (Type t, Location l)
2334 eclass = ExprClass.Type;
2338 public override TypeExpr DoResolveAsTypeStep (EmitContext ec)
2343 public override string Name {
2345 return Type.ToString ();
2351 /// Used to create types from a fully qualified name. These are just used
2352 /// by the parser to setup the core types. A TypeLookupExpression is always
2353 /// classified as a type.
2355 public class TypeLookupExpression : TypeExpr {
2358 public TypeLookupExpression (string name)
2363 public override TypeExpr DoResolveAsTypeStep (EmitContext ec)
2366 type = RootContext.LookupType (ec.DeclSpace, name, false, Location.Null);
2370 public override string Name {
2378 /// MethodGroup Expression.
2380 /// This is a fully resolved expression that evaluates to a type
2382 public class MethodGroupExpr : Expression, IMemberExpr {
2383 public MethodBase [] Methods;
2384 Expression instance_expression = null;
2385 bool is_explicit_impl = false;
2386 bool identical_type_name = false;
2388 public MethodGroupExpr (MemberInfo [] mi, Location l)
2390 Methods = new MethodBase [mi.Length];
2391 mi.CopyTo (Methods, 0);
2392 eclass = ExprClass.MethodGroup;
2393 type = TypeManager.object_type;
2397 public MethodGroupExpr (ArrayList list, Location l)
2399 Methods = new MethodBase [list.Count];
2402 list.CopyTo (Methods, 0);
2404 foreach (MemberInfo m in list){
2405 if (!(m is MethodBase)){
2406 Console.WriteLine ("Name " + m.Name);
2407 Console.WriteLine ("Found a: " + m.GetType ().FullName);
2414 eclass = ExprClass.MethodGroup;
2415 type = TypeManager.object_type;
2418 public Type DeclaringType {
2421 // The methods are arranged in this order:
2422 // derived type -> base type
2424 return Methods [0].DeclaringType;
2429 // `A method group may have associated an instance expression'
2431 public Expression InstanceExpression {
2433 return instance_expression;
2437 instance_expression = value;
2441 public bool IsExplicitImpl {
2443 return is_explicit_impl;
2447 is_explicit_impl = value;
2451 public bool IdenticalTypeName {
2453 return identical_type_name;
2457 identical_type_name = value;
2461 public string Name {
2463 return Methods [0].Name;
2467 public bool IsInstance {
2469 foreach (MethodBase mb in Methods)
2477 public bool IsStatic {
2479 foreach (MethodBase mb in Methods)
2487 override public Expression DoResolve (EmitContext ec)
2490 instance_expression = null;
2492 if (instance_expression != null) {
2493 instance_expression = instance_expression.DoResolve (ec);
2494 if (instance_expression == null)
2501 public void ReportUsageError ()
2503 Report.Error (654, loc, "Method `" + DeclaringType + "." +
2504 Name + "()' is referenced without parentheses");
2507 override public void Emit (EmitContext ec)
2509 ReportUsageError ();
2512 bool RemoveMethods (bool keep_static)
2514 ArrayList smethods = new ArrayList ();
2516 foreach (MethodBase mb in Methods){
2517 if (mb.IsStatic == keep_static)
2521 if (smethods.Count == 0)
2524 Methods = new MethodBase [smethods.Count];
2525 smethods.CopyTo (Methods, 0);
2531 /// Removes any instance methods from the MethodGroup, returns
2532 /// false if the resulting set is empty.
2534 public bool RemoveInstanceMethods ()
2536 return RemoveMethods (true);
2540 /// Removes any static methods from the MethodGroup, returns
2541 /// false if the resulting set is empty.
2543 public bool RemoveStaticMethods ()
2545 return RemoveMethods (false);
2550 /// Fully resolved expression that evaluates to a Field
2552 public class FieldExpr : Expression, IAssignMethod, IMemoryLocation, IMemberExpr, IVariable {
2553 public readonly FieldInfo FieldInfo;
2554 Expression instance_expr;
2555 VariableInfo variable_info;
2557 LocalTemporary temp;
2560 public FieldExpr (FieldInfo fi, Location l)
2563 eclass = ExprClass.Variable;
2564 type = fi.FieldType;
2568 public string Name {
2570 return FieldInfo.Name;
2574 public bool IsInstance {
2576 return !FieldInfo.IsStatic;
2580 public bool IsStatic {
2582 return FieldInfo.IsStatic;
2586 public Type DeclaringType {
2588 return FieldInfo.DeclaringType;
2592 public Expression InstanceExpression {
2594 return instance_expr;
2598 instance_expr = value;
2602 public VariableInfo VariableInfo {
2604 return variable_info;
2608 override public Expression DoResolve (EmitContext ec)
2610 if (!FieldInfo.IsStatic){
2611 if (instance_expr == null){
2613 // This can happen when referencing an instance field using
2614 // a fully qualified type expression: TypeName.InstanceField = xxx
2616 SimpleName.Error_ObjectRefRequired (ec, loc, FieldInfo.Name);
2620 // Resolve the field's instance expression while flow analysis is turned
2621 // off: when accessing a field "a.b", we must check whether the field
2622 // "a.b" is initialized, not whether the whole struct "a" is initialized.
2623 instance_expr = instance_expr.Resolve (ec, ResolveFlags.VariableOrValue |
2624 ResolveFlags.DisableFlowAnalysis);
2625 if (instance_expr == null)
2629 ObsoleteAttribute oa;
2630 FieldBase f = TypeManager.GetField (FieldInfo);
2632 oa = f.GetObsoleteAttribute (ec.DeclSpace);
2634 AttributeTester.Report_ObsoleteMessage (oa, f.GetSignatureForError (), loc);
2636 // To be sure that type is external because we do not register generated fields
2637 } else if (!(FieldInfo.DeclaringType is TypeBuilder)) {
2638 oa = AttributeTester.GetMemberObsoleteAttribute (FieldInfo);
2640 AttributeTester.Report_ObsoleteMessage (oa, TypeManager.GetFullNameSignature (FieldInfo), loc);
2643 // If the instance expression is a local variable or parameter.
2644 IVariable var = instance_expr as IVariable;
2645 if ((var == null) || (var.VariableInfo == null))
2648 VariableInfo vi = var.VariableInfo;
2649 if (!vi.IsFieldAssigned (ec, FieldInfo.Name, loc))
2652 variable_info = vi.GetSubStruct (FieldInfo.Name);
2656 void Report_AssignToReadonly (bool is_instance)
2661 msg = "Readonly field can not be assigned outside " +
2662 "of constructor or variable initializer";
2664 msg = "A static readonly field can only be assigned in " +
2665 "a static constructor";
2667 Report.Error (is_instance ? 191 : 198, loc, msg);
2670 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
2672 IVariable var = instance_expr as IVariable;
2673 if ((var != null) && (var.VariableInfo != null))
2674 var.VariableInfo.SetFieldAssigned (ec, FieldInfo.Name);
2676 Expression e = DoResolve (ec);
2681 if (!FieldInfo.IsStatic && (instance_expr.Type.IsValueType && !(instance_expr is IMemoryLocation))) {
2682 // FIXME: Provide better error reporting.
2683 Error (1612, "Cannot modify expression because it is not a variable.");
2687 if (!FieldInfo.IsInitOnly)
2690 FieldBase fb = TypeManager.GetField (FieldInfo);
2695 // InitOnly fields can only be assigned in constructors
2698 if (ec.IsConstructor){
2699 if (IsStatic && !ec.IsStatic)
2700 Report_AssignToReadonly (false);
2702 if (ec.ContainerType == FieldInfo.DeclaringType)
2706 Report_AssignToReadonly (true);
2711 public bool VerifyFixed (bool is_expression)
2713 IVariable variable = instance_expr as IVariable;
2714 if ((variable == null) || !variable.VerifyFixed (true))
2720 public void Emit (EmitContext ec, bool leave_copy)
2722 ILGenerator ig = ec.ig;
2723 bool is_volatile = false;
2725 if (FieldInfo is FieldBuilder){
2726 FieldBase f = TypeManager.GetField (FieldInfo);
2728 if ((f.ModFlags & Modifiers.VOLATILE) != 0)
2731 f.status |= Field.Status.USED;
2735 if (FieldInfo.IsStatic){
2737 ig.Emit (OpCodes.Volatile);
2739 ig.Emit (OpCodes.Ldsfld, FieldInfo);
2745 ig.Emit (OpCodes.Volatile);
2747 ig.Emit (OpCodes.Ldfld, FieldInfo);
2751 ec.ig.Emit (OpCodes.Dup);
2752 if (!FieldInfo.IsStatic) {
2753 temp = new LocalTemporary (ec, this.Type);
2759 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
2761 FieldAttributes fa = FieldInfo.Attributes;
2762 bool is_static = (fa & FieldAttributes.Static) != 0;
2763 bool is_readonly = (fa & FieldAttributes.InitOnly) != 0;
2764 ILGenerator ig = ec.ig;
2765 prepared = prepare_for_load;
2767 if (is_readonly && !ec.IsConstructor){
2768 Report_AssignToReadonly (!is_static);
2774 if (prepare_for_load)
2775 ig.Emit (OpCodes.Dup);
2780 ec.ig.Emit (OpCodes.Dup);
2781 if (!FieldInfo.IsStatic) {
2782 temp = new LocalTemporary (ec, this.Type);
2787 if (FieldInfo is FieldBuilder){
2788 FieldBase f = TypeManager.GetField (FieldInfo);
2790 if ((f.ModFlags & Modifiers.VOLATILE) != 0)
2791 ig.Emit (OpCodes.Volatile);
2793 f.status |= Field.Status.ASSIGNED;
2798 ig.Emit (OpCodes.Stsfld, FieldInfo);
2800 ig.Emit (OpCodes.Stfld, FieldInfo);
2806 void EmitInstance (EmitContext ec)
2808 if (instance_expr.Type.IsValueType) {
2809 if (instance_expr is IMemoryLocation) {
2810 ((IMemoryLocation) instance_expr).AddressOf (ec, AddressOp.LoadStore);
2812 LocalTemporary t = new LocalTemporary (ec, instance_expr.Type);
2813 instance_expr.Emit (ec);
2815 t.AddressOf (ec, AddressOp.Store);
2818 instance_expr.Emit (ec);
2821 public override void Emit (EmitContext ec)
2826 public void AddressOf (EmitContext ec, AddressOp mode)
2828 ILGenerator ig = ec.ig;
2830 if (FieldInfo is FieldBuilder){
2831 FieldBase f = TypeManager.GetField (FieldInfo);
2833 if ((f.ModFlags & Modifiers.VOLATILE) != 0){
2834 Error (676, "volatile variable: can not take its address, or pass as ref/out parameter");
2838 if ((mode & AddressOp.Store) != 0)
2839 f.status |= Field.Status.ASSIGNED;
2840 if ((mode & AddressOp.Load) != 0)
2841 f.status |= Field.Status.USED;
2846 // Handle initonly fields specially: make a copy and then
2847 // get the address of the copy.
2850 if (FieldInfo.IsInitOnly){
2852 if (ec.IsConstructor){
2853 if (FieldInfo.IsStatic){
2865 local = ig.DeclareLocal (type);
2866 ig.Emit (OpCodes.Stloc, local);
2867 ig.Emit (OpCodes.Ldloca, local);
2872 if (FieldInfo.IsStatic){
2873 ig.Emit (OpCodes.Ldsflda, FieldInfo);
2876 ig.Emit (OpCodes.Ldflda, FieldInfo);
2882 // A FieldExpr whose address can not be taken
2884 public class FieldExprNoAddress : FieldExpr, IMemoryLocation {
2885 public FieldExprNoAddress (FieldInfo fi, Location loc) : base (fi, loc)
2889 public new void AddressOf (EmitContext ec, AddressOp mode)
2891 Report.Error (-215, "Report this: Taking the address of a remapped parameter not supported");
2896 /// Expression that evaluates to a Property. The Assign class
2897 /// might set the `Value' expression if we are in an assignment.
2899 /// This is not an LValue because we need to re-write the expression, we
2900 /// can not take data from the stack and store it.
2902 public class PropertyExpr : ExpressionStatement, IAssignMethod, IMemberExpr {
2903 public readonly PropertyInfo PropertyInfo;
2906 // This is set externally by the `BaseAccess' class
2909 MethodInfo getter, setter;
2911 bool must_do_cs1540_check;
2913 Expression instance_expr;
2914 LocalTemporary temp;
2917 public PropertyExpr (EmitContext ec, PropertyInfo pi, Location l)
2920 eclass = ExprClass.PropertyAccess;
2924 type = TypeManager.TypeToCoreType (pi.PropertyType);
2926 ResolveAccessors (ec);
2929 public string Name {
2931 return PropertyInfo.Name;
2935 public bool IsInstance {
2941 public bool IsStatic {
2947 public Type DeclaringType {
2949 return PropertyInfo.DeclaringType;
2954 // The instance expression associated with this expression
2956 public Expression InstanceExpression {
2958 instance_expr = value;
2962 return instance_expr;
2966 public bool VerifyAssignable ()
2968 if (setter == null) {
2969 Report.Error (200, loc,
2970 "The property `" + PropertyInfo.Name +
2971 "' can not be assigned to, as it has not set accessor");
2978 MethodInfo FindAccessor (Type invocation_type, bool is_set)
2980 BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic |
2981 BindingFlags.Static | BindingFlags.Instance |
2982 BindingFlags.DeclaredOnly;
2984 Type current = PropertyInfo.DeclaringType;
2985 for (; current != null; current = current.BaseType) {
2986 MemberInfo[] group = TypeManager.MemberLookup (
2987 invocation_type, invocation_type, current,
2988 MemberTypes.Property, flags, PropertyInfo.Name, null);
2993 if (group.Length != 1)
2994 // Oooops, can this ever happen ?
2997 PropertyInfo pi = (PropertyInfo) group [0];
2999 MethodInfo get = pi.GetGetMethod (true);
3000 MethodInfo set = pi.GetSetMethod (true);
3010 MethodInfo accessor = get != null ? get : set;
3011 if (accessor == null)
3013 if ((accessor.Attributes & MethodAttributes.NewSlot) != 0)
3020 MethodInfo GetAccessor (Type invocation_type, bool is_set)
3022 MethodInfo mi = FindAccessor (invocation_type, is_set);
3026 MethodAttributes ma = mi.Attributes & MethodAttributes.MemberAccessMask;
3029 // If only accessible to the current class or children
3031 if (ma == MethodAttributes.Private) {
3032 Type declaring_type = mi.DeclaringType;
3034 if (invocation_type != declaring_type){
3035 if (TypeManager.IsSubclassOrNestedChildOf (invocation_type, mi.DeclaringType))
3043 // FamAndAssem requires that we not only derivate, but we are on the
3046 if (ma == MethodAttributes.FamANDAssem){
3047 if (mi.DeclaringType.Assembly != invocation_type.Assembly)
3053 // Assembly and FamORAssem succeed if we're in the same assembly.
3054 if ((ma == MethodAttributes.Assembly) || (ma == MethodAttributes.FamORAssem)){
3055 if (mi.DeclaringType.Assembly == invocation_type.Assembly)
3059 // We already know that we aren't in the same assembly.
3060 if (ma == MethodAttributes.Assembly)
3063 // Family and FamANDAssem require that we derive.
3064 if ((ma == MethodAttributes.Family) || (ma == MethodAttributes.FamANDAssem) || (ma == MethodAttributes.FamORAssem)){
3065 if (!TypeManager.IsSubclassOrNestedChildOf (invocation_type, mi.DeclaringType))
3068 if (!TypeManager.IsNestedChildOf (invocation_type, mi.DeclaringType))
3069 must_do_cs1540_check = true;
3079 // We also perform the permission checking here, as the PropertyInfo does not
3080 // hold the information for the accessibility of its setter/getter
3082 void ResolveAccessors (EmitContext ec)
3084 getter = GetAccessor (ec.ContainerType, false);
3085 if ((getter != null) && getter.IsStatic)
3088 setter = GetAccessor (ec.ContainerType, true);
3089 if ((setter != null) && setter.IsStatic)
3092 if (setter == null && getter == null){
3093 Report.Error_T (122, loc, PropertyInfo.Name);
3097 bool InstanceResolve (EmitContext ec)
3099 if ((instance_expr == null) && ec.IsStatic && !is_static) {
3100 SimpleName.Error_ObjectRefRequired (ec, loc, PropertyInfo.Name);
3104 if (instance_expr != null) {
3105 instance_expr = instance_expr.DoResolve (ec);
3106 if (instance_expr == null)
3110 if (must_do_cs1540_check && (instance_expr != null)) {
3111 if ((instance_expr.Type != ec.ContainerType) &&
3112 ec.ContainerType.IsSubclassOf (instance_expr.Type)) {
3113 Report.Error (1540, loc, "Cannot access protected member `" +
3114 PropertyInfo.DeclaringType + "." + PropertyInfo.Name +
3115 "' via a qualifier of type `" +
3116 TypeManager.CSharpName (instance_expr.Type) +
3117 "'; the qualifier must be of type `" +
3118 TypeManager.CSharpName (ec.ContainerType) +
3119 "' (or derived from it)");
3127 override public Expression DoResolve (EmitContext ec)
3129 if (getter != null){
3130 if (TypeManager.GetArgumentTypes (getter).Length != 0){
3132 117, loc, "`{0}' does not contain a " +
3133 "definition for `{1}'.", getter.DeclaringType,
3139 if (getter == null){
3141 // The following condition happens if the PropertyExpr was
3142 // created, but is invalid (ie, the property is inaccessible),
3143 // and we did not want to embed the knowledge about this in
3144 // the caller routine. This only avoids double error reporting.
3149 Report.Error (154, loc,
3150 "The property `" + PropertyInfo.Name +
3151 "' can not be used in " +
3152 "this context because it lacks a get accessor");
3156 if (!InstanceResolve (ec))
3160 // Only base will allow this invocation to happen.
3162 if (IsBase && getter.IsAbstract){
3163 Report.Error (205, loc, "Cannot call an abstract base property: " +
3164 PropertyInfo.DeclaringType + "." +PropertyInfo.Name);
3171 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
3173 if (setter == null){
3175 // The following condition happens if the PropertyExpr was
3176 // created, but is invalid (ie, the property is inaccessible),
3177 // and we did not want to embed the knowledge about this in
3178 // the caller routine. This only avoids double error reporting.
3183 Report.Error (154, loc,
3184 "The property `" + PropertyInfo.Name +
3185 "' can not be used in " +
3186 "this context because it lacks a set accessor");
3190 if (TypeManager.GetArgumentTypes (setter).Length != 1){
3192 117, loc, "`{0}' does not contain a " +
3193 "definition for `{1}'.", getter.DeclaringType,
3198 if (!InstanceResolve (ec))
3202 // Only base will allow this invocation to happen.
3204 if (IsBase && setter.IsAbstract){
3205 Report.Error (205, loc, "Cannot call an abstract base property: " +
3206 PropertyInfo.DeclaringType + "." +PropertyInfo.Name);
3211 // Check that we are not making changes to a temporary memory location
3213 if (instance_expr != null && instance_expr.Type.IsValueType && !(instance_expr is IMemoryLocation)) {
3214 // FIXME: Provide better error reporting.
3215 Error (1612, "Cannot modify expression because it is not a variable.");
3224 public override void Emit (EmitContext ec)
3229 void EmitInstance (EmitContext ec)
3234 if (instance_expr.Type.IsValueType) {
3235 if (instance_expr is IMemoryLocation) {
3236 ((IMemoryLocation) instance_expr).AddressOf (ec, AddressOp.LoadStore);
3238 LocalTemporary t = new LocalTemporary (ec, instance_expr.Type);
3239 instance_expr.Emit (ec);
3241 t.AddressOf (ec, AddressOp.Store);
3244 instance_expr.Emit (ec);
3247 ec.ig.Emit (OpCodes.Dup);
3251 public void Emit (EmitContext ec, bool leave_copy)
3257 // Special case: length of single dimension array property is turned into ldlen
3259 if ((getter == TypeManager.system_int_array_get_length) ||
3260 (getter == TypeManager.int_array_get_length)){
3261 Type iet = instance_expr.Type;
3264 // System.Array.Length can be called, but the Type does not
3265 // support invoking GetArrayRank, so test for that case first
3267 if (iet != TypeManager.array_type && (iet.GetArrayRank () == 1)) {
3268 ec.ig.Emit (OpCodes.Ldlen);
3269 ec.ig.Emit (OpCodes.Conv_I4);
3274 Invocation.EmitCall (ec, IsBase, IsStatic, new EmptyAddressOf (), getter, null, loc);
3279 ec.ig.Emit (OpCodes.Dup);
3281 temp = new LocalTemporary (ec, this.Type);
3287 // Implements the IAssignMethod interface for assignments
3289 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
3291 prepared = prepare_for_load;
3297 ec.ig.Emit (OpCodes.Dup);
3299 temp = new LocalTemporary (ec, this.Type);
3304 ArrayList args = new ArrayList (1);
3305 args.Add (new Argument (new EmptyAddressOf (), Argument.AType.Expression));
3307 Invocation.EmitCall (ec, IsBase, IsStatic, new EmptyAddressOf (), setter, args, loc);
3313 override public void EmitStatement (EmitContext ec)
3316 ec.ig.Emit (OpCodes.Pop);
3321 /// Fully resolved expression that evaluates to an Event
3323 public class EventExpr : Expression, IMemberExpr {
3324 public readonly EventInfo EventInfo;
3325 Expression instance_expr;
3328 MethodInfo add_accessor, remove_accessor;
3330 public EventExpr (EventInfo ei, Location loc)
3334 eclass = ExprClass.EventAccess;
3336 add_accessor = TypeManager.GetAddMethod (ei);
3337 remove_accessor = TypeManager.GetRemoveMethod (ei);
3339 if (add_accessor.IsStatic || remove_accessor.IsStatic)
3342 if (EventInfo is MyEventBuilder){
3343 MyEventBuilder eb = (MyEventBuilder) EventInfo;
3344 type = eb.EventType;
3347 type = EventInfo.EventHandlerType;
3350 public string Name {
3352 return EventInfo.Name;
3356 public bool IsInstance {
3362 public bool IsStatic {
3368 public Type DeclaringType {
3370 return EventInfo.DeclaringType;
3374 public Expression InstanceExpression {
3376 return instance_expr;
3380 instance_expr = value;
3384 public override Expression DoResolve (EmitContext ec)
3386 if (instance_expr != null) {
3387 instance_expr = instance_expr.DoResolve (ec);
3388 if (instance_expr == null)
3396 public override void Emit (EmitContext ec)
3398 Report.Error (70, loc, "The event `" + Name + "' can only appear on the left hand side of += or -= (except on the defining type)");
3401 public void EmitAddOrRemove (EmitContext ec, Expression source)
3403 BinaryDelegate source_del = (BinaryDelegate) source;
3404 Expression handler = source_del.Right;
3406 Argument arg = new Argument (handler, Argument.AType.Expression);
3407 ArrayList args = new ArrayList ();
3411 if (source_del.IsAddition)
3412 Invocation.EmitCall (
3413 ec, false, IsStatic, instance_expr, add_accessor, args, loc);
3415 Invocation.EmitCall (
3416 ec, false, IsStatic, instance_expr, remove_accessor, args, loc);