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)
1242 // Default implementation of IAssignMethod.CacheTemporaries
1244 public virtual void CacheTemporaries (EmitContext ec)
1248 static void Error_NegativeArrayIndex (Location loc)
1250 Report.Error (284, loc, "Can not create array with a negative size");
1254 // Converts `source' to an int, uint, long or ulong.
1256 public Expression ExpressionToArrayArgument (EmitContext ec, Expression source, Location loc)
1260 bool old_checked = ec.CheckState;
1261 ec.CheckState = true;
1263 target = Convert.ImplicitConversion (ec, source, TypeManager.int32_type, loc);
1264 if (target == null){
1265 target = Convert.ImplicitConversion (ec, source, TypeManager.uint32_type, loc);
1266 if (target == null){
1267 target = Convert.ImplicitConversion (ec, source, TypeManager.int64_type, loc);
1268 if (target == null){
1269 target = Convert.ImplicitConversion (ec, source, TypeManager.uint64_type, loc);
1271 Convert.Error_CannotImplicitConversion (loc, source.Type, TypeManager.int32_type);
1275 ec.CheckState = old_checked;
1278 // Only positive constants are allowed at compile time
1280 if (target is Constant){
1281 if (target is IntConstant){
1282 if (((IntConstant) target).Value < 0){
1283 Error_NegativeArrayIndex (loc);
1288 if (target is LongConstant){
1289 if (((LongConstant) target).Value < 0){
1290 Error_NegativeArrayIndex (loc);
1303 /// This is just a base class for expressions that can
1304 /// appear on statements (invocations, object creation,
1305 /// assignments, post/pre increment and decrement). The idea
1306 /// being that they would support an extra Emition interface that
1307 /// does not leave a result on the stack.
1309 public abstract class ExpressionStatement : Expression {
1311 public virtual ExpressionStatement ResolveStatement (EmitContext ec)
1313 Expression e = Resolve (ec);
1317 ExpressionStatement es = e as ExpressionStatement;
1319 Error (201, "Only assignment, call, increment, decrement and new object " +
1320 "expressions can be used as a statement");
1326 /// Requests the expression to be emitted in a `statement'
1327 /// context. This means that no new value is left on the
1328 /// stack after invoking this method (constrasted with
1329 /// Emit that will always leave a value on the stack).
1331 public abstract void EmitStatement (EmitContext ec);
1335 /// This kind of cast is used to encapsulate the child
1336 /// whose type is child.Type into an expression that is
1337 /// reported to return "return_type". This is used to encapsulate
1338 /// expressions which have compatible types, but need to be dealt
1339 /// at higher levels with.
1341 /// For example, a "byte" expression could be encapsulated in one
1342 /// of these as an "unsigned int". The type for the expression
1343 /// would be "unsigned int".
1346 public class EmptyCast : Expression {
1347 protected Expression child;
1349 public Expression Child {
1355 public EmptyCast (Expression child, Type return_type)
1357 eclass = child.eclass;
1362 public override Expression DoResolve (EmitContext ec)
1364 // This should never be invoked, we are born in fully
1365 // initialized state.
1370 public override void Emit (EmitContext ec)
1377 // We need to special case this since an empty cast of
1378 // a NullLiteral is still a Constant
1380 public class NullCast : Constant {
1381 protected Expression child;
1383 public NullCast (Expression child, Type return_type)
1385 eclass = child.eclass;
1390 override public string AsString ()
1395 public override object GetValue ()
1400 public override Expression DoResolve (EmitContext ec)
1402 // This should never be invoked, we are born in fully
1403 // initialized state.
1408 public override void Emit (EmitContext ec)
1416 /// This class is used to wrap literals which belong inside Enums
1418 public class EnumConstant : Constant {
1419 public Constant Child;
1421 public EnumConstant (Constant child, Type enum_type)
1423 eclass = child.eclass;
1428 public override Expression DoResolve (EmitContext ec)
1430 // This should never be invoked, we are born in fully
1431 // initialized state.
1436 public override void Emit (EmitContext ec)
1441 public override object GetValue ()
1443 return Child.GetValue ();
1447 // Converts from one of the valid underlying types for an enumeration
1448 // (int32, uint32, int64, uint64, short, ushort, byte, sbyte) to
1449 // one of the internal compiler literals: Int/UInt/Long/ULong Literals.
1451 public Constant WidenToCompilerConstant ()
1453 Type t = TypeManager.EnumToUnderlying (Child.Type);
1454 object v = ((Constant) Child).GetValue ();;
1456 if (t == TypeManager.int32_type)
1457 return new IntConstant ((int) v);
1458 if (t == TypeManager.uint32_type)
1459 return new UIntConstant ((uint) v);
1460 if (t == TypeManager.int64_type)
1461 return new LongConstant ((long) v);
1462 if (t == TypeManager.uint64_type)
1463 return new ULongConstant ((ulong) v);
1464 if (t == TypeManager.short_type)
1465 return new ShortConstant ((short) v);
1466 if (t == TypeManager.ushort_type)
1467 return new UShortConstant ((ushort) v);
1468 if (t == TypeManager.byte_type)
1469 return new ByteConstant ((byte) v);
1470 if (t == TypeManager.sbyte_type)
1471 return new SByteConstant ((sbyte) v);
1473 throw new Exception ("Invalid enumeration underlying type: " + t);
1477 // Extracts the value in the enumeration on its native representation
1479 public object GetPlainValue ()
1481 Type t = TypeManager.EnumToUnderlying (Child.Type);
1482 object v = ((Constant) Child).GetValue ();;
1484 if (t == TypeManager.int32_type)
1486 if (t == TypeManager.uint32_type)
1488 if (t == TypeManager.int64_type)
1490 if (t == TypeManager.uint64_type)
1492 if (t == TypeManager.short_type)
1494 if (t == TypeManager.ushort_type)
1496 if (t == TypeManager.byte_type)
1498 if (t == TypeManager.sbyte_type)
1504 public override string AsString ()
1506 return Child.AsString ();
1509 public override DoubleConstant ConvertToDouble ()
1511 return Child.ConvertToDouble ();
1514 public override FloatConstant ConvertToFloat ()
1516 return Child.ConvertToFloat ();
1519 public override ULongConstant ConvertToULong ()
1521 return Child.ConvertToULong ();
1524 public override LongConstant ConvertToLong ()
1526 return Child.ConvertToLong ();
1529 public override UIntConstant ConvertToUInt ()
1531 return Child.ConvertToUInt ();
1534 public override IntConstant ConvertToInt ()
1536 return Child.ConvertToInt ();
1539 public override bool IsZeroInteger {
1540 get { return Child.IsZeroInteger; }
1545 /// This kind of cast is used to encapsulate Value Types in objects.
1547 /// The effect of it is to box the value type emitted by the previous
1550 public class BoxedCast : EmptyCast {
1552 public BoxedCast (Expression expr)
1553 : base (expr, TypeManager.object_type)
1555 eclass = ExprClass.Value;
1558 public BoxedCast (Expression expr, Type target_type)
1559 : base (expr, target_type)
1561 eclass = ExprClass.Value;
1564 public override Expression DoResolve (EmitContext ec)
1566 // This should never be invoked, we are born in fully
1567 // initialized state.
1572 public override void Emit (EmitContext ec)
1576 ec.ig.Emit (OpCodes.Box, child.Type);
1580 public class UnboxCast : EmptyCast {
1581 public UnboxCast (Expression expr, Type return_type)
1582 : base (expr, return_type)
1586 public override Expression DoResolve (EmitContext ec)
1588 // This should never be invoked, we are born in fully
1589 // initialized state.
1594 public override void Emit (EmitContext ec)
1597 ILGenerator ig = ec.ig;
1600 ig.Emit (OpCodes.Unbox, t);
1602 LoadFromPtr (ig, t);
1607 /// This is used to perform explicit numeric conversions.
1609 /// Explicit numeric conversions might trigger exceptions in a checked
1610 /// context, so they should generate the conv.ovf opcodes instead of
1613 public class ConvCast : EmptyCast {
1614 public enum Mode : byte {
1615 I1_U1, I1_U2, I1_U4, I1_U8, I1_CH,
1617 I2_I1, I2_U1, I2_U2, I2_U4, I2_U8, I2_CH,
1618 U2_I1, U2_U1, U2_I2, U2_CH,
1619 I4_I1, I4_U1, I4_I2, I4_U2, I4_U4, I4_U8, I4_CH,
1620 U4_I1, U4_U1, U4_I2, U4_U2, U4_I4, U4_CH,
1621 I8_I1, I8_U1, I8_I2, I8_U2, I8_I4, I8_U4, I8_U8, I8_CH,
1622 U8_I1, U8_U1, U8_I2, U8_U2, U8_I4, U8_U4, U8_I8, U8_CH,
1623 CH_I1, CH_U1, CH_I2,
1624 R4_I1, R4_U1, R4_I2, R4_U2, R4_I4, R4_U4, R4_I8, R4_U8, R4_CH,
1625 R8_I1, R8_U1, R8_I2, R8_U2, R8_I4, R8_U4, R8_I8, R8_U8, R8_CH, R8_R4
1631 public ConvCast (EmitContext ec, Expression child, Type return_type, Mode m)
1632 : base (child, return_type)
1634 checked_state = ec.CheckState;
1638 public override Expression DoResolve (EmitContext ec)
1640 // This should never be invoked, we are born in fully
1641 // initialized state.
1646 public override string ToString ()
1648 return String.Format ("ConvCast ({0}, {1})", mode, child);
1651 public override void Emit (EmitContext ec)
1653 ILGenerator ig = ec.ig;
1659 case Mode.I1_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1660 case Mode.I1_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1661 case Mode.I1_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1662 case Mode.I1_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1663 case Mode.I1_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1665 case Mode.U1_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1666 case Mode.U1_CH: /* nothing */ break;
1668 case Mode.I2_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1669 case Mode.I2_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1670 case Mode.I2_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1671 case Mode.I2_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1672 case Mode.I2_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1673 case Mode.I2_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1675 case Mode.U2_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1676 case Mode.U2_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
1677 case Mode.U2_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
1678 case Mode.U2_CH: /* nothing */ break;
1680 case Mode.I4_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1681 case Mode.I4_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1682 case Mode.I4_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
1683 case Mode.I4_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1684 case Mode.I4_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1685 case Mode.I4_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1686 case Mode.I4_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1688 case Mode.U4_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1689 case Mode.U4_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
1690 case Mode.U4_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
1691 case Mode.U4_U2: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
1692 case Mode.U4_I4: ig.Emit (OpCodes.Conv_Ovf_I4_Un); break;
1693 case Mode.U4_CH: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
1695 case Mode.I8_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1696 case Mode.I8_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1697 case Mode.I8_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
1698 case Mode.I8_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1699 case Mode.I8_I4: ig.Emit (OpCodes.Conv_Ovf_I4); break;
1700 case Mode.I8_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1701 case Mode.I8_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1702 case Mode.I8_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1704 case Mode.U8_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1705 case Mode.U8_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
1706 case Mode.U8_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
1707 case Mode.U8_U2: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
1708 case Mode.U8_I4: ig.Emit (OpCodes.Conv_Ovf_I4_Un); break;
1709 case Mode.U8_U4: ig.Emit (OpCodes.Conv_Ovf_U4_Un); break;
1710 case Mode.U8_I8: ig.Emit (OpCodes.Conv_Ovf_I8_Un); break;
1711 case Mode.U8_CH: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
1713 case Mode.CH_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1714 case Mode.CH_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
1715 case Mode.CH_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
1717 case Mode.R4_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1718 case Mode.R4_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1719 case Mode.R4_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
1720 case Mode.R4_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1721 case Mode.R4_I4: ig.Emit (OpCodes.Conv_Ovf_I4); break;
1722 case Mode.R4_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1723 case Mode.R4_I8: ig.Emit (OpCodes.Conv_Ovf_I8); break;
1724 case Mode.R4_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1725 case Mode.R4_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1727 case Mode.R8_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1728 case Mode.R8_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1729 case Mode.R8_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
1730 case Mode.R8_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1731 case Mode.R8_I4: ig.Emit (OpCodes.Conv_Ovf_I4); break;
1732 case Mode.R8_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1733 case Mode.R8_I8: ig.Emit (OpCodes.Conv_Ovf_I8); break;
1734 case Mode.R8_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1735 case Mode.R8_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1736 case Mode.R8_R4: ig.Emit (OpCodes.Conv_R4); break;
1740 case Mode.I1_U1: ig.Emit (OpCodes.Conv_U1); break;
1741 case Mode.I1_U2: ig.Emit (OpCodes.Conv_U2); break;
1742 case Mode.I1_U4: ig.Emit (OpCodes.Conv_U4); break;
1743 case Mode.I1_U8: ig.Emit (OpCodes.Conv_I8); break;
1744 case Mode.I1_CH: ig.Emit (OpCodes.Conv_U2); break;
1746 case Mode.U1_I1: ig.Emit (OpCodes.Conv_I1); break;
1747 case Mode.U1_CH: ig.Emit (OpCodes.Conv_U2); break;
1749 case Mode.I2_I1: ig.Emit (OpCodes.Conv_I1); break;
1750 case Mode.I2_U1: ig.Emit (OpCodes.Conv_U1); break;
1751 case Mode.I2_U2: ig.Emit (OpCodes.Conv_U2); break;
1752 case Mode.I2_U4: ig.Emit (OpCodes.Conv_U4); break;
1753 case Mode.I2_U8: ig.Emit (OpCodes.Conv_I8); break;
1754 case Mode.I2_CH: ig.Emit (OpCodes.Conv_U2); break;
1756 case Mode.U2_I1: ig.Emit (OpCodes.Conv_I1); break;
1757 case Mode.U2_U1: ig.Emit (OpCodes.Conv_U1); break;
1758 case Mode.U2_I2: ig.Emit (OpCodes.Conv_I2); break;
1759 case Mode.U2_CH: /* nothing */ break;
1761 case Mode.I4_I1: ig.Emit (OpCodes.Conv_I1); break;
1762 case Mode.I4_U1: ig.Emit (OpCodes.Conv_U1); break;
1763 case Mode.I4_I2: ig.Emit (OpCodes.Conv_I2); break;
1764 case Mode.I4_U4: /* nothing */ break;
1765 case Mode.I4_U2: ig.Emit (OpCodes.Conv_U2); break;
1766 case Mode.I4_U8: ig.Emit (OpCodes.Conv_I8); break;
1767 case Mode.I4_CH: ig.Emit (OpCodes.Conv_U2); break;
1769 case Mode.U4_I1: ig.Emit (OpCodes.Conv_I1); break;
1770 case Mode.U4_U1: ig.Emit (OpCodes.Conv_U1); break;
1771 case Mode.U4_I2: ig.Emit (OpCodes.Conv_I2); break;
1772 case Mode.U4_U2: ig.Emit (OpCodes.Conv_U2); break;
1773 case Mode.U4_I4: /* nothing */ break;
1774 case Mode.U4_CH: ig.Emit (OpCodes.Conv_U2); break;
1776 case Mode.I8_I1: ig.Emit (OpCodes.Conv_I1); break;
1777 case Mode.I8_U1: ig.Emit (OpCodes.Conv_U1); break;
1778 case Mode.I8_I2: ig.Emit (OpCodes.Conv_I2); break;
1779 case Mode.I8_U2: ig.Emit (OpCodes.Conv_U2); break;
1780 case Mode.I8_I4: ig.Emit (OpCodes.Conv_I4); break;
1781 case Mode.I8_U4: ig.Emit (OpCodes.Conv_U4); break;
1782 case Mode.I8_U8: /* nothing */ break;
1783 case Mode.I8_CH: ig.Emit (OpCodes.Conv_U2); break;
1785 case Mode.U8_I1: ig.Emit (OpCodes.Conv_I1); break;
1786 case Mode.U8_U1: ig.Emit (OpCodes.Conv_U1); break;
1787 case Mode.U8_I2: ig.Emit (OpCodes.Conv_I2); break;
1788 case Mode.U8_U2: ig.Emit (OpCodes.Conv_U2); break;
1789 case Mode.U8_I4: ig.Emit (OpCodes.Conv_I4); break;
1790 case Mode.U8_U4: ig.Emit (OpCodes.Conv_U4); break;
1791 case Mode.U8_I8: /* nothing */ break;
1792 case Mode.U8_CH: ig.Emit (OpCodes.Conv_U2); break;
1794 case Mode.CH_I1: ig.Emit (OpCodes.Conv_I1); break;
1795 case Mode.CH_U1: ig.Emit (OpCodes.Conv_U1); break;
1796 case Mode.CH_I2: ig.Emit (OpCodes.Conv_I2); break;
1798 case Mode.R4_I1: ig.Emit (OpCodes.Conv_I1); break;
1799 case Mode.R4_U1: ig.Emit (OpCodes.Conv_U1); break;
1800 case Mode.R4_I2: ig.Emit (OpCodes.Conv_I2); break;
1801 case Mode.R4_U2: ig.Emit (OpCodes.Conv_U2); break;
1802 case Mode.R4_I4: ig.Emit (OpCodes.Conv_I4); break;
1803 case Mode.R4_U4: ig.Emit (OpCodes.Conv_U4); break;
1804 case Mode.R4_I8: ig.Emit (OpCodes.Conv_I8); break;
1805 case Mode.R4_U8: ig.Emit (OpCodes.Conv_U8); break;
1806 case Mode.R4_CH: ig.Emit (OpCodes.Conv_U2); break;
1808 case Mode.R8_I1: ig.Emit (OpCodes.Conv_I1); break;
1809 case Mode.R8_U1: ig.Emit (OpCodes.Conv_U1); break;
1810 case Mode.R8_I2: ig.Emit (OpCodes.Conv_I2); break;
1811 case Mode.R8_U2: ig.Emit (OpCodes.Conv_U2); break;
1812 case Mode.R8_I4: ig.Emit (OpCodes.Conv_I4); break;
1813 case Mode.R8_U4: ig.Emit (OpCodes.Conv_U4); break;
1814 case Mode.R8_I8: ig.Emit (OpCodes.Conv_I8); break;
1815 case Mode.R8_U8: ig.Emit (OpCodes.Conv_U8); break;
1816 case Mode.R8_CH: ig.Emit (OpCodes.Conv_U2); break;
1817 case Mode.R8_R4: ig.Emit (OpCodes.Conv_R4); break;
1823 public class OpcodeCast : EmptyCast {
1827 public OpcodeCast (Expression child, Type return_type, OpCode op)
1828 : base (child, return_type)
1832 second_valid = false;
1835 public OpcodeCast (Expression child, Type return_type, OpCode op, OpCode op2)
1836 : base (child, return_type)
1841 second_valid = true;
1844 public override Expression DoResolve (EmitContext ec)
1846 // This should never be invoked, we are born in fully
1847 // initialized state.
1852 public override void Emit (EmitContext ec)
1863 /// This kind of cast is used to encapsulate a child and cast it
1864 /// to the class requested
1866 public class ClassCast : EmptyCast {
1867 public ClassCast (Expression child, Type return_type)
1868 : base (child, return_type)
1873 public override Expression DoResolve (EmitContext ec)
1875 // This should never be invoked, we are born in fully
1876 // initialized state.
1881 public override void Emit (EmitContext ec)
1885 ec.ig.Emit (OpCodes.Castclass, type);
1891 /// SimpleName expressions are initially formed of a single
1892 /// word and it only happens at the beginning of the expression.
1896 /// The expression will try to be bound to a Field, a Method
1897 /// group or a Property. If those fail we pass the name to our
1898 /// caller and the SimpleName is compounded to perform a type
1899 /// lookup. The idea behind this process is that we want to avoid
1900 /// creating a namespace map from the assemblies, as that requires
1901 /// the GetExportedTypes function to be called and a hashtable to
1902 /// be constructed which reduces startup time. If later we find
1903 /// that this is slower, we should create a `NamespaceExpr' expression
1904 /// that fully participates in the resolution process.
1906 /// For example `System.Console.WriteLine' is decomposed into
1907 /// MemberAccess (MemberAccess (SimpleName ("System"), "Console"), "WriteLine")
1909 /// The first SimpleName wont produce a match on its own, so it will
1911 /// MemberAccess (SimpleName ("System.Console"), "WriteLine").
1913 /// System.Console will produce a TypeExpr match.
1915 /// The downside of this is that we might be hitting `LookupType' too many
1916 /// times with this scheme.
1918 public class SimpleName : Expression {
1922 // If true, then we are a simple name, not composed with a ".
1926 public SimpleName (string a, string b, Location l)
1928 Name = String.Concat (a, ".", b);
1933 public SimpleName (string name, Location l)
1940 public static void Error_ObjectRefRequired (EmitContext ec, Location l, string name)
1942 if (ec.IsFieldInitializer)
1945 "A field initializer cannot reference the non-static field, " +
1946 "method or property `"+name+"'");
1950 "An object reference is required " +
1951 "for the non-static field `"+name+"'");
1955 // Checks whether we are trying to access an instance
1956 // property, method or field from a static body.
1958 Expression MemberStaticCheck (EmitContext ec, Expression e)
1960 if (e is IMemberExpr){
1961 IMemberExpr member = (IMemberExpr) e;
1963 if (!member.IsStatic){
1964 Error_ObjectRefRequired (ec, loc, Name);
1972 public override Expression DoResolve (EmitContext ec)
1974 return SimpleNameResolve (ec, null, false, false);
1977 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
1979 return SimpleNameResolve (ec, right_side, false, false);
1983 public Expression DoResolveAllowStatic (EmitContext ec, bool intermediate)
1985 return SimpleNameResolve (ec, null, true, intermediate);
1988 public override Expression ResolveAsTypeStep (EmitContext ec)
1990 DeclSpace ds = ec.DeclSpace;
1991 NamespaceEntry ns = ds.NamespaceEntry;
1996 // Since we are cheating: we only do the Alias lookup for
1997 // namespaces if the name does not include any dots in it
1999 if (ns != null && is_base)
2000 alias_value = ns.LookupAlias (Name);
2004 if (ec.ResolvingTypeTree){
2005 int errors = Report.Errors;
2006 Type dt = ds.FindType (loc, Name);
2008 if (Report.Errors != errors)
2012 return new TypeExpression (dt, loc);
2014 if (alias_value != null){
2015 if ((t = RootContext.LookupType (ds, alias_value, true, loc)) != null)
2016 return new TypeExpression (t, loc);
2021 // First, the using aliases
2023 if (alias_value != null){
2024 if ((t = RootContext.LookupType (ds, alias_value, true, loc)) != null)
2025 return new TypeExpression (t, loc);
2027 // we have alias value, but it isn't Type, so try if it's namespace
2028 return new SimpleName (alias_value, loc);
2032 // Stage 2: Lookup up if we are an alias to a type
2036 if ((t = RootContext.LookupType (ds, Name, true, loc)) != null)
2037 return new TypeExpression (t, loc);
2039 // No match, maybe our parent can compose us
2040 // into something meaningful.
2044 Expression SimpleNameResolve (EmitContext ec, Expression right_side,
2045 bool allow_static, bool intermediate)
2047 Expression e = DoSimpleNameResolve (ec, right_side, allow_static, intermediate);
2051 Block current_block = ec.CurrentBlock;
2052 if (current_block != null){
2053 LocalInfo vi = current_block.GetLocalInfo (Name);
2055 current_block.IsVariableNameUsedInChildBlock(Name)) {
2056 Report.Error (135, Location,
2057 "'{0}' has a different meaning in a " +
2058 "child block", Name);
2067 /// 7.5.2: Simple Names.
2069 /// Local Variables and Parameters are handled at
2070 /// parse time, so they never occur as SimpleNames.
2072 /// The `allow_static' flag is used by MemberAccess only
2073 /// and it is used to inform us that it is ok for us to
2074 /// avoid the static check, because MemberAccess might end
2075 /// up resolving the Name as a Type name and the access as
2076 /// a static type access.
2078 /// ie: Type Type; .... { Type.GetType (""); }
2080 /// Type is both an instance variable and a Type; Type.GetType
2081 /// is the static method not an instance method of type.
2083 Expression DoSimpleNameResolve (EmitContext ec, Expression right_side, bool allow_static, bool intermediate)
2085 Expression e = null;
2088 // Stage 1: Performed by the parser (binding to locals or parameters).
2090 Block current_block = ec.CurrentBlock;
2091 if (current_block != null){
2092 LocalInfo vi = current_block.GetLocalInfo (Name);
2096 var = new LocalVariableReference (ec.CurrentBlock, Name, loc);
2098 if (right_side != null)
2099 return var.ResolveLValue (ec, right_side);
2101 return var.Resolve (ec);
2105 Parameter par = null;
2106 Parameters pars = current_block.Parameters;
2108 par = pars.GetParameterByName (Name, out idx);
2111 ParameterReference param;
2113 param = new ParameterReference (pars, current_block, idx, Name, loc);
2115 if (right_side != null)
2116 return param.ResolveLValue (ec, right_side);
2118 return param.Resolve (ec);
2123 // Stage 2: Lookup members
2126 DeclSpace lookup_ds = ec.DeclSpace;
2128 if (lookup_ds.TypeBuilder == null)
2131 e = MemberLookup (ec, lookup_ds.TypeBuilder, Name, loc);
2135 lookup_ds =lookup_ds.Parent;
2136 } while (lookup_ds != null);
2138 if (e == null && ec.ContainerType != null)
2139 e = MemberLookup (ec, ec.ContainerType, Name, loc);
2143 // Since we are cheating (is_base is our hint
2144 // that we are the beginning of the name): we
2145 // only do the Alias lookup for namespaces if
2146 // the name does not include any dots in it
2148 NamespaceEntry ns = ec.DeclSpace.NamespaceEntry;
2149 if (is_base && ns != null){
2150 string alias_value = ns.LookupAlias (Name);
2151 if (alias_value != null){
2155 if ((t = TypeManager.LookupType (Name)) != null)
2156 return new TypeExpression (t, loc);
2158 // No match, maybe our parent can compose us
2159 // into something meaningful.
2164 return ResolveAsTypeStep (ec);
2170 if (e is IMemberExpr) {
2171 e = MemberAccess.ResolveMemberAccess (ec, e, null, loc, this);
2175 IMemberExpr me = e as IMemberExpr;
2179 // This fails if ResolveMemberAccess() was unable to decide whether
2180 // it's a field or a type of the same name.
2182 if (!me.IsStatic && (me.InstanceExpression == null))
2186 TypeManager.IsNestedChildOf (me.InstanceExpression.Type, me.DeclaringType) &&
2187 !me.InstanceExpression.Type.IsSubclassOf (me.DeclaringType) &&
2188 (!intermediate || !MemberAccess.IdenticalNameAndTypeName (ec, this, e, loc))) {
2189 Error (38, "Cannot access nonstatic member `" + me.Name + "' of " +
2190 "outer type `" + me.DeclaringType + "' via nested type `" +
2191 me.InstanceExpression.Type + "'");
2195 return (right_side != null)
2196 ? e.DoResolveLValue (ec, right_side)
2200 if (ec.IsStatic || ec.IsFieldInitializer){
2204 return MemberStaticCheck (ec, e);
2209 public override void Emit (EmitContext ec)
2212 // If this is ever reached, then we failed to
2213 // find the name as a namespace
2216 Error (103, "The name `" + Name +
2217 "' does not exist in the class `" +
2218 ec.DeclSpace.Name + "'");
2221 public override string ToString ()
2228 /// Fully resolved expression that evaluates to a type
2230 public abstract class TypeExpr : Expression {
2231 override public Expression ResolveAsTypeStep (EmitContext ec)
2233 TypeExpr t = DoResolveAsTypeStep (ec);
2237 eclass = ExprClass.Type;
2241 override public Expression DoResolve (EmitContext ec)
2243 return ResolveAsTypeTerminal (ec);
2246 override public void Emit (EmitContext ec)
2248 throw new Exception ("Should never be called");
2251 public virtual bool CheckAccessLevel (DeclSpace ds)
2253 return ds.CheckAccessLevel (Type);
2256 public virtual bool AsAccessible (DeclSpace ds, int flags)
2258 return ds.AsAccessible (Type, flags);
2261 public virtual bool IsClass {
2262 get { return Type.IsClass; }
2265 public virtual bool IsValueType {
2266 get { return Type.IsValueType; }
2269 public virtual bool IsInterface {
2270 get { return Type.IsInterface; }
2273 public virtual bool IsSealed {
2274 get { return Type.IsSealed; }
2277 public virtual bool CanInheritFrom ()
2279 if (Type == TypeManager.enum_type ||
2280 (Type == TypeManager.value_type && RootContext.StdLib) ||
2281 Type == TypeManager.multicast_delegate_type ||
2282 Type == TypeManager.delegate_type ||
2283 Type == TypeManager.array_type)
2289 public virtual bool IsAttribute {
2291 return Type == TypeManager.attribute_type ||
2292 Type.IsSubclassOf (TypeManager.attribute_type);
2296 public virtual TypeExpr[] GetInterfaces ()
2298 return TypeManager.GetInterfaces (Type);
2301 public abstract TypeExpr DoResolveAsTypeStep (EmitContext ec);
2303 public virtual Type ResolveType (EmitContext ec)
2305 TypeExpr t = ResolveAsTypeTerminal (ec);
2312 public abstract string Name {
2316 public override bool Equals (object obj)
2318 TypeExpr tobj = obj as TypeExpr;
2322 return Type == tobj.Type;
2325 public override int GetHashCode ()
2327 return Type.GetHashCode ();
2330 public override string ToString ()
2336 public class TypeExpression : TypeExpr {
2337 public TypeExpression (Type t, Location l)
2340 eclass = ExprClass.Type;
2344 public override TypeExpr DoResolveAsTypeStep (EmitContext ec)
2349 public override string Name {
2351 return Type.ToString ();
2357 /// Used to create types from a fully qualified name. These are just used
2358 /// by the parser to setup the core types. A TypeLookupExpression is always
2359 /// classified as a type.
2361 public class TypeLookupExpression : TypeExpr {
2364 public TypeLookupExpression (string name)
2369 public override TypeExpr DoResolveAsTypeStep (EmitContext ec)
2372 type = RootContext.LookupType (ec.DeclSpace, name, false, Location.Null);
2376 public override string Name {
2384 /// MethodGroup Expression.
2386 /// This is a fully resolved expression that evaluates to a type
2388 public class MethodGroupExpr : Expression, IMemberExpr {
2389 public MethodBase [] Methods;
2390 Expression instance_expression = null;
2391 bool is_explicit_impl = false;
2392 bool identical_type_name = false;
2395 public MethodGroupExpr (MemberInfo [] mi, Location l)
2397 Methods = new MethodBase [mi.Length];
2398 mi.CopyTo (Methods, 0);
2399 eclass = ExprClass.MethodGroup;
2400 type = TypeManager.object_type;
2404 public MethodGroupExpr (ArrayList list, Location l)
2406 Methods = new MethodBase [list.Count];
2409 list.CopyTo (Methods, 0);
2411 foreach (MemberInfo m in list){
2412 if (!(m is MethodBase)){
2413 Console.WriteLine ("Name " + m.Name);
2414 Console.WriteLine ("Found a: " + m.GetType ().FullName);
2421 eclass = ExprClass.MethodGroup;
2422 type = TypeManager.object_type;
2425 public Type DeclaringType {
2428 // The methods are arranged in this order:
2429 // derived type -> base type
2431 return Methods [0].DeclaringType;
2436 // `A method group may have associated an instance expression'
2438 public Expression InstanceExpression {
2440 return instance_expression;
2444 instance_expression = value;
2448 public bool IsExplicitImpl {
2450 return is_explicit_impl;
2454 is_explicit_impl = value;
2458 public bool IdenticalTypeName {
2460 return identical_type_name;
2464 identical_type_name = value;
2468 public bool IsBase {
2477 public string Name {
2479 return Methods [0].Name;
2483 public bool IsInstance {
2485 foreach (MethodBase mb in Methods)
2493 public bool IsStatic {
2495 foreach (MethodBase mb in Methods)
2503 override public Expression DoResolve (EmitContext ec)
2506 instance_expression = null;
2508 if (instance_expression != null) {
2509 instance_expression = instance_expression.DoResolve (ec);
2510 if (instance_expression == null)
2517 public void ReportUsageError ()
2519 Report.Error (654, loc, "Method `" + DeclaringType + "." +
2520 Name + "()' is referenced without parentheses");
2523 override public void Emit (EmitContext ec)
2525 ReportUsageError ();
2528 bool RemoveMethods (bool keep_static)
2530 ArrayList smethods = new ArrayList ();
2532 foreach (MethodBase mb in Methods){
2533 if (mb.IsStatic == keep_static)
2537 if (smethods.Count == 0)
2540 Methods = new MethodBase [smethods.Count];
2541 smethods.CopyTo (Methods, 0);
2547 /// Removes any instance methods from the MethodGroup, returns
2548 /// false if the resulting set is empty.
2550 public bool RemoveInstanceMethods ()
2552 return RemoveMethods (true);
2556 /// Removes any static methods from the MethodGroup, returns
2557 /// false if the resulting set is empty.
2559 public bool RemoveStaticMethods ()
2561 return RemoveMethods (false);
2566 /// Fully resolved expression that evaluates to a Field
2568 public class FieldExpr : Expression, IAssignMethod, IMemoryLocation, IMemberExpr, IVariable {
2569 public readonly FieldInfo FieldInfo;
2570 Expression instance_expr;
2571 VariableInfo variable_info;
2573 LocalTemporary temporary;
2574 IMemoryLocation instance_ml;
2575 bool have_temporary;
2577 public FieldExpr (FieldInfo fi, Location l)
2580 eclass = ExprClass.Variable;
2581 type = fi.FieldType;
2585 public string Name {
2587 return FieldInfo.Name;
2591 public bool IsInstance {
2593 return !FieldInfo.IsStatic;
2597 public bool IsStatic {
2599 return FieldInfo.IsStatic;
2603 public Type DeclaringType {
2605 return FieldInfo.DeclaringType;
2609 public Expression InstanceExpression {
2611 return instance_expr;
2615 instance_expr = value;
2619 public VariableInfo VariableInfo {
2621 return variable_info;
2625 override public Expression DoResolve (EmitContext ec)
2627 if (!FieldInfo.IsStatic){
2628 if (instance_expr == null){
2630 // This can happen when referencing an instance field using
2631 // a fully qualified type expression: TypeName.InstanceField = xxx
2633 SimpleName.Error_ObjectRefRequired (ec, loc, FieldInfo.Name);
2637 // Resolve the field's instance expression while flow analysis is turned
2638 // off: when accessing a field "a.b", we must check whether the field
2639 // "a.b" is initialized, not whether the whole struct "a" is initialized.
2640 instance_expr = instance_expr.Resolve (ec, ResolveFlags.VariableOrValue |
2641 ResolveFlags.DisableFlowAnalysis);
2642 if (instance_expr == null)
2646 ObsoleteAttribute oa;
2647 FieldBase f = TypeManager.GetField (FieldInfo);
2649 oa = f.GetObsoleteAttribute (ec.DeclSpace);
2651 AttributeTester.Report_ObsoleteMessage (oa, f.GetSignatureForError (), loc);
2653 // To be sure that type is external because we do not register generated fields
2654 } else if (!(FieldInfo.DeclaringType is TypeBuilder)) {
2655 oa = AttributeTester.GetMemberObsoleteAttribute (FieldInfo);
2657 AttributeTester.Report_ObsoleteMessage (oa, TypeManager.GetFullNameSignature (FieldInfo), loc);
2660 // If the instance expression is a local variable or parameter.
2661 IVariable var = instance_expr as IVariable;
2662 if ((var == null) || (var.VariableInfo == null))
2665 VariableInfo vi = var.VariableInfo;
2666 if (!vi.IsFieldAssigned (ec, FieldInfo.Name, loc))
2669 variable_info = vi.GetSubStruct (FieldInfo.Name);
2673 void Report_AssignToReadonly (bool is_instance)
2678 msg = "Readonly field can not be assigned outside " +
2679 "of constructor or variable initializer";
2681 msg = "A static readonly field can only be assigned in " +
2682 "a static constructor";
2684 Report.Error (is_instance ? 191 : 198, loc, msg);
2687 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
2689 IVariable var = instance_expr as IVariable;
2690 if ((var != null) && (var.VariableInfo != null))
2691 var.VariableInfo.SetFieldAssigned (ec, FieldInfo.Name);
2693 Expression e = DoResolve (ec);
2698 if (!FieldInfo.IsStatic && (instance_expr.Type.IsValueType && !(instance_expr is IMemoryLocation))) {
2699 // FIXME: Provide better error reporting.
2700 Error (1612, "Cannot modify expression because it is not a variable.");
2704 if (!FieldInfo.IsInitOnly)
2707 FieldBase fb = TypeManager.GetField (FieldInfo);
2712 // InitOnly fields can only be assigned in constructors
2715 if (ec.IsConstructor){
2716 if (IsStatic && !ec.IsStatic)
2717 Report_AssignToReadonly (false);
2719 if (ec.ContainerType == FieldInfo.DeclaringType)
2723 Report_AssignToReadonly (true);
2728 public bool VerifyFixed (bool is_expression)
2730 IVariable variable = instance_expr as IVariable;
2731 if ((variable == null) || !variable.VerifyFixed (true))
2737 public override void CacheTemporaries (EmitContext ec)
2739 if (!FieldInfo.IsStatic && (temporary == null))
2740 temporary = new LocalTemporary (ec, instance_expr.Type);
2743 void EmitInstance (EmitContext ec)
2745 if (instance_expr.Type.IsValueType)
2746 CacheTemporaries (ec);
2748 if ((temporary == null) || have_temporary)
2751 if (instance_expr.Type.IsValueType) {
2752 instance_ml = instance_expr as IMemoryLocation;
2753 if (instance_ml == null) {
2754 instance_expr.Emit (ec);
2755 temporary.Store (ec);
2756 instance_ml = temporary;
2759 instance_expr.Emit (ec);
2760 temporary.Store (ec);
2763 have_temporary = true;
2766 override public void Emit (EmitContext ec)
2768 ILGenerator ig = ec.ig;
2769 bool is_volatile = false;
2771 if (FieldInfo is FieldBuilder){
2772 FieldBase f = TypeManager.GetField (FieldInfo);
2774 if ((f.ModFlags & Modifiers.VOLATILE) != 0)
2777 f.status |= Field.Status.USED;
2781 if (FieldInfo.IsStatic){
2783 ig.Emit (OpCodes.Volatile);
2785 ig.Emit (OpCodes.Ldsfld, FieldInfo);
2790 if (instance_ml != null)
2791 instance_ml.AddressOf (ec, AddressOp.Load);
2792 else if (temporary != null)
2793 temporary.Emit (ec);
2795 instance_expr.Emit (ec);
2798 ig.Emit (OpCodes.Volatile);
2800 ig.Emit (OpCodes.Ldfld, FieldInfo);
2803 public void EmitAssign (EmitContext ec, Expression source)
2805 FieldAttributes fa = FieldInfo.Attributes;
2806 bool is_static = (fa & FieldAttributes.Static) != 0;
2807 bool is_readonly = (fa & FieldAttributes.InitOnly) != 0;
2808 ILGenerator ig = ec.ig;
2810 if (is_readonly && !ec.IsConstructor){
2811 Report_AssignToReadonly (!is_static);
2817 if (instance_ml != null)
2818 instance_ml.AddressOf (ec, AddressOp.Store);
2819 else if (temporary != null)
2820 temporary.Emit (ec);
2822 instance_expr.Emit (ec);
2827 if (FieldInfo is FieldBuilder){
2828 FieldBase f = TypeManager.GetField (FieldInfo);
2830 if ((f.ModFlags & Modifiers.VOLATILE) != 0)
2831 ig.Emit (OpCodes.Volatile);
2833 f.status |= Field.Status.ASSIGNED;
2838 ig.Emit (OpCodes.Stsfld, FieldInfo);
2840 ig.Emit (OpCodes.Stfld, FieldInfo);
2843 public void AddressOf (EmitContext ec, AddressOp mode)
2845 ILGenerator ig = ec.ig;
2847 if (FieldInfo is FieldBuilder){
2848 FieldBase f = TypeManager.GetField (FieldInfo);
2850 if ((f.ModFlags & Modifiers.VOLATILE) != 0){
2851 Error (676, "volatile variable: can not take its address, or pass as ref/out parameter");
2855 if ((mode & AddressOp.Store) != 0)
2856 f.status |= Field.Status.ASSIGNED;
2857 if ((mode & AddressOp.Load) != 0)
2858 f.status |= Field.Status.USED;
2863 // Handle initonly fields specially: make a copy and then
2864 // get the address of the copy.
2867 if (FieldInfo.IsInitOnly){
2869 if (ec.IsConstructor){
2870 if (FieldInfo.IsStatic){
2882 local = ig.DeclareLocal (type);
2883 ig.Emit (OpCodes.Stloc, local);
2884 ig.Emit (OpCodes.Ldloca, local);
2889 if (FieldInfo.IsStatic){
2890 ig.Emit (OpCodes.Ldsflda, FieldInfo);
2893 // In the case of `This', we call the AddressOf method, which will
2894 // only load the pointer, and not perform an Ldobj immediately after
2895 // the value has been loaded into the stack.
2898 if (instance_ml != null)
2899 instance_ml.AddressOf (ec, AddressOp.LoadStore);
2900 else if (temporary != null)
2901 temporary.Emit (ec);
2902 else if (instance_expr is This)
2903 ((This)instance_expr).AddressOf (ec, AddressOp.LoadStore);
2905 instance_expr.Emit (ec);
2906 ig.Emit (OpCodes.Ldflda, FieldInfo);
2912 // A FieldExpr whose address can not be taken
2914 public class FieldExprNoAddress : FieldExpr, IMemoryLocation {
2915 public FieldExprNoAddress (FieldInfo fi, Location loc) : base (fi, loc)
2919 public new void AddressOf (EmitContext ec, AddressOp mode)
2921 Report.Error (-215, "Report this: Taking the address of a remapped parameter not supported");
2926 /// Expression that evaluates to a Property. The Assign class
2927 /// might set the `Value' expression if we are in an assignment.
2929 /// This is not an LValue because we need to re-write the expression, we
2930 /// can not take data from the stack and store it.
2932 public class PropertyExpr : ExpressionStatement, IAssignMethod, IMemberExpr {
2933 public readonly PropertyInfo PropertyInfo;
2936 // This is set externally by the `BaseAccess' class
2939 MethodInfo getter, setter;
2941 bool must_do_cs1540_check;
2943 Expression instance_expr;
2944 LocalTemporary temporary;
2945 bool have_temporary;
2947 public PropertyExpr (EmitContext ec, PropertyInfo pi, Location l)
2950 eclass = ExprClass.PropertyAccess;
2954 type = TypeManager.TypeToCoreType (pi.PropertyType);
2956 ResolveAccessors (ec);
2959 public string Name {
2961 return PropertyInfo.Name;
2965 public bool IsInstance {
2971 public bool IsStatic {
2977 public Type DeclaringType {
2979 return PropertyInfo.DeclaringType;
2984 // The instance expression associated with this expression
2986 public Expression InstanceExpression {
2988 instance_expr = value;
2992 return instance_expr;
2996 public bool VerifyAssignable ()
2998 if (setter == null) {
2999 Report.Error (200, loc,
3000 "The property `" + PropertyInfo.Name +
3001 "' can not be assigned to, as it has not set accessor");
3008 MethodInfo FindAccessor (Type invocation_type, bool is_set)
3010 BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic |
3011 BindingFlags.Static | BindingFlags.Instance |
3012 BindingFlags.DeclaredOnly;
3014 Type current = PropertyInfo.DeclaringType;
3015 for (; current != null; current = current.BaseType) {
3016 MemberInfo[] group = TypeManager.MemberLookup (
3017 invocation_type, invocation_type, current,
3018 MemberTypes.Property, flags, PropertyInfo.Name, null);
3023 if (group.Length != 1)
3024 // Oooops, can this ever happen ?
3027 PropertyInfo pi = (PropertyInfo) group [0];
3029 MethodInfo get = pi.GetGetMethod (true);
3030 MethodInfo set = pi.GetSetMethod (true);
3040 MethodInfo accessor = get != null ? get : set;
3041 if (accessor == null)
3043 if ((accessor.Attributes & MethodAttributes.NewSlot) != 0)
3050 MethodInfo GetAccessor (Type invocation_type, bool is_set)
3052 MethodInfo mi = FindAccessor (invocation_type, is_set);
3056 MethodAttributes ma = mi.Attributes & MethodAttributes.MemberAccessMask;
3059 // If only accessible to the current class or children
3061 if (ma == MethodAttributes.Private) {
3062 Type declaring_type = mi.DeclaringType;
3064 if (invocation_type != declaring_type){
3065 if (TypeManager.IsSubclassOrNestedChildOf (invocation_type, mi.DeclaringType))
3073 // FamAndAssem requires that we not only derivate, but we are on the
3076 if (ma == MethodAttributes.FamANDAssem){
3077 if (mi.DeclaringType.Assembly != invocation_type.Assembly)
3083 // Assembly and FamORAssem succeed if we're in the same assembly.
3084 if ((ma == MethodAttributes.Assembly) || (ma == MethodAttributes.FamORAssem)){
3085 if (mi.DeclaringType.Assembly == invocation_type.Assembly)
3089 // We already know that we aren't in the same assembly.
3090 if (ma == MethodAttributes.Assembly)
3093 // Family and FamANDAssem require that we derive.
3094 if ((ma == MethodAttributes.Family) || (ma == MethodAttributes.FamANDAssem) || (ma == MethodAttributes.FamORAssem)){
3095 if (!TypeManager.IsSubclassOrNestedChildOf (invocation_type, mi.DeclaringType))
3098 if (!TypeManager.IsNestedChildOf (invocation_type, mi.DeclaringType))
3099 must_do_cs1540_check = true;
3109 // We also perform the permission checking here, as the PropertyInfo does not
3110 // hold the information for the accessibility of its setter/getter
3112 void ResolveAccessors (EmitContext ec)
3114 getter = GetAccessor (ec.ContainerType, false);
3115 if ((getter != null) && getter.IsStatic)
3118 setter = GetAccessor (ec.ContainerType, true);
3119 if ((setter != null) && setter.IsStatic)
3122 if (setter == null && getter == null){
3123 Report.Error_T (122, loc, PropertyInfo.Name);
3127 bool InstanceResolve (EmitContext ec)
3129 if ((instance_expr == null) && ec.IsStatic && !is_static) {
3130 SimpleName.Error_ObjectRefRequired (ec, loc, PropertyInfo.Name);
3134 if (instance_expr != null) {
3135 instance_expr = instance_expr.DoResolve (ec);
3136 if (instance_expr == null)
3140 if (must_do_cs1540_check && (instance_expr != null)) {
3141 if ((instance_expr.Type != ec.ContainerType) &&
3142 ec.ContainerType.IsSubclassOf (instance_expr.Type)) {
3143 Report.Error (1540, loc, "Cannot access protected member `" +
3144 PropertyInfo.DeclaringType + "." + PropertyInfo.Name +
3145 "' via a qualifier of type `" +
3146 TypeManager.CSharpName (instance_expr.Type) +
3147 "'; the qualifier must be of type `" +
3148 TypeManager.CSharpName (ec.ContainerType) +
3149 "' (or derived from it)");
3157 override public Expression DoResolve (EmitContext ec)
3159 if (getter != null){
3160 if (TypeManager.GetArgumentTypes (getter).Length != 0){
3162 117, loc, "`{0}' does not contain a " +
3163 "definition for `{1}'.", getter.DeclaringType,
3169 if (getter == null){
3171 // The following condition happens if the PropertyExpr was
3172 // created, but is invalid (ie, the property is inaccessible),
3173 // and we did not want to embed the knowledge about this in
3174 // the caller routine. This only avoids double error reporting.
3179 Report.Error (154, loc,
3180 "The property `" + PropertyInfo.Name +
3181 "' can not be used in " +
3182 "this context because it lacks a get accessor");
3186 if (!InstanceResolve (ec))
3190 // Only base will allow this invocation to happen.
3192 if (IsBase && getter.IsAbstract){
3193 Report.Error (205, loc, "Cannot call an abstract base property: " +
3194 PropertyInfo.DeclaringType + "." +PropertyInfo.Name);
3201 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
3203 if (setter == null){
3205 // The following condition happens if the PropertyExpr was
3206 // created, but is invalid (ie, the property is inaccessible),
3207 // and we did not want to embed the knowledge about this in
3208 // the caller routine. This only avoids double error reporting.
3213 Report.Error (154, loc,
3214 "The property `" + PropertyInfo.Name +
3215 "' can not be used in " +
3216 "this context because it lacks a set accessor");
3220 if (TypeManager.GetArgumentTypes (setter).Length != 1){
3222 117, loc, "`{0}' does not contain a " +
3223 "definition for `{1}'.", getter.DeclaringType,
3228 if (!InstanceResolve (ec))
3232 // Only base will allow this invocation to happen.
3234 if (IsBase && setter.IsAbstract){
3235 Report.Error (205, loc, "Cannot call an abstract base property: " +
3236 PropertyInfo.DeclaringType + "." +PropertyInfo.Name);
3241 // Check that we are not making changes to a temporary memory location
3243 if (instance_expr != null && instance_expr.Type.IsValueType && !(instance_expr is IMemoryLocation)) {
3244 // FIXME: Provide better error reporting.
3245 Error (1612, "Cannot modify expression because it is not a variable.");
3252 public override void CacheTemporaries (EmitContext ec)
3255 // we need to do indirection on the pointer
3256 bool need_address = instance_expr.Type.IsValueType;
3257 temporary = new LocalTemporary (ec, instance_expr.Type, need_address);
3261 Expression EmitInstance (EmitContext ec)
3263 if (temporary != null){
3264 if (!have_temporary){
3265 if (temporary.PointsToAddress){
3266 // must store the managed pointer
3267 IMemoryLocation loc = instance_expr as IMemoryLocation;
3268 loc.AddressOf (ec, AddressOp.LoadStore);
3270 instance_expr.Emit (ec);
3271 temporary.Store (ec);
3273 have_temporary = true;
3277 return instance_expr;
3280 override public void Emit (EmitContext ec)
3282 Expression expr = EmitInstance (ec);
3285 // Special case: length of single dimension array property is turned into ldlen
3287 if ((getter == TypeManager.system_int_array_get_length) ||
3288 (getter == TypeManager.int_array_get_length)){
3289 Type iet = instance_expr.Type;
3292 // System.Array.Length can be called, but the Type does not
3293 // support invoking GetArrayRank, so test for that case first
3295 if (iet != TypeManager.array_type && (iet.GetArrayRank () == 1)){
3297 ec.ig.Emit (OpCodes.Ldlen);
3298 ec.ig.Emit (OpCodes.Conv_I4);
3303 Invocation.EmitCall (ec, IsBase, IsStatic, expr, getter, null, loc);
3308 // Implements the IAssignMethod interface for assignments
3310 public void EmitAssign (EmitContext ec, Expression source)
3312 Expression expr = EmitInstance (ec);
3314 Argument arg = new Argument (source, Argument.AType.Expression);
3315 ArrayList args = new ArrayList ();
3318 Invocation.EmitCall (ec, IsBase, IsStatic, expr, setter, args, loc);
3321 override public void EmitStatement (EmitContext ec)
3324 ec.ig.Emit (OpCodes.Pop);
3329 /// Fully resolved expression that evaluates to an Event
3331 public class EventExpr : Expression, IMemberExpr {
3332 public readonly EventInfo EventInfo;
3333 Expression instance_expr;
3336 MethodInfo add_accessor, remove_accessor;
3338 public EventExpr (EventInfo ei, Location loc)
3342 eclass = ExprClass.EventAccess;
3344 add_accessor = TypeManager.GetAddMethod (ei);
3345 remove_accessor = TypeManager.GetRemoveMethod (ei);
3347 if (add_accessor.IsStatic || remove_accessor.IsStatic)
3350 if (EventInfo is MyEventBuilder){
3351 MyEventBuilder eb = (MyEventBuilder) EventInfo;
3352 type = eb.EventType;
3355 type = EventInfo.EventHandlerType;
3358 public string Name {
3360 return EventInfo.Name;
3364 public bool IsInstance {
3370 public bool IsStatic {
3376 public Type DeclaringType {
3378 return EventInfo.DeclaringType;
3382 public Expression InstanceExpression {
3384 return instance_expr;
3388 instance_expr = value;
3392 public override Expression DoResolve (EmitContext ec)
3394 if (instance_expr != null) {
3395 instance_expr = instance_expr.DoResolve (ec);
3396 if (instance_expr == null)
3404 public override void Emit (EmitContext ec)
3406 Report.Error (70, loc, "The event `" + Name + "' can only appear on the left hand side of += or -= (except on the defining type)");
3409 public void EmitAddOrRemove (EmitContext ec, Expression source)
3411 BinaryDelegate source_del = (BinaryDelegate) source;
3412 Expression handler = source_del.Right;
3414 Argument arg = new Argument (handler, Argument.AType.Expression);
3415 ArrayList args = new ArrayList ();
3419 if (source_del.IsAddition)
3420 Invocation.EmitCall (
3421 ec, false, IsStatic, instance_expr, add_accessor, args, loc);
3423 Invocation.EmitCall (
3424 ec, false, IsStatic, instance_expr, remove_accessor, args, loc);