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 parent 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 (qualifier_type != null)
770 Report.Error (122, loc, "'{0}' is inaccessible due to its protection level", TypeManager.CSharpName (qualifier_type) + "." + name);
771 else if (name == ".ctor") {
772 Report.Error (143, loc, String.Format ("The type {0} has no constructors defined",
773 TypeManager.CSharpName (queried_type)));
775 Report.Error (122, loc, "'{0}' is inaccessible due to its protection level", name);
779 static public MemberInfo GetFieldFromEvent (EventExpr event_expr)
781 EventInfo ei = event_expr.EventInfo;
783 return TypeManager.GetPrivateFieldOfEvent (ei);
787 /// Returns an expression that can be used to invoke operator true
788 /// on the expression if it exists.
790 static public StaticCallExpr GetOperatorTrue (EmitContext ec, Expression e, Location loc)
792 return GetOperatorTrueOrFalse (ec, e, true, loc);
796 /// Returns an expression that can be used to invoke operator false
797 /// on the expression if it exists.
799 static public StaticCallExpr GetOperatorFalse (EmitContext ec, Expression e, Location loc)
801 return GetOperatorTrueOrFalse (ec, e, false, loc);
804 static StaticCallExpr GetOperatorTrueOrFalse (EmitContext ec, Expression e, bool is_true, Location loc)
807 Expression operator_group;
809 operator_group = MethodLookup (ec, e.Type, is_true ? "op_True" : "op_False", loc);
810 if (operator_group == null)
813 ArrayList arguments = new ArrayList ();
814 arguments.Add (new Argument (e, Argument.AType.Expression));
815 method = Invocation.OverloadResolve (
816 ec, (MethodGroupExpr) operator_group, arguments, false, loc);
821 return new StaticCallExpr ((MethodInfo) method, arguments, loc);
825 /// Resolves the expression `e' into a boolean expression: either through
826 /// an implicit conversion, or through an `operator true' invocation
828 public static Expression ResolveBoolean (EmitContext ec, Expression e, Location loc)
834 if (e.Type == TypeManager.bool_type)
837 Expression converted = Convert.ImplicitConversion (ec, e, TypeManager.bool_type, new Location (-1));
839 if (converted != null)
843 // If no implicit conversion to bool exists, try using `operator true'
845 Expression operator_true = Expression.GetOperatorTrue (ec, e, loc);
846 if (operator_true == null){
847 Report.Error (31, loc, "Can not convert the expression to a boolean");
850 return operator_true;
853 static string ExprClassName (ExprClass c)
856 case ExprClass.Invalid:
858 case ExprClass.Value:
860 case ExprClass.Variable:
862 case ExprClass.Namespace:
866 case ExprClass.MethodGroup:
867 return "method group";
868 case ExprClass.PropertyAccess:
869 return "property access";
870 case ExprClass.EventAccess:
871 return "event access";
872 case ExprClass.IndexerAccess:
873 return "indexer access";
874 case ExprClass.Nothing:
877 throw new Exception ("Should not happen");
881 /// Reports that we were expecting `expr' to be of class `expected'
883 public void Error_UnexpectedKind (string expected, Location loc)
885 string kind = "Unknown";
887 kind = ExprClassName (eclass);
889 Report.Error (118, loc, "Expression denotes a `" + kind +
890 "' where a `" + expected + "' was expected");
893 public void Error_UnexpectedKind (ResolveFlags flags, Location loc)
895 ArrayList valid = new ArrayList (10);
897 if ((flags & ResolveFlags.VariableOrValue) != 0) {
898 valid.Add ("variable");
902 if ((flags & ResolveFlags.Type) != 0)
905 if ((flags & ResolveFlags.MethodGroup) != 0)
906 valid.Add ("method group");
908 if ((flags & ResolveFlags.SimpleName) != 0)
909 valid.Add ("simple name");
911 if (valid.Count == 0)
912 valid.Add ("unknown");
914 StringBuilder sb = new StringBuilder ();
915 for (int i = 0; i < valid.Count; i++) {
918 else if (i == valid.Count)
920 sb.Append (valid [i]);
923 string kind = ExprClassName (eclass);
925 Error (119, "Expression denotes a `" + kind + "' where " +
926 "a `" + sb.ToString () + "' was expected");
929 static public void Error_ConstantValueCannotBeConverted (Location l, string val, Type t)
931 Report.Error (31, l, "Constant value `" + val + "' cannot be converted to " +
932 TypeManager.CSharpName (t));
935 public static void UnsafeError (Location loc)
937 Report.Error (214, loc, "Pointers may only be used in an unsafe context");
941 /// Converts the IntConstant, UIntConstant, LongConstant or
942 /// ULongConstant into the integral target_type. Notice
943 /// that we do not return an `Expression' we do return
944 /// a boxed integral type.
946 /// FIXME: Since I added the new constants, we need to
947 /// also support conversions from CharConstant, ByteConstant,
948 /// SByteConstant, UShortConstant, ShortConstant
950 /// This is used by the switch statement, so the domain
951 /// of work is restricted to the literals above, and the
952 /// targets are int32, uint32, char, byte, sbyte, ushort,
953 /// short, uint64 and int64
955 public static object ConvertIntLiteral (Constant c, Type target_type, Location loc)
957 if (!Convert.ImplicitStandardConversionExists (Convert.ConstantEC, c, target_type)){
958 Convert.Error_CannotImplicitConversion (loc, c.Type, target_type);
964 if (c.Type == target_type)
965 return ((Constant) c).GetValue ();
968 // Make into one of the literals we handle, we dont really care
969 // about this value as we will just return a few limited types
971 if (c is EnumConstant)
972 c = ((EnumConstant)c).WidenToCompilerConstant ();
974 if (c is IntConstant){
975 int v = ((IntConstant) c).Value;
977 if (target_type == TypeManager.uint32_type){
980 } else if (target_type == TypeManager.char_type){
981 if (v >= Char.MinValue && v <= Char.MaxValue)
983 } else if (target_type == TypeManager.byte_type){
984 if (v >= Byte.MinValue && v <= Byte.MaxValue)
986 } else if (target_type == TypeManager.sbyte_type){
987 if (v >= SByte.MinValue && v <= SByte.MaxValue)
989 } else if (target_type == TypeManager.short_type){
990 if (v >= Int16.MinValue && v <= UInt16.MaxValue)
992 } else if (target_type == TypeManager.ushort_type){
993 if (v >= UInt16.MinValue && v <= UInt16.MaxValue)
995 } else if (target_type == TypeManager.int64_type)
997 else if (target_type == TypeManager.uint64_type){
1003 } else if (c is UIntConstant){
1004 uint v = ((UIntConstant) c).Value;
1006 if (target_type == TypeManager.int32_type){
1007 if (v <= Int32.MaxValue)
1009 } else if (target_type == TypeManager.char_type){
1010 if (v >= Char.MinValue && v <= Char.MaxValue)
1012 } else if (target_type == TypeManager.byte_type){
1013 if (v <= Byte.MaxValue)
1015 } else if (target_type == TypeManager.sbyte_type){
1016 if (v <= SByte.MaxValue)
1018 } else if (target_type == TypeManager.short_type){
1019 if (v <= UInt16.MaxValue)
1021 } else if (target_type == TypeManager.ushort_type){
1022 if (v <= UInt16.MaxValue)
1024 } else if (target_type == TypeManager.int64_type)
1026 else if (target_type == TypeManager.uint64_type)
1029 } else if (c is LongConstant){
1030 long v = ((LongConstant) c).Value;
1032 if (target_type == TypeManager.int32_type){
1033 if (v >= UInt32.MinValue && v <= UInt32.MaxValue)
1035 } else if (target_type == TypeManager.uint32_type){
1036 if (v >= 0 && v <= UInt32.MaxValue)
1038 } else if (target_type == TypeManager.char_type){
1039 if (v >= Char.MinValue && v <= Char.MaxValue)
1041 } else if (target_type == TypeManager.byte_type){
1042 if (v >= Byte.MinValue && v <= Byte.MaxValue)
1044 } else if (target_type == TypeManager.sbyte_type){
1045 if (v >= SByte.MinValue && v <= SByte.MaxValue)
1047 } else if (target_type == TypeManager.short_type){
1048 if (v >= Int16.MinValue && v <= UInt16.MaxValue)
1050 } else if (target_type == TypeManager.ushort_type){
1051 if (v >= UInt16.MinValue && v <= UInt16.MaxValue)
1053 } else if (target_type == TypeManager.uint64_type){
1058 } else if (c is ULongConstant){
1059 ulong v = ((ULongConstant) c).Value;
1061 if (target_type == TypeManager.int32_type){
1062 if (v <= Int32.MaxValue)
1064 } else if (target_type == TypeManager.uint32_type){
1065 if (v <= UInt32.MaxValue)
1067 } else if (target_type == TypeManager.char_type){
1068 if (v >= Char.MinValue && v <= Char.MaxValue)
1070 } else if (target_type == TypeManager.byte_type){
1071 if (v >= Byte.MinValue && v <= Byte.MaxValue)
1073 } else if (target_type == TypeManager.sbyte_type){
1074 if (v <= (int) SByte.MaxValue)
1076 } else if (target_type == TypeManager.short_type){
1077 if (v <= UInt16.MaxValue)
1079 } else if (target_type == TypeManager.ushort_type){
1080 if (v <= UInt16.MaxValue)
1082 } else if (target_type == TypeManager.int64_type){
1083 if (v <= Int64.MaxValue)
1087 } else if (c is ByteConstant){
1088 byte v = ((ByteConstant) c).Value;
1090 if (target_type == TypeManager.int32_type)
1092 else if (target_type == TypeManager.uint32_type)
1094 else if (target_type == TypeManager.char_type)
1096 else if (target_type == TypeManager.sbyte_type){
1097 if (v <= SByte.MaxValue)
1099 } else if (target_type == TypeManager.short_type)
1101 else if (target_type == TypeManager.ushort_type)
1103 else if (target_type == TypeManager.int64_type)
1105 else if (target_type == TypeManager.uint64_type)
1108 } else if (c is SByteConstant){
1109 sbyte v = ((SByteConstant) c).Value;
1111 if (target_type == TypeManager.int32_type)
1113 else if (target_type == TypeManager.uint32_type){
1116 } else if (target_type == TypeManager.char_type){
1119 } else if (target_type == TypeManager.byte_type){
1122 } else if (target_type == TypeManager.short_type)
1124 else if (target_type == TypeManager.ushort_type){
1127 } else if (target_type == TypeManager.int64_type)
1129 else if (target_type == TypeManager.uint64_type){
1134 } else if (c is ShortConstant){
1135 short v = ((ShortConstant) c).Value;
1137 if (target_type == TypeManager.int32_type){
1139 } else if (target_type == TypeManager.uint32_type){
1142 } else if (target_type == TypeManager.char_type){
1145 } else if (target_type == TypeManager.byte_type){
1146 if (v >= Byte.MinValue && v <= Byte.MaxValue)
1148 } else if (target_type == TypeManager.sbyte_type){
1149 if (v >= SByte.MinValue && v <= SByte.MaxValue)
1151 } else if (target_type == TypeManager.ushort_type){
1154 } else if (target_type == TypeManager.int64_type)
1156 else if (target_type == TypeManager.uint64_type)
1160 } else if (c is UShortConstant){
1161 ushort v = ((UShortConstant) c).Value;
1163 if (target_type == TypeManager.int32_type)
1165 else if (target_type == TypeManager.uint32_type)
1167 else if (target_type == TypeManager.char_type){
1168 if (v >= Char.MinValue && v <= Char.MaxValue)
1170 } else if (target_type == TypeManager.byte_type){
1171 if (v >= Byte.MinValue && v <= Byte.MaxValue)
1173 } else if (target_type == TypeManager.sbyte_type){
1174 if (v <= SByte.MaxValue)
1176 } else if (target_type == TypeManager.short_type){
1177 if (v <= Int16.MaxValue)
1179 } else if (target_type == TypeManager.int64_type)
1181 else if (target_type == TypeManager.uint64_type)
1185 } else if (c is CharConstant){
1186 char v = ((CharConstant) c).Value;
1188 if (target_type == TypeManager.int32_type)
1190 else if (target_type == TypeManager.uint32_type)
1192 else if (target_type == TypeManager.byte_type){
1193 if (v >= Byte.MinValue && v <= Byte.MaxValue)
1195 } else if (target_type == TypeManager.sbyte_type){
1196 if (v <= SByte.MaxValue)
1198 } else if (target_type == TypeManager.short_type){
1199 if (v <= Int16.MaxValue)
1201 } else if (target_type == TypeManager.ushort_type)
1203 else if (target_type == TypeManager.int64_type)
1205 else if (target_type == TypeManager.uint64_type)
1210 Error_ConstantValueCannotBeConverted (loc, s, target_type);
1215 // Load the object from the pointer.
1217 public static void LoadFromPtr (ILGenerator ig, Type t)
1219 if (t == TypeManager.int32_type)
1220 ig.Emit (OpCodes.Ldind_I4);
1221 else if (t == TypeManager.uint32_type)
1222 ig.Emit (OpCodes.Ldind_U4);
1223 else if (t == TypeManager.short_type)
1224 ig.Emit (OpCodes.Ldind_I2);
1225 else if (t == TypeManager.ushort_type)
1226 ig.Emit (OpCodes.Ldind_U2);
1227 else if (t == TypeManager.char_type)
1228 ig.Emit (OpCodes.Ldind_U2);
1229 else if (t == TypeManager.byte_type)
1230 ig.Emit (OpCodes.Ldind_U1);
1231 else if (t == TypeManager.sbyte_type)
1232 ig.Emit (OpCodes.Ldind_I1);
1233 else if (t == TypeManager.uint64_type)
1234 ig.Emit (OpCodes.Ldind_I8);
1235 else if (t == TypeManager.int64_type)
1236 ig.Emit (OpCodes.Ldind_I8);
1237 else if (t == TypeManager.float_type)
1238 ig.Emit (OpCodes.Ldind_R4);
1239 else if (t == TypeManager.double_type)
1240 ig.Emit (OpCodes.Ldind_R8);
1241 else if (t == TypeManager.bool_type)
1242 ig.Emit (OpCodes.Ldind_I1);
1243 else if (t == TypeManager.intptr_type)
1244 ig.Emit (OpCodes.Ldind_I);
1245 else if (TypeManager.IsEnumType (t)) {
1246 if (t == TypeManager.enum_type)
1247 ig.Emit (OpCodes.Ldind_Ref);
1249 LoadFromPtr (ig, TypeManager.EnumToUnderlying (t));
1250 } else if (t.IsValueType)
1251 ig.Emit (OpCodes.Ldobj, t);
1252 else if (t.IsPointer)
1253 ig.Emit (OpCodes.Ldind_I);
1255 ig.Emit (OpCodes.Ldind_Ref);
1259 // The stack contains the pointer and the value of type `type'
1261 public static void StoreFromPtr (ILGenerator ig, Type type)
1263 if (TypeManager.IsEnumType (type))
1264 type = TypeManager.EnumToUnderlying (type);
1265 if (type == TypeManager.int32_type || type == TypeManager.uint32_type)
1266 ig.Emit (OpCodes.Stind_I4);
1267 else if (type == TypeManager.int64_type || type == TypeManager.uint64_type)
1268 ig.Emit (OpCodes.Stind_I8);
1269 else if (type == TypeManager.char_type || type == TypeManager.short_type ||
1270 type == TypeManager.ushort_type)
1271 ig.Emit (OpCodes.Stind_I2);
1272 else if (type == TypeManager.float_type)
1273 ig.Emit (OpCodes.Stind_R4);
1274 else if (type == TypeManager.double_type)
1275 ig.Emit (OpCodes.Stind_R8);
1276 else if (type == TypeManager.byte_type || type == TypeManager.sbyte_type ||
1277 type == TypeManager.bool_type)
1278 ig.Emit (OpCodes.Stind_I1);
1279 else if (type == TypeManager.intptr_type)
1280 ig.Emit (OpCodes.Stind_I);
1281 else if (type.IsValueType)
1282 ig.Emit (OpCodes.Stobj, type);
1284 ig.Emit (OpCodes.Stind_Ref);
1288 // Returns the size of type `t' if known, otherwise, 0
1290 public static int GetTypeSize (Type t)
1292 t = TypeManager.TypeToCoreType (t);
1293 if (t == TypeManager.int32_type ||
1294 t == TypeManager.uint32_type ||
1295 t == TypeManager.float_type)
1297 else if (t == TypeManager.int64_type ||
1298 t == TypeManager.uint64_type ||
1299 t == TypeManager.double_type)
1301 else if (t == TypeManager.byte_type ||
1302 t == TypeManager.sbyte_type ||
1303 t == TypeManager.bool_type)
1305 else if (t == TypeManager.short_type ||
1306 t == TypeManager.char_type ||
1307 t == TypeManager.ushort_type)
1309 else if (t == TypeManager.decimal_type)
1315 public static void Error_NegativeArrayIndex (Location loc)
1317 Report.Error (248, loc, "Cannot create an array with a negative size");
1321 // Converts `source' to an int, uint, long or ulong.
1323 public Expression ExpressionToArrayArgument (EmitContext ec, Expression source, Location loc)
1327 bool old_checked = ec.CheckState;
1328 ec.CheckState = true;
1330 target = Convert.ImplicitConversion (ec, source, TypeManager.int32_type, loc);
1331 if (target == null){
1332 target = Convert.ImplicitConversion (ec, source, TypeManager.uint32_type, loc);
1333 if (target == null){
1334 target = Convert.ImplicitConversion (ec, source, TypeManager.int64_type, loc);
1335 if (target == null){
1336 target = Convert.ImplicitConversion (ec, source, TypeManager.uint64_type, loc);
1338 Convert.Error_CannotImplicitConversion (loc, source.Type, TypeManager.int32_type);
1342 ec.CheckState = old_checked;
1345 // Only positive constants are allowed at compile time
1347 if (target is Constant){
1348 if (target is IntConstant){
1349 if (((IntConstant) target).Value < 0){
1350 Error_NegativeArrayIndex (loc);
1355 if (target is LongConstant){
1356 if (((LongConstant) target).Value < 0){
1357 Error_NegativeArrayIndex (loc);
1370 /// This is just a base class for expressions that can
1371 /// appear on statements (invocations, object creation,
1372 /// assignments, post/pre increment and decrement). The idea
1373 /// being that they would support an extra Emition interface that
1374 /// does not leave a result on the stack.
1376 public abstract class ExpressionStatement : Expression {
1378 public virtual ExpressionStatement ResolveStatement (EmitContext ec)
1380 Expression e = Resolve (ec);
1384 ExpressionStatement es = e as ExpressionStatement;
1386 Error (201, "Only assignment, call, increment, decrement and new object " +
1387 "expressions can be used as a statement");
1393 /// Requests the expression to be emitted in a `statement'
1394 /// context. This means that no new value is left on the
1395 /// stack after invoking this method (constrasted with
1396 /// Emit that will always leave a value on the stack).
1398 public abstract void EmitStatement (EmitContext ec);
1402 /// This kind of cast is used to encapsulate the child
1403 /// whose type is child.Type into an expression that is
1404 /// reported to return "return_type". This is used to encapsulate
1405 /// expressions which have compatible types, but need to be dealt
1406 /// at higher levels with.
1408 /// For example, a "byte" expression could be encapsulated in one
1409 /// of these as an "unsigned int". The type for the expression
1410 /// would be "unsigned int".
1413 public class EmptyCast : Expression {
1414 protected Expression child;
1416 public Expression Child {
1422 public EmptyCast (Expression child, Type return_type)
1424 eclass = child.eclass;
1429 public override Expression DoResolve (EmitContext ec)
1431 // This should never be invoked, we are born in fully
1432 // initialized state.
1437 public override void Emit (EmitContext ec)
1444 // We need to special case this since an empty cast of
1445 // a NullLiteral is still a Constant
1447 public class NullCast : Constant {
1448 protected Expression child;
1450 public NullCast (Expression child, Type return_type)
1452 eclass = child.eclass;
1457 override public string AsString ()
1462 public override object GetValue ()
1467 public override Expression DoResolve (EmitContext ec)
1469 // This should never be invoked, we are born in fully
1470 // initialized state.
1475 public override void Emit (EmitContext ec)
1480 public override bool IsNegative {
1489 /// This class is used to wrap literals which belong inside Enums
1491 public class EnumConstant : Constant {
1492 public Constant Child;
1494 public EnumConstant (Constant child, Type enum_type)
1496 eclass = child.eclass;
1501 public override Expression DoResolve (EmitContext ec)
1503 // This should never be invoked, we are born in fully
1504 // initialized state.
1509 public override void Emit (EmitContext ec)
1514 public override object GetValue ()
1516 return Child.GetValue ();
1519 public object GetValueAsEnumType ()
1521 return System.Enum.ToObject (type, Child.GetValue ());
1525 // Converts from one of the valid underlying types for an enumeration
1526 // (int32, uint32, int64, uint64, short, ushort, byte, sbyte) to
1527 // one of the internal compiler literals: Int/UInt/Long/ULong Literals.
1529 public Constant WidenToCompilerConstant ()
1531 Type t = TypeManager.EnumToUnderlying (Child.Type);
1532 object v = ((Constant) Child).GetValue ();;
1534 if (t == TypeManager.int32_type)
1535 return new IntConstant ((int) v);
1536 if (t == TypeManager.uint32_type)
1537 return new UIntConstant ((uint) v);
1538 if (t == TypeManager.int64_type)
1539 return new LongConstant ((long) v);
1540 if (t == TypeManager.uint64_type)
1541 return new ULongConstant ((ulong) v);
1542 if (t == TypeManager.short_type)
1543 return new ShortConstant ((short) v);
1544 if (t == TypeManager.ushort_type)
1545 return new UShortConstant ((ushort) v);
1546 if (t == TypeManager.byte_type)
1547 return new ByteConstant ((byte) v);
1548 if (t == TypeManager.sbyte_type)
1549 return new SByteConstant ((sbyte) v);
1551 throw new Exception ("Invalid enumeration underlying type: " + t);
1555 // Extracts the value in the enumeration on its native representation
1557 public object GetPlainValue ()
1559 Type t = TypeManager.EnumToUnderlying (Child.Type);
1560 object v = ((Constant) Child).GetValue ();;
1562 if (t == TypeManager.int32_type)
1564 if (t == TypeManager.uint32_type)
1566 if (t == TypeManager.int64_type)
1568 if (t == TypeManager.uint64_type)
1570 if (t == TypeManager.short_type)
1572 if (t == TypeManager.ushort_type)
1574 if (t == TypeManager.byte_type)
1576 if (t == TypeManager.sbyte_type)
1582 public override string AsString ()
1584 return Child.AsString ();
1587 public override DoubleConstant ConvertToDouble ()
1589 return Child.ConvertToDouble ();
1592 public override FloatConstant ConvertToFloat ()
1594 return Child.ConvertToFloat ();
1597 public override ULongConstant ConvertToULong ()
1599 return Child.ConvertToULong ();
1602 public override LongConstant ConvertToLong ()
1604 return Child.ConvertToLong ();
1607 public override UIntConstant ConvertToUInt ()
1609 return Child.ConvertToUInt ();
1612 public override IntConstant ConvertToInt ()
1614 return Child.ConvertToInt ();
1617 public override bool IsZeroInteger {
1618 get { return Child.IsZeroInteger; }
1621 public override bool IsNegative {
1623 return Child.IsNegative;
1629 /// This kind of cast is used to encapsulate Value Types in objects.
1631 /// The effect of it is to box the value type emitted by the previous
1634 public class BoxedCast : EmptyCast {
1636 public BoxedCast (Expression expr)
1637 : base (expr, TypeManager.object_type)
1639 eclass = ExprClass.Value;
1642 public BoxedCast (Expression expr, Type target_type)
1643 : base (expr, target_type)
1645 eclass = ExprClass.Value;
1648 public override Expression DoResolve (EmitContext ec)
1650 // This should never be invoked, we are born in fully
1651 // initialized state.
1656 public override void Emit (EmitContext ec)
1660 ec.ig.Emit (OpCodes.Box, child.Type);
1664 public class UnboxCast : EmptyCast {
1665 public UnboxCast (Expression expr, Type return_type)
1666 : base (expr, return_type)
1670 public override Expression DoResolve (EmitContext ec)
1672 // This should never be invoked, we are born in fully
1673 // initialized state.
1678 public override void Emit (EmitContext ec)
1681 ILGenerator ig = ec.ig;
1684 ig.Emit (OpCodes.Unbox, t);
1686 LoadFromPtr (ig, t);
1691 /// This is used to perform explicit numeric conversions.
1693 /// Explicit numeric conversions might trigger exceptions in a checked
1694 /// context, so they should generate the conv.ovf opcodes instead of
1697 public class ConvCast : EmptyCast {
1698 public enum Mode : byte {
1699 I1_U1, I1_U2, I1_U4, I1_U8, I1_CH,
1701 I2_I1, I2_U1, I2_U2, I2_U4, I2_U8, I2_CH,
1702 U2_I1, U2_U1, U2_I2, U2_CH,
1703 I4_I1, I4_U1, I4_I2, I4_U2, I4_U4, I4_U8, I4_CH,
1704 U4_I1, U4_U1, U4_I2, U4_U2, U4_I4, U4_CH,
1705 I8_I1, I8_U1, I8_I2, I8_U2, I8_I4, I8_U4, I8_U8, I8_CH,
1706 U8_I1, U8_U1, U8_I2, U8_U2, U8_I4, U8_U4, U8_I8, U8_CH,
1707 CH_I1, CH_U1, CH_I2,
1708 R4_I1, R4_U1, R4_I2, R4_U2, R4_I4, R4_U4, R4_I8, R4_U8, R4_CH,
1709 R8_I1, R8_U1, R8_I2, R8_U2, R8_I4, R8_U4, R8_I8, R8_U8, R8_CH, R8_R4
1715 public ConvCast (EmitContext ec, Expression child, Type return_type, Mode m)
1716 : base (child, return_type)
1718 checked_state = ec.CheckState;
1722 public override Expression DoResolve (EmitContext ec)
1724 // This should never be invoked, we are born in fully
1725 // initialized state.
1730 public override string ToString ()
1732 return String.Format ("ConvCast ({0}, {1})", mode, child);
1735 public override void Emit (EmitContext ec)
1737 ILGenerator ig = ec.ig;
1743 case Mode.I1_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1744 case Mode.I1_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1745 case Mode.I1_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1746 case Mode.I1_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1747 case Mode.I1_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1749 case Mode.U1_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1750 case Mode.U1_CH: /* nothing */ break;
1752 case Mode.I2_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1753 case Mode.I2_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1754 case Mode.I2_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1755 case Mode.I2_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1756 case Mode.I2_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1757 case Mode.I2_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1759 case Mode.U2_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1760 case Mode.U2_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
1761 case Mode.U2_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
1762 case Mode.U2_CH: /* nothing */ break;
1764 case Mode.I4_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1765 case Mode.I4_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1766 case Mode.I4_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
1767 case Mode.I4_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1768 case Mode.I4_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1769 case Mode.I4_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1770 case Mode.I4_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1772 case Mode.U4_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1773 case Mode.U4_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
1774 case Mode.U4_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
1775 case Mode.U4_U2: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
1776 case Mode.U4_I4: ig.Emit (OpCodes.Conv_Ovf_I4_Un); break;
1777 case Mode.U4_CH: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
1779 case Mode.I8_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1780 case Mode.I8_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1781 case Mode.I8_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
1782 case Mode.I8_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1783 case Mode.I8_I4: ig.Emit (OpCodes.Conv_Ovf_I4); break;
1784 case Mode.I8_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1785 case Mode.I8_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1786 case Mode.I8_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1788 case Mode.U8_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1789 case Mode.U8_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
1790 case Mode.U8_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
1791 case Mode.U8_U2: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
1792 case Mode.U8_I4: ig.Emit (OpCodes.Conv_Ovf_I4_Un); break;
1793 case Mode.U8_U4: ig.Emit (OpCodes.Conv_Ovf_U4_Un); break;
1794 case Mode.U8_I8: ig.Emit (OpCodes.Conv_Ovf_I8_Un); break;
1795 case Mode.U8_CH: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
1797 case Mode.CH_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1798 case Mode.CH_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
1799 case Mode.CH_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
1801 case Mode.R4_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1802 case Mode.R4_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1803 case Mode.R4_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
1804 case Mode.R4_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1805 case Mode.R4_I4: ig.Emit (OpCodes.Conv_Ovf_I4); break;
1806 case Mode.R4_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1807 case Mode.R4_I8: ig.Emit (OpCodes.Conv_Ovf_I8); break;
1808 case Mode.R4_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1809 case Mode.R4_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1811 case Mode.R8_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1812 case Mode.R8_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1813 case Mode.R8_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
1814 case Mode.R8_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1815 case Mode.R8_I4: ig.Emit (OpCodes.Conv_Ovf_I4); break;
1816 case Mode.R8_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1817 case Mode.R8_I8: ig.Emit (OpCodes.Conv_Ovf_I8); break;
1818 case Mode.R8_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1819 case Mode.R8_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1820 case Mode.R8_R4: ig.Emit (OpCodes.Conv_R4); break;
1824 case Mode.I1_U1: ig.Emit (OpCodes.Conv_U1); break;
1825 case Mode.I1_U2: ig.Emit (OpCodes.Conv_U2); break;
1826 case Mode.I1_U4: ig.Emit (OpCodes.Conv_U4); break;
1827 case Mode.I1_U8: ig.Emit (OpCodes.Conv_I8); break;
1828 case Mode.I1_CH: ig.Emit (OpCodes.Conv_U2); break;
1830 case Mode.U1_I1: ig.Emit (OpCodes.Conv_I1); break;
1831 case Mode.U1_CH: ig.Emit (OpCodes.Conv_U2); break;
1833 case Mode.I2_I1: ig.Emit (OpCodes.Conv_I1); break;
1834 case Mode.I2_U1: ig.Emit (OpCodes.Conv_U1); break;
1835 case Mode.I2_U2: ig.Emit (OpCodes.Conv_U2); break;
1836 case Mode.I2_U4: ig.Emit (OpCodes.Conv_U4); break;
1837 case Mode.I2_U8: ig.Emit (OpCodes.Conv_I8); break;
1838 case Mode.I2_CH: ig.Emit (OpCodes.Conv_U2); break;
1840 case Mode.U2_I1: ig.Emit (OpCodes.Conv_I1); break;
1841 case Mode.U2_U1: ig.Emit (OpCodes.Conv_U1); break;
1842 case Mode.U2_I2: ig.Emit (OpCodes.Conv_I2); break;
1843 case Mode.U2_CH: /* nothing */ break;
1845 case Mode.I4_I1: ig.Emit (OpCodes.Conv_I1); break;
1846 case Mode.I4_U1: ig.Emit (OpCodes.Conv_U1); break;
1847 case Mode.I4_I2: ig.Emit (OpCodes.Conv_I2); break;
1848 case Mode.I4_U4: /* nothing */ break;
1849 case Mode.I4_U2: ig.Emit (OpCodes.Conv_U2); break;
1850 case Mode.I4_U8: ig.Emit (OpCodes.Conv_I8); break;
1851 case Mode.I4_CH: ig.Emit (OpCodes.Conv_U2); break;
1853 case Mode.U4_I1: ig.Emit (OpCodes.Conv_I1); break;
1854 case Mode.U4_U1: ig.Emit (OpCodes.Conv_U1); break;
1855 case Mode.U4_I2: ig.Emit (OpCodes.Conv_I2); break;
1856 case Mode.U4_U2: ig.Emit (OpCodes.Conv_U2); break;
1857 case Mode.U4_I4: /* nothing */ break;
1858 case Mode.U4_CH: ig.Emit (OpCodes.Conv_U2); break;
1860 case Mode.I8_I1: ig.Emit (OpCodes.Conv_I1); break;
1861 case Mode.I8_U1: ig.Emit (OpCodes.Conv_U1); break;
1862 case Mode.I8_I2: ig.Emit (OpCodes.Conv_I2); break;
1863 case Mode.I8_U2: ig.Emit (OpCodes.Conv_U2); break;
1864 case Mode.I8_I4: ig.Emit (OpCodes.Conv_I4); break;
1865 case Mode.I8_U4: ig.Emit (OpCodes.Conv_U4); break;
1866 case Mode.I8_U8: /* nothing */ break;
1867 case Mode.I8_CH: ig.Emit (OpCodes.Conv_U2); break;
1869 case Mode.U8_I1: ig.Emit (OpCodes.Conv_I1); break;
1870 case Mode.U8_U1: ig.Emit (OpCodes.Conv_U1); break;
1871 case Mode.U8_I2: ig.Emit (OpCodes.Conv_I2); break;
1872 case Mode.U8_U2: ig.Emit (OpCodes.Conv_U2); break;
1873 case Mode.U8_I4: ig.Emit (OpCodes.Conv_I4); break;
1874 case Mode.U8_U4: ig.Emit (OpCodes.Conv_U4); break;
1875 case Mode.U8_I8: /* nothing */ break;
1876 case Mode.U8_CH: ig.Emit (OpCodes.Conv_U2); break;
1878 case Mode.CH_I1: ig.Emit (OpCodes.Conv_I1); break;
1879 case Mode.CH_U1: ig.Emit (OpCodes.Conv_U1); break;
1880 case Mode.CH_I2: ig.Emit (OpCodes.Conv_I2); break;
1882 case Mode.R4_I1: ig.Emit (OpCodes.Conv_I1); break;
1883 case Mode.R4_U1: ig.Emit (OpCodes.Conv_U1); break;
1884 case Mode.R4_I2: ig.Emit (OpCodes.Conv_I2); break;
1885 case Mode.R4_U2: ig.Emit (OpCodes.Conv_U2); break;
1886 case Mode.R4_I4: ig.Emit (OpCodes.Conv_I4); break;
1887 case Mode.R4_U4: ig.Emit (OpCodes.Conv_U4); break;
1888 case Mode.R4_I8: ig.Emit (OpCodes.Conv_I8); break;
1889 case Mode.R4_U8: ig.Emit (OpCodes.Conv_U8); break;
1890 case Mode.R4_CH: ig.Emit (OpCodes.Conv_U2); break;
1892 case Mode.R8_I1: ig.Emit (OpCodes.Conv_I1); break;
1893 case Mode.R8_U1: ig.Emit (OpCodes.Conv_U1); break;
1894 case Mode.R8_I2: ig.Emit (OpCodes.Conv_I2); break;
1895 case Mode.R8_U2: ig.Emit (OpCodes.Conv_U2); break;
1896 case Mode.R8_I4: ig.Emit (OpCodes.Conv_I4); break;
1897 case Mode.R8_U4: ig.Emit (OpCodes.Conv_U4); break;
1898 case Mode.R8_I8: ig.Emit (OpCodes.Conv_I8); break;
1899 case Mode.R8_U8: ig.Emit (OpCodes.Conv_U8); break;
1900 case Mode.R8_CH: ig.Emit (OpCodes.Conv_U2); break;
1901 case Mode.R8_R4: ig.Emit (OpCodes.Conv_R4); break;
1907 public class OpcodeCast : EmptyCast {
1911 public OpcodeCast (Expression child, Type return_type, OpCode op)
1912 : base (child, return_type)
1916 second_valid = false;
1919 public OpcodeCast (Expression child, Type return_type, OpCode op, OpCode op2)
1920 : base (child, return_type)
1925 second_valid = true;
1928 public override Expression DoResolve (EmitContext ec)
1930 // This should never be invoked, we are born in fully
1931 // initialized state.
1936 public override void Emit (EmitContext ec)
1947 /// This kind of cast is used to encapsulate a child and cast it
1948 /// to the class requested
1950 public class ClassCast : EmptyCast {
1951 public ClassCast (Expression child, Type return_type)
1952 : base (child, return_type)
1957 public override Expression DoResolve (EmitContext ec)
1959 // This should never be invoked, we are born in fully
1960 // initialized state.
1965 public override void Emit (EmitContext ec)
1969 ec.ig.Emit (OpCodes.Castclass, type);
1975 /// SimpleName expressions are initially formed of a single
1976 /// word and it only happens at the beginning of the expression.
1980 /// The expression will try to be bound to a Field, a Method
1981 /// group or a Property. If those fail we pass the name to our
1982 /// caller and the SimpleName is compounded to perform a type
1983 /// lookup. The idea behind this process is that we want to avoid
1984 /// creating a namespace map from the assemblies, as that requires
1985 /// the GetExportedTypes function to be called and a hashtable to
1986 /// be constructed which reduces startup time. If later we find
1987 /// that this is slower, we should create a `NamespaceExpr' expression
1988 /// that fully participates in the resolution process.
1990 /// For example `System.Console.WriteLine' is decomposed into
1991 /// MemberAccess (MemberAccess (SimpleName ("System"), "Console"), "WriteLine")
1993 /// The first SimpleName wont produce a match on its own, so it will
1995 /// MemberAccess (SimpleName ("System.Console"), "WriteLine").
1997 /// System.Console will produce a TypeExpr match.
1999 /// The downside of this is that we might be hitting `LookupType' too many
2000 /// times with this scheme.
2002 public class SimpleName : Expression {
2006 // If true, then we are a simple name, not composed with a ".
2010 public SimpleName (string a, string b, Location l)
2012 Name = String.Concat (a, ".", b);
2017 public SimpleName (string name, Location l)
2024 public static void Error_ObjectRefRequired (EmitContext ec, Location l, string name)
2026 if (ec.IsFieldInitializer)
2029 "A field initializer cannot reference the non-static field, " +
2030 "method or property `"+name+"'");
2034 "An object reference is required " +
2035 "for the non-static field `"+name+"'");
2039 // Checks whether we are trying to access an instance
2040 // property, method or field from a static body.
2042 Expression MemberStaticCheck (EmitContext ec, Expression e)
2044 if (e is IMemberExpr){
2045 IMemberExpr member = (IMemberExpr) e;
2047 if (!member.IsStatic){
2048 Error_ObjectRefRequired (ec, loc, Name);
2056 public override Expression DoResolve (EmitContext ec)
2058 return SimpleNameResolve (ec, null, false, false);
2061 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
2063 return SimpleNameResolve (ec, right_side, false, false);
2067 public Expression DoResolveAllowStatic (EmitContext ec, bool intermediate)
2069 return SimpleNameResolve (ec, null, true, intermediate);
2072 public override Expression ResolveAsTypeStep (EmitContext ec)
2074 DeclSpace ds = ec.DeclSpace;
2075 NamespaceEntry ns = ds.NamespaceEntry;
2080 // Since we are cheating: we only do the Alias lookup for
2081 // namespaces if the name does not include any dots in it
2083 if (ns != null && is_base)
2084 alias_value = ns.LookupAlias (Name);
2088 if (ec.ResolvingTypeTree){
2089 int errors = Report.Errors;
2090 Type dt = ds.FindType (loc, Name);
2092 if (Report.Errors != errors)
2096 return new TypeExpression (dt, loc);
2098 if (alias_value != null){
2099 if (alias_value.IsType)
2100 return alias_value.ResolveAsType (ec);
2101 if ((t = RootContext.LookupType (ds, alias_value.Name, true, loc)) != null)
2102 return new TypeExpression (t, loc);
2106 if ((t = RootContext.LookupType (ds, Name, true, loc)) != null)
2107 return new TypeExpression (t, loc);
2109 if (alias_value != null) {
2110 if (alias_value.IsType)
2111 return alias_value.ResolveAsType (ec);
2112 if ((t = RootContext.LookupType (ds, alias_value.Name, true, loc)) != null)
2113 return new TypeExpression (t, loc);
2115 // we have alias value, but it isn't Type, so try if it's namespace
2116 return new SimpleName (alias_value.Name, loc);
2119 // No match, maybe our parent can compose us
2120 // into something meaningful.
2124 Expression SimpleNameResolve (EmitContext ec, Expression right_side,
2125 bool allow_static, bool intermediate)
2127 Expression e = DoSimpleNameResolve (ec, right_side, allow_static, intermediate);
2131 Block current_block = ec.CurrentBlock;
2132 if (current_block != null){
2133 //LocalInfo vi = current_block.GetLocalInfo (Name);
2135 current_block.IsVariableNameUsedInChildBlock(Name)) {
2136 Report.Error (135, Location,
2137 "'{0}' has a different meaning in a " +
2138 "child block", Name);
2147 /// 7.5.2: Simple Names.
2149 /// Local Variables and Parameters are handled at
2150 /// parse time, so they never occur as SimpleNames.
2152 /// The `allow_static' flag is used by MemberAccess only
2153 /// and it is used to inform us that it is ok for us to
2154 /// avoid the static check, because MemberAccess might end
2155 /// up resolving the Name as a Type name and the access as
2156 /// a static type access.
2158 /// ie: Type Type; .... { Type.GetType (""); }
2160 /// Type is both an instance variable and a Type; Type.GetType
2161 /// is the static method not an instance method of type.
2163 Expression DoSimpleNameResolve (EmitContext ec, Expression right_side, bool allow_static, bool intermediate)
2165 Expression e = null;
2168 // Stage 1: Performed by the parser (binding to locals or parameters).
2170 Block current_block = ec.CurrentBlock;
2171 if (current_block != null){
2172 LocalInfo vi = current_block.GetLocalInfo (Name);
2176 var = new LocalVariableReference (ec.CurrentBlock, Name, loc);
2178 if (right_side != null)
2179 return var.ResolveLValue (ec, right_side);
2181 return var.Resolve (ec);
2184 ParameterReference pref = current_block.GetParameterReference (Name, loc);
2186 if (right_side != null)
2187 return pref.ResolveLValue (ec, right_side);
2189 return pref.Resolve (ec);
2194 // Stage 2: Lookup members
2197 DeclSpace lookup_ds = ec.DeclSpace;
2199 if (lookup_ds.TypeBuilder == null)
2202 e = MemberLookup (ec, lookup_ds.TypeBuilder, Name, loc);
2206 lookup_ds =lookup_ds.Parent;
2207 } while (lookup_ds != null);
2209 if (e == null && ec.ContainerType != null)
2210 e = MemberLookup (ec, ec.ContainerType, Name, loc);
2214 // Since we are cheating (is_base is our hint
2215 // that we are the beginning of the name): we
2216 // only do the Alias lookup for namespaces if
2217 // the name does not include any dots in it
2219 NamespaceEntry ns = ec.DeclSpace.NamespaceEntry;
2220 if (is_base && ns != null){
2221 IAlias alias_value = ns.LookupAlias (Name);
2222 if (alias_value != null){
2223 if (alias_value.IsType)
2224 return alias_value.ResolveAsType (ec);
2226 Name = alias_value.Name;
2229 if ((t = TypeManager.LookupType (Name)) != null)
2230 return new TypeExpression (t, loc);
2232 // No match, maybe our parent can compose us
2233 // into something meaningful.
2238 return ResolveAsTypeStep (ec);
2244 if (e is IMemberExpr) {
2245 e = MemberAccess.ResolveMemberAccess (ec, e, null, loc, this);
2249 IMemberExpr me = e as IMemberExpr;
2253 // This fails if ResolveMemberAccess() was unable to decide whether
2254 // it's a field or a type of the same name.
2256 if (!me.IsStatic && (me.InstanceExpression == null))
2260 TypeManager.IsNestedFamilyAccessible (me.InstanceExpression.Type, me.DeclaringType) &&
2261 me.InstanceExpression.Type != me.DeclaringType &&
2262 !me.InstanceExpression.Type.IsSubclassOf (me.DeclaringType) &&
2263 (!intermediate || !MemberAccess.IdenticalNameAndTypeName (ec, this, e, loc))) {
2264 Error (38, "Cannot access nonstatic member `" + me.Name + "' of " +
2265 "outer type `" + me.DeclaringType + "' via nested type `" +
2266 me.InstanceExpression.Type + "'");
2270 return (right_side != null)
2271 ? e.DoResolveLValue (ec, right_side)
2275 if (ec.IsStatic || ec.IsFieldInitializer){
2279 return MemberStaticCheck (ec, e);
2284 public override void Emit (EmitContext ec)
2287 // If this is ever reached, then we failed to
2288 // find the name as a namespace
2291 Error (103, "The name `" + Name +
2292 "' does not exist in the class `" +
2293 ec.DeclSpace.Name + "'");
2296 public override string ToString ()
2303 /// Fully resolved expression that evaluates to a type
2305 public abstract class TypeExpr : Expression, IAlias {
2306 override public Expression ResolveAsTypeStep (EmitContext ec)
2308 TypeExpr t = DoResolveAsTypeStep (ec);
2312 eclass = ExprClass.Type;
2316 override public Expression DoResolve (EmitContext ec)
2318 return ResolveAsTypeTerminal (ec, false);
2321 override public void Emit (EmitContext ec)
2323 throw new Exception ("Should never be called");
2326 public virtual bool CheckAccessLevel (DeclSpace ds)
2328 return ds.CheckAccessLevel (Type);
2331 public virtual bool AsAccessible (DeclSpace ds, int flags)
2333 return ds.AsAccessible (Type, flags);
2336 public virtual bool IsClass {
2337 get { return Type.IsClass; }
2340 public virtual bool IsValueType {
2341 get { return Type.IsValueType; }
2344 public virtual bool IsInterface {
2345 get { return Type.IsInterface; }
2348 public virtual bool IsSealed {
2349 get { return Type.IsSealed; }
2352 public virtual bool CanInheritFrom ()
2354 if (Type == TypeManager.enum_type ||
2355 (Type == TypeManager.value_type && RootContext.StdLib) ||
2356 Type == TypeManager.multicast_delegate_type ||
2357 Type == TypeManager.delegate_type ||
2358 Type == TypeManager.array_type)
2364 public virtual bool IsAttribute {
2366 return Type == TypeManager.attribute_type ||
2367 Type.IsSubclassOf (TypeManager.attribute_type);
2371 public abstract TypeExpr DoResolveAsTypeStep (EmitContext ec);
2373 public virtual Type ResolveType (EmitContext ec)
2375 TypeExpr t = ResolveAsTypeTerminal (ec, false);
2382 public abstract string Name {
2386 public override bool Equals (object obj)
2388 TypeExpr tobj = obj as TypeExpr;
2392 return Type == tobj.Type;
2395 public override int GetHashCode ()
2397 return Type.GetHashCode ();
2400 public override string ToString ()
2405 bool IAlias.IsType {
2406 get { return true; }
2409 TypeExpr IAlias.ResolveAsType (EmitContext ec)
2411 return ResolveAsTypeTerminal (ec, false);
2415 public class TypeExpression : TypeExpr, IAlias {
2416 public TypeExpression (Type t, Location l)
2419 eclass = ExprClass.Type;
2423 public override TypeExpr DoResolveAsTypeStep (EmitContext ec)
2428 public override string Name {
2430 return Type.ToString ();
2434 string IAlias.Name {
2436 return Type.FullName;
2442 /// Used to create types from a fully qualified name. These are just used
2443 /// by the parser to setup the core types. A TypeLookupExpression is always
2444 /// classified as a type.
2446 public class TypeLookupExpression : TypeExpr {
2449 public TypeLookupExpression (string name)
2454 public override TypeExpr DoResolveAsTypeStep (EmitContext ec)
2457 type = RootContext.LookupType (
2458 ec.DeclSpace, name, false, Location.Null);
2466 public override string Name {
2473 public class TypeAliasExpression : TypeExpr, IAlias {
2477 public TypeAliasExpression (TypeExpr texpr, Location l)
2480 loc = texpr.Location;
2482 eclass = ExprClass.Type;
2486 public override string Name {
2487 get { return name; }
2490 public override TypeExpr DoResolveAsTypeStep (EmitContext ec)
2492 Type type = texpr.ResolveType (ec);
2496 return new TypeExpression (type, loc);
2499 public override bool CheckAccessLevel (DeclSpace ds)
2501 return texpr.CheckAccessLevel (ds);
2504 public override bool AsAccessible (DeclSpace ds, int flags)
2506 return texpr.AsAccessible (ds, flags);
2509 public override bool IsClass {
2510 get { return texpr.IsClass; }
2513 public override bool IsValueType {
2514 get { return texpr.IsValueType; }
2517 public override bool IsInterface {
2518 get { return texpr.IsInterface; }
2521 public override bool IsSealed {
2522 get { return texpr.IsSealed; }
2525 public override bool IsAttribute {
2526 get { return texpr.IsAttribute; }
2531 /// MethodGroup Expression.
2533 /// This is a fully resolved expression that evaluates to a type
2535 public class MethodGroupExpr : Expression, IMemberExpr {
2536 public MethodBase [] Methods;
2537 Expression instance_expression = null;
2538 bool is_explicit_impl = false;
2539 bool identical_type_name = false;
2542 public MethodGroupExpr (MemberInfo [] mi, Location l)
2544 Methods = new MethodBase [mi.Length];
2545 mi.CopyTo (Methods, 0);
2546 eclass = ExprClass.MethodGroup;
2547 type = TypeManager.object_type;
2551 public MethodGroupExpr (ArrayList list, Location l)
2553 Methods = new MethodBase [list.Count];
2556 list.CopyTo (Methods, 0);
2558 foreach (MemberInfo m in list){
2559 if (!(m is MethodBase)){
2560 Console.WriteLine ("Name " + m.Name);
2561 Console.WriteLine ("Found a: " + m.GetType ().FullName);
2568 eclass = ExprClass.MethodGroup;
2569 type = TypeManager.object_type;
2572 public Type DeclaringType {
2575 // The methods are arranged in this order:
2576 // derived type -> base type
2578 return Methods [0].DeclaringType;
2583 // `A method group may have associated an instance expression'
2585 public Expression InstanceExpression {
2587 return instance_expression;
2591 instance_expression = value;
2595 public bool IsExplicitImpl {
2597 return is_explicit_impl;
2601 is_explicit_impl = value;
2605 public bool IdenticalTypeName {
2607 return identical_type_name;
2611 identical_type_name = value;
2615 public bool IsBase {
2624 public string Name {
2626 return Methods [0].Name;
2630 public bool IsInstance {
2632 foreach (MethodBase mb in Methods)
2640 public bool IsStatic {
2642 foreach (MethodBase mb in Methods)
2650 override public Expression DoResolve (EmitContext ec)
2653 instance_expression = null;
2655 if (instance_expression != null) {
2656 instance_expression = instance_expression.DoResolve (ec);
2657 if (instance_expression == null)
2664 public void ReportUsageError ()
2666 Report.Error (654, loc, "Method `" + DeclaringType + "." +
2667 Name + "()' is referenced without parentheses");
2670 override public void Emit (EmitContext ec)
2672 ReportUsageError ();
2675 bool RemoveMethods (bool keep_static)
2677 ArrayList smethods = new ArrayList ();
2679 foreach (MethodBase mb in Methods){
2680 if (mb.IsStatic == keep_static)
2684 if (smethods.Count == 0)
2687 Methods = new MethodBase [smethods.Count];
2688 smethods.CopyTo (Methods, 0);
2694 /// Removes any instance methods from the MethodGroup, returns
2695 /// false if the resulting set is empty.
2697 public bool RemoveInstanceMethods ()
2699 return RemoveMethods (true);
2703 /// Removes any static methods from the MethodGroup, returns
2704 /// false if the resulting set is empty.
2706 public bool RemoveStaticMethods ()
2708 return RemoveMethods (false);
2713 /// Fully resolved expression that evaluates to a Field
2715 public class FieldExpr : Expression, IAssignMethod, IMemoryLocation, IMemberExpr, IVariable {
2716 public readonly FieldInfo FieldInfo;
2717 Expression instance_expr;
2718 VariableInfo variable_info;
2720 LocalTemporary temp;
2723 public FieldExpr (FieldInfo fi, Location l)
2726 eclass = ExprClass.Variable;
2727 type = fi.FieldType;
2731 public string Name {
2733 return FieldInfo.Name;
2737 public bool IsInstance {
2739 return !FieldInfo.IsStatic;
2743 public bool IsStatic {
2745 return FieldInfo.IsStatic;
2749 public Type DeclaringType {
2751 return FieldInfo.DeclaringType;
2755 public Expression InstanceExpression {
2757 return instance_expr;
2761 instance_expr = value;
2765 public VariableInfo VariableInfo {
2767 return variable_info;
2771 override public Expression DoResolve (EmitContext ec)
2773 if (!FieldInfo.IsStatic){
2774 if (instance_expr == null){
2776 // This can happen when referencing an instance field using
2777 // a fully qualified type expression: TypeName.InstanceField = xxx
2779 SimpleName.Error_ObjectRefRequired (ec, loc, FieldInfo.Name);
2783 // Resolve the field's instance expression while flow analysis is turned
2784 // off: when accessing a field "a.b", we must check whether the field
2785 // "a.b" is initialized, not whether the whole struct "a" is initialized.
2786 instance_expr = instance_expr.Resolve (ec, ResolveFlags.VariableOrValue |
2787 ResolveFlags.DisableFlowAnalysis);
2788 if (instance_expr == null)
2792 ObsoleteAttribute oa;
2793 FieldBase f = TypeManager.GetField (FieldInfo);
2795 oa = f.GetObsoleteAttribute (f.Parent);
2797 AttributeTester.Report_ObsoleteMessage (oa, f.GetSignatureForError (), loc);
2799 // To be sure that type is external because we do not register generated fields
2800 } else if (!(FieldInfo.DeclaringType is TypeBuilder)) {
2801 oa = AttributeTester.GetMemberObsoleteAttribute (FieldInfo);
2803 AttributeTester.Report_ObsoleteMessage (oa, TypeManager.GetFullNameSignature (FieldInfo), loc);
2806 if (ec.CurrentAnonymousMethod != null){
2807 if (!FieldInfo.IsStatic){
2808 if (ec.TypeContainer is Struct){
2809 Report.Error (1673, loc, "Can not reference instance variables in anonymous methods hosted in structs");
2812 ec.CaptureField (this);
2816 // If the instance expression is a local variable or parameter.
2817 IVariable var = instance_expr as IVariable;
2818 if ((var == null) || (var.VariableInfo == null))
2821 VariableInfo vi = var.VariableInfo;
2822 if (!vi.IsFieldAssigned (ec, FieldInfo.Name, loc))
2825 variable_info = vi.GetSubStruct (FieldInfo.Name);
2829 void Report_AssignToReadonly (bool is_instance)
2834 msg = "Readonly field can not be assigned outside " +
2835 "of constructor or variable initializer";
2837 msg = "A static readonly field can only be assigned in " +
2838 "a static constructor";
2840 Report.Error (is_instance ? 191 : 198, loc, msg);
2843 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
2845 IVariable var = instance_expr as IVariable;
2846 if ((var != null) && (var.VariableInfo != null))
2847 var.VariableInfo.SetFieldAssigned (ec, FieldInfo.Name);
2849 Expression e = DoResolve (ec);
2854 if (!FieldInfo.IsStatic && (instance_expr.Type.IsValueType && !(instance_expr is IMemoryLocation))) {
2855 // FIXME: Provide better error reporting.
2856 Error (1612, "Cannot modify expression because it is not a variable.");
2860 if (!FieldInfo.IsInitOnly)
2863 FieldBase fb = TypeManager.GetField (FieldInfo);
2868 // InitOnly fields can only be assigned in constructors
2871 if (ec.IsConstructor){
2872 if (IsStatic && !ec.IsStatic)
2873 Report_AssignToReadonly (false);
2875 if (ec.ContainerType == FieldInfo.DeclaringType)
2879 Report_AssignToReadonly (!IsStatic);
2884 public override void CheckMarshallByRefAccess (Type container)
2886 if (!IsStatic && Type.IsValueType && !container.IsSubclassOf (TypeManager.mbr_type) && DeclaringType.IsSubclassOf (TypeManager.mbr_type)) {
2887 Report.SymbolRelatedToPreviousError (DeclaringType);
2888 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);
2892 public bool VerifyFixed (bool is_expression)
2894 IVariable variable = instance_expr as IVariable;
2895 if ((variable == null) || !variable.VerifyFixed (true))
2901 public void Emit (EmitContext ec, bool leave_copy)
2903 ILGenerator ig = ec.ig;
2904 bool is_volatile = false;
2906 if (FieldInfo is FieldBuilder){
2907 FieldBase f = TypeManager.GetField (FieldInfo);
2909 if ((f.ModFlags & Modifiers.VOLATILE) != 0)
2912 f.status |= Field.Status.USED;
2916 if (FieldInfo.IsStatic){
2918 ig.Emit (OpCodes.Volatile);
2920 ig.Emit (OpCodes.Ldsfld, FieldInfo);
2926 ig.Emit (OpCodes.Volatile);
2928 ig.Emit (OpCodes.Ldfld, FieldInfo);
2932 ec.ig.Emit (OpCodes.Dup);
2933 if (!FieldInfo.IsStatic) {
2934 temp = new LocalTemporary (ec, this.Type);
2940 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
2942 FieldAttributes fa = FieldInfo.Attributes;
2943 bool is_static = (fa & FieldAttributes.Static) != 0;
2944 bool is_readonly = (fa & FieldAttributes.InitOnly) != 0;
2945 ILGenerator ig = ec.ig;
2946 prepared = prepare_for_load;
2948 if (is_readonly && !ec.IsConstructor){
2949 Report_AssignToReadonly (!is_static);
2955 if (prepare_for_load)
2956 ig.Emit (OpCodes.Dup);
2961 ec.ig.Emit (OpCodes.Dup);
2962 if (!FieldInfo.IsStatic) {
2963 temp = new LocalTemporary (ec, this.Type);
2968 if (FieldInfo is FieldBuilder){
2969 FieldBase f = TypeManager.GetField (FieldInfo);
2971 if ((f.ModFlags & Modifiers.VOLATILE) != 0)
2972 ig.Emit (OpCodes.Volatile);
2974 f.status |= Field.Status.ASSIGNED;
2979 ig.Emit (OpCodes.Stsfld, FieldInfo);
2981 ig.Emit (OpCodes.Stfld, FieldInfo);
2987 void EmitInstance (EmitContext ec)
2989 if (instance_expr.Type.IsValueType) {
2990 if (instance_expr is IMemoryLocation) {
2991 ((IMemoryLocation) instance_expr).AddressOf (ec, AddressOp.LoadStore);
2993 LocalTemporary t = new LocalTemporary (ec, instance_expr.Type);
2994 instance_expr.Emit (ec);
2996 t.AddressOf (ec, AddressOp.Store);
2999 instance_expr.Emit (ec);
3002 public override void Emit (EmitContext ec)
3007 public void AddressOf (EmitContext ec, AddressOp mode)
3009 ILGenerator ig = ec.ig;
3011 if (FieldInfo is FieldBuilder){
3012 FieldBase f = TypeManager.GetField (FieldInfo);
3014 if ((f.ModFlags & Modifiers.VOLATILE) != 0){
3015 Error (676, "volatile variable: can not take its address, or pass as ref/out parameter");
3019 if ((mode & AddressOp.Store) != 0)
3020 f.status |= Field.Status.ASSIGNED;
3021 if ((mode & AddressOp.Load) != 0)
3022 f.status |= Field.Status.USED;
3027 // Handle initonly fields specially: make a copy and then
3028 // get the address of the copy.
3031 if (FieldInfo.IsInitOnly){
3033 if (ec.IsConstructor){
3034 if (FieldInfo.IsStatic){
3046 local = ig.DeclareLocal (type);
3047 ig.Emit (OpCodes.Stloc, local);
3048 ig.Emit (OpCodes.Ldloca, local);
3053 if (FieldInfo.IsStatic){
3054 ig.Emit (OpCodes.Ldsflda, FieldInfo);
3057 ig.Emit (OpCodes.Ldflda, FieldInfo);
3063 // A FieldExpr whose address can not be taken
3065 public class FieldExprNoAddress : FieldExpr, IMemoryLocation {
3066 public FieldExprNoAddress (FieldInfo fi, Location loc) : base (fi, loc)
3070 public new void AddressOf (EmitContext ec, AddressOp mode)
3072 Report.Error (-215, "Report this: Taking the address of a remapped parameter not supported");
3077 /// Expression that evaluates to a Property. The Assign class
3078 /// might set the `Value' expression if we are in an assignment.
3080 /// This is not an LValue because we need to re-write the expression, we
3081 /// can not take data from the stack and store it.
3083 public class PropertyExpr : ExpressionStatement, IAssignMethod, IMemberExpr {
3084 public readonly PropertyInfo PropertyInfo;
3087 // This is set externally by the `BaseAccess' class
3090 MethodInfo getter, setter;
3093 Expression instance_expr;
3094 LocalTemporary temp;
3097 public PropertyExpr (EmitContext ec, PropertyInfo pi, Location l)
3100 eclass = ExprClass.PropertyAccess;
3104 type = TypeManager.TypeToCoreType (pi.PropertyType);
3106 ResolveAccessors (ec);
3109 public string Name {
3111 return PropertyInfo.Name;
3115 public bool IsInstance {
3121 public bool IsStatic {
3127 public Type DeclaringType {
3129 return PropertyInfo.DeclaringType;
3134 // The instance expression associated with this expression
3136 public Expression InstanceExpression {
3138 instance_expr = value;
3142 return instance_expr;
3146 public bool VerifyAssignable ()
3148 if (setter == null) {
3149 Report.Error (200, loc,
3150 "The property `" + PropertyInfo.Name +
3151 "' can not be assigned to, as it has not set accessor");
3158 void FindAccessors (Type invocation_type)
3160 BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic |
3161 BindingFlags.Static | BindingFlags.Instance |
3162 BindingFlags.DeclaredOnly;
3164 Type current = PropertyInfo.DeclaringType;
3165 for (; current != null; current = current.BaseType) {
3166 MemberInfo[] group = TypeManager.MemberLookup (
3167 invocation_type, invocation_type, current,
3168 MemberTypes.Property, flags, PropertyInfo.Name, null);
3173 if (group.Length != 1)
3174 // Oooops, can this ever happen ?
3177 PropertyInfo pi = (PropertyInfo) group [0];
3180 getter = pi.GetGetMethod (true);;
3183 setter = pi.GetSetMethod (true);;
3185 MethodInfo accessor = getter != null ? getter : setter;
3187 if (!accessor.IsVirtual)
3193 // We also perform the permission checking here, as the PropertyInfo does not
3194 // hold the information for the accessibility of its setter/getter
3196 void ResolveAccessors (EmitContext ec)
3198 FindAccessors (ec.ContainerType);
3200 is_static = getter != null ? getter.IsStatic : setter.IsStatic;
3203 bool InstanceResolve (EmitContext ec, bool must_do_cs1540_check)
3205 if ((instance_expr == null) && ec.IsStatic && !is_static) {
3206 SimpleName.Error_ObjectRefRequired (ec, loc, PropertyInfo.Name);
3210 if (instance_expr != null) {
3211 instance_expr = instance_expr.DoResolve (ec);
3212 if (instance_expr == null)
3215 instance_expr.CheckMarshallByRefAccess (ec.ContainerType);
3218 if (must_do_cs1540_check && (instance_expr != null)) {
3219 if ((instance_expr.Type != ec.ContainerType) &&
3220 ec.ContainerType.IsSubclassOf (instance_expr.Type)) {
3221 Report.Error (1540, loc, "Cannot access protected member `" +
3222 PropertyInfo.DeclaringType + "." + PropertyInfo.Name +
3223 "' via a qualifier of type `" +
3224 TypeManager.CSharpName (instance_expr.Type) +
3225 "'; the qualifier must be of type `" +
3226 TypeManager.CSharpName (ec.ContainerType) +
3227 "' (or derived from it)");
3235 override public Expression DoResolve (EmitContext ec)
3237 if (getter != null){
3238 if (TypeManager.GetArgumentTypes (getter).Length != 0){
3240 117, loc, "`{0}' does not contain a " +
3241 "definition for `{1}'.", getter.DeclaringType,
3247 if (getter == null){
3249 // The following condition happens if the PropertyExpr was
3250 // created, but is invalid (ie, the property is inaccessible),
3251 // and we did not want to embed the knowledge about this in
3252 // the caller routine. This only avoids double error reporting.
3257 Report.Error (154, loc,
3258 "The property `" + PropertyInfo.Name +
3259 "' can not be used in " +
3260 "this context because it lacks a get accessor");
3264 bool must_do_cs1540_check;
3265 if (!IsAccessorAccessible (ec.ContainerType, getter, out must_do_cs1540_check)) {
3266 Report.Error (122, loc, "'{0}.get' is inaccessible due to its protection level", PropertyInfo.Name);
3270 if (!InstanceResolve (ec, must_do_cs1540_check))
3274 // Only base will allow this invocation to happen.
3276 if (IsBase && getter.IsAbstract){
3277 Report.Error (205, loc, "Cannot call an abstract base property: " +
3278 PropertyInfo.DeclaringType + "." +PropertyInfo.Name);
3285 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
3287 if (setter == null){
3289 // The following condition happens if the PropertyExpr was
3290 // created, but is invalid (ie, the property is inaccessible),
3291 // and we did not want to embed the knowledge about this in
3292 // the caller routine. This only avoids double error reporting.
3297 Report.Error (154, loc,
3298 "The property `" + PropertyInfo.Name +
3299 "' can not be used in " +
3300 "this context because it lacks a set accessor");
3304 if (TypeManager.GetArgumentTypes (setter).Length != 1){
3306 117, loc, "`{0}' does not contain a " +
3307 "definition for `{1}'.", getter.DeclaringType,
3312 bool must_do_cs1540_check;
3313 if (!IsAccessorAccessible (ec.ContainerType, setter, out must_do_cs1540_check)) {
3314 Report.Error (122, loc, "'{0}.set' is inaccessible due to its protection level", PropertyInfo.Name);
3318 if (!InstanceResolve (ec, must_do_cs1540_check))
3322 // Only base will allow this invocation to happen.
3324 if (IsBase && setter.IsAbstract){
3325 Report.Error (205, loc, "Cannot call an abstract base property: " +
3326 PropertyInfo.DeclaringType + "." +PropertyInfo.Name);
3331 // Check that we are not making changes to a temporary memory location
3333 if (instance_expr != null && instance_expr.Type.IsValueType && !(instance_expr is IMemoryLocation)) {
3334 // FIXME: Provide better error reporting.
3335 Error (1612, "Cannot modify expression because it is not a variable.");
3344 public override void Emit (EmitContext ec)
3349 void EmitInstance (EmitContext ec)
3354 if (instance_expr.Type.IsValueType) {
3355 if (instance_expr is IMemoryLocation) {
3356 ((IMemoryLocation) instance_expr).AddressOf (ec, AddressOp.LoadStore);
3358 LocalTemporary t = new LocalTemporary (ec, instance_expr.Type);
3359 instance_expr.Emit (ec);
3361 t.AddressOf (ec, AddressOp.Store);
3364 instance_expr.Emit (ec);
3367 ec.ig.Emit (OpCodes.Dup);
3371 public void Emit (EmitContext ec, bool leave_copy)
3377 // Special case: length of single dimension array property is turned into ldlen
3379 if ((getter == TypeManager.system_int_array_get_length) ||
3380 (getter == TypeManager.int_array_get_length)){
3381 Type iet = instance_expr.Type;
3384 // System.Array.Length can be called, but the Type does not
3385 // support invoking GetArrayRank, so test for that case first
3387 if (iet != TypeManager.array_type && (iet.GetArrayRank () == 1)) {
3388 ec.ig.Emit (OpCodes.Ldlen);
3389 ec.ig.Emit (OpCodes.Conv_I4);
3394 Invocation.EmitCall (ec, IsBase, IsStatic, new EmptyAddressOf (), getter, null, loc);
3399 ec.ig.Emit (OpCodes.Dup);
3401 temp = new LocalTemporary (ec, this.Type);
3407 // Implements the IAssignMethod interface for assignments
3409 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
3411 prepared = prepare_for_load;
3417 ec.ig.Emit (OpCodes.Dup);
3419 temp = new LocalTemporary (ec, this.Type);
3424 ArrayList args = new ArrayList (1);
3425 args.Add (new Argument (new EmptyAddressOf (), Argument.AType.Expression));
3427 Invocation.EmitCall (ec, IsBase, IsStatic, new EmptyAddressOf (), setter, args, loc);
3433 override public void EmitStatement (EmitContext ec)
3436 ec.ig.Emit (OpCodes.Pop);
3441 /// Fully resolved expression that evaluates to an Event
3443 public class EventExpr : Expression, IMemberExpr {
3444 public readonly EventInfo EventInfo;
3445 Expression instance_expr;
3448 MethodInfo add_accessor, remove_accessor;
3450 public EventExpr (EventInfo ei, Location loc)
3454 eclass = ExprClass.EventAccess;
3456 add_accessor = TypeManager.GetAddMethod (ei);
3457 remove_accessor = TypeManager.GetRemoveMethod (ei);
3459 if (add_accessor.IsStatic || remove_accessor.IsStatic)
3462 if (EventInfo is MyEventBuilder){
3463 MyEventBuilder eb = (MyEventBuilder) EventInfo;
3464 type = eb.EventType;
3467 type = EventInfo.EventHandlerType;
3470 public string Name {
3472 return EventInfo.Name;
3476 public bool IsInstance {
3482 public bool IsStatic {
3488 public Type DeclaringType {
3490 return EventInfo.DeclaringType;
3494 public Expression InstanceExpression {
3496 return instance_expr;
3500 instance_expr = value;
3504 bool InstanceResolve (EmitContext ec, bool must_do_cs1540_check)
3506 if ((instance_expr == null) && ec.IsStatic && !is_static) {
3507 SimpleName.Error_ObjectRefRequired (ec, loc, EventInfo.Name);
3511 if (instance_expr != null) {
3512 instance_expr = instance_expr.DoResolve (ec);
3513 if (instance_expr == null)
3518 // This is using the same mechanism as the CS1540 check in PropertyExpr.
3519 // However, in the Event case, we reported a CS0122 instead.
3521 if (must_do_cs1540_check && (instance_expr != null)) {
3522 if ((instance_expr.Type != ec.ContainerType) &&
3523 ec.ContainerType.IsSubclassOf (instance_expr.Type)) {
3524 Report.Error (122, loc, "'{0}' is inaccessible due to its protection level",
3525 DeclaringType.Name + "." + EventInfo.Name);
3534 public override Expression DoResolve (EmitContext ec)
3536 if (instance_expr != null) {
3537 instance_expr = instance_expr.DoResolve (ec);
3538 if (instance_expr == null)
3542 bool must_do_cs1540_check;
3543 if (!(IsAccessorAccessible (ec.ContainerType, add_accessor, out must_do_cs1540_check)
3544 && IsAccessorAccessible (ec.ContainerType, remove_accessor, out must_do_cs1540_check))) {
3546 Report.Error (122, loc, "'{0}' is inaccessible due to its protection level",
3547 DeclaringType.Name + "." + EventInfo.Name);
3551 if (!InstanceResolve (ec, must_do_cs1540_check))
3557 public override void Emit (EmitContext ec)
3559 if (instance_expr is This)
3560 Report.Error (79, loc, "The event `{0}' can only appear on the left hand side of += or -=, try calling the actual delegate");
3562 Report.Error (70, loc, "The event `{0}' can only appear on the left hand side of += or -= "+
3563 "(except on the defining type)", Name);
3566 public void EmitAddOrRemove (EmitContext ec, Expression source)
3568 BinaryDelegate source_del = (BinaryDelegate) source;
3569 Expression handler = source_del.Right;
3571 Argument arg = new Argument (handler, Argument.AType.Expression);
3572 ArrayList args = new ArrayList ();
3576 if (source_del.IsAddition)
3577 Invocation.EmitCall (
3578 ec, false, IsStatic, instance_expr, add_accessor, args, loc);
3580 Invocation.EmitCall (
3581 ec, false, IsStatic, instance_expr, remove_accessor, args, loc);