2 // ecore.cs: Core of the Expression representation for the intermediate tree.
5 // Miguel de Icaza (miguel@ximian.com)
7 // (C) 2001, 2002, 2003 Ximian, Inc.
11 namespace Mono.CSharp {
13 using System.Collections;
14 using System.Diagnostics;
15 using System.Reflection;
16 using System.Reflection.Emit;
20 /// The ExprClass class contains the is used to pass the
21 /// classification of an expression (value, variable, namespace,
22 /// type, method group, property access, event access, indexer access,
25 public enum ExprClass : byte {
40 /// This is used to tell Resolve in which types of expressions we're
44 public enum ResolveFlags {
45 // Returns Value, Variable, PropertyAccess, EventAccess or IndexerAccess.
48 // Returns a type expression.
51 // Returns a method group.
54 // Allows SimpleNames to be returned.
55 // This is used by MemberAccess to construct long names that can not be
56 // partially resolved (namespace-qualified names for example).
59 // Mask of all the expression class flags.
62 // Disable control flow analysis while resolving the expression.
63 // This is used when resolving the instance expression of a field expression.
64 DisableFlowAnalysis = 16,
66 // Set if this is resolving the first part of a MemberAccess.
71 // This is just as a hint to AddressOf of what will be done with the
74 public enum AddressOp {
81 /// This interface is implemented by variables
83 public interface IMemoryLocation {
85 /// The AddressOf method should generate code that loads
86 /// the address of the object and leaves it on the stack.
88 /// The `mode' argument is used to notify the expression
89 /// of whether this will be used to read from the address or
90 /// write to the address.
92 /// This is just a hint that can be used to provide good error
93 /// reporting, and should have no other side effects.
95 void AddressOf (EmitContext ec, AddressOp mode);
99 /// This interface is implemented by variables
101 public interface IVariable {
102 VariableInfo VariableInfo {
106 bool VerifyFixed (bool is_expression);
110 /// This interface denotes an expression which evaluates to a member
111 /// of a struct or a class.
113 public interface IMemberExpr
116 /// The name of this member.
123 /// Whether this is an instance member.
130 /// Whether this is a static member.
137 /// The type which declares this member.
144 /// The instance expression associated with this member, if it's a
145 /// non-static member.
147 Expression InstanceExpression {
153 /// Base class for expressions
155 public abstract class Expression {
156 public ExprClass eclass;
158 protected Location loc;
170 public Location Location {
177 /// Utility wrapper routine for Error, just to beautify the code
179 public void Error (int error, string s)
181 if (!Location.IsNull (loc))
182 Report.Error (error, loc, s);
184 Report.Error (error, s);
188 /// Utility wrapper routine for Warning, just to beautify the code
190 public void Warning (int code, string format, params object[] args)
192 Report.Warning (code, loc, format, args);
196 /// Tests presence of ObsoleteAttribute and report proper error
198 protected void CheckObsoleteAttribute (Type type)
200 ObsoleteAttribute obsolete_attr = AttributeTester.GetObsoleteAttribute (type);
201 if (obsolete_attr == null)
204 AttributeTester.Report_ObsoleteMessage (obsolete_attr, type.FullName, loc);
208 /// Performs semantic analysis on the Expression
212 /// The Resolve method is invoked to perform the semantic analysis
215 /// The return value is an expression (it can be the
216 /// same expression in some cases) or a new
217 /// expression that better represents this node.
219 /// For example, optimizations of Unary (LiteralInt)
220 /// would return a new LiteralInt with a negated
223 /// If there is an error during semantic analysis,
224 /// then an error should be reported (using Report)
225 /// and a null value should be returned.
227 /// There are two side effects expected from calling
228 /// Resolve(): the the field variable "eclass" should
229 /// be set to any value of the enumeration
230 /// `ExprClass' and the type variable should be set
231 /// to a valid type (this is the type of the
234 public abstract Expression DoResolve (EmitContext ec);
236 public virtual Expression DoResolveLValue (EmitContext ec, Expression right_side)
238 return DoResolve (ec);
242 // This is used if the expression should be resolved as a type.
243 // the default implementation fails. Use this method in
244 // those participants in the SimpleName chain system.
246 public virtual Expression ResolveAsTypeStep (EmitContext ec)
252 // This is used to resolve the expression as a type, a null
253 // value will be returned if the expression is not a type
256 public TypeExpr ResolveAsTypeTerminal (EmitContext ec, bool silent)
258 int errors = Report.Errors;
260 TypeExpr te = ResolveAsTypeStep (ec) as TypeExpr;
262 if (te == null || te.eclass != ExprClass.Type) {
263 if (!silent && errors == Report.Errors)
264 Report.Error (246, Location, "Cannot find type '{0}'", ToString ());
268 if (!te.CheckAccessLevel (ec.DeclSpace)) {
269 Report.Error (122, Location, "'{0}' is inaccessible due to its protection level", te.Name);
277 /// Resolves an expression and performs semantic analysis on it.
281 /// Currently Resolve wraps DoResolve to perform sanity
282 /// checking and assertion checking on what we expect from Resolve.
284 public Expression Resolve (EmitContext ec, ResolveFlags flags)
286 if ((flags & ResolveFlags.MaskExprClass) == ResolveFlags.Type)
287 return ResolveAsTypeStep (ec);
289 bool old_do_flow_analysis = ec.DoFlowAnalysis;
290 if ((flags & ResolveFlags.DisableFlowAnalysis) != 0)
291 ec.DoFlowAnalysis = false;
294 bool intermediate = (flags & ResolveFlags.Intermediate) == ResolveFlags.Intermediate;
295 if (this is SimpleName)
296 e = ((SimpleName) this).DoResolveAllowStatic (ec, intermediate);
301 ec.DoFlowAnalysis = old_do_flow_analysis;
306 if (e is SimpleName){
307 SimpleName s = (SimpleName) e;
309 if ((flags & ResolveFlags.SimpleName) == 0) {
310 MemberLookupFailed (ec, null, ec.ContainerType, s.Name,
311 ec.DeclSpace.Name, loc);
318 if ((e is TypeExpr) || (e is ComposedCast)) {
319 if ((flags & ResolveFlags.Type) == 0) {
320 e.Error_UnexpectedKind (flags, loc);
329 if ((flags & ResolveFlags.VariableOrValue) == 0) {
330 e.Error_UnexpectedKind (flags, loc);
335 case ExprClass.MethodGroup:
336 if (RootContext.Version == LanguageVersion.ISO_1){
337 if ((flags & ResolveFlags.MethodGroup) == 0) {
338 ((MethodGroupExpr) e).ReportUsageError ();
344 case ExprClass.Value:
345 case ExprClass.Variable:
346 case ExprClass.PropertyAccess:
347 case ExprClass.EventAccess:
348 case ExprClass.IndexerAccess:
349 if ((flags & ResolveFlags.VariableOrValue) == 0) {
350 Console.WriteLine ("I got: {0} and {1}", e.GetType (), e);
351 Console.WriteLine ("I am {0} and {1}", this.GetType (), this);
352 FieldInfo fi = ((FieldExpr) e).FieldInfo;
354 Console.WriteLine ("{0} and {1}", fi.DeclaringType, fi.Name);
355 e.Error_UnexpectedKind (flags, loc);
361 throw new Exception ("Expression " + e.GetType () +
362 " ExprClass is Invalid after resolve");
366 throw new Exception (
367 "Expression " + e.GetType () +
368 " did not set its type after Resolve\n" +
369 "called from: " + this.GetType ());
375 /// Resolves an expression and performs semantic analysis on it.
377 public Expression Resolve (EmitContext ec)
379 return Resolve (ec, ResolveFlags.VariableOrValue);
383 /// Resolves an expression for LValue assignment
387 /// Currently ResolveLValue wraps DoResolveLValue to perform sanity
388 /// checking and assertion checking on what we expect from Resolve
390 public Expression ResolveLValue (EmitContext ec, Expression right_side)
392 Expression e = DoResolveLValue (ec, right_side);
395 if (e is SimpleName){
396 SimpleName s = (SimpleName) e;
397 MemberLookupFailed (ec, null, ec.ContainerType, s.Name,
398 ec.DeclSpace.Name, loc);
402 if (e.eclass == ExprClass.Invalid)
403 throw new Exception ("Expression " + e +
404 " ExprClass is Invalid after resolve");
406 if (e.eclass == ExprClass.MethodGroup) {
407 ((MethodGroupExpr) e).ReportUsageError ();
412 throw new Exception ("Expression " + e +
413 " did not set its type after Resolve");
420 /// Emits the code for the expression
424 /// The Emit method is invoked to generate the code
425 /// for the expression.
427 public abstract void Emit (EmitContext ec);
429 public virtual void EmitBranchable (EmitContext ec, Label target, bool onTrue)
432 ec.ig.Emit (onTrue ? OpCodes.Brtrue : OpCodes.Brfalse, target);
436 /// Protected constructor. Only derivate types should
437 /// be able to be created
440 protected Expression ()
442 eclass = ExprClass.Invalid;
447 /// Returns a literalized version of a literal FieldInfo
451 /// The possible return values are:
452 /// IntConstant, UIntConstant
453 /// LongLiteral, ULongConstant
454 /// FloatConstant, DoubleConstant
457 /// The value returned is already resolved.
459 public static Constant Constantify (object v, Type t)
461 if (t == TypeManager.int32_type)
462 return new IntConstant ((int) v);
463 else if (t == TypeManager.uint32_type)
464 return new UIntConstant ((uint) v);
465 else if (t == TypeManager.int64_type)
466 return new LongConstant ((long) v);
467 else if (t == TypeManager.uint64_type)
468 return new ULongConstant ((ulong) v);
469 else if (t == TypeManager.float_type)
470 return new FloatConstant ((float) v);
471 else if (t == TypeManager.double_type)
472 return new DoubleConstant ((double) v);
473 else if (t == TypeManager.string_type)
474 return new StringConstant ((string) v);
475 else if (t == TypeManager.short_type)
476 return new ShortConstant ((short)v);
477 else if (t == TypeManager.ushort_type)
478 return new UShortConstant ((ushort)v);
479 else if (t == TypeManager.sbyte_type)
480 return new SByteConstant (((sbyte)v));
481 else if (t == TypeManager.byte_type)
482 return new ByteConstant ((byte)v);
483 else if (t == TypeManager.char_type)
484 return new CharConstant ((char)v);
485 else if (t == TypeManager.bool_type)
486 return new BoolConstant ((bool) v);
487 else if (t == TypeManager.decimal_type)
488 return new DecimalConstant ((decimal) v);
489 else if (TypeManager.IsEnumType (t)){
490 Type real_type = TypeManager.TypeToCoreType (v.GetType ());
492 real_type = System.Enum.GetUnderlyingType (real_type);
494 Constant e = Constantify (v, real_type);
496 return new EnumConstant (e, t);
497 } else if (v == null && !TypeManager.IsValueType (t))
498 return NullLiteral.Null;
500 throw new Exception ("Unknown type for constant (" + t +
505 /// Returns a fully formed expression after a MemberLookup
507 public static Expression ExprClassFromMemberInfo (EmitContext ec, MemberInfo mi, Location loc)
510 return new EventExpr ((EventInfo) mi, loc);
511 else if (mi is FieldInfo)
512 return new FieldExpr ((FieldInfo) mi, loc);
513 else if (mi is PropertyInfo)
514 return new PropertyExpr (ec, (PropertyInfo) mi, loc);
515 else if (mi is Type){
516 return new TypeExpression ((System.Type) mi, loc);
523 private static ArrayList almostMatchedMembers = new ArrayList (4);
526 // FIXME: Probably implement a cache for (t,name,current_access_set)?
528 // This code could use some optimizations, but we need to do some
529 // measurements. For example, we could use a delegate to `flag' when
530 // something can not any longer be a method-group (because it is something
534 // If the return value is an Array, then it is an array of
537 // If the return value is an MemberInfo, it is anything, but a Method
541 // FIXME: When calling MemberLookup inside an `Invocation', we should pass
542 // the arguments here and have MemberLookup return only the methods that
543 // match the argument count/type, unlike we are doing now (we delay this
546 // This is so we can catch correctly attempts to invoke instance methods
547 // from a static body (scan for error 120 in ResolveSimpleName).
550 // FIXME: Potential optimization, have a static ArrayList
553 public static Expression MemberLookup (EmitContext ec, Type queried_type, string name,
554 MemberTypes mt, BindingFlags bf, Location loc)
556 return MemberLookup (ec, ec.ContainerType, null, queried_type, name, mt, bf, loc);
560 // Lookup type `queried_type' for code in class `container_type' with a qualifier of
561 // `qualifier_type' or null to lookup members in the current class.
564 public static Expression MemberLookup (EmitContext ec, Type container_type,
565 Type qualifier_type, Type queried_type,
566 string name, MemberTypes mt,
567 BindingFlags bf, Location loc)
569 almostMatchedMembers.Clear ();
571 MemberInfo [] mi = TypeManager.MemberLookup (container_type, qualifier_type,
572 queried_type, mt, bf, name, almostMatchedMembers);
577 int count = mi.Length;
579 if (mi [0] is MethodBase)
580 return new MethodGroupExpr (mi, loc);
585 return ExprClassFromMemberInfo (ec, mi [0], loc);
588 public const MemberTypes AllMemberTypes =
589 MemberTypes.Constructor |
593 MemberTypes.NestedType |
594 MemberTypes.Property;
596 public const BindingFlags AllBindingFlags =
597 BindingFlags.Public |
598 BindingFlags.Static |
599 BindingFlags.Instance;
601 public static Expression MemberLookup (EmitContext ec, Type queried_type,
602 string name, Location loc)
604 return MemberLookup (ec, ec.ContainerType, null, queried_type, name,
605 AllMemberTypes, AllBindingFlags, loc);
608 public static Expression MemberLookup (EmitContext ec, Type qualifier_type,
609 Type queried_type, string name, Location loc)
611 return MemberLookup (ec, ec.ContainerType, qualifier_type, queried_type,
612 name, AllMemberTypes, AllBindingFlags, loc);
615 public static Expression MethodLookup (EmitContext ec, Type queried_type,
616 string name, Location loc)
618 return MemberLookup (ec, ec.ContainerType, null, queried_type, name,
619 MemberTypes.Method, AllBindingFlags, loc);
623 /// This is a wrapper for MemberLookup that is not used to "probe", but
624 /// to find a final definition. If the final definition is not found, we
625 /// look for private members and display a useful debugging message if we
628 public static Expression MemberLookupFinal (EmitContext ec, Type qualifier_type,
629 Type queried_type, string name, Location loc)
631 return MemberLookupFinal (ec, qualifier_type, queried_type, name,
632 AllMemberTypes, AllBindingFlags, loc);
635 public static Expression MemberLookupFinal (EmitContext ec, Type qualifier_type,
636 Type queried_type, string name,
637 MemberTypes mt, BindingFlags bf,
642 int errors = Report.Errors;
644 e = MemberLookup (ec, ec.ContainerType, qualifier_type, queried_type, name, mt, bf, loc);
646 if (e == null && errors == Report.Errors)
647 // No errors were reported by MemberLookup, but there was an error.
648 MemberLookupFailed (ec, qualifier_type, queried_type, name, null, loc);
653 public static void MemberLookupFailed (EmitContext ec, Type qualifier_type,
654 Type queried_type, string name,
655 string class_name, Location loc)
657 if (almostMatchedMembers.Count != 0) {
658 if (qualifier_type == null) {
659 foreach (MemberInfo m in almostMatchedMembers)
660 Report.Error (38, loc,
661 "Cannot access non-static member `{0}' via nested type `{1}'",
662 TypeManager.GetFullNameSignature (m),
663 TypeManager.CSharpName (ec.ContainerType));
667 if (qualifier_type != ec.ContainerType) {
668 // Although a derived class can access protected members of
669 // its base class it cannot do so through an instance of the
670 // base class (CS1540). If the qualifier_type is a parent of the
671 // ec.ContainerType and the lookup succeeds with the latter one,
672 // then we are in this situation.
673 foreach (MemberInfo m in almostMatchedMembers)
674 Report.Error (1540, loc,
675 "Cannot access protected member `{0}' via a qualifier of type `{1}';"
676 + " the qualifier must be of type `{2}' (or derived from it)",
677 TypeManager.GetFullNameSignature (m),
678 TypeManager.CSharpName (qualifier_type),
679 TypeManager.CSharpName (ec.ContainerType));
682 almostMatchedMembers.Clear ();
685 object lookup = TypeManager.MemberLookup (queried_type, null, queried_type,
686 AllMemberTypes, AllBindingFlags |
687 BindingFlags.NonPublic, name, null);
689 if (lookup == null) {
690 if (class_name != null)
691 Report.Error (103, loc, "The name `" + name + "' could not be " +
692 "found in `" + class_name + "'");
695 117, loc, "`" + queried_type + "' does not contain a " +
696 "definition for `" + name + "'");
700 if (qualifier_type != null)
701 Report.Error (122, loc, "'{0}' is inaccessible due to its protection level", TypeManager.CSharpName (qualifier_type) + "." + name);
702 else if (name == ".ctor") {
703 Report.Error (143, loc, String.Format ("The type {0} has no constructors defined",
704 TypeManager.CSharpName (queried_type)));
706 Report.Error (122, loc, "'{0}' is inaccessible due to its protection level", name);
710 static public MemberInfo GetFieldFromEvent (EventExpr event_expr)
712 EventInfo ei = event_expr.EventInfo;
714 return TypeManager.GetPrivateFieldOfEvent (ei);
718 /// Returns an expression that can be used to invoke operator true
719 /// on the expression if it exists.
721 static public StaticCallExpr GetOperatorTrue (EmitContext ec, Expression e, Location loc)
723 return GetOperatorTrueOrFalse (ec, e, true, loc);
727 /// Returns an expression that can be used to invoke operator false
728 /// on the expression if it exists.
730 static public StaticCallExpr GetOperatorFalse (EmitContext ec, Expression e, Location loc)
732 return GetOperatorTrueOrFalse (ec, e, false, loc);
735 static StaticCallExpr GetOperatorTrueOrFalse (EmitContext ec, Expression e, bool is_true, Location loc)
738 Expression operator_group;
740 operator_group = MethodLookup (ec, e.Type, is_true ? "op_True" : "op_False", loc);
741 if (operator_group == null)
744 ArrayList arguments = new ArrayList ();
745 arguments.Add (new Argument (e, Argument.AType.Expression));
746 method = Invocation.OverloadResolve (
747 ec, (MethodGroupExpr) operator_group, arguments, false, loc);
752 return new StaticCallExpr ((MethodInfo) method, arguments, loc);
756 /// Resolves the expression `e' into a boolean expression: either through
757 /// an implicit conversion, or through an `operator true' invocation
759 public static Expression ResolveBoolean (EmitContext ec, Expression e, Location loc)
765 Expression converted = e;
766 if (e.Type != TypeManager.bool_type)
767 converted = Convert.ImplicitConversion (ec, e, TypeManager.bool_type, new Location (-1));
770 // If no implicit conversion to bool exists, try using `operator true'
772 if (converted == null){
773 Expression operator_true = Expression.GetOperatorTrue (ec, e, loc);
774 if (operator_true == null){
776 31, loc, "Can not convert the expression to a boolean");
786 static string ExprClassName (ExprClass c)
789 case ExprClass.Invalid:
791 case ExprClass.Value:
793 case ExprClass.Variable:
795 case ExprClass.Namespace:
799 case ExprClass.MethodGroup:
800 return "method group";
801 case ExprClass.PropertyAccess:
802 return "property access";
803 case ExprClass.EventAccess:
804 return "event access";
805 case ExprClass.IndexerAccess:
806 return "indexer access";
807 case ExprClass.Nothing:
810 throw new Exception ("Should not happen");
814 /// Reports that we were expecting `expr' to be of class `expected'
816 public void Error_UnexpectedKind (string expected, Location loc)
818 string kind = "Unknown";
820 kind = ExprClassName (eclass);
822 Report.Error (118, loc, "Expression denotes a `" + kind +
823 "' where a `" + expected + "' was expected");
826 public void Error_UnexpectedKind (ResolveFlags flags, Location loc)
828 ArrayList valid = new ArrayList (10);
830 if ((flags & ResolveFlags.VariableOrValue) != 0) {
831 valid.Add ("variable");
835 if ((flags & ResolveFlags.Type) != 0)
838 if ((flags & ResolveFlags.MethodGroup) != 0)
839 valid.Add ("method group");
841 if ((flags & ResolveFlags.SimpleName) != 0)
842 valid.Add ("simple name");
844 if (valid.Count == 0)
845 valid.Add ("unknown");
847 StringBuilder sb = new StringBuilder ();
848 for (int i = 0; i < valid.Count; i++) {
851 else if (i == valid.Count)
853 sb.Append (valid [i]);
856 string kind = ExprClassName (eclass);
858 Error (119, "Expression denotes a `" + kind + "' where " +
859 "a `" + sb.ToString () + "' was expected");
862 static public void Error_ConstantValueCannotBeConverted (Location l, string val, Type t)
864 Report.Error (31, l, "Constant value `" + val + "' cannot be converted to " +
865 TypeManager.CSharpName (t));
868 public static void UnsafeError (Location loc)
870 Report.Error (214, loc, "Pointers may only be used in an unsafe context");
874 /// Converts the IntConstant, UIntConstant, LongConstant or
875 /// ULongConstant into the integral target_type. Notice
876 /// that we do not return an `Expression' we do return
877 /// a boxed integral type.
879 /// FIXME: Since I added the new constants, we need to
880 /// also support conversions from CharConstant, ByteConstant,
881 /// SByteConstant, UShortConstant, ShortConstant
883 /// This is used by the switch statement, so the domain
884 /// of work is restricted to the literals above, and the
885 /// targets are int32, uint32, char, byte, sbyte, ushort,
886 /// short, uint64 and int64
888 public static object ConvertIntLiteral (Constant c, Type target_type, Location loc)
890 if (!Convert.ImplicitStandardConversionExists (Convert.ConstantEC, c, target_type)){
891 Convert.Error_CannotImplicitConversion (loc, c.Type, target_type);
897 if (c.Type == target_type)
898 return ((Constant) c).GetValue ();
901 // Make into one of the literals we handle, we dont really care
902 // about this value as we will just return a few limited types
904 if (c is EnumConstant)
905 c = ((EnumConstant)c).WidenToCompilerConstant ();
907 if (c is IntConstant){
908 int v = ((IntConstant) c).Value;
910 if (target_type == TypeManager.uint32_type){
913 } else if (target_type == TypeManager.char_type){
914 if (v >= Char.MinValue && v <= Char.MaxValue)
916 } else if (target_type == TypeManager.byte_type){
917 if (v >= Byte.MinValue && v <= Byte.MaxValue)
919 } else if (target_type == TypeManager.sbyte_type){
920 if (v >= SByte.MinValue && v <= SByte.MaxValue)
922 } else if (target_type == TypeManager.short_type){
923 if (v >= Int16.MinValue && v <= UInt16.MaxValue)
925 } else if (target_type == TypeManager.ushort_type){
926 if (v >= UInt16.MinValue && v <= UInt16.MaxValue)
928 } else if (target_type == TypeManager.int64_type)
930 else if (target_type == TypeManager.uint64_type){
936 } else if (c is UIntConstant){
937 uint v = ((UIntConstant) c).Value;
939 if (target_type == TypeManager.int32_type){
940 if (v <= Int32.MaxValue)
942 } else if (target_type == TypeManager.char_type){
943 if (v >= Char.MinValue && v <= Char.MaxValue)
945 } else if (target_type == TypeManager.byte_type){
946 if (v <= Byte.MaxValue)
948 } else if (target_type == TypeManager.sbyte_type){
949 if (v <= SByte.MaxValue)
951 } else if (target_type == TypeManager.short_type){
952 if (v <= UInt16.MaxValue)
954 } else if (target_type == TypeManager.ushort_type){
955 if (v <= UInt16.MaxValue)
957 } else if (target_type == TypeManager.int64_type)
959 else if (target_type == TypeManager.uint64_type)
962 } else if (c is LongConstant){
963 long v = ((LongConstant) c).Value;
965 if (target_type == TypeManager.int32_type){
966 if (v >= UInt32.MinValue && v <= UInt32.MaxValue)
968 } else if (target_type == TypeManager.uint32_type){
969 if (v >= 0 && v <= UInt32.MaxValue)
971 } else if (target_type == TypeManager.char_type){
972 if (v >= Char.MinValue && v <= Char.MaxValue)
974 } else if (target_type == TypeManager.byte_type){
975 if (v >= Byte.MinValue && v <= Byte.MaxValue)
977 } else if (target_type == TypeManager.sbyte_type){
978 if (v >= SByte.MinValue && v <= SByte.MaxValue)
980 } else if (target_type == TypeManager.short_type){
981 if (v >= Int16.MinValue && v <= UInt16.MaxValue)
983 } else if (target_type == TypeManager.ushort_type){
984 if (v >= UInt16.MinValue && v <= UInt16.MaxValue)
986 } else if (target_type == TypeManager.uint64_type){
991 } else if (c is ULongConstant){
992 ulong v = ((ULongConstant) c).Value;
994 if (target_type == TypeManager.int32_type){
995 if (v <= Int32.MaxValue)
997 } else if (target_type == TypeManager.uint32_type){
998 if (v <= UInt32.MaxValue)
1000 } else if (target_type == TypeManager.char_type){
1001 if (v >= Char.MinValue && v <= Char.MaxValue)
1003 } else if (target_type == TypeManager.byte_type){
1004 if (v >= Byte.MinValue && v <= Byte.MaxValue)
1006 } else if (target_type == TypeManager.sbyte_type){
1007 if (v <= (int) SByte.MaxValue)
1009 } else if (target_type == TypeManager.short_type){
1010 if (v <= UInt16.MaxValue)
1012 } else if (target_type == TypeManager.ushort_type){
1013 if (v <= UInt16.MaxValue)
1015 } else if (target_type == TypeManager.int64_type){
1016 if (v <= Int64.MaxValue)
1020 } else if (c is ByteConstant){
1021 byte v = ((ByteConstant) c).Value;
1023 if (target_type == TypeManager.int32_type)
1025 else if (target_type == TypeManager.uint32_type)
1027 else if (target_type == TypeManager.char_type)
1029 else if (target_type == TypeManager.sbyte_type){
1030 if (v <= SByte.MaxValue)
1032 } else if (target_type == TypeManager.short_type)
1034 else if (target_type == TypeManager.ushort_type)
1036 else if (target_type == TypeManager.int64_type)
1038 else if (target_type == TypeManager.uint64_type)
1041 } else if (c is SByteConstant){
1042 sbyte v = ((SByteConstant) c).Value;
1044 if (target_type == TypeManager.int32_type)
1046 else if (target_type == TypeManager.uint32_type){
1049 } else if (target_type == TypeManager.char_type){
1052 } else if (target_type == TypeManager.byte_type){
1055 } else if (target_type == TypeManager.short_type)
1057 else if (target_type == TypeManager.ushort_type){
1060 } else if (target_type == TypeManager.int64_type)
1062 else if (target_type == TypeManager.uint64_type){
1067 } else if (c is ShortConstant){
1068 short v = ((ShortConstant) c).Value;
1070 if (target_type == TypeManager.int32_type){
1072 } else if (target_type == TypeManager.uint32_type){
1075 } else if (target_type == TypeManager.char_type){
1078 } else if (target_type == TypeManager.byte_type){
1079 if (v >= Byte.MinValue && v <= Byte.MaxValue)
1081 } else if (target_type == TypeManager.sbyte_type){
1082 if (v >= SByte.MinValue && v <= SByte.MaxValue)
1084 } else if (target_type == TypeManager.ushort_type){
1087 } else if (target_type == TypeManager.int64_type)
1089 else if (target_type == TypeManager.uint64_type)
1093 } else if (c is UShortConstant){
1094 ushort v = ((UShortConstant) c).Value;
1096 if (target_type == TypeManager.int32_type)
1098 else if (target_type == TypeManager.uint32_type)
1100 else if (target_type == TypeManager.char_type){
1101 if (v >= Char.MinValue && v <= Char.MaxValue)
1103 } else if (target_type == TypeManager.byte_type){
1104 if (v >= Byte.MinValue && v <= Byte.MaxValue)
1106 } else if (target_type == TypeManager.sbyte_type){
1107 if (v <= SByte.MaxValue)
1109 } else if (target_type == TypeManager.short_type){
1110 if (v <= Int16.MaxValue)
1112 } else if (target_type == TypeManager.int64_type)
1114 else if (target_type == TypeManager.uint64_type)
1118 } else if (c is CharConstant){
1119 char v = ((CharConstant) c).Value;
1121 if (target_type == TypeManager.int32_type)
1123 else if (target_type == TypeManager.uint32_type)
1125 else if (target_type == TypeManager.byte_type){
1126 if (v >= Byte.MinValue && v <= Byte.MaxValue)
1128 } else if (target_type == TypeManager.sbyte_type){
1129 if (v <= SByte.MaxValue)
1131 } else if (target_type == TypeManager.short_type){
1132 if (v <= Int16.MaxValue)
1134 } else if (target_type == TypeManager.ushort_type)
1136 else if (target_type == TypeManager.int64_type)
1138 else if (target_type == TypeManager.uint64_type)
1143 Error_ConstantValueCannotBeConverted (loc, s, target_type);
1148 // Load the object from the pointer.
1150 public static void LoadFromPtr (ILGenerator ig, Type t)
1152 if (t == TypeManager.int32_type)
1153 ig.Emit (OpCodes.Ldind_I4);
1154 else if (t == TypeManager.uint32_type)
1155 ig.Emit (OpCodes.Ldind_U4);
1156 else if (t == TypeManager.short_type)
1157 ig.Emit (OpCodes.Ldind_I2);
1158 else if (t == TypeManager.ushort_type)
1159 ig.Emit (OpCodes.Ldind_U2);
1160 else if (t == TypeManager.char_type)
1161 ig.Emit (OpCodes.Ldind_U2);
1162 else if (t == TypeManager.byte_type)
1163 ig.Emit (OpCodes.Ldind_U1);
1164 else if (t == TypeManager.sbyte_type)
1165 ig.Emit (OpCodes.Ldind_I1);
1166 else if (t == TypeManager.uint64_type)
1167 ig.Emit (OpCodes.Ldind_I8);
1168 else if (t == TypeManager.int64_type)
1169 ig.Emit (OpCodes.Ldind_I8);
1170 else if (t == TypeManager.float_type)
1171 ig.Emit (OpCodes.Ldind_R4);
1172 else if (t == TypeManager.double_type)
1173 ig.Emit (OpCodes.Ldind_R8);
1174 else if (t == TypeManager.bool_type)
1175 ig.Emit (OpCodes.Ldind_I1);
1176 else if (t == TypeManager.intptr_type)
1177 ig.Emit (OpCodes.Ldind_I);
1178 else if (TypeManager.IsEnumType (t)) {
1179 if (t == TypeManager.enum_type)
1180 ig.Emit (OpCodes.Ldind_Ref);
1182 LoadFromPtr (ig, TypeManager.EnumToUnderlying (t));
1183 } else if (t.IsValueType)
1184 ig.Emit (OpCodes.Ldobj, t);
1185 else if (t.IsPointer)
1186 ig.Emit (OpCodes.Ldind_I);
1188 ig.Emit (OpCodes.Ldind_Ref);
1192 // The stack contains the pointer and the value of type `type'
1194 public static void StoreFromPtr (ILGenerator ig, Type type)
1196 if (TypeManager.IsEnumType (type))
1197 type = TypeManager.EnumToUnderlying (type);
1198 if (type == TypeManager.int32_type || type == TypeManager.uint32_type)
1199 ig.Emit (OpCodes.Stind_I4);
1200 else if (type == TypeManager.int64_type || type == TypeManager.uint64_type)
1201 ig.Emit (OpCodes.Stind_I8);
1202 else if (type == TypeManager.char_type || type == TypeManager.short_type ||
1203 type == TypeManager.ushort_type)
1204 ig.Emit (OpCodes.Stind_I2);
1205 else if (type == TypeManager.float_type)
1206 ig.Emit (OpCodes.Stind_R4);
1207 else if (type == TypeManager.double_type)
1208 ig.Emit (OpCodes.Stind_R8);
1209 else if (type == TypeManager.byte_type || type == TypeManager.sbyte_type ||
1210 type == TypeManager.bool_type)
1211 ig.Emit (OpCodes.Stind_I1);
1212 else if (type == TypeManager.intptr_type)
1213 ig.Emit (OpCodes.Stind_I);
1214 else if (type.IsValueType)
1215 ig.Emit (OpCodes.Stobj, type);
1217 ig.Emit (OpCodes.Stind_Ref);
1221 // Returns the size of type `t' if known, otherwise, 0
1223 public static int GetTypeSize (Type t)
1225 t = TypeManager.TypeToCoreType (t);
1226 if (t == TypeManager.int32_type ||
1227 t == TypeManager.uint32_type ||
1228 t == TypeManager.float_type)
1230 else if (t == TypeManager.int64_type ||
1231 t == TypeManager.uint64_type ||
1232 t == TypeManager.double_type)
1234 else if (t == TypeManager.byte_type ||
1235 t == TypeManager.sbyte_type ||
1236 t == TypeManager.bool_type)
1238 else if (t == TypeManager.short_type ||
1239 t == TypeManager.char_type ||
1240 t == TypeManager.ushort_type)
1242 else if (t == TypeManager.decimal_type)
1248 public static void Error_NegativeArrayIndex (Location loc)
1250 Report.Error (248, loc, "Cannot create an 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)
1413 public override bool IsNegative {
1422 /// This class is used to wrap literals which belong inside Enums
1424 public class EnumConstant : Constant {
1425 public Constant Child;
1427 public EnumConstant (Constant child, Type enum_type)
1429 eclass = child.eclass;
1434 public override Expression DoResolve (EmitContext ec)
1436 // This should never be invoked, we are born in fully
1437 // initialized state.
1442 public override void Emit (EmitContext ec)
1447 public override object GetValue ()
1449 return Child.GetValue ();
1452 public object GetValueAsEnumType ()
1454 return System.Enum.ToObject (type, Child.GetValue ());
1458 // Converts from one of the valid underlying types for an enumeration
1459 // (int32, uint32, int64, uint64, short, ushort, byte, sbyte) to
1460 // one of the internal compiler literals: Int/UInt/Long/ULong Literals.
1462 public Constant WidenToCompilerConstant ()
1464 Type t = TypeManager.EnumToUnderlying (Child.Type);
1465 object v = ((Constant) Child).GetValue ();;
1467 if (t == TypeManager.int32_type)
1468 return new IntConstant ((int) v);
1469 if (t == TypeManager.uint32_type)
1470 return new UIntConstant ((uint) v);
1471 if (t == TypeManager.int64_type)
1472 return new LongConstant ((long) v);
1473 if (t == TypeManager.uint64_type)
1474 return new ULongConstant ((ulong) v);
1475 if (t == TypeManager.short_type)
1476 return new ShortConstant ((short) v);
1477 if (t == TypeManager.ushort_type)
1478 return new UShortConstant ((ushort) v);
1479 if (t == TypeManager.byte_type)
1480 return new ByteConstant ((byte) v);
1481 if (t == TypeManager.sbyte_type)
1482 return new SByteConstant ((sbyte) v);
1484 throw new Exception ("Invalid enumeration underlying type: " + t);
1488 // Extracts the value in the enumeration on its native representation
1490 public object GetPlainValue ()
1492 Type t = TypeManager.EnumToUnderlying (Child.Type);
1493 object v = ((Constant) Child).GetValue ();;
1495 if (t == TypeManager.int32_type)
1497 if (t == TypeManager.uint32_type)
1499 if (t == TypeManager.int64_type)
1501 if (t == TypeManager.uint64_type)
1503 if (t == TypeManager.short_type)
1505 if (t == TypeManager.ushort_type)
1507 if (t == TypeManager.byte_type)
1509 if (t == TypeManager.sbyte_type)
1515 public override string AsString ()
1517 return Child.AsString ();
1520 public override DoubleConstant ConvertToDouble ()
1522 return Child.ConvertToDouble ();
1525 public override FloatConstant ConvertToFloat ()
1527 return Child.ConvertToFloat ();
1530 public override ULongConstant ConvertToULong ()
1532 return Child.ConvertToULong ();
1535 public override LongConstant ConvertToLong ()
1537 return Child.ConvertToLong ();
1540 public override UIntConstant ConvertToUInt ()
1542 return Child.ConvertToUInt ();
1545 public override IntConstant ConvertToInt ()
1547 return Child.ConvertToInt ();
1550 public override bool IsZeroInteger {
1551 get { return Child.IsZeroInteger; }
1554 public override bool IsNegative {
1556 return Child.IsNegative;
1562 /// This kind of cast is used to encapsulate Value Types in objects.
1564 /// The effect of it is to box the value type emitted by the previous
1567 public class BoxedCast : EmptyCast {
1569 public BoxedCast (Expression expr)
1570 : base (expr, TypeManager.object_type)
1572 eclass = ExprClass.Value;
1575 public BoxedCast (Expression expr, Type target_type)
1576 : base (expr, target_type)
1578 eclass = ExprClass.Value;
1581 public override Expression DoResolve (EmitContext ec)
1583 // This should never be invoked, we are born in fully
1584 // initialized state.
1589 public override void Emit (EmitContext ec)
1593 ec.ig.Emit (OpCodes.Box, child.Type);
1597 public class UnboxCast : EmptyCast {
1598 public UnboxCast (Expression expr, Type return_type)
1599 : base (expr, return_type)
1603 public override Expression DoResolve (EmitContext ec)
1605 // This should never be invoked, we are born in fully
1606 // initialized state.
1611 public override void Emit (EmitContext ec)
1614 ILGenerator ig = ec.ig;
1617 ig.Emit (OpCodes.Unbox, t);
1619 LoadFromPtr (ig, t);
1624 /// This is used to perform explicit numeric conversions.
1626 /// Explicit numeric conversions might trigger exceptions in a checked
1627 /// context, so they should generate the conv.ovf opcodes instead of
1630 public class ConvCast : EmptyCast {
1631 public enum Mode : byte {
1632 I1_U1, I1_U2, I1_U4, I1_U8, I1_CH,
1634 I2_I1, I2_U1, I2_U2, I2_U4, I2_U8, I2_CH,
1635 U2_I1, U2_U1, U2_I2, U2_CH,
1636 I4_I1, I4_U1, I4_I2, I4_U2, I4_U4, I4_U8, I4_CH,
1637 U4_I1, U4_U1, U4_I2, U4_U2, U4_I4, U4_CH,
1638 I8_I1, I8_U1, I8_I2, I8_U2, I8_I4, I8_U4, I8_U8, I8_CH,
1639 U8_I1, U8_U1, U8_I2, U8_U2, U8_I4, U8_U4, U8_I8, U8_CH,
1640 CH_I1, CH_U1, CH_I2,
1641 R4_I1, R4_U1, R4_I2, R4_U2, R4_I4, R4_U4, R4_I8, R4_U8, R4_CH,
1642 R8_I1, R8_U1, R8_I2, R8_U2, R8_I4, R8_U4, R8_I8, R8_U8, R8_CH, R8_R4
1648 public ConvCast (EmitContext ec, Expression child, Type return_type, Mode m)
1649 : base (child, return_type)
1651 checked_state = ec.CheckState;
1655 public override Expression DoResolve (EmitContext ec)
1657 // This should never be invoked, we are born in fully
1658 // initialized state.
1663 public override string ToString ()
1665 return String.Format ("ConvCast ({0}, {1})", mode, child);
1668 public override void Emit (EmitContext ec)
1670 ILGenerator ig = ec.ig;
1676 case Mode.I1_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1677 case Mode.I1_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1678 case Mode.I1_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1679 case Mode.I1_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1680 case Mode.I1_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1682 case Mode.U1_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1683 case Mode.U1_CH: /* nothing */ break;
1685 case Mode.I2_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1686 case Mode.I2_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1687 case Mode.I2_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1688 case Mode.I2_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1689 case Mode.I2_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1690 case Mode.I2_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1692 case Mode.U2_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1693 case Mode.U2_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
1694 case Mode.U2_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
1695 case Mode.U2_CH: /* nothing */ break;
1697 case Mode.I4_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1698 case Mode.I4_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1699 case Mode.I4_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
1700 case Mode.I4_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1701 case Mode.I4_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1702 case Mode.I4_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1703 case Mode.I4_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1705 case Mode.U4_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1706 case Mode.U4_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
1707 case Mode.U4_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
1708 case Mode.U4_U2: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
1709 case Mode.U4_I4: ig.Emit (OpCodes.Conv_Ovf_I4_Un); break;
1710 case Mode.U4_CH: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
1712 case Mode.I8_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1713 case Mode.I8_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1714 case Mode.I8_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
1715 case Mode.I8_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1716 case Mode.I8_I4: ig.Emit (OpCodes.Conv_Ovf_I4); break;
1717 case Mode.I8_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1718 case Mode.I8_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1719 case Mode.I8_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1721 case Mode.U8_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1722 case Mode.U8_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
1723 case Mode.U8_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
1724 case Mode.U8_U2: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
1725 case Mode.U8_I4: ig.Emit (OpCodes.Conv_Ovf_I4_Un); break;
1726 case Mode.U8_U4: ig.Emit (OpCodes.Conv_Ovf_U4_Un); break;
1727 case Mode.U8_I8: ig.Emit (OpCodes.Conv_Ovf_I8_Un); break;
1728 case Mode.U8_CH: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
1730 case Mode.CH_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1731 case Mode.CH_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
1732 case Mode.CH_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
1734 case Mode.R4_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1735 case Mode.R4_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1736 case Mode.R4_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
1737 case Mode.R4_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1738 case Mode.R4_I4: ig.Emit (OpCodes.Conv_Ovf_I4); break;
1739 case Mode.R4_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1740 case Mode.R4_I8: ig.Emit (OpCodes.Conv_Ovf_I8); break;
1741 case Mode.R4_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1742 case Mode.R4_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1744 case Mode.R8_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1745 case Mode.R8_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1746 case Mode.R8_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
1747 case Mode.R8_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1748 case Mode.R8_I4: ig.Emit (OpCodes.Conv_Ovf_I4); break;
1749 case Mode.R8_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1750 case Mode.R8_I8: ig.Emit (OpCodes.Conv_Ovf_I8); break;
1751 case Mode.R8_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1752 case Mode.R8_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1753 case Mode.R8_R4: ig.Emit (OpCodes.Conv_R4); break;
1757 case Mode.I1_U1: ig.Emit (OpCodes.Conv_U1); break;
1758 case Mode.I1_U2: ig.Emit (OpCodes.Conv_U2); break;
1759 case Mode.I1_U4: ig.Emit (OpCodes.Conv_U4); break;
1760 case Mode.I1_U8: ig.Emit (OpCodes.Conv_I8); break;
1761 case Mode.I1_CH: ig.Emit (OpCodes.Conv_U2); break;
1763 case Mode.U1_I1: ig.Emit (OpCodes.Conv_I1); break;
1764 case Mode.U1_CH: ig.Emit (OpCodes.Conv_U2); break;
1766 case Mode.I2_I1: ig.Emit (OpCodes.Conv_I1); break;
1767 case Mode.I2_U1: ig.Emit (OpCodes.Conv_U1); break;
1768 case Mode.I2_U2: ig.Emit (OpCodes.Conv_U2); break;
1769 case Mode.I2_U4: ig.Emit (OpCodes.Conv_U4); break;
1770 case Mode.I2_U8: ig.Emit (OpCodes.Conv_I8); break;
1771 case Mode.I2_CH: ig.Emit (OpCodes.Conv_U2); break;
1773 case Mode.U2_I1: ig.Emit (OpCodes.Conv_I1); break;
1774 case Mode.U2_U1: ig.Emit (OpCodes.Conv_U1); break;
1775 case Mode.U2_I2: ig.Emit (OpCodes.Conv_I2); break;
1776 case Mode.U2_CH: /* nothing */ break;
1778 case Mode.I4_I1: ig.Emit (OpCodes.Conv_I1); break;
1779 case Mode.I4_U1: ig.Emit (OpCodes.Conv_U1); break;
1780 case Mode.I4_I2: ig.Emit (OpCodes.Conv_I2); break;
1781 case Mode.I4_U4: /* nothing */ break;
1782 case Mode.I4_U2: ig.Emit (OpCodes.Conv_U2); break;
1783 case Mode.I4_U8: ig.Emit (OpCodes.Conv_I8); break;
1784 case Mode.I4_CH: ig.Emit (OpCodes.Conv_U2); break;
1786 case Mode.U4_I1: ig.Emit (OpCodes.Conv_I1); break;
1787 case Mode.U4_U1: ig.Emit (OpCodes.Conv_U1); break;
1788 case Mode.U4_I2: ig.Emit (OpCodes.Conv_I2); break;
1789 case Mode.U4_U2: ig.Emit (OpCodes.Conv_U2); break;
1790 case Mode.U4_I4: /* nothing */ break;
1791 case Mode.U4_CH: ig.Emit (OpCodes.Conv_U2); break;
1793 case Mode.I8_I1: ig.Emit (OpCodes.Conv_I1); break;
1794 case Mode.I8_U1: ig.Emit (OpCodes.Conv_U1); break;
1795 case Mode.I8_I2: ig.Emit (OpCodes.Conv_I2); break;
1796 case Mode.I8_U2: ig.Emit (OpCodes.Conv_U2); break;
1797 case Mode.I8_I4: ig.Emit (OpCodes.Conv_I4); break;
1798 case Mode.I8_U4: ig.Emit (OpCodes.Conv_U4); break;
1799 case Mode.I8_U8: /* nothing */ break;
1800 case Mode.I8_CH: ig.Emit (OpCodes.Conv_U2); break;
1802 case Mode.U8_I1: ig.Emit (OpCodes.Conv_I1); break;
1803 case Mode.U8_U1: ig.Emit (OpCodes.Conv_U1); break;
1804 case Mode.U8_I2: ig.Emit (OpCodes.Conv_I2); break;
1805 case Mode.U8_U2: ig.Emit (OpCodes.Conv_U2); break;
1806 case Mode.U8_I4: ig.Emit (OpCodes.Conv_I4); break;
1807 case Mode.U8_U4: ig.Emit (OpCodes.Conv_U4); break;
1808 case Mode.U8_I8: /* nothing */ break;
1809 case Mode.U8_CH: ig.Emit (OpCodes.Conv_U2); break;
1811 case Mode.CH_I1: ig.Emit (OpCodes.Conv_I1); break;
1812 case Mode.CH_U1: ig.Emit (OpCodes.Conv_U1); break;
1813 case Mode.CH_I2: ig.Emit (OpCodes.Conv_I2); break;
1815 case Mode.R4_I1: ig.Emit (OpCodes.Conv_I1); break;
1816 case Mode.R4_U1: ig.Emit (OpCodes.Conv_U1); break;
1817 case Mode.R4_I2: ig.Emit (OpCodes.Conv_I2); break;
1818 case Mode.R4_U2: ig.Emit (OpCodes.Conv_U2); break;
1819 case Mode.R4_I4: ig.Emit (OpCodes.Conv_I4); break;
1820 case Mode.R4_U4: ig.Emit (OpCodes.Conv_U4); break;
1821 case Mode.R4_I8: ig.Emit (OpCodes.Conv_I8); break;
1822 case Mode.R4_U8: ig.Emit (OpCodes.Conv_U8); break;
1823 case Mode.R4_CH: ig.Emit (OpCodes.Conv_U2); break;
1825 case Mode.R8_I1: ig.Emit (OpCodes.Conv_I1); break;
1826 case Mode.R8_U1: ig.Emit (OpCodes.Conv_U1); break;
1827 case Mode.R8_I2: ig.Emit (OpCodes.Conv_I2); break;
1828 case Mode.R8_U2: ig.Emit (OpCodes.Conv_U2); break;
1829 case Mode.R8_I4: ig.Emit (OpCodes.Conv_I4); break;
1830 case Mode.R8_U4: ig.Emit (OpCodes.Conv_U4); break;
1831 case Mode.R8_I8: ig.Emit (OpCodes.Conv_I8); break;
1832 case Mode.R8_U8: ig.Emit (OpCodes.Conv_U8); break;
1833 case Mode.R8_CH: ig.Emit (OpCodes.Conv_U2); break;
1834 case Mode.R8_R4: ig.Emit (OpCodes.Conv_R4); break;
1840 public class OpcodeCast : EmptyCast {
1844 public OpcodeCast (Expression child, Type return_type, OpCode op)
1845 : base (child, return_type)
1849 second_valid = false;
1852 public OpcodeCast (Expression child, Type return_type, OpCode op, OpCode op2)
1853 : base (child, return_type)
1858 second_valid = true;
1861 public override Expression DoResolve (EmitContext ec)
1863 // This should never be invoked, we are born in fully
1864 // initialized state.
1869 public override void Emit (EmitContext ec)
1880 /// This kind of cast is used to encapsulate a child and cast it
1881 /// to the class requested
1883 public class ClassCast : EmptyCast {
1884 public ClassCast (Expression child, Type return_type)
1885 : base (child, return_type)
1890 public override Expression DoResolve (EmitContext ec)
1892 // This should never be invoked, we are born in fully
1893 // initialized state.
1898 public override void Emit (EmitContext ec)
1902 ec.ig.Emit (OpCodes.Castclass, type);
1908 /// SimpleName expressions are initially formed of a single
1909 /// word and it only happens at the beginning of the expression.
1913 /// The expression will try to be bound to a Field, a Method
1914 /// group or a Property. If those fail we pass the name to our
1915 /// caller and the SimpleName is compounded to perform a type
1916 /// lookup. The idea behind this process is that we want to avoid
1917 /// creating a namespace map from the assemblies, as that requires
1918 /// the GetExportedTypes function to be called and a hashtable to
1919 /// be constructed which reduces startup time. If later we find
1920 /// that this is slower, we should create a `NamespaceExpr' expression
1921 /// that fully participates in the resolution process.
1923 /// For example `System.Console.WriteLine' is decomposed into
1924 /// MemberAccess (MemberAccess (SimpleName ("System"), "Console"), "WriteLine")
1926 /// The first SimpleName wont produce a match on its own, so it will
1928 /// MemberAccess (SimpleName ("System.Console"), "WriteLine").
1930 /// System.Console will produce a TypeExpr match.
1932 /// The downside of this is that we might be hitting `LookupType' too many
1933 /// times with this scheme.
1935 public class SimpleName : Expression {
1939 // If true, then we are a simple name, not composed with a ".
1943 public SimpleName (string a, string b, Location l)
1945 Name = String.Concat (a, ".", b);
1950 public SimpleName (string name, Location l)
1957 public static void Error_ObjectRefRequired (EmitContext ec, Location l, string name)
1959 if (ec.IsFieldInitializer)
1962 "A field initializer cannot reference the non-static field, " +
1963 "method or property `"+name+"'");
1967 "An object reference is required " +
1968 "for the non-static field `"+name+"'");
1972 // Checks whether we are trying to access an instance
1973 // property, method or field from a static body.
1975 Expression MemberStaticCheck (EmitContext ec, Expression e)
1977 if (e is IMemberExpr){
1978 IMemberExpr member = (IMemberExpr) e;
1980 if (!member.IsStatic){
1981 Error_ObjectRefRequired (ec, loc, Name);
1989 public override Expression DoResolve (EmitContext ec)
1991 return SimpleNameResolve (ec, null, false, false);
1994 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
1996 return SimpleNameResolve (ec, right_side, false, false);
2000 public Expression DoResolveAllowStatic (EmitContext ec, bool intermediate)
2002 return SimpleNameResolve (ec, null, true, intermediate);
2005 public override Expression ResolveAsTypeStep (EmitContext ec)
2007 DeclSpace ds = ec.DeclSpace;
2008 NamespaceEntry ns = ds.NamespaceEntry;
2013 // Since we are cheating: we only do the Alias lookup for
2014 // namespaces if the name does not include any dots in it
2016 if (ns != null && is_base)
2017 alias_value = ns.LookupAlias (Name);
2021 if (ec.ResolvingTypeTree){
2022 int errors = Report.Errors;
2023 Type dt = ds.FindType (loc, Name);
2025 if (Report.Errors != errors)
2029 return new TypeExpression (dt, loc);
2031 if (alias_value != null){
2032 if ((t = RootContext.LookupType (ds, alias_value, true, loc)) != null)
2033 return new TypeExpression (t, loc);
2037 if ((t = RootContext.LookupType (ds, Name, true, loc)) != null)
2038 return new TypeExpression (t, loc);
2040 if (alias_value != null) {
2041 if ((t = RootContext.LookupType (ds, alias_value, true, loc)) != null)
2042 return new TypeExpression (t, loc);
2044 // we have alias value, but it isn't Type, so try if it's namespace
2045 return new SimpleName (alias_value, loc);
2048 // No match, maybe our parent can compose us
2049 // into something meaningful.
2053 Expression SimpleNameResolve (EmitContext ec, Expression right_side,
2054 bool allow_static, bool intermediate)
2056 Expression e = DoSimpleNameResolve (ec, right_side, allow_static, intermediate);
2060 Block current_block = ec.CurrentBlock;
2061 if (current_block != null){
2062 //LocalInfo vi = current_block.GetLocalInfo (Name);
2064 current_block.IsVariableNameUsedInChildBlock(Name)) {
2065 Report.Error (135, Location,
2066 "'{0}' has a different meaning in a " +
2067 "child block", Name);
2076 /// 7.5.2: Simple Names.
2078 /// Local Variables and Parameters are handled at
2079 /// parse time, so they never occur as SimpleNames.
2081 /// The `allow_static' flag is used by MemberAccess only
2082 /// and it is used to inform us that it is ok for us to
2083 /// avoid the static check, because MemberAccess might end
2084 /// up resolving the Name as a Type name and the access as
2085 /// a static type access.
2087 /// ie: Type Type; .... { Type.GetType (""); }
2089 /// Type is both an instance variable and a Type; Type.GetType
2090 /// is the static method not an instance method of type.
2092 Expression DoSimpleNameResolve (EmitContext ec, Expression right_side, bool allow_static, bool intermediate)
2094 Expression e = null;
2097 // Stage 1: Performed by the parser (binding to locals or parameters).
2099 Block current_block = ec.CurrentBlock;
2100 if (current_block != null){
2101 LocalInfo vi = current_block.GetLocalInfo (Name);
2105 var = new LocalVariableReference (ec.CurrentBlock, Name, loc);
2107 if (right_side != null)
2108 return var.ResolveLValue (ec, right_side);
2110 return var.Resolve (ec);
2113 ParameterReference pref = current_block.GetParameterReference (Name, loc);
2115 if (right_side != null)
2116 return pref.ResolveLValue (ec, right_side);
2118 return pref.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.IsSubclassOrNestedChildOf (me.InstanceExpression.Type, me.DeclaringType) &&
2187 me.InstanceExpression.Type != me.DeclaringType &&
2188 !me.InstanceExpression.Type.IsSubclassOf (me.DeclaringType) &&
2189 (!intermediate || !MemberAccess.IdenticalNameAndTypeName (ec, this, e, loc))) {
2190 Error (38, "Cannot access nonstatic member `" + me.Name + "' of " +
2191 "outer type `" + me.DeclaringType + "' via nested type `" +
2192 me.InstanceExpression.Type + "'");
2196 return (right_side != null)
2197 ? e.DoResolveLValue (ec, right_side)
2201 if (ec.IsStatic || ec.IsFieldInitializer){
2205 return MemberStaticCheck (ec, e);
2210 public override void Emit (EmitContext ec)
2213 // If this is ever reached, then we failed to
2214 // find the name as a namespace
2217 Error (103, "The name `" + Name +
2218 "' does not exist in the class `" +
2219 ec.DeclSpace.Name + "'");
2222 public override string ToString ()
2229 /// Fully resolved expression that evaluates to a type
2231 public abstract class TypeExpr : Expression {
2232 override public Expression ResolveAsTypeStep (EmitContext ec)
2234 TypeExpr t = DoResolveAsTypeStep (ec);
2238 eclass = ExprClass.Type;
2242 override public Expression DoResolve (EmitContext ec)
2244 return ResolveAsTypeTerminal (ec, false);
2247 override public void Emit (EmitContext ec)
2249 throw new Exception ("Should never be called");
2252 public virtual bool CheckAccessLevel (DeclSpace ds)
2254 return ds.CheckAccessLevel (Type);
2257 public virtual bool AsAccessible (DeclSpace ds, int flags)
2259 return ds.AsAccessible (Type, flags);
2262 public virtual bool IsClass {
2263 get { return Type.IsClass; }
2266 public virtual bool IsValueType {
2267 get { return Type.IsValueType; }
2270 public virtual bool IsInterface {
2271 get { return Type.IsInterface; }
2274 public virtual bool IsSealed {
2275 get { return Type.IsSealed; }
2278 public virtual bool CanInheritFrom ()
2280 if (Type == TypeManager.enum_type ||
2281 (Type == TypeManager.value_type && RootContext.StdLib) ||
2282 Type == TypeManager.multicast_delegate_type ||
2283 Type == TypeManager.delegate_type ||
2284 Type == TypeManager.array_type)
2290 public virtual bool IsAttribute {
2292 return Type == TypeManager.attribute_type ||
2293 Type.IsSubclassOf (TypeManager.attribute_type);
2297 public abstract TypeExpr DoResolveAsTypeStep (EmitContext ec);
2299 public virtual Type ResolveType (EmitContext ec)
2301 TypeExpr t = ResolveAsTypeTerminal (ec, false);
2308 public abstract string Name {
2312 public override bool Equals (object obj)
2314 TypeExpr tobj = obj as TypeExpr;
2318 return Type == tobj.Type;
2321 public override int GetHashCode ()
2323 return Type.GetHashCode ();
2326 public override string ToString ()
2332 public class TypeExpression : TypeExpr {
2333 public TypeExpression (Type t, Location l)
2336 eclass = ExprClass.Type;
2340 public override TypeExpr DoResolveAsTypeStep (EmitContext ec)
2345 public override string Name {
2347 return Type.ToString ();
2353 /// Used to create types from a fully qualified name. These are just used
2354 /// by the parser to setup the core types. A TypeLookupExpression is always
2355 /// classified as a type.
2357 public class TypeLookupExpression : TypeExpr {
2360 public TypeLookupExpression (string name)
2365 public override TypeExpr DoResolveAsTypeStep (EmitContext ec)
2368 type = RootContext.LookupType (ec.DeclSpace, name, false, Location.Null);
2372 public override string Name {
2380 /// MethodGroup Expression.
2382 /// This is a fully resolved expression that evaluates to a type
2384 public class MethodGroupExpr : Expression, IMemberExpr {
2385 public MethodBase [] Methods;
2386 Expression instance_expression = null;
2387 bool is_explicit_impl = false;
2388 bool identical_type_name = false;
2391 public MethodGroupExpr (MemberInfo [] mi, Location l)
2393 Methods = new MethodBase [mi.Length];
2394 mi.CopyTo (Methods, 0);
2395 eclass = ExprClass.MethodGroup;
2396 type = TypeManager.object_type;
2400 public MethodGroupExpr (ArrayList list, Location l)
2402 Methods = new MethodBase [list.Count];
2405 list.CopyTo (Methods, 0);
2407 foreach (MemberInfo m in list){
2408 if (!(m is MethodBase)){
2409 Console.WriteLine ("Name " + m.Name);
2410 Console.WriteLine ("Found a: " + m.GetType ().FullName);
2417 eclass = ExprClass.MethodGroup;
2418 type = TypeManager.object_type;
2421 public Type DeclaringType {
2424 // The methods are arranged in this order:
2425 // derived type -> base type
2427 return Methods [0].DeclaringType;
2432 // `A method group may have associated an instance expression'
2434 public Expression InstanceExpression {
2436 return instance_expression;
2440 instance_expression = value;
2444 public bool IsExplicitImpl {
2446 return is_explicit_impl;
2450 is_explicit_impl = value;
2454 public bool IdenticalTypeName {
2456 return identical_type_name;
2460 identical_type_name = value;
2464 public bool IsBase {
2473 public string Name {
2475 return Methods [0].Name;
2479 public bool IsInstance {
2481 foreach (MethodBase mb in Methods)
2489 public bool IsStatic {
2491 foreach (MethodBase mb in Methods)
2499 override public Expression DoResolve (EmitContext ec)
2502 instance_expression = null;
2504 if (instance_expression != null) {
2505 instance_expression = instance_expression.DoResolve (ec);
2506 if (instance_expression == null)
2513 public void ReportUsageError ()
2515 Report.Error (654, loc, "Method `" + DeclaringType + "." +
2516 Name + "()' is referenced without parentheses");
2519 override public void Emit (EmitContext ec)
2521 ReportUsageError ();
2524 bool RemoveMethods (bool keep_static)
2526 ArrayList smethods = new ArrayList ();
2528 foreach (MethodBase mb in Methods){
2529 if (mb.IsStatic == keep_static)
2533 if (smethods.Count == 0)
2536 Methods = new MethodBase [smethods.Count];
2537 smethods.CopyTo (Methods, 0);
2543 /// Removes any instance methods from the MethodGroup, returns
2544 /// false if the resulting set is empty.
2546 public bool RemoveInstanceMethods ()
2548 return RemoveMethods (true);
2552 /// Removes any static methods from the MethodGroup, returns
2553 /// false if the resulting set is empty.
2555 public bool RemoveStaticMethods ()
2557 return RemoveMethods (false);
2562 /// Fully resolved expression that evaluates to a Field
2564 public class FieldExpr : Expression, IAssignMethod, IMemoryLocation, IMemberExpr, IVariable {
2565 public readonly FieldInfo FieldInfo;
2566 Expression instance_expr;
2567 VariableInfo variable_info;
2569 LocalTemporary temp;
2572 public FieldExpr (FieldInfo fi, Location l)
2575 eclass = ExprClass.Variable;
2576 type = fi.FieldType;
2580 public string Name {
2582 return FieldInfo.Name;
2586 public bool IsInstance {
2588 return !FieldInfo.IsStatic;
2592 public bool IsStatic {
2594 return FieldInfo.IsStatic;
2598 public Type DeclaringType {
2600 return FieldInfo.DeclaringType;
2604 public Expression InstanceExpression {
2606 return instance_expr;
2610 instance_expr = value;
2614 public VariableInfo VariableInfo {
2616 return variable_info;
2620 override public Expression DoResolve (EmitContext ec)
2622 if (!FieldInfo.IsStatic){
2623 if (instance_expr == null){
2625 // This can happen when referencing an instance field using
2626 // a fully qualified type expression: TypeName.InstanceField = xxx
2628 SimpleName.Error_ObjectRefRequired (ec, loc, FieldInfo.Name);
2632 // Resolve the field's instance expression while flow analysis is turned
2633 // off: when accessing a field "a.b", we must check whether the field
2634 // "a.b" is initialized, not whether the whole struct "a" is initialized.
2635 instance_expr = instance_expr.Resolve (ec, ResolveFlags.VariableOrValue |
2636 ResolveFlags.DisableFlowAnalysis);
2637 if (instance_expr == null)
2641 ObsoleteAttribute oa;
2642 FieldBase f = TypeManager.GetField (FieldInfo);
2644 oa = f.GetObsoleteAttribute (f.Parent);
2646 AttributeTester.Report_ObsoleteMessage (oa, f.GetSignatureForError (), loc);
2648 // To be sure that type is external because we do not register generated fields
2649 } else if (!(FieldInfo.DeclaringType is TypeBuilder)) {
2650 oa = AttributeTester.GetMemberObsoleteAttribute (FieldInfo);
2652 AttributeTester.Report_ObsoleteMessage (oa, TypeManager.GetFullNameSignature (FieldInfo), loc);
2655 if (ec.CurrentAnonymousMethod != null){
2656 if (!FieldInfo.IsStatic){
2657 if (ec.TypeContainer is Struct){
2658 Report.Error (1673, loc, "Can not reference instance variables in anonymous methods hosted in structs");
2661 ec.CaptureField (this);
2665 // If the instance expression is a local variable or parameter.
2666 IVariable var = instance_expr as IVariable;
2667 if ((var == null) || (var.VariableInfo == null))
2670 VariableInfo vi = var.VariableInfo;
2671 if (!vi.IsFieldAssigned (ec, FieldInfo.Name, loc))
2674 variable_info = vi.GetSubStruct (FieldInfo.Name);
2678 void Report_AssignToReadonly (bool is_instance)
2683 msg = "Readonly field can not be assigned outside " +
2684 "of constructor or variable initializer";
2686 msg = "A static readonly field can only be assigned in " +
2687 "a static constructor";
2689 Report.Error (is_instance ? 191 : 198, loc, msg);
2692 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
2694 IVariable var = instance_expr as IVariable;
2695 if ((var != null) && (var.VariableInfo != null))
2696 var.VariableInfo.SetFieldAssigned (ec, FieldInfo.Name);
2698 Expression e = DoResolve (ec);
2703 if (!FieldInfo.IsStatic && (instance_expr.Type.IsValueType && !(instance_expr is IMemoryLocation))) {
2704 // FIXME: Provide better error reporting.
2705 Error (1612, "Cannot modify expression because it is not a variable.");
2709 if (!FieldInfo.IsInitOnly)
2712 FieldBase fb = TypeManager.GetField (FieldInfo);
2717 // InitOnly fields can only be assigned in constructors
2720 if (ec.IsConstructor){
2721 if (IsStatic && !ec.IsStatic)
2722 Report_AssignToReadonly (false);
2724 if (ec.ContainerType == FieldInfo.DeclaringType)
2728 Report_AssignToReadonly (!IsStatic);
2733 public bool VerifyFixed (bool is_expression)
2735 IVariable variable = instance_expr as IVariable;
2736 if ((variable == null) || !variable.VerifyFixed (true))
2742 public void Emit (EmitContext ec, bool leave_copy)
2744 ILGenerator ig = ec.ig;
2745 bool is_volatile = false;
2747 if (FieldInfo is FieldBuilder){
2748 FieldBase f = TypeManager.GetField (FieldInfo);
2750 if ((f.ModFlags & Modifiers.VOLATILE) != 0)
2753 f.status |= Field.Status.USED;
2757 if (FieldInfo.IsStatic){
2759 ig.Emit (OpCodes.Volatile);
2761 ig.Emit (OpCodes.Ldsfld, FieldInfo);
2767 ig.Emit (OpCodes.Volatile);
2769 ig.Emit (OpCodes.Ldfld, FieldInfo);
2773 ec.ig.Emit (OpCodes.Dup);
2774 if (!FieldInfo.IsStatic) {
2775 temp = new LocalTemporary (ec, this.Type);
2781 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
2783 FieldAttributes fa = FieldInfo.Attributes;
2784 bool is_static = (fa & FieldAttributes.Static) != 0;
2785 bool is_readonly = (fa & FieldAttributes.InitOnly) != 0;
2786 ILGenerator ig = ec.ig;
2787 prepared = prepare_for_load;
2789 if (is_readonly && !ec.IsConstructor){
2790 Report_AssignToReadonly (!is_static);
2796 if (prepare_for_load)
2797 ig.Emit (OpCodes.Dup);
2802 ec.ig.Emit (OpCodes.Dup);
2803 if (!FieldInfo.IsStatic) {
2804 temp = new LocalTemporary (ec, this.Type);
2809 if (FieldInfo is FieldBuilder){
2810 FieldBase f = TypeManager.GetField (FieldInfo);
2812 if ((f.ModFlags & Modifiers.VOLATILE) != 0)
2813 ig.Emit (OpCodes.Volatile);
2815 f.status |= Field.Status.ASSIGNED;
2820 ig.Emit (OpCodes.Stsfld, FieldInfo);
2822 ig.Emit (OpCodes.Stfld, FieldInfo);
2828 void EmitInstance (EmitContext ec)
2830 if (instance_expr.Type.IsValueType) {
2831 if (instance_expr is IMemoryLocation) {
2832 ((IMemoryLocation) instance_expr).AddressOf (ec, AddressOp.LoadStore);
2834 LocalTemporary t = new LocalTemporary (ec, instance_expr.Type);
2835 instance_expr.Emit (ec);
2837 t.AddressOf (ec, AddressOp.Store);
2840 instance_expr.Emit (ec);
2843 public override void Emit (EmitContext ec)
2848 public void AddressOf (EmitContext ec, AddressOp mode)
2850 ILGenerator ig = ec.ig;
2852 if (FieldInfo is FieldBuilder){
2853 FieldBase f = TypeManager.GetField (FieldInfo);
2855 if ((f.ModFlags & Modifiers.VOLATILE) != 0){
2856 Error (676, "volatile variable: can not take its address, or pass as ref/out parameter");
2860 if ((mode & AddressOp.Store) != 0)
2861 f.status |= Field.Status.ASSIGNED;
2862 if ((mode & AddressOp.Load) != 0)
2863 f.status |= Field.Status.USED;
2868 // Handle initonly fields specially: make a copy and then
2869 // get the address of the copy.
2872 if (FieldInfo.IsInitOnly){
2874 if (ec.IsConstructor){
2875 if (FieldInfo.IsStatic){
2887 local = ig.DeclareLocal (type);
2888 ig.Emit (OpCodes.Stloc, local);
2889 ig.Emit (OpCodes.Ldloca, local);
2894 if (FieldInfo.IsStatic){
2895 ig.Emit (OpCodes.Ldsflda, FieldInfo);
2898 ig.Emit (OpCodes.Ldflda, FieldInfo);
2904 // A FieldExpr whose address can not be taken
2906 public class FieldExprNoAddress : FieldExpr, IMemoryLocation {
2907 public FieldExprNoAddress (FieldInfo fi, Location loc) : base (fi, loc)
2911 public new void AddressOf (EmitContext ec, AddressOp mode)
2913 Report.Error (-215, "Report this: Taking the address of a remapped parameter not supported");
2918 /// Expression that evaluates to a Property. The Assign class
2919 /// might set the `Value' expression if we are in an assignment.
2921 /// This is not an LValue because we need to re-write the expression, we
2922 /// can not take data from the stack and store it.
2924 public class PropertyExpr : ExpressionStatement, IAssignMethod, IMemberExpr {
2925 public readonly PropertyInfo PropertyInfo;
2928 // This is set externally by the `BaseAccess' class
2931 MethodInfo getter, setter;
2933 bool must_do_cs1540_check;
2935 Expression instance_expr;
2936 LocalTemporary temp;
2939 public PropertyExpr (EmitContext ec, PropertyInfo pi, Location l)
2942 eclass = ExprClass.PropertyAccess;
2946 type = TypeManager.TypeToCoreType (pi.PropertyType);
2948 ResolveAccessors (ec);
2951 public string Name {
2953 return PropertyInfo.Name;
2957 public bool IsInstance {
2963 public bool IsStatic {
2969 public Type DeclaringType {
2971 return PropertyInfo.DeclaringType;
2976 // The instance expression associated with this expression
2978 public Expression InstanceExpression {
2980 instance_expr = value;
2984 return instance_expr;
2988 public bool VerifyAssignable ()
2990 if (setter == null) {
2991 Report.Error (200, loc,
2992 "The property `" + PropertyInfo.Name +
2993 "' can not be assigned to, as it has not set accessor");
3000 void FindAccessors (Type invocation_type)
3002 BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic |
3003 BindingFlags.Static | BindingFlags.Instance |
3004 BindingFlags.DeclaredOnly;
3006 Type current = PropertyInfo.DeclaringType;
3007 for (; current != null; current = current.BaseType) {
3008 MemberInfo[] group = TypeManager.MemberLookup (
3009 invocation_type, invocation_type, current,
3010 MemberTypes.Property, flags, PropertyInfo.Name, null);
3015 if (group.Length != 1)
3016 // Oooops, can this ever happen ?
3019 PropertyInfo pi = (PropertyInfo) group [0];
3022 getter = pi.GetGetMethod (true);;
3025 setter = pi.GetSetMethod (true);;
3027 MethodInfo accessor = getter != null ? getter : setter;
3029 if (!accessor.IsVirtual)
3034 bool IsAccessorAccessible (Type invocation_type, MethodInfo mi)
3036 MethodAttributes ma = mi.Attributes & MethodAttributes.MemberAccessMask;
3039 // If only accessible to the current class or children
3041 if (ma == MethodAttributes.Private) {
3042 Type declaring_type = mi.DeclaringType;
3044 if (invocation_type != declaring_type)
3045 return TypeManager.IsSubclassOrNestedChildOf (invocation_type, declaring_type);
3050 // FamAndAssem requires that we not only derivate, but we are on the
3053 if (ma == MethodAttributes.FamANDAssem){
3054 return (mi.DeclaringType.Assembly != invocation_type.Assembly);
3057 // Assembly and FamORAssem succeed if we're in the same assembly.
3058 if ((ma == MethodAttributes.Assembly) || (ma == MethodAttributes.FamORAssem)){
3059 if (mi.DeclaringType.Assembly == invocation_type.Assembly)
3063 // We already know that we aren't in the same assembly.
3064 if (ma == MethodAttributes.Assembly)
3067 // Family and FamANDAssem require that we derive.
3068 if ((ma == MethodAttributes.Family) || (ma == MethodAttributes.FamANDAssem) || (ma == MethodAttributes.FamORAssem)){
3069 if (!TypeManager.IsSubclassOrNestedChildOf (invocation_type, mi.DeclaringType))
3072 if (!TypeManager.IsNestedChildOf (invocation_type, mi.DeclaringType))
3073 must_do_cs1540_check = true;
3082 // We also perform the permission checking here, as the PropertyInfo does not
3083 // hold the information for the accessibility of its setter/getter
3085 void ResolveAccessors (EmitContext ec)
3087 FindAccessors (ec.ContainerType);
3089 is_static = getter != null ? getter.IsStatic : setter.IsStatic;
3092 bool InstanceResolve (EmitContext ec)
3094 if ((instance_expr == null) && ec.IsStatic && !is_static) {
3095 SimpleName.Error_ObjectRefRequired (ec, loc, PropertyInfo.Name);
3099 if (instance_expr != null) {
3100 instance_expr = instance_expr.DoResolve (ec);
3101 if (instance_expr == null)
3105 if (must_do_cs1540_check && (instance_expr != null)) {
3106 if ((instance_expr.Type != ec.ContainerType) &&
3107 ec.ContainerType.IsSubclassOf (instance_expr.Type)) {
3108 Report.Error (1540, loc, "Cannot access protected member `" +
3109 PropertyInfo.DeclaringType + "." + PropertyInfo.Name +
3110 "' via a qualifier of type `" +
3111 TypeManager.CSharpName (instance_expr.Type) +
3112 "'; the qualifier must be of type `" +
3113 TypeManager.CSharpName (ec.ContainerType) +
3114 "' (or derived from it)");
3122 override public Expression DoResolve (EmitContext ec)
3124 if (getter != null){
3125 if (TypeManager.GetArgumentTypes (getter).Length != 0){
3127 117, loc, "`{0}' does not contain a " +
3128 "definition for `{1}'.", getter.DeclaringType,
3134 if (getter == null){
3136 // The following condition happens if the PropertyExpr was
3137 // created, but is invalid (ie, the property is inaccessible),
3138 // and we did not want to embed the knowledge about this in
3139 // the caller routine. This only avoids double error reporting.
3144 Report.Error (154, loc,
3145 "The property `" + PropertyInfo.Name +
3146 "' can not be used in " +
3147 "this context because it lacks a get accessor");
3151 if (!IsAccessorAccessible (ec.ContainerType, getter)) {
3152 Report.Error (122, loc, "'{0}.get' is inaccessible due to its protection level", PropertyInfo.Name);
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 (!IsAccessorAccessible (ec.ContainerType, setter)) {
3199 Report.Error (122, loc, "'{0}.set' is inaccessible due to its protection level", PropertyInfo.Name);
3203 if (!InstanceResolve (ec))
3207 // Only base will allow this invocation to happen.
3209 if (IsBase && setter.IsAbstract){
3210 Report.Error (205, loc, "Cannot call an abstract base property: " +
3211 PropertyInfo.DeclaringType + "." +PropertyInfo.Name);
3216 // Check that we are not making changes to a temporary memory location
3218 if (instance_expr != null && instance_expr.Type.IsValueType && !(instance_expr is IMemoryLocation)) {
3219 // FIXME: Provide better error reporting.
3220 Error (1612, "Cannot modify expression because it is not a variable.");
3229 public override void Emit (EmitContext ec)
3234 void EmitInstance (EmitContext ec)
3239 if (instance_expr.Type.IsValueType) {
3240 if (instance_expr is IMemoryLocation) {
3241 ((IMemoryLocation) instance_expr).AddressOf (ec, AddressOp.LoadStore);
3243 LocalTemporary t = new LocalTemporary (ec, instance_expr.Type);
3244 instance_expr.Emit (ec);
3246 t.AddressOf (ec, AddressOp.Store);
3249 instance_expr.Emit (ec);
3252 ec.ig.Emit (OpCodes.Dup);
3256 public void Emit (EmitContext ec, bool leave_copy)
3262 // Special case: length of single dimension array property is turned into ldlen
3264 if ((getter == TypeManager.system_int_array_get_length) ||
3265 (getter == TypeManager.int_array_get_length)){
3266 Type iet = instance_expr.Type;
3269 // System.Array.Length can be called, but the Type does not
3270 // support invoking GetArrayRank, so test for that case first
3272 if (iet != TypeManager.array_type && (iet.GetArrayRank () == 1)) {
3273 ec.ig.Emit (OpCodes.Ldlen);
3274 ec.ig.Emit (OpCodes.Conv_I4);
3279 Invocation.EmitCall (ec, IsBase, IsStatic, new EmptyAddressOf (), getter, null, loc);
3284 ec.ig.Emit (OpCodes.Dup);
3286 temp = new LocalTemporary (ec, this.Type);
3292 // Implements the IAssignMethod interface for assignments
3294 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
3296 prepared = prepare_for_load;
3302 ec.ig.Emit (OpCodes.Dup);
3304 temp = new LocalTemporary (ec, this.Type);
3309 ArrayList args = new ArrayList (1);
3310 args.Add (new Argument (new EmptyAddressOf (), Argument.AType.Expression));
3312 Invocation.EmitCall (ec, IsBase, IsStatic, new EmptyAddressOf (), setter, args, loc);
3318 override public void EmitStatement (EmitContext ec)
3321 ec.ig.Emit (OpCodes.Pop);
3326 /// Fully resolved expression that evaluates to an Event
3328 public class EventExpr : Expression, IMemberExpr {
3329 public readonly EventInfo EventInfo;
3330 Expression instance_expr;
3333 MethodInfo add_accessor, remove_accessor;
3335 public EventExpr (EventInfo ei, Location loc)
3339 eclass = ExprClass.EventAccess;
3341 add_accessor = TypeManager.GetAddMethod (ei);
3342 remove_accessor = TypeManager.GetRemoveMethod (ei);
3344 if (add_accessor.IsStatic || remove_accessor.IsStatic)
3347 if (EventInfo is MyEventBuilder){
3348 MyEventBuilder eb = (MyEventBuilder) EventInfo;
3349 type = eb.EventType;
3352 type = EventInfo.EventHandlerType;
3355 public string Name {
3357 return EventInfo.Name;
3361 public bool IsInstance {
3367 public bool IsStatic {
3373 public Type DeclaringType {
3375 return EventInfo.DeclaringType;
3379 public Expression InstanceExpression {
3381 return instance_expr;
3385 instance_expr = value;
3389 public override Expression DoResolve (EmitContext ec)
3391 if (instance_expr != null) {
3392 instance_expr = instance_expr.DoResolve (ec);
3393 if (instance_expr == null)
3401 public override void Emit (EmitContext ec)
3403 Report.Error (70, loc, "The event `" + Name + "' can only appear on the left hand side of += or -= (except on the defining type)");
3406 public void EmitAddOrRemove (EmitContext ec, Expression source)
3408 BinaryDelegate source_del = (BinaryDelegate) source;
3409 Expression handler = source_del.Right;
3411 Argument arg = new Argument (handler, Argument.AType.Expression);
3412 ArrayList args = new ArrayList ();
3416 if (source_del.IsAddition)
3417 Invocation.EmitCall (
3418 ec, false, IsStatic, instance_expr, add_accessor, args, loc);
3420 Invocation.EmitCall (
3421 ec, false, IsStatic, instance_expr, remove_accessor, args, loc);