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 virtual TypeExpr ResolveAsTypeTerminal (EmitContext ec)
327 int errors = Report.Errors;
329 TypeExpr te = ResolveAsTypeStep (ec) as TypeExpr;
331 if ((te == null) || (te.eclass != ExprClass.Type) || (te.Type == null)) {
332 if (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 ();
480 if ((e.type == null) && !(e is ConstructedType))
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 (
641 container_type, qualifier_type,queried_type, mt, bf, name,
642 almostMatchedMembers);
647 int count = mi.Length;
649 if (mi [0] is MethodBase)
650 return new MethodGroupExpr (mi, loc);
655 return ExprClassFromMemberInfo (ec, mi [0], loc);
658 public const MemberTypes AllMemberTypes =
659 MemberTypes.Constructor |
663 MemberTypes.NestedType |
664 MemberTypes.Property;
666 public const BindingFlags AllBindingFlags =
667 BindingFlags.Public |
668 BindingFlags.Static |
669 BindingFlags.Instance;
671 public static Expression MemberLookup (EmitContext ec, Type queried_type,
672 string name, Location loc)
674 return MemberLookup (ec, ec.ContainerType, null, queried_type, name,
675 AllMemberTypes, AllBindingFlags, loc);
678 public static Expression MemberLookup (EmitContext ec, Type qualifier_type,
679 Type queried_type, string name, Location loc)
681 return MemberLookup (ec, ec.ContainerType, qualifier_type, queried_type,
682 name, AllMemberTypes, AllBindingFlags, loc);
685 public static Expression MethodLookup (EmitContext ec, Type queried_type,
686 string name, Location loc)
688 return MemberLookup (ec, ec.ContainerType, null, queried_type, name,
689 MemberTypes.Method, AllBindingFlags, loc);
693 /// This is a wrapper for MemberLookup that is not used to "probe", but
694 /// to find a final definition. If the final definition is not found, we
695 /// look for private members and display a useful debugging message if we
698 public static Expression MemberLookupFinal (EmitContext ec, Type qualifier_type,
699 Type queried_type, string name,
702 return MemberLookupFinal (ec, qualifier_type, queried_type, name,
703 AllMemberTypes, AllBindingFlags, loc);
706 public static Expression MemberLookupFinal (EmitContext ec, Type qualifier_type,
707 Type queried_type, string name,
708 MemberTypes mt, BindingFlags bf,
713 int errors = Report.Errors;
715 e = MemberLookup (ec, ec.ContainerType, qualifier_type, queried_type,
718 if (e == null && errors == Report.Errors)
719 // No errors were reported by MemberLookup, but there was an error.
720 MemberLookupFailed (ec, qualifier_type, queried_type, name,
726 public static void MemberLookupFailed (EmitContext ec, Type qualifier_type,
727 Type queried_type, string name,
728 string class_name, Location loc)
730 if (almostMatchedMembers.Count != 0) {
731 if (qualifier_type == null) {
732 foreach (MemberInfo m in almostMatchedMembers)
733 Report.Error (38, loc,
734 "Cannot access non-static member `{0}' via nested type `{1}'",
735 TypeManager.GetFullNameSignature (m),
736 TypeManager.CSharpName (ec.ContainerType));
741 if (qualifier_type != ec.ContainerType) {
742 // Although a derived class can access protected members of
743 // its base class it cannot do so through an instance of the
744 // base class (CS1540). If the qualifier_type is a parent of the
745 // ec.ContainerType and the lookup succeeds with the latter one,
746 // then we are in this situation.
747 foreach (MemberInfo m in almostMatchedMembers)
748 Report.Error (1540, loc,
749 "Cannot access protected member `{0}' via a qualifier of type `{1}';"
750 + " the qualifier must be of type `{2}' (or derived from it)",
751 TypeManager.GetFullNameSignature (m),
752 TypeManager.CSharpName (qualifier_type),
753 TypeManager.CSharpName (ec.ContainerType));
756 almostMatchedMembers.Clear ();
759 MemberInfo[] mi = TypeManager.MemberLookup (queried_type, null, queried_type,
760 AllMemberTypes, AllBindingFlags |
761 BindingFlags.NonPublic, name, null);
764 if (class_name != null)
765 Report.Error (103, loc, "The name `" + name + "' could not be " +
766 "found in `" + class_name + "'");
769 117, loc, "`" + queried_type + "' does not contain a " +
770 "definition for `" + name + "'");
774 if (TypeManager.MemberLookup (queried_type, null, queried_type,
775 AllMemberTypes, AllBindingFlags |
776 BindingFlags.NonPublic, name, null) == null) {
777 if ((mi.Length == 1) && (mi [0] is Type)) {
778 Type t = (Type) mi [0];
780 Report.Error (305, loc,
781 "Using the generic type `{0}' " +
782 "requires {1} type arguments",
783 TypeManager.GetFullName (t),
784 TypeManager.GetNumberOfTypeArguments (t));
791 if (qualifier_type != null)
792 Report.Error (122, loc, "'{0}' is inaccessible due to its protection level", TypeManager.CSharpName (qualifier_type) + "." + name);
793 else if (name == ".ctor") {
794 Report.Error (143, loc, String.Format ("The type {0} has no constructors defined",
795 TypeManager.CSharpName (queried_type)));
797 Report.Error (122, loc, "'{0}' is inaccessible due to its protection level", name);
801 static public MemberInfo GetFieldFromEvent (EventExpr event_expr)
803 EventInfo ei = event_expr.EventInfo;
805 return TypeManager.GetPrivateFieldOfEvent (ei);
809 /// Returns an expression that can be used to invoke operator true
810 /// on the expression if it exists.
812 static public StaticCallExpr GetOperatorTrue (EmitContext ec, Expression e, Location loc)
814 return GetOperatorTrueOrFalse (ec, e, true, loc);
818 /// Returns an expression that can be used to invoke operator false
819 /// on the expression if it exists.
821 static public StaticCallExpr GetOperatorFalse (EmitContext ec, Expression e, Location loc)
823 return GetOperatorTrueOrFalse (ec, e, false, loc);
826 static StaticCallExpr GetOperatorTrueOrFalse (EmitContext ec, Expression e, bool is_true, Location loc)
829 Expression operator_group;
831 operator_group = MethodLookup (ec, e.Type, is_true ? "op_True" : "op_False", loc);
832 if (operator_group == null)
835 ArrayList arguments = new ArrayList ();
836 arguments.Add (new Argument (e, Argument.AType.Expression));
837 method = Invocation.OverloadResolve (
838 ec, (MethodGroupExpr) operator_group, arguments, false, loc);
843 return new StaticCallExpr ((MethodInfo) method, arguments, loc);
847 /// Resolves the expression `e' into a boolean expression: either through
848 /// an implicit conversion, or through an `operator true' invocation
850 public static Expression ResolveBoolean (EmitContext ec, Expression e, Location loc)
856 Expression converted = e;
857 if (e.Type != TypeManager.bool_type)
858 converted = Convert.ImplicitConversion (ec, e, TypeManager.bool_type, new Location (-1));
861 // If no implicit conversion to bool exists, try using `operator true'
863 if (converted == null){
864 Expression operator_true = Expression.GetOperatorTrue (ec, e, loc);
865 if (operator_true == null){
867 31, loc, "Can not convert the expression to a boolean");
877 static string ExprClassName (ExprClass c)
880 case ExprClass.Invalid:
882 case ExprClass.Value:
884 case ExprClass.Variable:
886 case ExprClass.Namespace:
890 case ExprClass.MethodGroup:
891 return "method group";
892 case ExprClass.PropertyAccess:
893 return "property access";
894 case ExprClass.EventAccess:
895 return "event access";
896 case ExprClass.IndexerAccess:
897 return "indexer access";
898 case ExprClass.Nothing:
901 throw new Exception ("Should not happen");
905 /// Reports that we were expecting `expr' to be of class `expected'
907 public void Error_UnexpectedKind (string expected, Location loc)
909 string kind = "Unknown";
911 kind = ExprClassName (eclass);
913 Report.Error (118, loc, "Expression denotes a `" + kind +
914 "' where a `" + expected + "' was expected");
917 public void Error_UnexpectedKind (ResolveFlags flags, Location loc)
919 ArrayList valid = new ArrayList (10);
921 if ((flags & ResolveFlags.VariableOrValue) != 0) {
922 valid.Add ("variable");
926 if ((flags & ResolveFlags.Type) != 0)
929 if ((flags & ResolveFlags.MethodGroup) != 0)
930 valid.Add ("method group");
932 if ((flags & ResolveFlags.SimpleName) != 0)
933 valid.Add ("simple name");
935 if (valid.Count == 0)
936 valid.Add ("unknown");
938 StringBuilder sb = new StringBuilder ();
939 for (int i = 0; i < valid.Count; i++) {
942 else if (i == valid.Count)
944 sb.Append (valid [i]);
947 string kind = ExprClassName (eclass);
949 Error (119, "Expression denotes a `" + kind + "' where " +
950 "a `" + sb.ToString () + "' was expected");
953 static public void Error_ConstantValueCannotBeConverted (Location l, string val, Type t)
955 Report.Error (31, l, "Constant value `" + val + "' cannot be converted to " +
956 TypeManager.CSharpName (t));
959 public static void UnsafeError (Location loc)
961 Report.Error (214, loc, "Pointers may only be used in an unsafe context");
965 /// Converts the IntConstant, UIntConstant, LongConstant or
966 /// ULongConstant into the integral target_type. Notice
967 /// that we do not return an `Expression' we do return
968 /// a boxed integral type.
970 /// FIXME: Since I added the new constants, we need to
971 /// also support conversions from CharConstant, ByteConstant,
972 /// SByteConstant, UShortConstant, ShortConstant
974 /// This is used by the switch statement, so the domain
975 /// of work is restricted to the literals above, and the
976 /// targets are int32, uint32, char, byte, sbyte, ushort,
977 /// short, uint64 and int64
979 public static object ConvertIntLiteral (Constant c, Type target_type, Location loc)
981 if (!Convert.ImplicitStandardConversionExists (Convert.ConstantEC, c, target_type)){
982 Convert.Error_CannotImplicitConversion (loc, c.Type, target_type);
988 if (c.Type == target_type)
989 return ((Constant) c).GetValue ();
992 // Make into one of the literals we handle, we dont really care
993 // about this value as we will just return a few limited types
995 if (c is EnumConstant)
996 c = ((EnumConstant)c).WidenToCompilerConstant ();
998 if (c is IntConstant){
999 int v = ((IntConstant) c).Value;
1001 if (target_type == TypeManager.uint32_type){
1004 } else if (target_type == TypeManager.char_type){
1005 if (v >= Char.MinValue && v <= Char.MaxValue)
1007 } else if (target_type == TypeManager.byte_type){
1008 if (v >= Byte.MinValue && v <= Byte.MaxValue)
1010 } else if (target_type == TypeManager.sbyte_type){
1011 if (v >= SByte.MinValue && v <= SByte.MaxValue)
1013 } else if (target_type == TypeManager.short_type){
1014 if (v >= Int16.MinValue && v <= UInt16.MaxValue)
1016 } else if (target_type == TypeManager.ushort_type){
1017 if (v >= UInt16.MinValue && v <= UInt16.MaxValue)
1019 } else if (target_type == TypeManager.int64_type)
1021 else if (target_type == TypeManager.uint64_type){
1027 } else if (c is UIntConstant){
1028 uint v = ((UIntConstant) c).Value;
1030 if (target_type == TypeManager.int32_type){
1031 if (v <= Int32.MaxValue)
1033 } else if (target_type == TypeManager.char_type){
1034 if (v >= Char.MinValue && v <= Char.MaxValue)
1036 } else if (target_type == TypeManager.byte_type){
1037 if (v <= Byte.MaxValue)
1039 } else if (target_type == TypeManager.sbyte_type){
1040 if (v <= SByte.MaxValue)
1042 } else if (target_type == TypeManager.short_type){
1043 if (v <= UInt16.MaxValue)
1045 } else if (target_type == TypeManager.ushort_type){
1046 if (v <= UInt16.MaxValue)
1048 } else if (target_type == TypeManager.int64_type)
1050 else if (target_type == TypeManager.uint64_type)
1053 } else if (c is LongConstant){
1054 long v = ((LongConstant) c).Value;
1056 if (target_type == TypeManager.int32_type){
1057 if (v >= UInt32.MinValue && v <= UInt32.MaxValue)
1059 } else if (target_type == TypeManager.uint32_type){
1060 if (v >= 0 && v <= UInt32.MaxValue)
1062 } else if (target_type == TypeManager.char_type){
1063 if (v >= Char.MinValue && v <= Char.MaxValue)
1065 } else if (target_type == TypeManager.byte_type){
1066 if (v >= Byte.MinValue && v <= Byte.MaxValue)
1068 } else if (target_type == TypeManager.sbyte_type){
1069 if (v >= SByte.MinValue && v <= SByte.MaxValue)
1071 } else if (target_type == TypeManager.short_type){
1072 if (v >= Int16.MinValue && v <= UInt16.MaxValue)
1074 } else if (target_type == TypeManager.ushort_type){
1075 if (v >= UInt16.MinValue && v <= UInt16.MaxValue)
1077 } else if (target_type == TypeManager.uint64_type){
1082 } else if (c is ULongConstant){
1083 ulong v = ((ULongConstant) c).Value;
1085 if (target_type == TypeManager.int32_type){
1086 if (v <= Int32.MaxValue)
1088 } else if (target_type == TypeManager.uint32_type){
1089 if (v <= UInt32.MaxValue)
1091 } else if (target_type == TypeManager.char_type){
1092 if (v >= Char.MinValue && v <= Char.MaxValue)
1094 } else if (target_type == TypeManager.byte_type){
1095 if (v >= Byte.MinValue && v <= Byte.MaxValue)
1097 } else if (target_type == TypeManager.sbyte_type){
1098 if (v <= (int) SByte.MaxValue)
1100 } else if (target_type == TypeManager.short_type){
1101 if (v <= UInt16.MaxValue)
1103 } else if (target_type == TypeManager.ushort_type){
1104 if (v <= UInt16.MaxValue)
1106 } else if (target_type == TypeManager.int64_type){
1107 if (v <= Int64.MaxValue)
1111 } else if (c is ByteConstant){
1112 byte v = ((ByteConstant) c).Value;
1114 if (target_type == TypeManager.int32_type)
1116 else if (target_type == TypeManager.uint32_type)
1118 else if (target_type == TypeManager.char_type)
1120 else if (target_type == TypeManager.sbyte_type){
1121 if (v <= SByte.MaxValue)
1123 } else if (target_type == TypeManager.short_type)
1125 else if (target_type == TypeManager.ushort_type)
1127 else if (target_type == TypeManager.int64_type)
1129 else if (target_type == TypeManager.uint64_type)
1132 } else if (c is SByteConstant){
1133 sbyte v = ((SByteConstant) c).Value;
1135 if (target_type == TypeManager.int32_type)
1137 else if (target_type == TypeManager.uint32_type){
1140 } else if (target_type == TypeManager.char_type){
1143 } else if (target_type == TypeManager.byte_type){
1146 } else if (target_type == TypeManager.short_type)
1148 else if (target_type == TypeManager.ushort_type){
1151 } else if (target_type == TypeManager.int64_type)
1153 else if (target_type == TypeManager.uint64_type){
1158 } else if (c is ShortConstant){
1159 short v = ((ShortConstant) c).Value;
1161 if (target_type == TypeManager.int32_type){
1163 } else if (target_type == TypeManager.uint32_type){
1166 } else if (target_type == TypeManager.char_type){
1169 } else if (target_type == TypeManager.byte_type){
1170 if (v >= Byte.MinValue && v <= Byte.MaxValue)
1172 } else if (target_type == TypeManager.sbyte_type){
1173 if (v >= SByte.MinValue && v <= SByte.MaxValue)
1175 } else if (target_type == TypeManager.ushort_type){
1178 } else if (target_type == TypeManager.int64_type)
1180 else if (target_type == TypeManager.uint64_type)
1184 } else if (c is UShortConstant){
1185 ushort v = ((UShortConstant) c).Value;
1187 if (target_type == TypeManager.int32_type)
1189 else if (target_type == TypeManager.uint32_type)
1191 else if (target_type == TypeManager.char_type){
1192 if (v >= Char.MinValue && v <= Char.MaxValue)
1194 } else if (target_type == TypeManager.byte_type){
1195 if (v >= Byte.MinValue && v <= Byte.MaxValue)
1197 } else if (target_type == TypeManager.sbyte_type){
1198 if (v <= SByte.MaxValue)
1200 } else if (target_type == TypeManager.short_type){
1201 if (v <= Int16.MaxValue)
1203 } else if (target_type == TypeManager.int64_type)
1205 else if (target_type == TypeManager.uint64_type)
1209 } else if (c is CharConstant){
1210 char v = ((CharConstant) c).Value;
1212 if (target_type == TypeManager.int32_type)
1214 else if (target_type == TypeManager.uint32_type)
1216 else if (target_type == TypeManager.byte_type){
1217 if (v >= Byte.MinValue && v <= Byte.MaxValue)
1219 } else if (target_type == TypeManager.sbyte_type){
1220 if (v <= SByte.MaxValue)
1222 } else if (target_type == TypeManager.short_type){
1223 if (v <= Int16.MaxValue)
1225 } else if (target_type == TypeManager.ushort_type)
1227 else if (target_type == TypeManager.int64_type)
1229 else if (target_type == TypeManager.uint64_type)
1234 Error_ConstantValueCannotBeConverted (loc, s, target_type);
1239 // Load the object from the pointer.
1241 public static void LoadFromPtr (ILGenerator ig, Type t)
1243 if (t == TypeManager.int32_type)
1244 ig.Emit (OpCodes.Ldind_I4);
1245 else if (t == TypeManager.uint32_type)
1246 ig.Emit (OpCodes.Ldind_U4);
1247 else if (t == TypeManager.short_type)
1248 ig.Emit (OpCodes.Ldind_I2);
1249 else if (t == TypeManager.ushort_type)
1250 ig.Emit (OpCodes.Ldind_U2);
1251 else if (t == TypeManager.char_type)
1252 ig.Emit (OpCodes.Ldind_U2);
1253 else if (t == TypeManager.byte_type)
1254 ig.Emit (OpCodes.Ldind_U1);
1255 else if (t == TypeManager.sbyte_type)
1256 ig.Emit (OpCodes.Ldind_I1);
1257 else if (t == TypeManager.uint64_type)
1258 ig.Emit (OpCodes.Ldind_I8);
1259 else if (t == TypeManager.int64_type)
1260 ig.Emit (OpCodes.Ldind_I8);
1261 else if (t == TypeManager.float_type)
1262 ig.Emit (OpCodes.Ldind_R4);
1263 else if (t == TypeManager.double_type)
1264 ig.Emit (OpCodes.Ldind_R8);
1265 else if (t == TypeManager.bool_type)
1266 ig.Emit (OpCodes.Ldind_I1);
1267 else if (t == TypeManager.intptr_type)
1268 ig.Emit (OpCodes.Ldind_I);
1269 else if (TypeManager.IsEnumType (t)) {
1270 if (t == TypeManager.enum_type)
1271 ig.Emit (OpCodes.Ldind_Ref);
1273 LoadFromPtr (ig, TypeManager.EnumToUnderlying (t));
1274 } else if (t.IsValueType || t.IsGenericParameter)
1275 ig.Emit (OpCodes.Ldobj, t);
1276 else if (t.IsPointer)
1277 ig.Emit (OpCodes.Ldind_I);
1279 ig.Emit (OpCodes.Ldind_Ref);
1283 // The stack contains the pointer and the value of type `type'
1285 public static void StoreFromPtr (ILGenerator ig, Type type)
1287 if (TypeManager.IsEnumType (type))
1288 type = TypeManager.EnumToUnderlying (type);
1289 if (type == TypeManager.int32_type || type == TypeManager.uint32_type)
1290 ig.Emit (OpCodes.Stind_I4);
1291 else if (type == TypeManager.int64_type || type == TypeManager.uint64_type)
1292 ig.Emit (OpCodes.Stind_I8);
1293 else if (type == TypeManager.char_type || type == TypeManager.short_type ||
1294 type == TypeManager.ushort_type)
1295 ig.Emit (OpCodes.Stind_I2);
1296 else if (type == TypeManager.float_type)
1297 ig.Emit (OpCodes.Stind_R4);
1298 else if (type == TypeManager.double_type)
1299 ig.Emit (OpCodes.Stind_R8);
1300 else if (type == TypeManager.byte_type || type == TypeManager.sbyte_type ||
1301 type == TypeManager.bool_type)
1302 ig.Emit (OpCodes.Stind_I1);
1303 else if (type == TypeManager.intptr_type)
1304 ig.Emit (OpCodes.Stind_I);
1305 else if (type.IsValueType || type.IsGenericParameter)
1306 ig.Emit (OpCodes.Stobj, type);
1308 ig.Emit (OpCodes.Stind_Ref);
1312 // Returns the size of type `t' if known, otherwise, 0
1314 public static int GetTypeSize (Type t)
1316 t = TypeManager.TypeToCoreType (t);
1317 if (t == TypeManager.int32_type ||
1318 t == TypeManager.uint32_type ||
1319 t == TypeManager.float_type)
1321 else if (t == TypeManager.int64_type ||
1322 t == TypeManager.uint64_type ||
1323 t == TypeManager.double_type)
1325 else if (t == TypeManager.byte_type ||
1326 t == TypeManager.sbyte_type ||
1327 t == TypeManager.bool_type)
1329 else if (t == TypeManager.short_type ||
1330 t == TypeManager.char_type ||
1331 t == TypeManager.ushort_type)
1333 else if (t == TypeManager.decimal_type)
1339 public static void Error_NegativeArrayIndex (Location loc)
1341 Report.Error (248, loc, "Cannot create an array with a negative size");
1345 // Converts `source' to an int, uint, long or ulong.
1347 public Expression ExpressionToArrayArgument (EmitContext ec, Expression source, Location loc)
1351 bool old_checked = ec.CheckState;
1352 ec.CheckState = true;
1354 target = Convert.ImplicitConversion (ec, source, TypeManager.int32_type, loc);
1355 if (target == null){
1356 target = Convert.ImplicitConversion (ec, source, TypeManager.uint32_type, loc);
1357 if (target == null){
1358 target = Convert.ImplicitConversion (ec, source, TypeManager.int64_type, loc);
1359 if (target == null){
1360 target = Convert.ImplicitConversion (ec, source, TypeManager.uint64_type, loc);
1362 Convert.Error_CannotImplicitConversion (loc, source.Type, TypeManager.int32_type);
1366 ec.CheckState = old_checked;
1369 // Only positive constants are allowed at compile time
1371 if (target is Constant){
1372 if (target is IntConstant){
1373 if (((IntConstant) target).Value < 0){
1374 Error_NegativeArrayIndex (loc);
1379 if (target is LongConstant){
1380 if (((LongConstant) target).Value < 0){
1381 Error_NegativeArrayIndex (loc);
1394 /// This is just a base class for expressions that can
1395 /// appear on statements (invocations, object creation,
1396 /// assignments, post/pre increment and decrement). The idea
1397 /// being that they would support an extra Emition interface that
1398 /// does not leave a result on the stack.
1400 public abstract class ExpressionStatement : Expression {
1402 public virtual ExpressionStatement ResolveStatement (EmitContext ec)
1404 Expression e = Resolve (ec);
1408 ExpressionStatement es = e as ExpressionStatement;
1410 Error (201, "Only assignment, call, increment, decrement and new object " +
1411 "expressions can be used as a statement");
1417 /// Requests the expression to be emitted in a `statement'
1418 /// context. This means that no new value is left on the
1419 /// stack after invoking this method (constrasted with
1420 /// Emit that will always leave a value on the stack).
1422 public abstract void EmitStatement (EmitContext ec);
1426 /// This kind of cast is used to encapsulate the child
1427 /// whose type is child.Type into an expression that is
1428 /// reported to return "return_type". This is used to encapsulate
1429 /// expressions which have compatible types, but need to be dealt
1430 /// at higher levels with.
1432 /// For example, a "byte" expression could be encapsulated in one
1433 /// of these as an "unsigned int". The type for the expression
1434 /// would be "unsigned int".
1437 public class EmptyCast : Expression {
1438 protected Expression child;
1440 public Expression Child {
1446 public EmptyCast (Expression child, Type return_type)
1448 eclass = child.eclass;
1453 public override Expression DoResolve (EmitContext ec)
1455 // This should never be invoked, we are born in fully
1456 // initialized state.
1461 public override void Emit (EmitContext ec)
1468 // We need to special case this since an empty cast of
1469 // a NullLiteral is still a Constant
1471 public class NullCast : Constant {
1472 protected Expression child;
1474 public NullCast (Expression child, Type return_type)
1476 eclass = child.eclass;
1481 override public string AsString ()
1486 public override object GetValue ()
1491 public override Expression DoResolve (EmitContext ec)
1493 // This should never be invoked, we are born in fully
1494 // initialized state.
1499 public override void Emit (EmitContext ec)
1504 public override bool IsNegative {
1513 /// This class is used to wrap literals which belong inside Enums
1515 public class EnumConstant : Constant {
1516 public Constant Child;
1518 public EnumConstant (Constant child, Type enum_type)
1520 eclass = child.eclass;
1525 public override Expression DoResolve (EmitContext ec)
1527 // This should never be invoked, we are born in fully
1528 // initialized state.
1533 public override void Emit (EmitContext ec)
1538 public override object GetValue ()
1540 return Child.GetValue ();
1543 public object GetValueAsEnumType ()
1545 return System.Enum.ToObject (type, Child.GetValue ());
1549 // Converts from one of the valid underlying types for an enumeration
1550 // (int32, uint32, int64, uint64, short, ushort, byte, sbyte) to
1551 // one of the internal compiler literals: Int/UInt/Long/ULong Literals.
1553 public Constant WidenToCompilerConstant ()
1555 Type t = TypeManager.EnumToUnderlying (Child.Type);
1556 object v = ((Constant) Child).GetValue ();;
1558 if (t == TypeManager.int32_type)
1559 return new IntConstant ((int) v);
1560 if (t == TypeManager.uint32_type)
1561 return new UIntConstant ((uint) v);
1562 if (t == TypeManager.int64_type)
1563 return new LongConstant ((long) v);
1564 if (t == TypeManager.uint64_type)
1565 return new ULongConstant ((ulong) v);
1566 if (t == TypeManager.short_type)
1567 return new ShortConstant ((short) v);
1568 if (t == TypeManager.ushort_type)
1569 return new UShortConstant ((ushort) v);
1570 if (t == TypeManager.byte_type)
1571 return new ByteConstant ((byte) v);
1572 if (t == TypeManager.sbyte_type)
1573 return new SByteConstant ((sbyte) v);
1575 throw new Exception ("Invalid enumeration underlying type: " + t);
1579 // Extracts the value in the enumeration on its native representation
1581 public object GetPlainValue ()
1583 Type t = TypeManager.EnumToUnderlying (Child.Type);
1584 object v = ((Constant) Child).GetValue ();;
1586 if (t == TypeManager.int32_type)
1588 if (t == TypeManager.uint32_type)
1590 if (t == TypeManager.int64_type)
1592 if (t == TypeManager.uint64_type)
1594 if (t == TypeManager.short_type)
1596 if (t == TypeManager.ushort_type)
1598 if (t == TypeManager.byte_type)
1600 if (t == TypeManager.sbyte_type)
1606 public override string AsString ()
1608 return Child.AsString ();
1611 public override DoubleConstant ConvertToDouble ()
1613 return Child.ConvertToDouble ();
1616 public override FloatConstant ConvertToFloat ()
1618 return Child.ConvertToFloat ();
1621 public override ULongConstant ConvertToULong ()
1623 return Child.ConvertToULong ();
1626 public override LongConstant ConvertToLong ()
1628 return Child.ConvertToLong ();
1631 public override UIntConstant ConvertToUInt ()
1633 return Child.ConvertToUInt ();
1636 public override IntConstant ConvertToInt ()
1638 return Child.ConvertToInt ();
1641 public override bool IsZeroInteger {
1642 get { return Child.IsZeroInteger; }
1645 public override bool IsNegative {
1647 return Child.IsNegative;
1653 /// This kind of cast is used to encapsulate Value Types in objects.
1655 /// The effect of it is to box the value type emitted by the previous
1658 public class BoxedCast : EmptyCast {
1660 public BoxedCast (Expression expr)
1661 : base (expr, TypeManager.object_type)
1663 eclass = ExprClass.Value;
1666 public BoxedCast (Expression expr, Type target_type)
1667 : base (expr, target_type)
1669 eclass = ExprClass.Value;
1672 public override Expression DoResolve (EmitContext ec)
1674 // This should never be invoked, we are born in fully
1675 // initialized state.
1680 public override void Emit (EmitContext ec)
1684 ec.ig.Emit (OpCodes.Box, child.Type);
1688 public class UnboxCast : EmptyCast {
1689 public UnboxCast (Expression expr, Type return_type)
1690 : base (expr, return_type)
1694 public override Expression DoResolve (EmitContext ec)
1696 // This should never be invoked, we are born in fully
1697 // initialized state.
1702 public override void Emit (EmitContext ec)
1705 ILGenerator ig = ec.ig;
1708 if (t.IsGenericParameter)
1709 ig.Emit (OpCodes.Unbox_Any, t);
1711 ig.Emit (OpCodes.Unbox, t);
1713 LoadFromPtr (ig, t);
1719 /// This is used to perform explicit numeric conversions.
1721 /// Explicit numeric conversions might trigger exceptions in a checked
1722 /// context, so they should generate the conv.ovf opcodes instead of
1725 public class ConvCast : EmptyCast {
1726 public enum Mode : byte {
1727 I1_U1, I1_U2, I1_U4, I1_U8, I1_CH,
1729 I2_I1, I2_U1, I2_U2, I2_U4, I2_U8, I2_CH,
1730 U2_I1, U2_U1, U2_I2, U2_CH,
1731 I4_I1, I4_U1, I4_I2, I4_U2, I4_U4, I4_U8, I4_CH,
1732 U4_I1, U4_U1, U4_I2, U4_U2, U4_I4, U4_CH,
1733 I8_I1, I8_U1, I8_I2, I8_U2, I8_I4, I8_U4, I8_U8, I8_CH,
1734 U8_I1, U8_U1, U8_I2, U8_U2, U8_I4, U8_U4, U8_I8, U8_CH,
1735 CH_I1, CH_U1, CH_I2,
1736 R4_I1, R4_U1, R4_I2, R4_U2, R4_I4, R4_U4, R4_I8, R4_U8, R4_CH,
1737 R8_I1, R8_U1, R8_I2, R8_U2, R8_I4, R8_U4, R8_I8, R8_U8, R8_CH, R8_R4
1743 public ConvCast (EmitContext ec, Expression child, Type return_type, Mode m)
1744 : base (child, return_type)
1746 checked_state = ec.CheckState;
1750 public override Expression DoResolve (EmitContext ec)
1752 // This should never be invoked, we are born in fully
1753 // initialized state.
1758 public override string ToString ()
1760 return String.Format ("ConvCast ({0}, {1})", mode, child);
1763 public override void Emit (EmitContext ec)
1765 ILGenerator ig = ec.ig;
1771 case Mode.I1_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1772 case Mode.I1_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1773 case Mode.I1_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1774 case Mode.I1_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1775 case Mode.I1_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1777 case Mode.U1_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1778 case Mode.U1_CH: /* nothing */ break;
1780 case Mode.I2_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1781 case Mode.I2_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1782 case Mode.I2_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1783 case Mode.I2_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1784 case Mode.I2_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1785 case Mode.I2_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1787 case Mode.U2_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1788 case Mode.U2_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
1789 case Mode.U2_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
1790 case Mode.U2_CH: /* nothing */ break;
1792 case Mode.I4_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1793 case Mode.I4_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1794 case Mode.I4_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
1795 case Mode.I4_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1796 case Mode.I4_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1797 case Mode.I4_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1798 case Mode.I4_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1800 case Mode.U4_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1801 case Mode.U4_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
1802 case Mode.U4_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
1803 case Mode.U4_U2: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
1804 case Mode.U4_I4: ig.Emit (OpCodes.Conv_Ovf_I4_Un); break;
1805 case Mode.U4_CH: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
1807 case Mode.I8_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1808 case Mode.I8_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1809 case Mode.I8_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
1810 case Mode.I8_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1811 case Mode.I8_I4: ig.Emit (OpCodes.Conv_Ovf_I4); break;
1812 case Mode.I8_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1813 case Mode.I8_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1814 case Mode.I8_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1816 case Mode.U8_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1817 case Mode.U8_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
1818 case Mode.U8_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
1819 case Mode.U8_U2: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
1820 case Mode.U8_I4: ig.Emit (OpCodes.Conv_Ovf_I4_Un); break;
1821 case Mode.U8_U4: ig.Emit (OpCodes.Conv_Ovf_U4_Un); break;
1822 case Mode.U8_I8: ig.Emit (OpCodes.Conv_Ovf_I8_Un); break;
1823 case Mode.U8_CH: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
1825 case Mode.CH_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1826 case Mode.CH_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
1827 case Mode.CH_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
1829 case Mode.R4_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1830 case Mode.R4_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1831 case Mode.R4_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
1832 case Mode.R4_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1833 case Mode.R4_I4: ig.Emit (OpCodes.Conv_Ovf_I4); break;
1834 case Mode.R4_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1835 case Mode.R4_I8: ig.Emit (OpCodes.Conv_Ovf_I8); break;
1836 case Mode.R4_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1837 case Mode.R4_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1839 case Mode.R8_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1840 case Mode.R8_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1841 case Mode.R8_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
1842 case Mode.R8_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1843 case Mode.R8_I4: ig.Emit (OpCodes.Conv_Ovf_I4); break;
1844 case Mode.R8_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1845 case Mode.R8_I8: ig.Emit (OpCodes.Conv_Ovf_I8); break;
1846 case Mode.R8_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1847 case Mode.R8_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1848 case Mode.R8_R4: ig.Emit (OpCodes.Conv_R4); break;
1852 case Mode.I1_U1: ig.Emit (OpCodes.Conv_U1); break;
1853 case Mode.I1_U2: ig.Emit (OpCodes.Conv_U2); break;
1854 case Mode.I1_U4: ig.Emit (OpCodes.Conv_U4); break;
1855 case Mode.I1_U8: ig.Emit (OpCodes.Conv_I8); break;
1856 case Mode.I1_CH: ig.Emit (OpCodes.Conv_U2); break;
1858 case Mode.U1_I1: ig.Emit (OpCodes.Conv_I1); break;
1859 case Mode.U1_CH: ig.Emit (OpCodes.Conv_U2); break;
1861 case Mode.I2_I1: ig.Emit (OpCodes.Conv_I1); break;
1862 case Mode.I2_U1: ig.Emit (OpCodes.Conv_U1); break;
1863 case Mode.I2_U2: ig.Emit (OpCodes.Conv_U2); break;
1864 case Mode.I2_U4: ig.Emit (OpCodes.Conv_U4); break;
1865 case Mode.I2_U8: ig.Emit (OpCodes.Conv_I8); break;
1866 case Mode.I2_CH: ig.Emit (OpCodes.Conv_U2); break;
1868 case Mode.U2_I1: ig.Emit (OpCodes.Conv_I1); break;
1869 case Mode.U2_U1: ig.Emit (OpCodes.Conv_U1); break;
1870 case Mode.U2_I2: ig.Emit (OpCodes.Conv_I2); break;
1871 case Mode.U2_CH: /* nothing */ break;
1873 case Mode.I4_I1: ig.Emit (OpCodes.Conv_I1); break;
1874 case Mode.I4_U1: ig.Emit (OpCodes.Conv_U1); break;
1875 case Mode.I4_I2: ig.Emit (OpCodes.Conv_I2); break;
1876 case Mode.I4_U4: /* nothing */ break;
1877 case Mode.I4_U2: ig.Emit (OpCodes.Conv_U2); break;
1878 case Mode.I4_U8: ig.Emit (OpCodes.Conv_I8); break;
1879 case Mode.I4_CH: ig.Emit (OpCodes.Conv_U2); break;
1881 case Mode.U4_I1: ig.Emit (OpCodes.Conv_I1); break;
1882 case Mode.U4_U1: ig.Emit (OpCodes.Conv_U1); break;
1883 case Mode.U4_I2: ig.Emit (OpCodes.Conv_I2); break;
1884 case Mode.U4_U2: ig.Emit (OpCodes.Conv_U2); break;
1885 case Mode.U4_I4: /* nothing */ break;
1886 case Mode.U4_CH: ig.Emit (OpCodes.Conv_U2); break;
1888 case Mode.I8_I1: ig.Emit (OpCodes.Conv_I1); break;
1889 case Mode.I8_U1: ig.Emit (OpCodes.Conv_U1); break;
1890 case Mode.I8_I2: ig.Emit (OpCodes.Conv_I2); break;
1891 case Mode.I8_U2: ig.Emit (OpCodes.Conv_U2); break;
1892 case Mode.I8_I4: ig.Emit (OpCodes.Conv_I4); break;
1893 case Mode.I8_U4: ig.Emit (OpCodes.Conv_U4); break;
1894 case Mode.I8_U8: /* nothing */ break;
1895 case Mode.I8_CH: ig.Emit (OpCodes.Conv_U2); break;
1897 case Mode.U8_I1: ig.Emit (OpCodes.Conv_I1); break;
1898 case Mode.U8_U1: ig.Emit (OpCodes.Conv_U1); break;
1899 case Mode.U8_I2: ig.Emit (OpCodes.Conv_I2); break;
1900 case Mode.U8_U2: ig.Emit (OpCodes.Conv_U2); break;
1901 case Mode.U8_I4: ig.Emit (OpCodes.Conv_I4); break;
1902 case Mode.U8_U4: ig.Emit (OpCodes.Conv_U4); break;
1903 case Mode.U8_I8: /* nothing */ break;
1904 case Mode.U8_CH: ig.Emit (OpCodes.Conv_U2); break;
1906 case Mode.CH_I1: ig.Emit (OpCodes.Conv_I1); break;
1907 case Mode.CH_U1: ig.Emit (OpCodes.Conv_U1); break;
1908 case Mode.CH_I2: ig.Emit (OpCodes.Conv_I2); break;
1910 case Mode.R4_I1: ig.Emit (OpCodes.Conv_I1); break;
1911 case Mode.R4_U1: ig.Emit (OpCodes.Conv_U1); break;
1912 case Mode.R4_I2: ig.Emit (OpCodes.Conv_I2); break;
1913 case Mode.R4_U2: ig.Emit (OpCodes.Conv_U2); break;
1914 case Mode.R4_I4: ig.Emit (OpCodes.Conv_I4); break;
1915 case Mode.R4_U4: ig.Emit (OpCodes.Conv_U4); break;
1916 case Mode.R4_I8: ig.Emit (OpCodes.Conv_I8); break;
1917 case Mode.R4_U8: ig.Emit (OpCodes.Conv_U8); break;
1918 case Mode.R4_CH: ig.Emit (OpCodes.Conv_U2); break;
1920 case Mode.R8_I1: ig.Emit (OpCodes.Conv_I1); break;
1921 case Mode.R8_U1: ig.Emit (OpCodes.Conv_U1); break;
1922 case Mode.R8_I2: ig.Emit (OpCodes.Conv_I2); break;
1923 case Mode.R8_U2: ig.Emit (OpCodes.Conv_U2); break;
1924 case Mode.R8_I4: ig.Emit (OpCodes.Conv_I4); break;
1925 case Mode.R8_U4: ig.Emit (OpCodes.Conv_U4); break;
1926 case Mode.R8_I8: ig.Emit (OpCodes.Conv_I8); break;
1927 case Mode.R8_U8: ig.Emit (OpCodes.Conv_U8); break;
1928 case Mode.R8_CH: ig.Emit (OpCodes.Conv_U2); break;
1929 case Mode.R8_R4: ig.Emit (OpCodes.Conv_R4); break;
1935 public class OpcodeCast : EmptyCast {
1939 public OpcodeCast (Expression child, Type return_type, OpCode op)
1940 : base (child, return_type)
1944 second_valid = false;
1947 public OpcodeCast (Expression child, Type return_type, OpCode op, OpCode op2)
1948 : base (child, return_type)
1953 second_valid = true;
1956 public override Expression DoResolve (EmitContext ec)
1958 // This should never be invoked, we are born in fully
1959 // initialized state.
1964 public override void Emit (EmitContext ec)
1975 /// This kind of cast is used to encapsulate a child and cast it
1976 /// to the class requested
1978 public class ClassCast : EmptyCast {
1979 public ClassCast (Expression child, Type return_type)
1980 : base (child, return_type)
1985 public override Expression DoResolve (EmitContext ec)
1987 // This should never be invoked, we are born in fully
1988 // initialized state.
1993 public override void Emit (EmitContext ec)
1997 if (child.Type.IsGenericParameter)
1998 ec.ig.Emit (OpCodes.Box, child.Type);
2000 if (type.IsGenericParameter)
2001 ec.ig.Emit (OpCodes.Unbox_Any, type);
2003 ec.ig.Emit (OpCodes.Castclass, type);
2008 /// SimpleName expressions are initially formed of a single
2009 /// word and it only happens at the beginning of the expression.
2013 /// The expression will try to be bound to a Field, a Method
2014 /// group or a Property. If those fail we pass the name to our
2015 /// caller and the SimpleName is compounded to perform a type
2016 /// lookup. The idea behind this process is that we want to avoid
2017 /// creating a namespace map from the assemblies, as that requires
2018 /// the GetExportedTypes function to be called and a hashtable to
2019 /// be constructed which reduces startup time. If later we find
2020 /// that this is slower, we should create a `NamespaceExpr' expression
2021 /// that fully participates in the resolution process.
2023 /// For example `System.Console.WriteLine' is decomposed into
2024 /// MemberAccess (MemberAccess (SimpleName ("System"), "Console"), "WriteLine")
2026 /// The first SimpleName wont produce a match on its own, so it will
2028 /// MemberAccess (SimpleName ("System.Console"), "WriteLine").
2030 /// System.Console will produce a TypeExpr match.
2032 /// The downside of this is that we might be hitting `LookupType' too many
2033 /// times with this scheme.
2035 public class SimpleName : Expression {
2037 public readonly TypeArguments Arguments;
2040 // If true, then we are a simple name, not composed with a ".
2044 public SimpleName (string a, string b, Location l)
2046 Name = String.Concat (a, ".", b);
2051 public SimpleName (string name, Location l)
2058 public SimpleName (string name, TypeArguments args, Location l)
2066 public static void Error_ObjectRefRequired (EmitContext ec, Location l, string name)
2068 if (ec.IsFieldInitializer)
2071 "A field initializer cannot reference the non-static field, " +
2072 "method or property `"+name+"'");
2076 "An object reference is required " +
2077 "for the non-static field `"+name+"'");
2081 // Checks whether we are trying to access an instance
2082 // property, method or field from a static body.
2084 Expression MemberStaticCheck (EmitContext ec, Expression e)
2086 if (e is IMemberExpr){
2087 IMemberExpr member = (IMemberExpr) e;
2089 if (!member.IsStatic){
2090 Error_ObjectRefRequired (ec, loc, Name);
2098 public override Expression DoResolve (EmitContext ec)
2100 return SimpleNameResolve (ec, null, false, false);
2103 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
2105 return SimpleNameResolve (ec, right_side, false, false);
2109 public Expression DoResolveAllowStatic (EmitContext ec, bool intermediate)
2111 return SimpleNameResolve (ec, null, true, intermediate);
2114 public override Expression ResolveAsTypeStep (EmitContext ec)
2116 DeclSpace ds = ec.DeclSpace;
2117 NamespaceEntry ns = ds.NamespaceEntry;
2122 // Since we are cheating: we only do the Alias lookup for
2123 // namespaces if the name does not include any dots in it
2125 if (ns != null && is_base)
2126 alias_value = ns.LookupAlias (Name);
2130 TypeParameterExpr generic_type = ds.LookupGeneric (Name, loc);
2131 if (generic_type != null)
2132 return generic_type.ResolveAsTypeTerminal (ec);
2134 if (ec.ResolvingTypeTree){
2135 int errors = Report.Errors;
2136 Type dt = ds.FindType (loc, Name);
2138 if (Report.Errors != errors)
2142 return new TypeExpression (dt, loc);
2144 if (alias_value != null){
2145 if (alias_value.IsType)
2146 return alias_value.ResolveAsType (ec);
2147 if ((t = RootContext.LookupType (ds, alias_value.Name, true, loc)) != null)
2148 return new TypeExpression (t, loc);
2152 if ((t = RootContext.LookupType (ds, Name, true, loc)) != null)
2153 return new TypeExpression (t, loc);
2155 if (alias_value != null) {
2156 if (alias_value.IsType)
2157 return alias_value.ResolveAsType (ec);
2158 if ((t = RootContext.LookupType (ds, alias_value.Name, true, loc)) != null)
2159 return new TypeExpression (t, loc);
2161 // we have alias value, but it isn't Type, so try if it's namespace
2162 return new SimpleName (alias_value.Name, loc);
2165 // No match, maybe our parent can compose us
2166 // into something meaningful.
2170 Expression SimpleNameResolve (EmitContext ec, Expression right_side,
2171 bool allow_static, bool intermediate)
2173 Expression e = DoSimpleNameResolve (ec, right_side, allow_static, intermediate);
2177 Block current_block = ec.CurrentBlock;
2178 if (current_block != null){
2179 //LocalInfo vi = current_block.GetLocalInfo (Name);
2181 current_block.IsVariableNameUsedInChildBlock(Name)) {
2182 Report.Error (135, Location,
2183 "'{0}' has a different meaning in a " +
2184 "child block", Name);
2189 if (e.Type != null && e.Type.IsPointer && !ec.InUnsafe) {
2198 /// 7.5.2: Simple Names.
2200 /// Local Variables and Parameters are handled at
2201 /// parse time, so they never occur as SimpleNames.
2203 /// The `allow_static' flag is used by MemberAccess only
2204 /// and it is used to inform us that it is ok for us to
2205 /// avoid the static check, because MemberAccess might end
2206 /// up resolving the Name as a Type name and the access as
2207 /// a static type access.
2209 /// ie: Type Type; .... { Type.GetType (""); }
2211 /// Type is both an instance variable and a Type; Type.GetType
2212 /// is the static method not an instance method of type.
2214 Expression DoSimpleNameResolve (EmitContext ec, Expression right_side, bool allow_static, bool intermediate)
2216 Expression e = null;
2219 // Stage 1: Performed by the parser (binding to locals or parameters).
2221 Block current_block = ec.CurrentBlock;
2222 if (current_block != null){
2223 LocalInfo vi = current_block.GetLocalInfo (Name);
2227 var = new LocalVariableReference (ec.CurrentBlock, Name, loc);
2229 if (right_side != null)
2230 return var.ResolveLValue (ec, right_side);
2232 return var.Resolve (ec);
2235 ParameterReference pref = current_block.GetParameterReference (Name, loc);
2237 if (right_side != null)
2238 return pref.ResolveLValue (ec, right_side);
2240 return pref.Resolve (ec);
2245 // Stage 2: Lookup members
2248 DeclSpace lookup_ds = ec.DeclSpace;
2250 if (lookup_ds.TypeBuilder == null)
2253 e = MemberLookup (ec, lookup_ds.TypeBuilder, Name, loc);
2257 lookup_ds =lookup_ds.Parent;
2258 } while (lookup_ds != null);
2260 if (e == null && ec.ContainerType != null)
2261 e = MemberLookup (ec, ec.ContainerType, Name, loc);
2265 // Since we are cheating (is_base is our hint
2266 // that we are the beginning of the name): we
2267 // only do the Alias lookup for namespaces if
2268 // the name does not include any dots in it
2270 NamespaceEntry ns = ec.DeclSpace.NamespaceEntry;
2271 if (is_base && ns != null){
2272 IAlias alias_value = ns.LookupAlias (Name);
2273 if (alias_value != null){
2274 if (alias_value.IsType)
2275 return alias_value.ResolveAsType (ec);
2277 Name = alias_value.Name;
2280 if ((t = TypeManager.LookupType (Name)) != null)
2281 return new TypeExpression (t, loc);
2283 // No match, maybe our parent can compose us
2284 // into something meaningful.
2289 return ResolveAsTypeStep (ec);
2295 if (e is IMemberExpr) {
2296 e = MemberAccess.ResolveMemberAccess (ec, e, null, loc, this);
2300 IMemberExpr me = e as IMemberExpr;
2304 if (Arguments != null) {
2305 MethodGroupExpr mg = me as MethodGroupExpr;
2309 return mg.ResolveGeneric (ec, Arguments);
2312 // This fails if ResolveMemberAccess() was unable to decide whether
2313 // it's a field or a type of the same name.
2315 if (!me.IsStatic && (me.InstanceExpression == null))
2319 TypeManager.IsNestedFamilyAccessible (me.InstanceExpression.Type, me.DeclaringType) &&
2320 me.InstanceExpression.Type != me.DeclaringType &&
2321 !TypeManager.IsFamilyAccessible (me.InstanceExpression.Type, me.DeclaringType) &&
2322 (!intermediate || !MemberAccess.IdenticalNameAndTypeName (ec, this, e, loc))) {
2323 Error (38, "Cannot access nonstatic member `" + me.Name + "' of " +
2324 "outer type `" + me.DeclaringType + "' via nested type `" +
2325 me.InstanceExpression.Type + "'");
2329 return (right_side != null)
2330 ? e.DoResolveLValue (ec, right_side)
2334 if (ec.IsStatic || ec.IsFieldInitializer){
2338 return MemberStaticCheck (ec, e);
2343 public override void Emit (EmitContext ec)
2346 // If this is ever reached, then we failed to
2347 // find the name as a namespace
2350 Error (103, "The name `" + Name +
2351 "' does not exist in the class `" +
2352 ec.DeclSpace.Name + "'");
2355 public override string ToString ()
2362 /// Fully resolved expression that evaluates to a type
2364 public abstract class TypeExpr : Expression, IAlias {
2365 override public Expression ResolveAsTypeStep (EmitContext ec)
2367 TypeExpr t = DoResolveAsTypeStep (ec);
2371 eclass = ExprClass.Type;
2375 override public Expression DoResolve (EmitContext ec)
2377 return ResolveAsTypeTerminal (ec);
2380 override public void Emit (EmitContext ec)
2382 throw new Exception ("Should never be called");
2385 public virtual bool CheckAccessLevel (DeclSpace ds)
2387 return ds.CheckAccessLevel (Type);
2390 public virtual bool AsAccessible (DeclSpace ds, int flags)
2392 return ds.AsAccessible (Type, flags);
2395 public virtual bool IsClass {
2396 get { return Type.IsClass; }
2399 public virtual bool IsValueType {
2400 get { return Type.IsValueType; }
2403 public virtual bool IsInterface {
2404 get { return Type.IsInterface; }
2407 public virtual bool IsSealed {
2408 get { return Type.IsSealed; }
2411 public virtual bool CanInheritFrom ()
2413 if (Type == TypeManager.enum_type ||
2414 (Type == TypeManager.value_type && RootContext.StdLib) ||
2415 Type == TypeManager.multicast_delegate_type ||
2416 Type == TypeManager.delegate_type ||
2417 Type == TypeManager.array_type)
2423 public virtual bool IsAttribute {
2425 return Type == TypeManager.attribute_type ||
2426 Type.IsSubclassOf (TypeManager.attribute_type);
2430 protected abstract TypeExpr DoResolveAsTypeStep (EmitContext ec);
2432 public abstract string Name {
2436 public override bool Equals (object obj)
2438 TypeExpr tobj = obj as TypeExpr;
2442 return Type == tobj.Type;
2445 public override int GetHashCode ()
2447 return Type.GetHashCode ();
2450 public override string ToString ()
2455 bool IAlias.IsType {
2456 get { return true; }
2459 TypeExpr IAlias.ResolveAsType (EmitContext ec)
2461 return ResolveAsTypeTerminal (ec);
2465 public class TypeExpression : TypeExpr, IAlias {
2466 public TypeExpression (Type t, Location l)
2469 eclass = ExprClass.Type;
2473 protected override TypeExpr DoResolveAsTypeStep (EmitContext ec)
2478 public override string Name {
2480 return Type.ToString ();
2484 string IAlias.Name {
2486 return Type.FullName != null ? Type.FullName : Type.Name;
2492 /// Used to create types from a fully qualified name. These are just used
2493 /// by the parser to setup the core types. A TypeLookupExpression is always
2494 /// classified as a type.
2496 public class TypeLookupExpression : TypeExpr {
2499 public TypeLookupExpression (string name)
2504 protected override TypeExpr DoResolveAsTypeStep (EmitContext ec)
2507 type = RootContext.LookupType (
2508 ec.DeclSpace, name, false, Location.Null);
2516 public override string Name {
2524 /// Represents an "unbound generic type", ie. typeof (Foo<>).
2527 public class UnboundTypeExpression : TypeLookupExpression {
2528 public UnboundTypeExpression (string name)
2533 public class TypeAliasExpression : TypeExpr, IAlias {
2539 public TypeAliasExpression (IAlias alias, TypeArguments args, Location l)
2545 eclass = ExprClass.Type;
2547 name = alias.Name + "<" + args.ToString () + ">";
2552 public override string Name {
2553 get { return name; }
2556 protected override TypeExpr DoResolveAsTypeStep (EmitContext ec)
2558 texpr = alias.ResolveAsType (ec);
2562 Type type = texpr.Type;
2563 int num_args = TypeManager.GetNumberOfTypeArguments (type);
2566 if (num_args == 0) {
2567 Report.Error (308, loc,
2568 "The non-generic type `{0}' cannot " +
2569 "be used with type arguments.",
2570 TypeManager.CSharpName (type));
2574 ConstructedType ctype = new ConstructedType (type, args, loc);
2575 return ctype.ResolveAsTypeTerminal (ec);
2576 } else if (num_args > 0) {
2577 Report.Error (305, loc,
2578 "Using the generic type `{0}' " +
2579 "requires {1} type arguments",
2580 TypeManager.GetFullName (type), num_args);
2584 return new TypeExpression (type, loc);
2587 public override bool CheckAccessLevel (DeclSpace ds)
2589 return texpr.CheckAccessLevel (ds);
2592 public override bool AsAccessible (DeclSpace ds, int flags)
2594 return texpr.AsAccessible (ds, flags);
2597 public override bool IsClass {
2598 get { return texpr.IsClass; }
2601 public override bool IsValueType {
2602 get { return texpr.IsValueType; }
2605 public override bool IsInterface {
2606 get { return texpr.IsInterface; }
2609 public override bool IsSealed {
2610 get { return texpr.IsSealed; }
2613 public override bool IsAttribute {
2614 get { return texpr.IsAttribute; }
2619 /// MethodGroup Expression.
2621 /// This is a fully resolved expression that evaluates to a type
2623 public class MethodGroupExpr : Expression, IMemberExpr {
2624 public MethodBase [] Methods;
2625 Expression instance_expression = null;
2626 bool is_explicit_impl = false;
2627 bool has_type_arguments = false;
2628 bool identical_type_name = false;
2631 public MethodGroupExpr (MemberInfo [] mi, Location l)
2633 Methods = new MethodBase [mi.Length];
2634 mi.CopyTo (Methods, 0);
2635 eclass = ExprClass.MethodGroup;
2636 type = TypeManager.object_type;
2640 public MethodGroupExpr (ArrayList list, Location l)
2642 Methods = new MethodBase [list.Count];
2645 list.CopyTo (Methods, 0);
2647 foreach (MemberInfo m in list){
2648 if (!(m is MethodBase)){
2649 Console.WriteLine ("Name " + m.Name);
2650 Console.WriteLine ("Found a: " + m.GetType ().FullName);
2657 eclass = ExprClass.MethodGroup;
2658 type = TypeManager.object_type;
2661 public Type DeclaringType {
2664 // We assume that the top-level type is in the end
2666 return Methods [Methods.Length - 1].DeclaringType;
2667 //return Methods [0].DeclaringType;
2672 // `A method group may have associated an instance expression'
2674 public Expression InstanceExpression {
2676 return instance_expression;
2680 instance_expression = value;
2684 public bool IsExplicitImpl {
2686 return is_explicit_impl;
2690 is_explicit_impl = value;
2694 public bool HasTypeArguments {
2696 return has_type_arguments;
2700 has_type_arguments = value;
2704 public bool IdenticalTypeName {
2706 return identical_type_name;
2710 identical_type_name = value;
2714 public bool IsBase {
2723 public string Name {
2725 //return Methods [0].Name;
2726 return Methods [Methods.Length - 1].Name;
2730 public bool IsInstance {
2732 foreach (MethodBase mb in Methods)
2740 public bool IsStatic {
2742 foreach (MethodBase mb in Methods)
2750 override public Expression DoResolve (EmitContext ec)
2753 instance_expression = null;
2755 if (instance_expression != null) {
2756 instance_expression = instance_expression.DoResolve (ec);
2757 if (instance_expression == null)
2764 public void ReportUsageError ()
2766 Report.Error (654, loc, "Method `" + DeclaringType + "." +
2767 Name + "()' is referenced without parentheses");
2770 override public void Emit (EmitContext ec)
2772 ReportUsageError ();
2775 bool RemoveMethods (bool keep_static)
2777 ArrayList smethods = new ArrayList ();
2779 foreach (MethodBase mb in Methods){
2780 if (mb.IsStatic == keep_static)
2784 if (smethods.Count == 0)
2787 Methods = new MethodBase [smethods.Count];
2788 smethods.CopyTo (Methods, 0);
2794 /// Removes any instance methods from the MethodGroup, returns
2795 /// false if the resulting set is empty.
2797 public bool RemoveInstanceMethods ()
2799 return RemoveMethods (true);
2803 /// Removes any static methods from the MethodGroup, returns
2804 /// false if the resulting set is empty.
2806 public bool RemoveStaticMethods ()
2808 return RemoveMethods (false);
2811 public Expression ResolveGeneric (EmitContext ec, TypeArguments args)
2813 if (args.Resolve (ec) == false)
2816 Type[] atypes = args.Arguments;
2818 int first_count = 0;
2819 MethodInfo first = null;
2821 ArrayList list = new ArrayList ();
2822 foreach (MethodBase mb in Methods) {
2823 MethodInfo mi = mb as MethodInfo;
2824 if ((mi == null) || !mi.HasGenericParameters)
2827 Type[] gen_params = mi.GetGenericArguments ();
2829 if (first == null) {
2831 first_count = gen_params.Length;
2834 if (gen_params.Length != atypes.Length)
2837 list.Add (mi.BindGenericParameters (atypes));
2840 if (list.Count > 0) {
2841 MethodGroupExpr new_mg = new MethodGroupExpr (list, Location);
2842 new_mg.InstanceExpression = InstanceExpression;
2843 new_mg.HasTypeArguments = true;
2849 305, loc, "Using the generic method `{0}' " +
2850 "requires {1} type arguments", Name,
2854 308, loc, "The non-generic method `{0}' " +
2855 "cannot be used with type arguments", Name);
2862 /// Fully resolved expression that evaluates to a Field
2864 public class FieldExpr : Expression, IAssignMethod, IMemoryLocation, IMemberExpr, IVariable {
2865 public readonly FieldInfo FieldInfo;
2866 Expression instance_expr;
2867 VariableInfo variable_info;
2869 LocalTemporary temp;
2871 bool is_field_initializer;
2873 public FieldExpr (FieldInfo fi, Location l)
2876 eclass = ExprClass.Variable;
2877 type = TypeManager.TypeToCoreType (fi.FieldType);
2881 public string Name {
2883 return FieldInfo.Name;
2887 public bool IsInstance {
2889 return !FieldInfo.IsStatic;
2893 public bool IsStatic {
2895 return FieldInfo.IsStatic;
2899 public Type DeclaringType {
2901 return FieldInfo.DeclaringType;
2905 public Expression InstanceExpression {
2907 return instance_expr;
2911 instance_expr = value;
2915 public bool IsFieldInitializer {
2917 return is_field_initializer;
2921 is_field_initializer = value;
2925 public VariableInfo VariableInfo {
2927 return variable_info;
2931 override public Expression DoResolve (EmitContext ec)
2933 if (!FieldInfo.IsStatic){
2934 if (instance_expr == null){
2936 // This can happen when referencing an instance field using
2937 // a fully qualified type expression: TypeName.InstanceField = xxx
2939 SimpleName.Error_ObjectRefRequired (ec, loc, FieldInfo.Name);
2943 // Resolve the field's instance expression while flow analysis is turned
2944 // off: when accessing a field "a.b", we must check whether the field
2945 // "a.b" is initialized, not whether the whole struct "a" is initialized.
2946 instance_expr = instance_expr.Resolve (ec, ResolveFlags.VariableOrValue |
2947 ResolveFlags.DisableFlowAnalysis);
2948 if (instance_expr == null)
2952 ObsoleteAttribute oa;
2953 FieldBase f = TypeManager.GetField (FieldInfo);
2955 oa = f.GetObsoleteAttribute (f.Parent);
2957 AttributeTester.Report_ObsoleteMessage (oa, f.GetSignatureForError (), loc);
2958 // To be sure that type is external because we do not register generated fields
2959 } else if (!(FieldInfo.DeclaringType is TypeBuilder)) {
2960 oa = AttributeTester.GetMemberObsoleteAttribute (FieldInfo);
2962 AttributeTester.Report_ObsoleteMessage (oa, TypeManager.GetFullNameSignature (FieldInfo), loc);
2965 if (ec.CurrentAnonymousMethod != null){
2966 if (!FieldInfo.IsStatic){
2967 if (ec.TypeContainer is Struct){
2968 Report.Error (1673, loc, "Can not reference instance variables in anonymous methods hosted in structs");
2971 ec.CaptureField (this);
2975 // If the instance expression is a local variable or parameter.
2976 IVariable var = instance_expr as IVariable;
2977 if ((var == null) || (var.VariableInfo == null))
2980 VariableInfo vi = var.VariableInfo;
2981 if (!vi.IsFieldAssigned (ec, FieldInfo.Name, loc))
2984 variable_info = vi.GetSubStruct (FieldInfo.Name);
2988 void Report_AssignToReadonly (bool is_instance)
2993 msg = "Readonly field can not be assigned outside " +
2994 "of constructor or variable initializer";
2996 msg = "A static readonly field can only be assigned in " +
2997 "a static constructor";
2999 Report.Error (is_instance ? 191 : 198, loc, msg);
3002 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
3004 IVariable var = instance_expr as IVariable;
3005 if ((var != null) && (var.VariableInfo != null))
3006 var.VariableInfo.SetFieldAssigned (ec, FieldInfo.Name);
3008 Expression e = DoResolve (ec);
3013 if (!FieldInfo.IsStatic && (instance_expr.Type.IsValueType && !(instance_expr is IMemoryLocation))) {
3014 // FIXME: Provide better error reporting.
3015 Error (1612, "Cannot modify expression because it is not a variable.");
3019 if (!FieldInfo.IsInitOnly)
3022 FieldBase fb = TypeManager.GetField (FieldInfo);
3027 // InitOnly fields can only be assigned in constructors
3030 if (ec.IsConstructor){
3031 if (IsStatic && !ec.IsStatic)
3032 Report_AssignToReadonly (false);
3035 if (!is_field_initializer &&
3036 (ec.TypeContainer.CurrentType != null))
3037 ctype = ec.TypeContainer.CurrentType;
3039 ctype = ec.ContainerType;
3041 if (TypeManager.IsEqual (ctype, FieldInfo.DeclaringType))
3045 Report_AssignToReadonly (!IsStatic);
3050 public override void CheckMarshallByRefAccess (Type container)
3052 if (!IsStatic && Type.IsValueType && !container.IsSubclassOf (TypeManager.mbr_type) && DeclaringType.IsSubclassOf (TypeManager.mbr_type)) {
3053 Report.SymbolRelatedToPreviousError (DeclaringType);
3054 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);
3058 public bool VerifyFixed (bool is_expression)
3060 IVariable variable = instance_expr as IVariable;
3061 if ((variable == null) || !variable.VerifyFixed (true))
3067 public void Emit (EmitContext ec, bool leave_copy)
3069 ILGenerator ig = ec.ig;
3070 bool is_volatile = false;
3072 if (FieldInfo is FieldBuilder){
3073 FieldBase f = TypeManager.GetField (FieldInfo);
3075 if ((f.ModFlags & Modifiers.VOLATILE) != 0)
3078 f.status |= Field.Status.USED;
3082 if (FieldInfo.IsStatic){
3084 ig.Emit (OpCodes.Volatile);
3086 ig.Emit (OpCodes.Ldsfld, FieldInfo);
3092 ig.Emit (OpCodes.Volatile);
3094 ig.Emit (OpCodes.Ldfld, FieldInfo);
3098 ec.ig.Emit (OpCodes.Dup);
3099 if (!FieldInfo.IsStatic) {
3100 temp = new LocalTemporary (ec, this.Type);
3106 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
3108 FieldAttributes fa = FieldInfo.Attributes;
3109 bool is_static = (fa & FieldAttributes.Static) != 0;
3110 bool is_readonly = (fa & FieldAttributes.InitOnly) != 0;
3111 ILGenerator ig = ec.ig;
3112 prepared = prepare_for_load;
3114 if (is_readonly && !ec.IsConstructor){
3115 Report_AssignToReadonly (!is_static);
3121 if (prepare_for_load)
3122 ig.Emit (OpCodes.Dup);
3127 ec.ig.Emit (OpCodes.Dup);
3128 if (!FieldInfo.IsStatic) {
3129 temp = new LocalTemporary (ec, this.Type);
3134 if (FieldInfo is FieldBuilder){
3135 FieldBase f = TypeManager.GetField (FieldInfo);
3137 if ((f.ModFlags & Modifiers.VOLATILE) != 0)
3138 ig.Emit (OpCodes.Volatile);
3140 f.status |= Field.Status.ASSIGNED;
3145 ig.Emit (OpCodes.Stsfld, FieldInfo);
3147 ig.Emit (OpCodes.Stfld, FieldInfo);
3153 void EmitInstance (EmitContext ec)
3155 if (instance_expr.Type.IsValueType) {
3156 if (instance_expr is IMemoryLocation) {
3157 ((IMemoryLocation) instance_expr).AddressOf (ec, AddressOp.LoadStore);
3159 LocalTemporary t = new LocalTemporary (ec, instance_expr.Type);
3160 instance_expr.Emit (ec);
3162 t.AddressOf (ec, AddressOp.Store);
3165 instance_expr.Emit (ec);
3168 public override void Emit (EmitContext ec)
3173 public void AddressOf (EmitContext ec, AddressOp mode)
3175 ILGenerator ig = ec.ig;
3177 if (FieldInfo is FieldBuilder){
3178 FieldBase f = TypeManager.GetField (FieldInfo);
3180 if ((f.ModFlags & Modifiers.VOLATILE) != 0){
3181 Error (676, "volatile variable: can not take its address, or pass as ref/out parameter");
3185 if ((mode & AddressOp.Store) != 0)
3186 f.status |= Field.Status.ASSIGNED;
3187 if ((mode & AddressOp.Load) != 0)
3188 f.status |= Field.Status.USED;
3193 // Handle initonly fields specially: make a copy and then
3194 // get the address of the copy.
3197 if (FieldInfo.IsInitOnly){
3199 if (ec.IsConstructor){
3200 if (FieldInfo.IsStatic){
3212 local = ig.DeclareLocal (type);
3213 ig.Emit (OpCodes.Stloc, local);
3214 ig.Emit (OpCodes.Ldloca, local);
3219 if (FieldInfo.IsStatic){
3220 ig.Emit (OpCodes.Ldsflda, FieldInfo);
3223 ig.Emit (OpCodes.Ldflda, FieldInfo);
3229 // A FieldExpr whose address can not be taken
3231 public class FieldExprNoAddress : FieldExpr, IMemoryLocation {
3232 public FieldExprNoAddress (FieldInfo fi, Location loc) : base (fi, loc)
3236 public new void AddressOf (EmitContext ec, AddressOp mode)
3238 Report.Error (-215, "Report this: Taking the address of a remapped parameter not supported");
3243 /// Expression that evaluates to a Property. The Assign class
3244 /// might set the `Value' expression if we are in an assignment.
3246 /// This is not an LValue because we need to re-write the expression, we
3247 /// can not take data from the stack and store it.
3249 public class PropertyExpr : ExpressionStatement, IAssignMethod, IMemberExpr {
3250 public readonly PropertyInfo PropertyInfo;
3253 // This is set externally by the `BaseAccess' class
3256 MethodInfo getter, setter;
3259 Expression instance_expr;
3260 LocalTemporary temp;
3263 public PropertyExpr (EmitContext ec, PropertyInfo pi, Location l)
3266 eclass = ExprClass.PropertyAccess;
3270 type = TypeManager.TypeToCoreType (pi.PropertyType);
3272 ResolveAccessors (ec);
3275 public string Name {
3277 return PropertyInfo.Name;
3281 public bool IsInstance {
3287 public bool IsStatic {
3293 public Type DeclaringType {
3295 return PropertyInfo.DeclaringType;
3300 // The instance expression associated with this expression
3302 public Expression InstanceExpression {
3304 instance_expr = value;
3308 return instance_expr;
3312 public bool VerifyAssignable ()
3314 if (setter == null) {
3315 Report.Error (200, loc,
3316 "The property `" + PropertyInfo.Name +
3317 "' can not be assigned to, as it has not set accessor");
3324 void FindAccessors (Type invocation_type)
3326 BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic |
3327 BindingFlags.Static | BindingFlags.Instance |
3328 BindingFlags.DeclaredOnly;
3330 Type current = PropertyInfo.DeclaringType;
3331 for (; current != null; current = current.BaseType) {
3332 MemberInfo[] group = TypeManager.MemberLookup (
3333 invocation_type, invocation_type, current,
3334 MemberTypes.Property, flags, PropertyInfo.Name, null);
3339 if (group.Length != 1)
3340 // Oooops, can this ever happen ?
3343 PropertyInfo pi = (PropertyInfo) group [0];
3346 getter = pi.GetGetMethod (true);;
3349 setter = pi.GetSetMethod (true);;
3351 MethodInfo accessor = getter != null ? getter : setter;
3353 if (!accessor.IsVirtual)
3359 // We also perform the permission checking here, as the PropertyInfo does not
3360 // hold the information for the accessibility of its setter/getter
3362 void ResolveAccessors (EmitContext ec)
3364 FindAccessors (ec.ContainerType);
3366 is_static = getter != null ? getter.IsStatic : setter.IsStatic;
3369 bool InstanceResolve (EmitContext ec, bool must_do_cs1540_check)
3371 if ((instance_expr == null) && ec.IsStatic && !is_static) {
3372 SimpleName.Error_ObjectRefRequired (ec, loc, PropertyInfo.Name);
3376 if (instance_expr != null) {
3377 instance_expr = instance_expr.DoResolve (ec);
3378 if (instance_expr == null)
3381 instance_expr.CheckMarshallByRefAccess (ec.ContainerType);
3384 if (must_do_cs1540_check && (instance_expr != null)) {
3385 if ((instance_expr.Type != ec.ContainerType) &&
3386 ec.ContainerType.IsSubclassOf (instance_expr.Type)) {
3387 Report.Error (1540, loc, "Cannot access protected member `" +
3388 PropertyInfo.DeclaringType + "." + PropertyInfo.Name +
3389 "' via a qualifier of type `" +
3390 TypeManager.CSharpName (instance_expr.Type) +
3391 "'; the qualifier must be of type `" +
3392 TypeManager.CSharpName (ec.ContainerType) +
3393 "' (or derived from it)");
3401 override public Expression DoResolve (EmitContext ec)
3403 if (getter != null){
3404 if (TypeManager.GetArgumentTypes (getter).Length != 0){
3406 117, loc, "`{0}' does not contain a " +
3407 "definition for `{1}'.", getter.DeclaringType,
3413 if (getter == null){
3415 // The following condition happens if the PropertyExpr was
3416 // created, but is invalid (ie, the property is inaccessible),
3417 // and we did not want to embed the knowledge about this in
3418 // the caller routine. This only avoids double error reporting.
3423 Report.Error (154, loc,
3424 "The property `" + PropertyInfo.Name +
3425 "' can not be used in " +
3426 "this context because it lacks a get accessor");
3430 bool must_do_cs1540_check;
3431 if (!IsAccessorAccessible (ec.ContainerType, getter, out must_do_cs1540_check)) {
3432 Report.Error (122, loc, "'{0}.get' is inaccessible due to its protection level", PropertyInfo.Name);
3436 if (!InstanceResolve (ec, must_do_cs1540_check))
3440 // Only base will allow this invocation to happen.
3442 if (IsBase && getter.IsAbstract){
3443 Report.Error (205, loc, "Cannot call an abstract base property: " +
3444 PropertyInfo.DeclaringType + "." +PropertyInfo.Name);
3451 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
3453 if (setter == null){
3455 // The following condition happens if the PropertyExpr was
3456 // created, but is invalid (ie, the property is inaccessible),
3457 // and we did not want to embed the knowledge about this in
3458 // the caller routine. This only avoids double error reporting.
3463 Report.Error (154, loc,
3464 "The property `" + PropertyInfo.Name +
3465 "' can not be used in " +
3466 "this context because it lacks a set accessor");
3470 if (TypeManager.GetArgumentTypes (setter).Length != 1){
3472 117, loc, "`{0}' does not contain a " +
3473 "definition for `{1}'.", getter.DeclaringType,
3478 bool must_do_cs1540_check;
3479 if (!IsAccessorAccessible (ec.ContainerType, setter, out must_do_cs1540_check)) {
3480 Report.Error (122, loc, "'{0}.set' is inaccessible due to its protection level", PropertyInfo.Name);
3484 if (!InstanceResolve (ec, must_do_cs1540_check))
3488 // Only base will allow this invocation to happen.
3490 if (IsBase && setter.IsAbstract){
3491 Report.Error (205, loc, "Cannot call an abstract base property: " +
3492 PropertyInfo.DeclaringType + "." +PropertyInfo.Name);
3497 // Check that we are not making changes to a temporary memory location
3499 if (instance_expr != null && instance_expr.Type.IsValueType && !(instance_expr is IMemoryLocation)) {
3500 // FIXME: Provide better error reporting.
3501 Error (1612, "Cannot modify expression because it is not a variable.");
3510 public override void Emit (EmitContext ec)
3515 void EmitInstance (EmitContext ec)
3520 if (instance_expr.Type.IsValueType) {
3521 if (instance_expr is IMemoryLocation) {
3522 ((IMemoryLocation) instance_expr).AddressOf (ec, AddressOp.LoadStore);
3524 LocalTemporary t = new LocalTemporary (ec, instance_expr.Type);
3525 instance_expr.Emit (ec);
3527 t.AddressOf (ec, AddressOp.Store);
3530 instance_expr.Emit (ec);
3533 ec.ig.Emit (OpCodes.Dup);
3537 public void Emit (EmitContext ec, bool leave_copy)
3543 // Special case: length of single dimension array property is turned into ldlen
3545 if ((getter == TypeManager.system_int_array_get_length) ||
3546 (getter == TypeManager.int_array_get_length)){
3547 Type iet = instance_expr.Type;
3550 // System.Array.Length can be called, but the Type does not
3551 // support invoking GetArrayRank, so test for that case first
3553 if (iet != TypeManager.array_type && (iet.GetArrayRank () == 1)) {
3554 ec.ig.Emit (OpCodes.Ldlen);
3555 ec.ig.Emit (OpCodes.Conv_I4);
3560 Invocation.EmitCall (ec, IsBase, IsStatic, new EmptyAddressOf (), getter, null, loc);
3565 ec.ig.Emit (OpCodes.Dup);
3567 temp = new LocalTemporary (ec, this.Type);
3573 // Implements the IAssignMethod interface for assignments
3575 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
3577 prepared = prepare_for_load;
3583 ec.ig.Emit (OpCodes.Dup);
3585 temp = new LocalTemporary (ec, this.Type);
3590 ArrayList args = new ArrayList (1);
3591 args.Add (new Argument (new EmptyAddressOf (), Argument.AType.Expression));
3593 Invocation.EmitCall (ec, IsBase, IsStatic, new EmptyAddressOf (), setter, args, loc);
3599 override public void EmitStatement (EmitContext ec)
3602 ec.ig.Emit (OpCodes.Pop);
3607 /// Fully resolved expression that evaluates to an Event
3609 public class EventExpr : Expression, IMemberExpr {
3610 public readonly EventInfo EventInfo;
3611 Expression instance_expr;
3614 MethodInfo add_accessor, remove_accessor;
3616 public EventExpr (EventInfo ei, Location loc)
3620 eclass = ExprClass.EventAccess;
3622 add_accessor = TypeManager.GetAddMethod (ei);
3623 remove_accessor = TypeManager.GetRemoveMethod (ei);
3625 if (add_accessor.IsStatic || remove_accessor.IsStatic)
3628 if (EventInfo is MyEventBuilder){
3629 MyEventBuilder eb = (MyEventBuilder) EventInfo;
3630 type = eb.EventType;
3633 type = EventInfo.EventHandlerType;
3636 public string Name {
3638 return EventInfo.Name;
3642 public bool IsInstance {
3648 public bool IsStatic {
3654 public Type DeclaringType {
3656 return EventInfo.DeclaringType;
3660 public Expression InstanceExpression {
3662 return instance_expr;
3666 instance_expr = value;
3670 bool InstanceResolve (EmitContext ec, bool must_do_cs1540_check)
3672 if ((instance_expr == null) && ec.IsStatic && !is_static) {
3673 SimpleName.Error_ObjectRefRequired (ec, loc, EventInfo.Name);
3677 if (instance_expr != null) {
3678 instance_expr = instance_expr.DoResolve (ec);
3679 if (instance_expr == null)
3684 // This is using the same mechanism as the CS1540 check in PropertyExpr.
3685 // However, in the Event case, we reported a CS0122 instead.
3687 if (must_do_cs1540_check && (instance_expr != null)) {
3688 if ((instance_expr.Type != ec.ContainerType) &&
3689 ec.ContainerType.IsSubclassOf (instance_expr.Type)) {
3690 Report.Error (122, loc, "'{0}' is inaccessible due to its protection level",
3691 DeclaringType.Name + "." + EventInfo.Name);
3700 public override Expression DoResolve (EmitContext ec)
3702 if (instance_expr != null) {
3703 instance_expr = instance_expr.DoResolve (ec);
3704 if (instance_expr == null)
3708 bool must_do_cs1540_check;
3709 if (!(IsAccessorAccessible (ec.ContainerType, add_accessor, out must_do_cs1540_check)
3710 && IsAccessorAccessible (ec.ContainerType, remove_accessor, out must_do_cs1540_check))) {
3712 Report.Error (122, loc, "'{0}' is inaccessible due to its protection level",
3713 DeclaringType.Name + "." + EventInfo.Name);
3717 if (!InstanceResolve (ec, must_do_cs1540_check))
3723 public override void Emit (EmitContext ec)
3725 if (instance_expr is This)
3726 Report.Error (79, loc, "The event `{0}' can only appear on the left hand side of += or -=, try calling the actual delegate");
3728 Report.Error (70, loc, "The event `{0}' can only appear on the left hand side of += or -= "+
3729 "(except on the defining type)", Name);
3732 public void EmitAddOrRemove (EmitContext ec, Expression source)
3734 BinaryDelegate source_del = (BinaryDelegate) source;
3735 Expression handler = source_del.Right;
3737 Argument arg = new Argument (handler, Argument.AType.Expression);
3738 ArrayList args = new ArrayList ();
3742 if (source_del.IsAddition)
3743 Invocation.EmitCall (
3744 ec, false, IsStatic, instance_expr, add_accessor, args, loc);
3746 Invocation.EmitCall (
3747 ec, false, IsStatic, instance_expr, remove_accessor, args, loc);