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 /// We are either a namespace or a type.
100 /// If we're a type, `IsType' is true and we may use `Type' to get
101 /// a TypeExpr representing that type.
103 public interface IAlias {
112 TypeExpr ResolveAsType (EmitContext ec);
116 /// This interface is implemented by variables
118 public interface IVariable {
119 VariableInfo VariableInfo {
123 bool VerifyFixed (bool is_expression);
127 /// This interface denotes an expression which evaluates to a member
128 /// of a struct or a class.
130 public interface IMemberExpr
133 /// The name of this member.
140 /// Whether this is an instance member.
147 /// Whether this is a static member.
154 /// The type which declares this member.
161 /// The instance expression associated with this member, if it's a
162 /// non-static member.
164 Expression InstanceExpression {
170 /// Base class for expressions
172 public abstract class Expression {
173 public ExprClass eclass;
175 protected Location loc;
187 public Location Location {
194 /// Utility wrapper routine for Error, just to beautify the code
196 public void Error (int error, string s)
198 if (!Location.IsNull (loc))
199 Report.Error (error, loc, s);
201 Report.Error (error, s);
205 /// Utility wrapper routine for Warning, just to beautify the code
207 public void Warning (int code, string format, params object[] args)
209 Report.Warning (code, loc, format, args);
212 // Not nice but we have broken hierarchy
213 public virtual void CheckMarshallByRefAccess (Type container) {}
216 /// Tests presence of ObsoleteAttribute and report proper error
218 protected void CheckObsoleteAttribute (Type type)
220 ObsoleteAttribute obsolete_attr = AttributeTester.GetObsoleteAttribute (type);
221 if (obsolete_attr == null)
224 AttributeTester.Report_ObsoleteMessage (obsolete_attr, type.FullName, loc);
227 public static bool IsAccessorAccessible (Type invocation_type, MethodInfo mi, out bool must_do_cs1540_check)
229 MethodAttributes ma = mi.Attributes & MethodAttributes.MemberAccessMask;
231 must_do_cs1540_check = false; // by default we do not check for this
234 // If only accessible to the current class or children
236 if (ma == MethodAttributes.Private) {
237 Type declaring_type = mi.DeclaringType;
239 if (invocation_type != declaring_type)
240 return TypeManager.IsNestedFamilyAccessible (invocation_type, declaring_type);
245 // FamAndAssem requires that we not only derivate, but we are on the
248 if (ma == MethodAttributes.FamANDAssem){
249 return (mi.DeclaringType.Assembly != invocation_type.Assembly);
252 // Assembly and FamORAssem succeed if we're in the same assembly.
253 if ((ma == MethodAttributes.Assembly) || (ma == MethodAttributes.FamORAssem)){
254 if (mi.DeclaringType.Assembly == invocation_type.Assembly)
258 // We already know that we aren't in the same assembly.
259 if (ma == MethodAttributes.Assembly)
262 // Family and FamANDAssem require that we derive.
263 if ((ma == MethodAttributes.Family) || (ma == MethodAttributes.FamANDAssem) || (ma == MethodAttributes.FamORAssem)){
264 if (!TypeManager.IsNestedFamilyAccessible (invocation_type, mi.DeclaringType))
267 if (!TypeManager.IsNestedChildOf (invocation_type, mi.DeclaringType))
268 must_do_cs1540_check = true;
277 /// Performs semantic analysis on the Expression
281 /// The Resolve method is invoked to perform the semantic analysis
284 /// The return value is an expression (it can be the
285 /// same expression in some cases) or a new
286 /// expression that better represents this node.
288 /// For example, optimizations of Unary (LiteralInt)
289 /// would return a new LiteralInt with a negated
292 /// If there is an error during semantic analysis,
293 /// then an error should be reported (using Report)
294 /// and a null value should be returned.
296 /// There are two side effects expected from calling
297 /// Resolve(): the the field variable "eclass" should
298 /// be set to any value of the enumeration
299 /// `ExprClass' and the type variable should be set
300 /// to a valid type (this is the type of the
303 public abstract Expression DoResolve (EmitContext ec);
305 public virtual Expression DoResolveLValue (EmitContext ec, Expression right_side)
307 return DoResolve (ec);
311 // This is used if the expression should be resolved as a type.
312 // the default implementation fails. Use this method in
313 // those participants in the SimpleName chain system.
315 public virtual Expression ResolveAsTypeStep (EmitContext ec)
321 // This is used to resolve the expression as a type, a null
322 // value will be returned if the expression is not a type
325 public TypeExpr ResolveAsTypeTerminal (EmitContext ec, bool silent)
327 int errors = Report.Errors;
329 TypeExpr te = ResolveAsTypeStep (ec) as TypeExpr;
331 if (te == null || te.eclass != ExprClass.Type) {
332 if (!silent && errors == Report.Errors)
333 Report.Error (246, Location, "Cannot find type '{0}'", ToString ());
337 if (!te.CheckAccessLevel (ec.DeclSpace)) {
338 Report.Error (122, Location, "'{0}' is inaccessible due to its protection level", te.Name);
346 /// Resolves an expression and performs semantic analysis on it.
350 /// Currently Resolve wraps DoResolve to perform sanity
351 /// checking and assertion checking on what we expect from Resolve.
353 public Expression Resolve (EmitContext ec, ResolveFlags flags)
355 if ((flags & ResolveFlags.MaskExprClass) == ResolveFlags.Type)
356 return ResolveAsTypeStep (ec);
358 bool old_do_flow_analysis = ec.DoFlowAnalysis;
359 if ((flags & ResolveFlags.DisableFlowAnalysis) != 0)
360 ec.DoFlowAnalysis = false;
363 bool intermediate = (flags & ResolveFlags.Intermediate) == ResolveFlags.Intermediate;
364 if (this is SimpleName)
365 e = ((SimpleName) this).DoResolveAllowStatic (ec, intermediate);
370 ec.DoFlowAnalysis = old_do_flow_analysis;
375 if (e is SimpleName){
376 SimpleName s = (SimpleName) e;
378 if ((flags & ResolveFlags.SimpleName) == 0) {
379 MemberLookupFailed (ec, null, ec.ContainerType, s.Name,
380 ec.DeclSpace.Name, loc);
387 if ((e is TypeExpr) || (e is ComposedCast)) {
388 if ((flags & ResolveFlags.Type) == 0) {
389 e.Error_UnexpectedKind (flags, loc);
398 if ((flags & ResolveFlags.VariableOrValue) == 0) {
399 e.Error_UnexpectedKind (flags, loc);
404 case ExprClass.MethodGroup:
405 if (RootContext.Version == LanguageVersion.ISO_1){
406 if ((flags & ResolveFlags.MethodGroup) == 0) {
407 ((MethodGroupExpr) e).ReportUsageError ();
413 case ExprClass.Value:
414 case ExprClass.Variable:
415 case ExprClass.PropertyAccess:
416 case ExprClass.EventAccess:
417 case ExprClass.IndexerAccess:
418 if ((flags & ResolveFlags.VariableOrValue) == 0) {
419 Console.WriteLine ("I got: {0} and {1}", e.GetType (), e);
420 Console.WriteLine ("I am {0} and {1}", this.GetType (), this);
421 FieldInfo fi = ((FieldExpr) e).FieldInfo;
423 Console.WriteLine ("{0} and {1}", fi.DeclaringType, fi.Name);
424 e.Error_UnexpectedKind (flags, loc);
430 throw new Exception ("Expression " + e.GetType () +
431 " ExprClass is Invalid after resolve");
435 throw new Exception (
436 "Expression " + e.GetType () +
437 " did not set its type after Resolve\n" +
438 "called from: " + this.GetType ());
444 /// Resolves an expression and performs semantic analysis on it.
446 public Expression Resolve (EmitContext ec)
448 return Resolve (ec, ResolveFlags.VariableOrValue);
452 /// Resolves an expression for LValue assignment
456 /// Currently ResolveLValue wraps DoResolveLValue to perform sanity
457 /// checking and assertion checking on what we expect from Resolve
459 public Expression ResolveLValue (EmitContext ec, Expression right_side)
461 Expression e = DoResolveLValue (ec, right_side);
464 if (e is SimpleName){
465 SimpleName s = (SimpleName) e;
466 MemberLookupFailed (ec, null, ec.ContainerType, s.Name,
467 ec.DeclSpace.Name, loc);
471 if (e.eclass == ExprClass.Invalid)
472 throw new Exception ("Expression " + e +
473 " ExprClass is Invalid after resolve");
475 if (e.eclass == ExprClass.MethodGroup) {
476 ((MethodGroupExpr) e).ReportUsageError ();
481 throw new Exception ("Expression " + e +
482 " did not set its type after Resolve");
489 /// Emits the code for the expression
493 /// The Emit method is invoked to generate the code
494 /// for the expression.
496 public abstract void Emit (EmitContext ec);
498 public virtual void EmitBranchable (EmitContext ec, Label target, bool onTrue)
501 ec.ig.Emit (onTrue ? OpCodes.Brtrue : OpCodes.Brfalse, target);
505 /// Protected constructor. Only derivate types should
506 /// be able to be created
509 protected Expression ()
511 eclass = ExprClass.Invalid;
516 /// Returns a literalized version of a literal FieldInfo
520 /// The possible return values are:
521 /// IntConstant, UIntConstant
522 /// LongLiteral, ULongConstant
523 /// FloatConstant, DoubleConstant
526 /// The value returned is already resolved.
528 public static Constant Constantify (object v, Type t)
530 if (t == TypeManager.int32_type)
531 return new IntConstant ((int) v);
532 else if (t == TypeManager.uint32_type)
533 return new UIntConstant ((uint) v);
534 else if (t == TypeManager.int64_type)
535 return new LongConstant ((long) v);
536 else if (t == TypeManager.uint64_type)
537 return new ULongConstant ((ulong) v);
538 else if (t == TypeManager.float_type)
539 return new FloatConstant ((float) v);
540 else if (t == TypeManager.double_type)
541 return new DoubleConstant ((double) v);
542 else if (t == TypeManager.string_type)
543 return new StringConstant ((string) v);
544 else if (t == TypeManager.short_type)
545 return new ShortConstant ((short)v);
546 else if (t == TypeManager.ushort_type)
547 return new UShortConstant ((ushort)v);
548 else if (t == TypeManager.sbyte_type)
549 return new SByteConstant (((sbyte)v));
550 else if (t == TypeManager.byte_type)
551 return new ByteConstant ((byte)v);
552 else if (t == TypeManager.char_type)
553 return new CharConstant ((char)v);
554 else if (t == TypeManager.bool_type)
555 return new BoolConstant ((bool) v);
556 else if (t == TypeManager.decimal_type)
557 return new DecimalConstant ((decimal) v);
558 else if (TypeManager.IsEnumType (t)){
559 Type real_type = TypeManager.TypeToCoreType (v.GetType ());
561 real_type = System.Enum.GetUnderlyingType (real_type);
563 Constant e = Constantify (v, real_type);
565 return new EnumConstant (e, t);
566 } else if (v == null && !TypeManager.IsValueType (t))
567 return NullLiteral.Null;
569 throw new Exception ("Unknown type for constant (" + t +
574 /// Returns a fully formed expression after a MemberLookup
576 public static Expression ExprClassFromMemberInfo (EmitContext ec, MemberInfo mi, Location loc)
579 return new EventExpr ((EventInfo) mi, loc);
580 else if (mi is FieldInfo)
581 return new FieldExpr ((FieldInfo) mi, loc);
582 else if (mi is PropertyInfo)
583 return new PropertyExpr (ec, (PropertyInfo) mi, loc);
584 else if (mi is Type){
585 return new TypeExpression ((System.Type) mi, loc);
592 private static ArrayList almostMatchedMembers = new ArrayList (4);
595 // FIXME: Probably implement a cache for (t,name,current_access_set)?
597 // This code could use some optimizations, but we need to do some
598 // measurements. For example, we could use a delegate to `flag' when
599 // something can not any longer be a method-group (because it is something
603 // If the return value is an Array, then it is an array of
606 // If the return value is an MemberInfo, it is anything, but a Method
610 // FIXME: When calling MemberLookup inside an `Invocation', we should pass
611 // the arguments here and have MemberLookup return only the methods that
612 // match the argument count/type, unlike we are doing now (we delay this
615 // This is so we can catch correctly attempts to invoke instance methods
616 // from a static body (scan for error 120 in ResolveSimpleName).
619 // FIXME: Potential optimization, have a static ArrayList
622 public static Expression MemberLookup (EmitContext ec, Type queried_type, string name,
623 MemberTypes mt, BindingFlags bf, Location loc)
625 return MemberLookup (ec, ec.ContainerType, null, queried_type, name, mt, bf, loc);
629 // Lookup type `queried_type' for code in class `container_type' with a qualifier of
630 // `qualifier_type' or null to lookup members in the current class.
633 public static Expression MemberLookup (EmitContext ec, Type container_type,
634 Type qualifier_type, Type queried_type,
635 string name, MemberTypes mt,
636 BindingFlags bf, Location loc)
638 almostMatchedMembers.Clear ();
640 MemberInfo [] mi = TypeManager.MemberLookup (container_type, qualifier_type,
641 queried_type, mt, bf, name, almostMatchedMembers);
646 int count = mi.Length;
648 if (mi [0] is MethodBase)
649 return new MethodGroupExpr (mi, loc);
654 return ExprClassFromMemberInfo (ec, mi [0], loc);
657 public const MemberTypes AllMemberTypes =
658 MemberTypes.Constructor |
662 MemberTypes.NestedType |
663 MemberTypes.Property;
665 public const BindingFlags AllBindingFlags =
666 BindingFlags.Public |
667 BindingFlags.Static |
668 BindingFlags.Instance;
670 public static Expression MemberLookup (EmitContext ec, Type queried_type,
671 string name, Location loc)
673 return MemberLookup (ec, ec.ContainerType, null, queried_type, name,
674 AllMemberTypes, AllBindingFlags, loc);
677 public static Expression MemberLookup (EmitContext ec, Type qualifier_type,
678 Type queried_type, string name, Location loc)
680 return MemberLookup (ec, ec.ContainerType, qualifier_type, queried_type,
681 name, AllMemberTypes, AllBindingFlags, loc);
684 public static Expression MethodLookup (EmitContext ec, Type queried_type,
685 string name, Location loc)
687 return MemberLookup (ec, ec.ContainerType, null, queried_type, name,
688 MemberTypes.Method, AllBindingFlags, loc);
692 /// This is a wrapper for MemberLookup that is not used to "probe", but
693 /// to find a final definition. If the final definition is not found, we
694 /// look for private members and display a useful debugging message if we
697 public static Expression MemberLookupFinal (EmitContext ec, Type qualifier_type,
698 Type queried_type, string name, Location loc)
700 return MemberLookupFinal (ec, qualifier_type, queried_type, name,
701 AllMemberTypes, AllBindingFlags, loc);
704 public static Expression MemberLookupFinal (EmitContext ec, Type qualifier_type,
705 Type queried_type, string name,
706 MemberTypes mt, BindingFlags bf,
711 int errors = Report.Errors;
713 e = MemberLookup (ec, ec.ContainerType, qualifier_type, queried_type, name, mt, bf, loc);
715 if (e == null && errors == Report.Errors)
716 // No errors were reported by MemberLookup, but there was an error.
717 MemberLookupFailed (ec, qualifier_type, queried_type, name, null, loc);
722 public static void MemberLookupFailed (EmitContext ec, Type qualifier_type,
723 Type queried_type, string name,
724 string class_name, Location loc)
726 if (almostMatchedMembers.Count != 0) {
727 if (qualifier_type == null) {
728 foreach (MemberInfo m in almostMatchedMembers)
729 Report.Error (38, loc,
730 "Cannot access non-static member `{0}' via nested type `{1}'",
731 TypeManager.GetFullNameSignature (m),
732 TypeManager.CSharpName (ec.ContainerType));
736 if (qualifier_type != ec.ContainerType) {
737 // Although a derived class can access protected members of
738 // its base class it cannot do so through an instance of the
739 // base class (CS1540). If the qualifier_type is a base of the
740 // ec.ContainerType and the lookup succeeds with the latter one,
741 // then we are in this situation.
742 foreach (MemberInfo m in almostMatchedMembers)
743 Report.Error (1540, loc,
744 "Cannot access protected member `{0}' via a qualifier of type `{1}';"
745 + " the qualifier must be of type `{2}' (or derived from it)",
746 TypeManager.GetFullNameSignature (m),
747 TypeManager.CSharpName (qualifier_type),
748 TypeManager.CSharpName (ec.ContainerType));
751 almostMatchedMembers.Clear ();
754 object lookup = TypeManager.MemberLookup (queried_type, null, queried_type,
755 AllMemberTypes, AllBindingFlags |
756 BindingFlags.NonPublic, name, null);
758 if (lookup == null) {
759 if (class_name != null)
760 Report.Error (103, loc, "The name `" + name + "' could not be " +
761 "found in `" + class_name + "'");
764 117, loc, "`" + queried_type + "' does not contain a " +
765 "definition for `" + name + "'");
769 if (name == ".ctor" && TypeManager.FindMembers (qualifier_type, MemberTypes.Constructor,
770 BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly, null, null).Count == 0)
772 Report.Error (143, loc, String.Format ("The type '{0}' has no constructors defined", TypeManager.CSharpName (queried_type)));
776 if (qualifier_type != null) {
777 Report.Error (122, loc, "'{0}' is inaccessible due to its protection level", TypeManager.CSharpName (qualifier_type) + "." + name);
779 Report.Error (122, loc, "'{0}' is inaccessible due to its protection level", name);
783 static public MemberInfo GetFieldFromEvent (EventExpr event_expr)
785 EventInfo ei = event_expr.EventInfo;
787 return TypeManager.GetPrivateFieldOfEvent (ei);
791 /// Returns an expression that can be used to invoke operator true
792 /// on the expression if it exists.
794 static public StaticCallExpr GetOperatorTrue (EmitContext ec, Expression e, Location loc)
796 return GetOperatorTrueOrFalse (ec, e, true, loc);
800 /// Returns an expression that can be used to invoke operator false
801 /// on the expression if it exists.
803 static public StaticCallExpr GetOperatorFalse (EmitContext ec, Expression e, Location loc)
805 return GetOperatorTrueOrFalse (ec, e, false, loc);
808 static StaticCallExpr GetOperatorTrueOrFalse (EmitContext ec, Expression e, bool is_true, Location loc)
811 Expression operator_group;
813 operator_group = MethodLookup (ec, e.Type, is_true ? "op_True" : "op_False", loc);
814 if (operator_group == null)
817 ArrayList arguments = new ArrayList ();
818 arguments.Add (new Argument (e, Argument.AType.Expression));
819 method = Invocation.OverloadResolve (
820 ec, (MethodGroupExpr) operator_group, arguments, false, loc);
825 return new StaticCallExpr ((MethodInfo) method, arguments, loc);
829 /// Resolves the expression `e' into a boolean expression: either through
830 /// an implicit conversion, or through an `operator true' invocation
832 public static Expression ResolveBoolean (EmitContext ec, Expression e, Location loc)
838 if (e.Type == TypeManager.bool_type)
841 Expression converted = Convert.ImplicitConversion (ec, e, TypeManager.bool_type, new Location (-1));
843 if (converted != null)
847 // If no implicit conversion to bool exists, try using `operator true'
849 Expression operator_true = Expression.GetOperatorTrue (ec, e, loc);
850 if (operator_true == null){
851 Report.Error (31, loc, "Can not convert the expression to a boolean");
854 return operator_true;
857 static string ExprClassName (ExprClass c)
860 case ExprClass.Invalid:
862 case ExprClass.Value:
864 case ExprClass.Variable:
866 case ExprClass.Namespace:
870 case ExprClass.MethodGroup:
871 return "method group";
872 case ExprClass.PropertyAccess:
873 return "property access";
874 case ExprClass.EventAccess:
875 return "event access";
876 case ExprClass.IndexerAccess:
877 return "indexer access";
878 case ExprClass.Nothing:
881 throw new Exception ("Should not happen");
885 /// Reports that we were expecting `expr' to be of class `expected'
887 public void Error_UnexpectedKind (string expected, Location loc)
889 string kind = "Unknown";
891 kind = ExprClassName (eclass);
893 Report.Error (118, loc, "Expression denotes a `" + kind +
894 "' where a `" + expected + "' was expected");
897 public void Error_UnexpectedKind (ResolveFlags flags, Location loc)
899 ArrayList valid = new ArrayList (10);
901 if ((flags & ResolveFlags.VariableOrValue) != 0) {
902 valid.Add ("variable");
906 if ((flags & ResolveFlags.Type) != 0)
909 if ((flags & ResolveFlags.MethodGroup) != 0)
910 valid.Add ("method group");
912 if ((flags & ResolveFlags.SimpleName) != 0)
913 valid.Add ("simple name");
915 if (valid.Count == 0)
916 valid.Add ("unknown");
918 StringBuilder sb = new StringBuilder ();
919 for (int i = 0; i < valid.Count; i++) {
922 else if (i == valid.Count)
924 sb.Append (valid [i]);
927 string kind = ExprClassName (eclass);
929 Error (119, "Expression denotes a `" + kind + "' where " +
930 "a `" + sb.ToString () + "' was expected");
933 static public void Error_ConstantValueCannotBeConverted (Location l, string val, Type t)
935 Report.Error (31, l, "Constant value `" + val + "' cannot be converted to " +
936 TypeManager.CSharpName (t));
939 public static void UnsafeError (Location loc)
941 Report.Error (214, loc, "Pointers may only be used in an unsafe context");
945 /// Converts the IntConstant, UIntConstant, LongConstant or
946 /// ULongConstant into the integral target_type. Notice
947 /// that we do not return an `Expression' we do return
948 /// a boxed integral type.
950 /// FIXME: Since I added the new constants, we need to
951 /// also support conversions from CharConstant, ByteConstant,
952 /// SByteConstant, UShortConstant, ShortConstant
954 /// This is used by the switch statement, so the domain
955 /// of work is restricted to the literals above, and the
956 /// targets are int32, uint32, char, byte, sbyte, ushort,
957 /// short, uint64 and int64
959 public static object ConvertIntLiteral (Constant c, Type target_type, Location loc)
961 if (!Convert.ImplicitStandardConversionExists (Convert.ConstantEC, c, target_type)){
962 Convert.Error_CannotImplicitConversion (loc, c.Type, target_type);
968 if (c.Type == target_type)
969 return ((Constant) c).GetValue ();
972 // Make into one of the literals we handle, we dont really care
973 // about this value as we will just return a few limited types
975 if (c is EnumConstant)
976 c = ((EnumConstant)c).WidenToCompilerConstant ();
978 if (c is IntConstant){
979 int v = ((IntConstant) c).Value;
981 if (target_type == TypeManager.uint32_type){
984 } else if (target_type == TypeManager.char_type){
985 if (v >= Char.MinValue && v <= Char.MaxValue)
987 } else if (target_type == TypeManager.byte_type){
988 if (v >= Byte.MinValue && v <= Byte.MaxValue)
990 } else if (target_type == TypeManager.sbyte_type){
991 if (v >= SByte.MinValue && v <= SByte.MaxValue)
993 } else if (target_type == TypeManager.short_type){
994 if (v >= Int16.MinValue && v <= UInt16.MaxValue)
996 } else if (target_type == TypeManager.ushort_type){
997 if (v >= UInt16.MinValue && v <= UInt16.MaxValue)
999 } else if (target_type == TypeManager.int64_type)
1001 else if (target_type == TypeManager.uint64_type){
1007 } else if (c is UIntConstant){
1008 uint v = ((UIntConstant) c).Value;
1010 if (target_type == TypeManager.int32_type){
1011 if (v <= Int32.MaxValue)
1013 } else if (target_type == TypeManager.char_type){
1014 if (v >= Char.MinValue && v <= Char.MaxValue)
1016 } else if (target_type == TypeManager.byte_type){
1017 if (v <= Byte.MaxValue)
1019 } else if (target_type == TypeManager.sbyte_type){
1020 if (v <= SByte.MaxValue)
1022 } else if (target_type == TypeManager.short_type){
1023 if (v <= UInt16.MaxValue)
1025 } else if (target_type == TypeManager.ushort_type){
1026 if (v <= UInt16.MaxValue)
1028 } else if (target_type == TypeManager.int64_type)
1030 else if (target_type == TypeManager.uint64_type)
1033 } else if (c is LongConstant){
1034 long v = ((LongConstant) c).Value;
1036 if (target_type == TypeManager.int32_type){
1037 if (v >= UInt32.MinValue && v <= UInt32.MaxValue)
1039 } else if (target_type == TypeManager.uint32_type){
1040 if (v >= 0 && v <= UInt32.MaxValue)
1042 } else if (target_type == TypeManager.char_type){
1043 if (v >= Char.MinValue && v <= Char.MaxValue)
1045 } else if (target_type == TypeManager.byte_type){
1046 if (v >= Byte.MinValue && v <= Byte.MaxValue)
1048 } else if (target_type == TypeManager.sbyte_type){
1049 if (v >= SByte.MinValue && v <= SByte.MaxValue)
1051 } else if (target_type == TypeManager.short_type){
1052 if (v >= Int16.MinValue && v <= UInt16.MaxValue)
1054 } else if (target_type == TypeManager.ushort_type){
1055 if (v >= UInt16.MinValue && v <= UInt16.MaxValue)
1057 } else if (target_type == TypeManager.uint64_type){
1062 } else if (c is ULongConstant){
1063 ulong v = ((ULongConstant) c).Value;
1065 if (target_type == TypeManager.int32_type){
1066 if (v <= Int32.MaxValue)
1068 } else if (target_type == TypeManager.uint32_type){
1069 if (v <= UInt32.MaxValue)
1071 } else if (target_type == TypeManager.char_type){
1072 if (v >= Char.MinValue && v <= Char.MaxValue)
1074 } else if (target_type == TypeManager.byte_type){
1075 if (v >= Byte.MinValue && v <= Byte.MaxValue)
1077 } else if (target_type == TypeManager.sbyte_type){
1078 if (v <= (int) SByte.MaxValue)
1080 } else if (target_type == TypeManager.short_type){
1081 if (v <= UInt16.MaxValue)
1083 } else if (target_type == TypeManager.ushort_type){
1084 if (v <= UInt16.MaxValue)
1086 } else if (target_type == TypeManager.int64_type){
1087 if (v <= Int64.MaxValue)
1091 } else if (c is ByteConstant){
1092 byte v = ((ByteConstant) c).Value;
1094 if (target_type == TypeManager.int32_type)
1096 else if (target_type == TypeManager.uint32_type)
1098 else if (target_type == TypeManager.char_type)
1100 else if (target_type == TypeManager.sbyte_type){
1101 if (v <= SByte.MaxValue)
1103 } else if (target_type == TypeManager.short_type)
1105 else if (target_type == TypeManager.ushort_type)
1107 else if (target_type == TypeManager.int64_type)
1109 else if (target_type == TypeManager.uint64_type)
1112 } else if (c is SByteConstant){
1113 sbyte v = ((SByteConstant) c).Value;
1115 if (target_type == TypeManager.int32_type)
1117 else if (target_type == TypeManager.uint32_type){
1120 } else if (target_type == TypeManager.char_type){
1123 } else if (target_type == TypeManager.byte_type){
1126 } else if (target_type == TypeManager.short_type)
1128 else if (target_type == TypeManager.ushort_type){
1131 } else if (target_type == TypeManager.int64_type)
1133 else if (target_type == TypeManager.uint64_type){
1138 } else if (c is ShortConstant){
1139 short v = ((ShortConstant) c).Value;
1141 if (target_type == TypeManager.int32_type){
1143 } else if (target_type == TypeManager.uint32_type){
1146 } else if (target_type == TypeManager.char_type){
1149 } else if (target_type == TypeManager.byte_type){
1150 if (v >= Byte.MinValue && v <= Byte.MaxValue)
1152 } else if (target_type == TypeManager.sbyte_type){
1153 if (v >= SByte.MinValue && v <= SByte.MaxValue)
1155 } else if (target_type == TypeManager.ushort_type){
1158 } else if (target_type == TypeManager.int64_type)
1160 else if (target_type == TypeManager.uint64_type)
1164 } else if (c is UShortConstant){
1165 ushort v = ((UShortConstant) c).Value;
1167 if (target_type == TypeManager.int32_type)
1169 else if (target_type == TypeManager.uint32_type)
1171 else if (target_type == TypeManager.char_type){
1172 if (v >= Char.MinValue && v <= Char.MaxValue)
1174 } else if (target_type == TypeManager.byte_type){
1175 if (v >= Byte.MinValue && v <= Byte.MaxValue)
1177 } else if (target_type == TypeManager.sbyte_type){
1178 if (v <= SByte.MaxValue)
1180 } else if (target_type == TypeManager.short_type){
1181 if (v <= Int16.MaxValue)
1183 } else if (target_type == TypeManager.int64_type)
1185 else if (target_type == TypeManager.uint64_type)
1189 } else if (c is CharConstant){
1190 char v = ((CharConstant) c).Value;
1192 if (target_type == TypeManager.int32_type)
1194 else if (target_type == TypeManager.uint32_type)
1196 else if (target_type == TypeManager.byte_type){
1197 if (v >= Byte.MinValue && v <= Byte.MaxValue)
1199 } else if (target_type == TypeManager.sbyte_type){
1200 if (v <= SByte.MaxValue)
1202 } else if (target_type == TypeManager.short_type){
1203 if (v <= Int16.MaxValue)
1205 } else if (target_type == TypeManager.ushort_type)
1207 else if (target_type == TypeManager.int64_type)
1209 else if (target_type == TypeManager.uint64_type)
1214 Error_ConstantValueCannotBeConverted (loc, s, target_type);
1219 // Load the object from the pointer.
1221 public static void LoadFromPtr (ILGenerator ig, Type t)
1223 if (t == TypeManager.int32_type)
1224 ig.Emit (OpCodes.Ldind_I4);
1225 else if (t == TypeManager.uint32_type)
1226 ig.Emit (OpCodes.Ldind_U4);
1227 else if (t == TypeManager.short_type)
1228 ig.Emit (OpCodes.Ldind_I2);
1229 else if (t == TypeManager.ushort_type)
1230 ig.Emit (OpCodes.Ldind_U2);
1231 else if (t == TypeManager.char_type)
1232 ig.Emit (OpCodes.Ldind_U2);
1233 else if (t == TypeManager.byte_type)
1234 ig.Emit (OpCodes.Ldind_U1);
1235 else if (t == TypeManager.sbyte_type)
1236 ig.Emit (OpCodes.Ldind_I1);
1237 else if (t == TypeManager.uint64_type)
1238 ig.Emit (OpCodes.Ldind_I8);
1239 else if (t == TypeManager.int64_type)
1240 ig.Emit (OpCodes.Ldind_I8);
1241 else if (t == TypeManager.float_type)
1242 ig.Emit (OpCodes.Ldind_R4);
1243 else if (t == TypeManager.double_type)
1244 ig.Emit (OpCodes.Ldind_R8);
1245 else if (t == TypeManager.bool_type)
1246 ig.Emit (OpCodes.Ldind_I1);
1247 else if (t == TypeManager.intptr_type)
1248 ig.Emit (OpCodes.Ldind_I);
1249 else if (TypeManager.IsEnumType (t)) {
1250 if (t == TypeManager.enum_type)
1251 ig.Emit (OpCodes.Ldind_Ref);
1253 LoadFromPtr (ig, TypeManager.EnumToUnderlying (t));
1254 } else if (t.IsValueType)
1255 ig.Emit (OpCodes.Ldobj, t);
1256 else if (t.IsPointer)
1257 ig.Emit (OpCodes.Ldind_I);
1259 ig.Emit (OpCodes.Ldind_Ref);
1263 // The stack contains the pointer and the value of type `type'
1265 public static void StoreFromPtr (ILGenerator ig, Type type)
1267 if (TypeManager.IsEnumType (type))
1268 type = TypeManager.EnumToUnderlying (type);
1269 if (type == TypeManager.int32_type || type == TypeManager.uint32_type)
1270 ig.Emit (OpCodes.Stind_I4);
1271 else if (type == TypeManager.int64_type || type == TypeManager.uint64_type)
1272 ig.Emit (OpCodes.Stind_I8);
1273 else if (type == TypeManager.char_type || type == TypeManager.short_type ||
1274 type == TypeManager.ushort_type)
1275 ig.Emit (OpCodes.Stind_I2);
1276 else if (type == TypeManager.float_type)
1277 ig.Emit (OpCodes.Stind_R4);
1278 else if (type == TypeManager.double_type)
1279 ig.Emit (OpCodes.Stind_R8);
1280 else if (type == TypeManager.byte_type || type == TypeManager.sbyte_type ||
1281 type == TypeManager.bool_type)
1282 ig.Emit (OpCodes.Stind_I1);
1283 else if (type == TypeManager.intptr_type)
1284 ig.Emit (OpCodes.Stind_I);
1285 else if (type.IsValueType)
1286 ig.Emit (OpCodes.Stobj, type);
1288 ig.Emit (OpCodes.Stind_Ref);
1292 // Returns the size of type `t' if known, otherwise, 0
1294 public static int GetTypeSize (Type t)
1296 t = TypeManager.TypeToCoreType (t);
1297 if (t == TypeManager.int32_type ||
1298 t == TypeManager.uint32_type ||
1299 t == TypeManager.float_type)
1301 else if (t == TypeManager.int64_type ||
1302 t == TypeManager.uint64_type ||
1303 t == TypeManager.double_type)
1305 else if (t == TypeManager.byte_type ||
1306 t == TypeManager.sbyte_type ||
1307 t == TypeManager.bool_type)
1309 else if (t == TypeManager.short_type ||
1310 t == TypeManager.char_type ||
1311 t == TypeManager.ushort_type)
1313 else if (t == TypeManager.decimal_type)
1319 public static void Error_NegativeArrayIndex (Location loc)
1321 Report.Error (248, loc, "Cannot create an array with a negative size");
1325 // Converts `source' to an int, uint, long or ulong.
1327 public Expression ExpressionToArrayArgument (EmitContext ec, Expression source, Location loc)
1331 bool old_checked = ec.CheckState;
1332 ec.CheckState = true;
1334 target = Convert.ImplicitConversion (ec, source, TypeManager.int32_type, loc);
1335 if (target == null){
1336 target = Convert.ImplicitConversion (ec, source, TypeManager.uint32_type, loc);
1337 if (target == null){
1338 target = Convert.ImplicitConversion (ec, source, TypeManager.int64_type, loc);
1339 if (target == null){
1340 target = Convert.ImplicitConversion (ec, source, TypeManager.uint64_type, loc);
1342 Convert.Error_CannotImplicitConversion (loc, source.Type, TypeManager.int32_type);
1346 ec.CheckState = old_checked;
1349 // Only positive constants are allowed at compile time
1351 if (target is Constant){
1352 if (target is IntConstant){
1353 if (((IntConstant) target).Value < 0){
1354 Error_NegativeArrayIndex (loc);
1359 if (target is LongConstant){
1360 if (((LongConstant) target).Value < 0){
1361 Error_NegativeArrayIndex (loc);
1374 /// This is just a base class for expressions that can
1375 /// appear on statements (invocations, object creation,
1376 /// assignments, post/pre increment and decrement). The idea
1377 /// being that they would support an extra Emition interface that
1378 /// does not leave a result on the stack.
1380 public abstract class ExpressionStatement : Expression {
1382 public virtual ExpressionStatement ResolveStatement (EmitContext ec)
1384 Expression e = Resolve (ec);
1388 ExpressionStatement es = e as ExpressionStatement;
1390 Error (201, "Only assignment, call, increment, decrement and new object " +
1391 "expressions can be used as a statement");
1397 /// Requests the expression to be emitted in a `statement'
1398 /// context. This means that no new value is left on the
1399 /// stack after invoking this method (constrasted with
1400 /// Emit that will always leave a value on the stack).
1402 public abstract void EmitStatement (EmitContext ec);
1406 /// This kind of cast is used to encapsulate the child
1407 /// whose type is child.Type into an expression that is
1408 /// reported to return "return_type". This is used to encapsulate
1409 /// expressions which have compatible types, but need to be dealt
1410 /// at higher levels with.
1412 /// For example, a "byte" expression could be encapsulated in one
1413 /// of these as an "unsigned int". The type for the expression
1414 /// would be "unsigned int".
1417 public class EmptyCast : Expression {
1418 protected Expression child;
1420 public Expression Child {
1426 public EmptyCast (Expression child, Type return_type)
1428 eclass = child.eclass;
1433 public override Expression DoResolve (EmitContext ec)
1435 // This should never be invoked, we are born in fully
1436 // initialized state.
1441 public override void Emit (EmitContext ec)
1448 // We need to special case this since an empty cast of
1449 // a NullLiteral is still a Constant
1451 public class NullCast : Constant {
1452 protected Expression child;
1454 public NullCast (Expression child, Type return_type)
1456 eclass = child.eclass;
1461 override public string AsString ()
1466 public override object GetValue ()
1471 public override Expression DoResolve (EmitContext ec)
1473 // This should never be invoked, we are born in fully
1474 // initialized state.
1479 public override void Emit (EmitContext ec)
1484 public override bool IsNegative {
1493 /// This class is used to wrap literals which belong inside Enums
1495 public class EnumConstant : Constant {
1496 public Constant Child;
1498 public EnumConstant (Constant child, Type enum_type)
1500 eclass = child.eclass;
1505 public override Expression DoResolve (EmitContext ec)
1507 // This should never be invoked, we are born in fully
1508 // initialized state.
1513 public override void Emit (EmitContext ec)
1518 public override object GetValue ()
1520 return Child.GetValue ();
1523 public object GetValueAsEnumType ()
1525 return System.Enum.ToObject (type, Child.GetValue ());
1529 // Converts from one of the valid underlying types for an enumeration
1530 // (int32, uint32, int64, uint64, short, ushort, byte, sbyte) to
1531 // one of the internal compiler literals: Int/UInt/Long/ULong Literals.
1533 public Constant WidenToCompilerConstant ()
1535 Type t = TypeManager.EnumToUnderlying (Child.Type);
1536 object v = ((Constant) Child).GetValue ();;
1538 if (t == TypeManager.int32_type)
1539 return new IntConstant ((int) v);
1540 if (t == TypeManager.uint32_type)
1541 return new UIntConstant ((uint) v);
1542 if (t == TypeManager.int64_type)
1543 return new LongConstant ((long) v);
1544 if (t == TypeManager.uint64_type)
1545 return new ULongConstant ((ulong) v);
1546 if (t == TypeManager.short_type)
1547 return new ShortConstant ((short) v);
1548 if (t == TypeManager.ushort_type)
1549 return new UShortConstant ((ushort) v);
1550 if (t == TypeManager.byte_type)
1551 return new ByteConstant ((byte) v);
1552 if (t == TypeManager.sbyte_type)
1553 return new SByteConstant ((sbyte) v);
1555 throw new Exception ("Invalid enumeration underlying type: " + t);
1559 // Extracts the value in the enumeration on its native representation
1561 public object GetPlainValue ()
1563 Type t = TypeManager.EnumToUnderlying (Child.Type);
1564 object v = ((Constant) Child).GetValue ();;
1566 if (t == TypeManager.int32_type)
1568 if (t == TypeManager.uint32_type)
1570 if (t == TypeManager.int64_type)
1572 if (t == TypeManager.uint64_type)
1574 if (t == TypeManager.short_type)
1576 if (t == TypeManager.ushort_type)
1578 if (t == TypeManager.byte_type)
1580 if (t == TypeManager.sbyte_type)
1586 public override string AsString ()
1588 return Child.AsString ();
1591 public override DoubleConstant ConvertToDouble ()
1593 return Child.ConvertToDouble ();
1596 public override FloatConstant ConvertToFloat ()
1598 return Child.ConvertToFloat ();
1601 public override ULongConstant ConvertToULong ()
1603 return Child.ConvertToULong ();
1606 public override LongConstant ConvertToLong ()
1608 return Child.ConvertToLong ();
1611 public override UIntConstant ConvertToUInt ()
1613 return Child.ConvertToUInt ();
1616 public override IntConstant ConvertToInt ()
1618 return Child.ConvertToInt ();
1621 public override bool IsZeroInteger {
1622 get { return Child.IsZeroInteger; }
1625 public override bool IsNegative {
1627 return Child.IsNegative;
1633 /// This kind of cast is used to encapsulate Value Types in objects.
1635 /// The effect of it is to box the value type emitted by the previous
1638 public class BoxedCast : EmptyCast {
1640 public BoxedCast (Expression expr)
1641 : base (expr, TypeManager.object_type)
1643 eclass = ExprClass.Value;
1646 public BoxedCast (Expression expr, Type target_type)
1647 : base (expr, target_type)
1649 eclass = ExprClass.Value;
1652 public override Expression DoResolve (EmitContext ec)
1654 // This should never be invoked, we are born in fully
1655 // initialized state.
1660 public override void Emit (EmitContext ec)
1664 ec.ig.Emit (OpCodes.Box, child.Type);
1668 public class UnboxCast : EmptyCast {
1669 public UnboxCast (Expression expr, Type return_type)
1670 : base (expr, return_type)
1674 public override Expression DoResolve (EmitContext ec)
1676 // This should never be invoked, we are born in fully
1677 // initialized state.
1682 public override void Emit (EmitContext ec)
1685 ILGenerator ig = ec.ig;
1688 ig.Emit (OpCodes.Unbox, t);
1690 LoadFromPtr (ig, t);
1695 /// This is used to perform explicit numeric conversions.
1697 /// Explicit numeric conversions might trigger exceptions in a checked
1698 /// context, so they should generate the conv.ovf opcodes instead of
1701 public class ConvCast : EmptyCast {
1702 public enum Mode : byte {
1703 I1_U1, I1_U2, I1_U4, I1_U8, I1_CH,
1705 I2_I1, I2_U1, I2_U2, I2_U4, I2_U8, I2_CH,
1706 U2_I1, U2_U1, U2_I2, U2_CH,
1707 I4_I1, I4_U1, I4_I2, I4_U2, I4_U4, I4_U8, I4_CH,
1708 U4_I1, U4_U1, U4_I2, U4_U2, U4_I4, U4_CH,
1709 I8_I1, I8_U1, I8_I2, I8_U2, I8_I4, I8_U4, I8_U8, I8_CH,
1710 U8_I1, U8_U1, U8_I2, U8_U2, U8_I4, U8_U4, U8_I8, U8_CH,
1711 CH_I1, CH_U1, CH_I2,
1712 R4_I1, R4_U1, R4_I2, R4_U2, R4_I4, R4_U4, R4_I8, R4_U8, R4_CH,
1713 R8_I1, R8_U1, R8_I2, R8_U2, R8_I4, R8_U4, R8_I8, R8_U8, R8_CH, R8_R4
1719 public ConvCast (EmitContext ec, Expression child, Type return_type, Mode m)
1720 : base (child, return_type)
1722 checked_state = ec.CheckState;
1726 public override Expression DoResolve (EmitContext ec)
1728 // This should never be invoked, we are born in fully
1729 // initialized state.
1734 public override string ToString ()
1736 return String.Format ("ConvCast ({0}, {1})", mode, child);
1739 public override void Emit (EmitContext ec)
1741 ILGenerator ig = ec.ig;
1747 case Mode.I1_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1748 case Mode.I1_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1749 case Mode.I1_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1750 case Mode.I1_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1751 case Mode.I1_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1753 case Mode.U1_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1754 case Mode.U1_CH: /* nothing */ break;
1756 case Mode.I2_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1757 case Mode.I2_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1758 case Mode.I2_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1759 case Mode.I2_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1760 case Mode.I2_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1761 case Mode.I2_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1763 case Mode.U2_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1764 case Mode.U2_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
1765 case Mode.U2_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
1766 case Mode.U2_CH: /* nothing */ break;
1768 case Mode.I4_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1769 case Mode.I4_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1770 case Mode.I4_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
1771 case Mode.I4_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1772 case Mode.I4_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1773 case Mode.I4_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1774 case Mode.I4_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1776 case Mode.U4_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1777 case Mode.U4_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
1778 case Mode.U4_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
1779 case Mode.U4_U2: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
1780 case Mode.U4_I4: ig.Emit (OpCodes.Conv_Ovf_I4_Un); break;
1781 case Mode.U4_CH: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
1783 case Mode.I8_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1784 case Mode.I8_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1785 case Mode.I8_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
1786 case Mode.I8_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1787 case Mode.I8_I4: ig.Emit (OpCodes.Conv_Ovf_I4); break;
1788 case Mode.I8_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1789 case Mode.I8_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1790 case Mode.I8_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1792 case Mode.U8_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1793 case Mode.U8_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
1794 case Mode.U8_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
1795 case Mode.U8_U2: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
1796 case Mode.U8_I4: ig.Emit (OpCodes.Conv_Ovf_I4_Un); break;
1797 case Mode.U8_U4: ig.Emit (OpCodes.Conv_Ovf_U4_Un); break;
1798 case Mode.U8_I8: ig.Emit (OpCodes.Conv_Ovf_I8_Un); break;
1799 case Mode.U8_CH: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
1801 case Mode.CH_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1802 case Mode.CH_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
1803 case Mode.CH_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
1805 case Mode.R4_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1806 case Mode.R4_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1807 case Mode.R4_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
1808 case Mode.R4_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1809 case Mode.R4_I4: ig.Emit (OpCodes.Conv_Ovf_I4); break;
1810 case Mode.R4_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1811 case Mode.R4_I8: ig.Emit (OpCodes.Conv_Ovf_I8); break;
1812 case Mode.R4_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1813 case Mode.R4_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1815 case Mode.R8_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1816 case Mode.R8_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1817 case Mode.R8_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
1818 case Mode.R8_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1819 case Mode.R8_I4: ig.Emit (OpCodes.Conv_Ovf_I4); break;
1820 case Mode.R8_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1821 case Mode.R8_I8: ig.Emit (OpCodes.Conv_Ovf_I8); break;
1822 case Mode.R8_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1823 case Mode.R8_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1824 case Mode.R8_R4: ig.Emit (OpCodes.Conv_R4); break;
1828 case Mode.I1_U1: ig.Emit (OpCodes.Conv_U1); break;
1829 case Mode.I1_U2: ig.Emit (OpCodes.Conv_U2); break;
1830 case Mode.I1_U4: ig.Emit (OpCodes.Conv_U4); break;
1831 case Mode.I1_U8: ig.Emit (OpCodes.Conv_I8); break;
1832 case Mode.I1_CH: ig.Emit (OpCodes.Conv_U2); break;
1834 case Mode.U1_I1: ig.Emit (OpCodes.Conv_I1); break;
1835 case Mode.U1_CH: ig.Emit (OpCodes.Conv_U2); break;
1837 case Mode.I2_I1: ig.Emit (OpCodes.Conv_I1); break;
1838 case Mode.I2_U1: ig.Emit (OpCodes.Conv_U1); break;
1839 case Mode.I2_U2: ig.Emit (OpCodes.Conv_U2); break;
1840 case Mode.I2_U4: ig.Emit (OpCodes.Conv_U4); break;
1841 case Mode.I2_U8: ig.Emit (OpCodes.Conv_I8); break;
1842 case Mode.I2_CH: ig.Emit (OpCodes.Conv_U2); break;
1844 case Mode.U2_I1: ig.Emit (OpCodes.Conv_I1); break;
1845 case Mode.U2_U1: ig.Emit (OpCodes.Conv_U1); break;
1846 case Mode.U2_I2: ig.Emit (OpCodes.Conv_I2); break;
1847 case Mode.U2_CH: /* nothing */ break;
1849 case Mode.I4_I1: ig.Emit (OpCodes.Conv_I1); break;
1850 case Mode.I4_U1: ig.Emit (OpCodes.Conv_U1); break;
1851 case Mode.I4_I2: ig.Emit (OpCodes.Conv_I2); break;
1852 case Mode.I4_U4: /* nothing */ break;
1853 case Mode.I4_U2: ig.Emit (OpCodes.Conv_U2); break;
1854 case Mode.I4_U8: ig.Emit (OpCodes.Conv_I8); break;
1855 case Mode.I4_CH: ig.Emit (OpCodes.Conv_U2); break;
1857 case Mode.U4_I1: ig.Emit (OpCodes.Conv_I1); break;
1858 case Mode.U4_U1: ig.Emit (OpCodes.Conv_U1); break;
1859 case Mode.U4_I2: ig.Emit (OpCodes.Conv_I2); break;
1860 case Mode.U4_U2: ig.Emit (OpCodes.Conv_U2); break;
1861 case Mode.U4_I4: /* nothing */ break;
1862 case Mode.U4_CH: ig.Emit (OpCodes.Conv_U2); break;
1864 case Mode.I8_I1: ig.Emit (OpCodes.Conv_I1); break;
1865 case Mode.I8_U1: ig.Emit (OpCodes.Conv_U1); break;
1866 case Mode.I8_I2: ig.Emit (OpCodes.Conv_I2); break;
1867 case Mode.I8_U2: ig.Emit (OpCodes.Conv_U2); break;
1868 case Mode.I8_I4: ig.Emit (OpCodes.Conv_I4); break;
1869 case Mode.I8_U4: ig.Emit (OpCodes.Conv_U4); break;
1870 case Mode.I8_U8: /* nothing */ break;
1871 case Mode.I8_CH: ig.Emit (OpCodes.Conv_U2); break;
1873 case Mode.U8_I1: ig.Emit (OpCodes.Conv_I1); break;
1874 case Mode.U8_U1: ig.Emit (OpCodes.Conv_U1); break;
1875 case Mode.U8_I2: ig.Emit (OpCodes.Conv_I2); break;
1876 case Mode.U8_U2: ig.Emit (OpCodes.Conv_U2); break;
1877 case Mode.U8_I4: ig.Emit (OpCodes.Conv_I4); break;
1878 case Mode.U8_U4: ig.Emit (OpCodes.Conv_U4); break;
1879 case Mode.U8_I8: /* nothing */ break;
1880 case Mode.U8_CH: ig.Emit (OpCodes.Conv_U2); break;
1882 case Mode.CH_I1: ig.Emit (OpCodes.Conv_I1); break;
1883 case Mode.CH_U1: ig.Emit (OpCodes.Conv_U1); break;
1884 case Mode.CH_I2: ig.Emit (OpCodes.Conv_I2); break;
1886 case Mode.R4_I1: ig.Emit (OpCodes.Conv_I1); break;
1887 case Mode.R4_U1: ig.Emit (OpCodes.Conv_U1); break;
1888 case Mode.R4_I2: ig.Emit (OpCodes.Conv_I2); break;
1889 case Mode.R4_U2: ig.Emit (OpCodes.Conv_U2); break;
1890 case Mode.R4_I4: ig.Emit (OpCodes.Conv_I4); break;
1891 case Mode.R4_U4: ig.Emit (OpCodes.Conv_U4); break;
1892 case Mode.R4_I8: ig.Emit (OpCodes.Conv_I8); break;
1893 case Mode.R4_U8: ig.Emit (OpCodes.Conv_U8); break;
1894 case Mode.R4_CH: ig.Emit (OpCodes.Conv_U2); break;
1896 case Mode.R8_I1: ig.Emit (OpCodes.Conv_I1); break;
1897 case Mode.R8_U1: ig.Emit (OpCodes.Conv_U1); break;
1898 case Mode.R8_I2: ig.Emit (OpCodes.Conv_I2); break;
1899 case Mode.R8_U2: ig.Emit (OpCodes.Conv_U2); break;
1900 case Mode.R8_I4: ig.Emit (OpCodes.Conv_I4); break;
1901 case Mode.R8_U4: ig.Emit (OpCodes.Conv_U4); break;
1902 case Mode.R8_I8: ig.Emit (OpCodes.Conv_I8); break;
1903 case Mode.R8_U8: ig.Emit (OpCodes.Conv_U8); break;
1904 case Mode.R8_CH: ig.Emit (OpCodes.Conv_U2); break;
1905 case Mode.R8_R4: ig.Emit (OpCodes.Conv_R4); break;
1911 public class OpcodeCast : EmptyCast {
1915 public OpcodeCast (Expression child, Type return_type, OpCode op)
1916 : base (child, return_type)
1920 second_valid = false;
1923 public OpcodeCast (Expression child, Type return_type, OpCode op, OpCode op2)
1924 : base (child, return_type)
1929 second_valid = true;
1932 public override Expression DoResolve (EmitContext ec)
1934 // This should never be invoked, we are born in fully
1935 // initialized state.
1940 public override void Emit (EmitContext ec)
1951 /// This kind of cast is used to encapsulate a child and cast it
1952 /// to the class requested
1954 public class ClassCast : EmptyCast {
1955 public ClassCast (Expression child, Type return_type)
1956 : base (child, return_type)
1961 public override Expression DoResolve (EmitContext ec)
1963 // This should never be invoked, we are born in fully
1964 // initialized state.
1969 public override void Emit (EmitContext ec)
1973 ec.ig.Emit (OpCodes.Castclass, type);
1979 /// SimpleName expressions are initially formed of a single
1980 /// word and it only happens at the beginning of the expression.
1984 /// The expression will try to be bound to a Field, a Method
1985 /// group or a Property. If those fail we pass the name to our
1986 /// caller and the SimpleName is compounded to perform a type
1987 /// lookup. The idea behind this process is that we want to avoid
1988 /// creating a namespace map from the assemblies, as that requires
1989 /// the GetExportedTypes function to be called and a hashtable to
1990 /// be constructed which reduces startup time. If later we find
1991 /// that this is slower, we should create a `NamespaceExpr' expression
1992 /// that fully participates in the resolution process.
1994 /// For example `System.Console.WriteLine' is decomposed into
1995 /// MemberAccess (MemberAccess (SimpleName ("System"), "Console"), "WriteLine")
1997 /// The first SimpleName wont produce a match on its own, so it will
1999 /// MemberAccess (SimpleName ("System.Console"), "WriteLine").
2001 /// System.Console will produce a TypeExpr match.
2003 /// The downside of this is that we might be hitting `LookupType' too many
2004 /// times with this scheme.
2006 public class SimpleName : Expression {
2010 // If true, then we are a simple name, not composed with a ".
2014 public SimpleName (string a, string b, Location l)
2016 Name = String.Concat (a, ".", b);
2021 public SimpleName (string name, Location l)
2028 public static void Error_ObjectRefRequired (EmitContext ec, Location l, string name)
2030 if (ec.IsFieldInitializer)
2033 "A field initializer cannot reference the non-static field, " +
2034 "method or property `"+name+"'");
2038 "An object reference is required " +
2039 "for the non-static field `"+name+"'");
2043 // Checks whether we are trying to access an instance
2044 // property, method or field from a static body.
2046 Expression MemberStaticCheck (EmitContext ec, Expression e)
2048 if (e is IMemberExpr){
2049 IMemberExpr member = (IMemberExpr) e;
2051 if (!member.IsStatic){
2052 Error_ObjectRefRequired (ec, loc, Name);
2060 public override Expression DoResolve (EmitContext ec)
2062 return SimpleNameResolve (ec, null, false, false);
2065 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
2067 return SimpleNameResolve (ec, right_side, false, false);
2071 public Expression DoResolveAllowStatic (EmitContext ec, bool intermediate)
2073 return SimpleNameResolve (ec, null, true, intermediate);
2076 public override Expression ResolveAsTypeStep (EmitContext ec)
2078 DeclSpace ds = ec.DeclSpace;
2079 NamespaceEntry ns = ds.NamespaceEntry;
2084 // Since we are cheating: we only do the Alias lookup for
2085 // namespaces if the name does not include any dots in it
2087 if (ns != null && is_base)
2088 alias_value = ns.LookupAlias (Name);
2092 if (ec.ResolvingTypeTree){
2093 int errors = Report.Errors;
2094 Type dt = ds.FindType (loc, Name);
2096 if (Report.Errors != errors)
2100 return new TypeExpression (dt, loc);
2102 if (alias_value != null){
2103 if (alias_value.IsType)
2104 return alias_value.ResolveAsType (ec);
2105 if ((t = RootContext.LookupType (ds, alias_value.Name, true, loc)) != null)
2106 return new TypeExpression (t, loc);
2110 if ((t = RootContext.LookupType (ds, Name, true, loc)) != null)
2111 return new TypeExpression (t, loc);
2113 if (alias_value != null) {
2114 if (alias_value.IsType)
2115 return alias_value.ResolveAsType (ec);
2116 if ((t = RootContext.LookupType (ds, alias_value.Name, true, loc)) != null)
2117 return new TypeExpression (t, loc);
2119 // we have alias value, but it isn't Type, so try if it's namespace
2120 return new SimpleName (alias_value.Name, loc);
2123 // No match, maybe our parent can compose us
2124 // into something meaningful.
2128 Expression SimpleNameResolve (EmitContext ec, Expression right_side,
2129 bool allow_static, bool intermediate)
2131 Expression e = DoSimpleNameResolve (ec, right_side, allow_static, intermediate);
2135 Block current_block = ec.CurrentBlock;
2136 if (current_block != null){
2137 //LocalInfo vi = current_block.GetLocalInfo (Name);
2139 current_block.IsVariableNameUsedInChildBlock(Name)) {
2140 Report.Error (135, Location,
2141 "'{0}' has a different meaning in a " +
2142 "child block", Name);
2151 /// 7.5.2: Simple Names.
2153 /// Local Variables and Parameters are handled at
2154 /// parse time, so they never occur as SimpleNames.
2156 /// The `allow_static' flag is used by MemberAccess only
2157 /// and it is used to inform us that it is ok for us to
2158 /// avoid the static check, because MemberAccess might end
2159 /// up resolving the Name as a Type name and the access as
2160 /// a static type access.
2162 /// ie: Type Type; .... { Type.GetType (""); }
2164 /// Type is both an instance variable and a Type; Type.GetType
2165 /// is the static method not an instance method of type.
2167 Expression DoSimpleNameResolve (EmitContext ec, Expression right_side, bool allow_static, bool intermediate)
2169 Expression e = null;
2172 // Stage 1: Performed by the parser (binding to locals or parameters).
2174 Block current_block = ec.CurrentBlock;
2175 if (current_block != null){
2176 LocalInfo vi = current_block.GetLocalInfo (Name);
2180 var = new LocalVariableReference (ec.CurrentBlock, Name, loc);
2182 if (right_side != null)
2183 return var.ResolveLValue (ec, right_side);
2185 return var.Resolve (ec);
2188 ParameterReference pref = current_block.GetParameterReference (Name, loc);
2190 if (right_side != null)
2191 return pref.ResolveLValue (ec, right_side);
2193 return pref.Resolve (ec);
2198 // Stage 2: Lookup members
2201 DeclSpace lookup_ds = ec.DeclSpace;
2203 if (lookup_ds.TypeBuilder == null)
2206 e = MemberLookup (ec, lookup_ds.TypeBuilder, Name, loc);
2210 lookup_ds =lookup_ds.Parent;
2211 } while (lookup_ds != null);
2213 if (e == null && ec.ContainerType != null)
2214 e = MemberLookup (ec, ec.ContainerType, Name, loc);
2218 // Since we are cheating (is_base is our hint
2219 // that we are the beginning of the name): we
2220 // only do the Alias lookup for namespaces if
2221 // the name does not include any dots in it
2223 NamespaceEntry ns = ec.DeclSpace.NamespaceEntry;
2224 if (is_base && ns != null){
2225 IAlias alias_value = ns.LookupAlias (Name);
2226 if (alias_value != null){
2227 if (alias_value.IsType)
2228 return alias_value.ResolveAsType (ec);
2230 Name = alias_value.Name;
2233 if ((t = TypeManager.LookupType (Name)) != null)
2234 return new TypeExpression (t, loc);
2236 // No match, maybe our parent can compose us
2237 // into something meaningful.
2242 return ResolveAsTypeStep (ec);
2248 if (e is IMemberExpr) {
2249 e = MemberAccess.ResolveMemberAccess (ec, e, null, loc, this);
2253 IMemberExpr me = e as IMemberExpr;
2257 // This fails if ResolveMemberAccess() was unable to decide whether
2258 // it's a field or a type of the same name.
2260 if (!me.IsStatic && (me.InstanceExpression == null))
2264 TypeManager.IsNestedFamilyAccessible (me.InstanceExpression.Type, me.DeclaringType) &&
2265 me.InstanceExpression.Type != me.DeclaringType &&
2266 !me.InstanceExpression.Type.IsSubclassOf (me.DeclaringType) &&
2267 (!intermediate || !MemberAccess.IdenticalNameAndTypeName (ec, this, e, loc))) {
2268 Error (38, "Cannot access nonstatic member `" + me.Name + "' of " +
2269 "outer type `" + me.DeclaringType + "' via nested type `" +
2270 me.InstanceExpression.Type + "'");
2274 return (right_side != null)
2275 ? e.DoResolveLValue (ec, right_side)
2279 if (ec.IsStatic || ec.IsFieldInitializer){
2283 return MemberStaticCheck (ec, e);
2288 public override void Emit (EmitContext ec)
2291 // If this is ever reached, then we failed to
2292 // find the name as a namespace
2295 Error (103, "The name `" + Name +
2296 "' does not exist in the class `" +
2297 ec.DeclSpace.Name + "'");
2300 public override string ToString ()
2307 /// Fully resolved expression that evaluates to a type
2309 public abstract class TypeExpr : Expression, IAlias {
2310 override public Expression ResolveAsTypeStep (EmitContext ec)
2312 TypeExpr t = DoResolveAsTypeStep (ec);
2316 eclass = ExprClass.Type;
2320 override public Expression DoResolve (EmitContext ec)
2322 return ResolveAsTypeTerminal (ec, false);
2325 override public void Emit (EmitContext ec)
2327 throw new Exception ("Should never be called");
2330 public virtual bool CheckAccessLevel (DeclSpace ds)
2332 return ds.CheckAccessLevel (Type);
2335 public virtual bool AsAccessible (DeclSpace ds, int flags)
2337 return ds.AsAccessible (Type, flags);
2340 public virtual bool IsClass {
2341 get { return Type.IsClass; }
2344 public virtual bool IsValueType {
2345 get { return Type.IsValueType; }
2348 public virtual bool IsInterface {
2349 get { return Type.IsInterface; }
2352 public virtual bool IsSealed {
2353 get { return Type.IsSealed; }
2356 public virtual bool CanInheritFrom ()
2358 if (Type == TypeManager.enum_type ||
2359 (Type == TypeManager.value_type && RootContext.StdLib) ||
2360 Type == TypeManager.multicast_delegate_type ||
2361 Type == TypeManager.delegate_type ||
2362 Type == TypeManager.array_type)
2368 public virtual bool IsAttribute {
2370 return Type == TypeManager.attribute_type ||
2371 Type.IsSubclassOf (TypeManager.attribute_type);
2375 public abstract TypeExpr DoResolveAsTypeStep (EmitContext ec);
2377 public virtual Type ResolveType (EmitContext ec)
2379 TypeExpr t = ResolveAsTypeTerminal (ec, false);
2386 public abstract string Name {
2390 public override bool Equals (object obj)
2392 TypeExpr tobj = obj as TypeExpr;
2396 return Type == tobj.Type;
2399 public override int GetHashCode ()
2401 return Type.GetHashCode ();
2404 public override string ToString ()
2409 bool IAlias.IsType {
2410 get { return true; }
2413 TypeExpr IAlias.ResolveAsType (EmitContext ec)
2415 return ResolveAsTypeTerminal (ec, false);
2419 public class TypeExpression : TypeExpr, IAlias {
2420 public TypeExpression (Type t, Location l)
2423 eclass = ExprClass.Type;
2427 public override TypeExpr DoResolveAsTypeStep (EmitContext ec)
2432 public override string Name {
2434 return Type.ToString ();
2438 string IAlias.Name {
2440 return Type.FullName;
2446 /// Used to create types from a fully qualified name. These are just used
2447 /// by the parser to setup the core types. A TypeLookupExpression is always
2448 /// classified as a type.
2450 public class TypeLookupExpression : TypeExpr {
2453 public TypeLookupExpression (string name)
2458 public override TypeExpr DoResolveAsTypeStep (EmitContext ec)
2461 type = RootContext.LookupType (
2462 ec.DeclSpace, name, false, Location.Null);
2470 public override string Name {
2477 public class TypeAliasExpression : TypeExpr, IAlias {
2481 public TypeAliasExpression (TypeExpr texpr, Location l)
2484 loc = texpr.Location;
2486 eclass = ExprClass.Type;
2490 public override string Name {
2491 get { return name; }
2494 public override TypeExpr DoResolveAsTypeStep (EmitContext ec)
2496 Type type = texpr.ResolveType (ec);
2500 return new TypeExpression (type, loc);
2503 public override bool CheckAccessLevel (DeclSpace ds)
2505 return texpr.CheckAccessLevel (ds);
2508 public override bool AsAccessible (DeclSpace ds, int flags)
2510 return texpr.AsAccessible (ds, flags);
2513 public override bool IsClass {
2514 get { return texpr.IsClass; }
2517 public override bool IsValueType {
2518 get { return texpr.IsValueType; }
2521 public override bool IsInterface {
2522 get { return texpr.IsInterface; }
2525 public override bool IsSealed {
2526 get { return texpr.IsSealed; }
2529 public override bool IsAttribute {
2530 get { return texpr.IsAttribute; }
2535 /// MethodGroup Expression.
2537 /// This is a fully resolved expression that evaluates to a type
2539 public class MethodGroupExpr : Expression, IMemberExpr {
2540 public MethodBase [] Methods;
2541 Expression instance_expression = null;
2542 bool is_explicit_impl = false;
2543 bool identical_type_name = false;
2546 public MethodGroupExpr (MemberInfo [] mi, Location l)
2548 Methods = new MethodBase [mi.Length];
2549 mi.CopyTo (Methods, 0);
2550 eclass = ExprClass.MethodGroup;
2551 type = TypeManager.object_type;
2555 public MethodGroupExpr (ArrayList list, Location l)
2557 Methods = new MethodBase [list.Count];
2560 list.CopyTo (Methods, 0);
2562 foreach (MemberInfo m in list){
2563 if (!(m is MethodBase)){
2564 Console.WriteLine ("Name " + m.Name);
2565 Console.WriteLine ("Found a: " + m.GetType ().FullName);
2572 eclass = ExprClass.MethodGroup;
2573 type = TypeManager.object_type;
2576 public Type DeclaringType {
2579 // The methods are arranged in this order:
2580 // derived type -> base type
2582 return Methods [0].DeclaringType;
2587 // `A method group may have associated an instance expression'
2589 public Expression InstanceExpression {
2591 return instance_expression;
2595 instance_expression = value;
2599 public bool IsExplicitImpl {
2601 return is_explicit_impl;
2605 is_explicit_impl = value;
2609 public bool IdenticalTypeName {
2611 return identical_type_name;
2615 identical_type_name = value;
2619 public bool IsBase {
2628 public string Name {
2630 return Methods [0].Name;
2634 public bool IsInstance {
2636 foreach (MethodBase mb in Methods)
2644 public bool IsStatic {
2646 foreach (MethodBase mb in Methods)
2654 override public Expression DoResolve (EmitContext ec)
2657 instance_expression = null;
2659 if (instance_expression != null) {
2660 instance_expression = instance_expression.DoResolve (ec);
2661 if (instance_expression == null)
2668 public void ReportUsageError ()
2670 Report.Error (654, loc, "Method `" + DeclaringType + "." +
2671 Name + "()' is referenced without parentheses");
2674 override public void Emit (EmitContext ec)
2676 ReportUsageError ();
2679 bool RemoveMethods (bool keep_static)
2681 ArrayList smethods = new ArrayList ();
2683 foreach (MethodBase mb in Methods){
2684 if (mb.IsStatic == keep_static)
2688 if (smethods.Count == 0)
2691 Methods = new MethodBase [smethods.Count];
2692 smethods.CopyTo (Methods, 0);
2698 /// Removes any instance methods from the MethodGroup, returns
2699 /// false if the resulting set is empty.
2701 public bool RemoveInstanceMethods ()
2703 return RemoveMethods (true);
2707 /// Removes any static methods from the MethodGroup, returns
2708 /// false if the resulting set is empty.
2710 public bool RemoveStaticMethods ()
2712 return RemoveMethods (false);
2717 /// Fully resolved expression that evaluates to a Field
2719 public class FieldExpr : Expression, IAssignMethod, IMemoryLocation, IMemberExpr, IVariable {
2720 public readonly FieldInfo FieldInfo;
2721 Expression instance_expr;
2722 VariableInfo variable_info;
2724 LocalTemporary temp;
2727 public FieldExpr (FieldInfo fi, Location l)
2730 eclass = ExprClass.Variable;
2731 type = fi.FieldType;
2735 public string Name {
2737 return FieldInfo.Name;
2741 public bool IsInstance {
2743 return !FieldInfo.IsStatic;
2747 public bool IsStatic {
2749 return FieldInfo.IsStatic;
2753 public Type DeclaringType {
2755 return FieldInfo.DeclaringType;
2759 public Expression InstanceExpression {
2761 return instance_expr;
2765 instance_expr = value;
2769 public VariableInfo VariableInfo {
2771 return variable_info;
2775 override public Expression DoResolve (EmitContext ec)
2777 if (!FieldInfo.IsStatic){
2778 if (instance_expr == null){
2780 // This can happen when referencing an instance field using
2781 // a fully qualified type expression: TypeName.InstanceField = xxx
2783 SimpleName.Error_ObjectRefRequired (ec, loc, FieldInfo.Name);
2787 // Resolve the field's instance expression while flow analysis is turned
2788 // off: when accessing a field "a.b", we must check whether the field
2789 // "a.b" is initialized, not whether the whole struct "a" is initialized.
2790 instance_expr = instance_expr.Resolve (ec, ResolveFlags.VariableOrValue |
2791 ResolveFlags.DisableFlowAnalysis);
2792 if (instance_expr == null)
2796 ObsoleteAttribute oa;
2797 FieldBase f = TypeManager.GetField (FieldInfo);
2799 oa = f.GetObsoleteAttribute (f.Parent);
2801 AttributeTester.Report_ObsoleteMessage (oa, f.GetSignatureForError (), loc);
2803 // To be sure that type is external because we do not register generated fields
2804 } else if (!(FieldInfo.DeclaringType is TypeBuilder)) {
2805 oa = AttributeTester.GetMemberObsoleteAttribute (FieldInfo);
2807 AttributeTester.Report_ObsoleteMessage (oa, TypeManager.GetFullNameSignature (FieldInfo), loc);
2810 if (ec.CurrentAnonymousMethod != null){
2811 if (!FieldInfo.IsStatic){
2812 if (ec.TypeContainer is Struct){
2813 Report.Error (1673, loc, "Can not reference instance variables in anonymous methods hosted in structs");
2816 ec.CaptureField (this);
2820 // If the instance expression is a local variable or parameter.
2821 IVariable var = instance_expr as IVariable;
2822 if ((var == null) || (var.VariableInfo == null))
2825 VariableInfo vi = var.VariableInfo;
2826 if (!vi.IsFieldAssigned (ec, FieldInfo.Name, loc))
2829 variable_info = vi.GetSubStruct (FieldInfo.Name);
2833 void Report_AssignToReadonly (bool is_instance)
2838 msg = "Readonly field can not be assigned outside " +
2839 "of constructor or variable initializer";
2841 msg = "A static readonly field can only be assigned in " +
2842 "a static constructor";
2844 Report.Error (is_instance ? 191 : 198, loc, msg);
2847 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
2849 IVariable var = instance_expr as IVariable;
2850 if ((var != null) && (var.VariableInfo != null))
2851 var.VariableInfo.SetFieldAssigned (ec, FieldInfo.Name);
2853 Expression e = DoResolve (ec);
2858 if (!FieldInfo.IsStatic && (instance_expr.Type.IsValueType && !(instance_expr is IMemoryLocation))) {
2859 // FIXME: Provide better error reporting.
2860 Error (1612, "Cannot modify expression because it is not a variable.");
2864 if (!FieldInfo.IsInitOnly)
2867 FieldBase fb = TypeManager.GetField (FieldInfo);
2872 // InitOnly fields can only be assigned in constructors
2875 if (ec.IsConstructor){
2876 if (IsStatic && !ec.IsStatic)
2877 Report_AssignToReadonly (false);
2879 if (ec.ContainerType == FieldInfo.DeclaringType)
2883 Report_AssignToReadonly (!IsStatic);
2888 public override void CheckMarshallByRefAccess (Type container)
2890 if (!IsStatic && Type.IsValueType && !container.IsSubclassOf (TypeManager.mbr_type) && DeclaringType.IsSubclassOf (TypeManager.mbr_type)) {
2891 Report.SymbolRelatedToPreviousError (DeclaringType);
2892 Report.Error (1690, loc, "Cannot call '{0}' method, property, or indexer because it is a value type member of a marshal-by-reference class", Name);
2896 public bool VerifyFixed (bool is_expression)
2898 IVariable variable = instance_expr as IVariable;
2899 if ((variable == null) || !variable.VerifyFixed (true))
2905 public void Emit (EmitContext ec, bool leave_copy)
2907 ILGenerator ig = ec.ig;
2908 bool is_volatile = false;
2910 if (FieldInfo is FieldBuilder){
2911 FieldBase f = TypeManager.GetField (FieldInfo);
2913 if ((f.ModFlags & Modifiers.VOLATILE) != 0)
2916 f.status |= Field.Status.USED;
2920 if (FieldInfo.IsStatic){
2922 ig.Emit (OpCodes.Volatile);
2924 ig.Emit (OpCodes.Ldsfld, FieldInfo);
2930 ig.Emit (OpCodes.Volatile);
2932 ig.Emit (OpCodes.Ldfld, FieldInfo);
2936 ec.ig.Emit (OpCodes.Dup);
2937 if (!FieldInfo.IsStatic) {
2938 temp = new LocalTemporary (ec, this.Type);
2944 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
2946 FieldAttributes fa = FieldInfo.Attributes;
2947 bool is_static = (fa & FieldAttributes.Static) != 0;
2948 bool is_readonly = (fa & FieldAttributes.InitOnly) != 0;
2949 ILGenerator ig = ec.ig;
2950 prepared = prepare_for_load;
2952 if (is_readonly && !ec.IsConstructor){
2953 Report_AssignToReadonly (!is_static);
2959 if (prepare_for_load)
2960 ig.Emit (OpCodes.Dup);
2965 ec.ig.Emit (OpCodes.Dup);
2966 if (!FieldInfo.IsStatic) {
2967 temp = new LocalTemporary (ec, this.Type);
2972 if (FieldInfo is FieldBuilder){
2973 FieldBase f = TypeManager.GetField (FieldInfo);
2975 if ((f.ModFlags & Modifiers.VOLATILE) != 0)
2976 ig.Emit (OpCodes.Volatile);
2978 f.status |= Field.Status.ASSIGNED;
2983 ig.Emit (OpCodes.Stsfld, FieldInfo);
2985 ig.Emit (OpCodes.Stfld, FieldInfo);
2991 void EmitInstance (EmitContext ec)
2993 if (instance_expr.Type.IsValueType) {
2994 if (instance_expr is IMemoryLocation) {
2995 ((IMemoryLocation) instance_expr).AddressOf (ec, AddressOp.LoadStore);
2997 LocalTemporary t = new LocalTemporary (ec, instance_expr.Type);
2998 instance_expr.Emit (ec);
3000 t.AddressOf (ec, AddressOp.Store);
3003 instance_expr.Emit (ec);
3006 public override void Emit (EmitContext ec)
3011 public void AddressOf (EmitContext ec, AddressOp mode)
3013 ILGenerator ig = ec.ig;
3015 if (FieldInfo is FieldBuilder){
3016 FieldBase f = TypeManager.GetField (FieldInfo);
3018 if ((f.ModFlags & Modifiers.VOLATILE) != 0){
3019 Error (676, "volatile variable: can not take its address, or pass as ref/out parameter");
3023 if ((mode & AddressOp.Store) != 0)
3024 f.status |= Field.Status.ASSIGNED;
3025 if ((mode & AddressOp.Load) != 0)
3026 f.status |= Field.Status.USED;
3031 // Handle initonly fields specially: make a copy and then
3032 // get the address of the copy.
3035 if (FieldInfo.IsInitOnly){
3037 if (ec.IsConstructor){
3038 if (FieldInfo.IsStatic){
3050 local = ig.DeclareLocal (type);
3051 ig.Emit (OpCodes.Stloc, local);
3052 ig.Emit (OpCodes.Ldloca, local);
3057 if (FieldInfo.IsStatic){
3058 ig.Emit (OpCodes.Ldsflda, FieldInfo);
3061 ig.Emit (OpCodes.Ldflda, FieldInfo);
3067 // A FieldExpr whose address can not be taken
3069 public class FieldExprNoAddress : FieldExpr, IMemoryLocation {
3070 public FieldExprNoAddress (FieldInfo fi, Location loc) : base (fi, loc)
3074 public new void AddressOf (EmitContext ec, AddressOp mode)
3076 Report.Error (-215, "Report this: Taking the address of a remapped parameter not supported");
3081 /// Expression that evaluates to a Property. The Assign class
3082 /// might set the `Value' expression if we are in an assignment.
3084 /// This is not an LValue because we need to re-write the expression, we
3085 /// can not take data from the stack and store it.
3087 public class PropertyExpr : ExpressionStatement, IAssignMethod, IMemberExpr {
3088 public readonly PropertyInfo PropertyInfo;
3091 // This is set externally by the `BaseAccess' class
3094 MethodInfo getter, setter;
3097 Expression instance_expr;
3098 LocalTemporary temp;
3101 public PropertyExpr (EmitContext ec, PropertyInfo pi, Location l)
3104 eclass = ExprClass.PropertyAccess;
3108 type = TypeManager.TypeToCoreType (pi.PropertyType);
3110 ResolveAccessors (ec);
3113 public string Name {
3115 return PropertyInfo.Name;
3119 public bool IsInstance {
3125 public bool IsStatic {
3131 public Type DeclaringType {
3133 return PropertyInfo.DeclaringType;
3138 // The instance expression associated with this expression
3140 public Expression InstanceExpression {
3142 instance_expr = value;
3146 return instance_expr;
3150 public bool VerifyAssignable ()
3152 if (setter == null) {
3153 Report.Error (200, loc,
3154 "The property `" + PropertyInfo.Name +
3155 "' can not be assigned to, as it has not set accessor");
3162 void FindAccessors (Type invocation_type)
3164 BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic |
3165 BindingFlags.Static | BindingFlags.Instance |
3166 BindingFlags.DeclaredOnly;
3168 Type current = PropertyInfo.DeclaringType;
3169 for (; current != null; current = current.BaseType) {
3170 MemberInfo[] group = TypeManager.MemberLookup (
3171 invocation_type, invocation_type, current,
3172 MemberTypes.Property, flags, PropertyInfo.Name, null);
3177 if (group.Length != 1)
3178 // Oooops, can this ever happen ?
3181 PropertyInfo pi = (PropertyInfo) group [0];
3184 getter = pi.GetGetMethod (true);;
3187 setter = pi.GetSetMethod (true);;
3189 MethodInfo accessor = getter != null ? getter : setter;
3191 if (!accessor.IsVirtual)
3197 // We also perform the permission checking here, as the PropertyInfo does not
3198 // hold the information for the accessibility of its setter/getter
3200 void ResolveAccessors (EmitContext ec)
3202 FindAccessors (ec.ContainerType);
3204 is_static = getter != null ? getter.IsStatic : setter.IsStatic;
3207 bool InstanceResolve (EmitContext ec, bool must_do_cs1540_check)
3209 if ((instance_expr == null) && ec.IsStatic && !is_static) {
3210 SimpleName.Error_ObjectRefRequired (ec, loc, PropertyInfo.Name);
3214 if (instance_expr != null) {
3215 instance_expr = instance_expr.DoResolve (ec);
3216 if (instance_expr == null)
3219 instance_expr.CheckMarshallByRefAccess (ec.ContainerType);
3222 if (must_do_cs1540_check && (instance_expr != null)) {
3223 if ((instance_expr.Type != ec.ContainerType) &&
3224 ec.ContainerType.IsSubclassOf (instance_expr.Type)) {
3225 Report.Error (1540, loc, "Cannot access protected member `" +
3226 PropertyInfo.DeclaringType + "." + PropertyInfo.Name +
3227 "' via a qualifier of type `" +
3228 TypeManager.CSharpName (instance_expr.Type) +
3229 "'; the qualifier must be of type `" +
3230 TypeManager.CSharpName (ec.ContainerType) +
3231 "' (or derived from it)");
3239 override public Expression DoResolve (EmitContext ec)
3241 if (getter != null){
3242 if (TypeManager.GetArgumentTypes (getter).Length != 0){
3244 117, loc, "`{0}' does not contain a " +
3245 "definition for `{1}'.", getter.DeclaringType,
3251 if (getter == null){
3253 // The following condition happens if the PropertyExpr was
3254 // created, but is invalid (ie, the property is inaccessible),
3255 // and we did not want to embed the knowledge about this in
3256 // the caller routine. This only avoids double error reporting.
3261 Report.Error (154, loc,
3262 "The property `" + PropertyInfo.Name +
3263 "' can not be used in " +
3264 "this context because it lacks a get accessor");
3268 bool must_do_cs1540_check;
3269 if (!IsAccessorAccessible (ec.ContainerType, getter, out must_do_cs1540_check)) {
3270 Report.Error (122, loc, "'{0}.get' is inaccessible due to its protection level", PropertyInfo.Name);
3274 if (!InstanceResolve (ec, must_do_cs1540_check))
3278 // Only base will allow this invocation to happen.
3280 if (IsBase && getter.IsAbstract){
3281 Report.Error (205, loc, "Cannot call an abstract base property: " +
3282 PropertyInfo.DeclaringType + "." +PropertyInfo.Name);
3289 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
3291 if (setter == null){
3293 // The following condition happens if the PropertyExpr was
3294 // created, but is invalid (ie, the property is inaccessible),
3295 // and we did not want to embed the knowledge about this in
3296 // the caller routine. This only avoids double error reporting.
3301 Report.Error (154, loc,
3302 "The property `" + PropertyInfo.Name +
3303 "' can not be used in " +
3304 "this context because it lacks a set accessor");
3308 if (TypeManager.GetArgumentTypes (setter).Length != 1){
3310 117, loc, "`{0}' does not contain a " +
3311 "definition for `{1}'.", getter.DeclaringType,
3316 bool must_do_cs1540_check;
3317 if (!IsAccessorAccessible (ec.ContainerType, setter, out must_do_cs1540_check)) {
3318 Report.Error (122, loc, "'{0}.set' is inaccessible due to its protection level", PropertyInfo.Name);
3322 if (!InstanceResolve (ec, must_do_cs1540_check))
3326 // Only base will allow this invocation to happen.
3328 if (IsBase && setter.IsAbstract){
3329 Report.Error (205, loc, "Cannot call an abstract base property: " +
3330 PropertyInfo.DeclaringType + "." +PropertyInfo.Name);
3335 // Check that we are not making changes to a temporary memory location
3337 if (instance_expr != null && instance_expr.Type.IsValueType && !(instance_expr is IMemoryLocation)) {
3338 // FIXME: Provide better error reporting.
3339 Error (1612, "Cannot modify expression because it is not a variable.");
3348 public override void Emit (EmitContext ec)
3353 void EmitInstance (EmitContext ec)
3358 if (instance_expr.Type.IsValueType) {
3359 if (instance_expr is IMemoryLocation) {
3360 ((IMemoryLocation) instance_expr).AddressOf (ec, AddressOp.LoadStore);
3362 LocalTemporary t = new LocalTemporary (ec, instance_expr.Type);
3363 instance_expr.Emit (ec);
3365 t.AddressOf (ec, AddressOp.Store);
3368 instance_expr.Emit (ec);
3371 ec.ig.Emit (OpCodes.Dup);
3375 public void Emit (EmitContext ec, bool leave_copy)
3381 // Special case: length of single dimension array property is turned into ldlen
3383 if ((getter == TypeManager.system_int_array_get_length) ||
3384 (getter == TypeManager.int_array_get_length)){
3385 Type iet = instance_expr.Type;
3388 // System.Array.Length can be called, but the Type does not
3389 // support invoking GetArrayRank, so test for that case first
3391 if (iet != TypeManager.array_type && (iet.GetArrayRank () == 1)) {
3392 ec.ig.Emit (OpCodes.Ldlen);
3393 ec.ig.Emit (OpCodes.Conv_I4);
3398 Invocation.EmitCall (ec, IsBase, IsStatic, new EmptyAddressOf (), getter, null, loc);
3403 ec.ig.Emit (OpCodes.Dup);
3405 temp = new LocalTemporary (ec, this.Type);
3411 // Implements the IAssignMethod interface for assignments
3413 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
3415 prepared = prepare_for_load;
3421 ec.ig.Emit (OpCodes.Dup);
3423 temp = new LocalTemporary (ec, this.Type);
3428 ArrayList args = new ArrayList (1);
3429 args.Add (new Argument (new EmptyAddressOf (), Argument.AType.Expression));
3431 Invocation.EmitCall (ec, IsBase, IsStatic, new EmptyAddressOf (), setter, args, loc);
3437 override public void EmitStatement (EmitContext ec)
3440 ec.ig.Emit (OpCodes.Pop);
3445 /// Fully resolved expression that evaluates to an Event
3447 public class EventExpr : Expression, IMemberExpr {
3448 public readonly EventInfo EventInfo;
3449 Expression instance_expr;
3452 MethodInfo add_accessor, remove_accessor;
3454 public EventExpr (EventInfo ei, Location loc)
3458 eclass = ExprClass.EventAccess;
3460 add_accessor = TypeManager.GetAddMethod (ei);
3461 remove_accessor = TypeManager.GetRemoveMethod (ei);
3463 if (add_accessor.IsStatic || remove_accessor.IsStatic)
3466 if (EventInfo is MyEventBuilder){
3467 MyEventBuilder eb = (MyEventBuilder) EventInfo;
3468 type = eb.EventType;
3471 type = EventInfo.EventHandlerType;
3474 public string Name {
3476 return EventInfo.Name;
3480 public bool IsInstance {
3486 public bool IsStatic {
3492 public Type DeclaringType {
3494 return EventInfo.DeclaringType;
3498 public Expression InstanceExpression {
3500 return instance_expr;
3504 instance_expr = value;
3508 bool InstanceResolve (EmitContext ec, bool must_do_cs1540_check)
3510 if ((instance_expr == null) && ec.IsStatic && !is_static) {
3511 SimpleName.Error_ObjectRefRequired (ec, loc, EventInfo.Name);
3515 if (instance_expr != null) {
3516 instance_expr = instance_expr.DoResolve (ec);
3517 if (instance_expr == null)
3522 // This is using the same mechanism as the CS1540 check in PropertyExpr.
3523 // However, in the Event case, we reported a CS0122 instead.
3525 if (must_do_cs1540_check && (instance_expr != null)) {
3526 if ((instance_expr.Type != ec.ContainerType) &&
3527 ec.ContainerType.IsSubclassOf (instance_expr.Type)) {
3528 Report.Error (122, loc, "'{0}' is inaccessible due to its protection level",
3529 DeclaringType.Name + "." + EventInfo.Name);
3538 public override Expression DoResolve (EmitContext ec)
3540 if (instance_expr != null) {
3541 instance_expr = instance_expr.DoResolve (ec);
3542 if (instance_expr == null)
3546 bool must_do_cs1540_check;
3547 if (!(IsAccessorAccessible (ec.ContainerType, add_accessor, out must_do_cs1540_check)
3548 && IsAccessorAccessible (ec.ContainerType, remove_accessor, out must_do_cs1540_check))) {
3550 Report.Error (122, loc, "'{0}' is inaccessible due to its protection level",
3551 DeclaringType.Name + "." + EventInfo.Name);
3555 if (!InstanceResolve (ec, must_do_cs1540_check))
3561 public override void Emit (EmitContext ec)
3563 if (instance_expr is This)
3564 Report.Error (79, loc, "The event `{0}' can only appear on the left hand side of += or -=, try calling the actual delegate", Name);
3566 Report.Error (70, loc, "The event `{0}' can only appear on the left hand side of += or -= "+
3567 "(except on the defining type)", Name);
3570 public void EmitAddOrRemove (EmitContext ec, Expression source)
3572 BinaryDelegate source_del = (BinaryDelegate) source;
3573 Expression handler = source_del.Right;
3575 Argument arg = new Argument (handler, Argument.AType.Expression);
3576 ArrayList args = new ArrayList ();
3580 if (source_del.IsAddition)
3581 Invocation.EmitCall (
3582 ec, false, IsStatic, instance_expr, add_accessor, args, loc);
3584 Invocation.EmitCall (
3585 ec, false, IsStatic, instance_expr, remove_accessor, args, loc);