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 // Mask of all the expression class flags.
57 // Disable control flow analysis while resolving the expression.
58 // This is used when resolving the instance expression of a field expression.
59 DisableFlowAnalysis = 8,
61 // Set if this is resolving the first part of a MemberAccess.
66 // This is just as a hint to AddressOf of what will be done with the
69 public enum AddressOp {
76 /// This interface is implemented by variables
78 public interface IMemoryLocation {
80 /// The AddressOf method should generate code that loads
81 /// the address of the object and leaves it on the stack.
83 /// The `mode' argument is used to notify the expression
84 /// of whether this will be used to read from the address or
85 /// write to the address.
87 /// This is just a hint that can be used to provide good error
88 /// reporting, and should have no other side effects.
90 void AddressOf (EmitContext ec, AddressOp mode);
94 /// We are either a namespace or a type.
95 /// If we're a type, `IsType' is true and we may use `Type' to get
96 /// a TypeExpr representing that type.
98 public interface IAlias {
107 TypeExpr ResolveAsType (EmitContext ec);
111 /// This interface is implemented by variables
113 public interface IVariable {
114 VariableInfo VariableInfo {
118 bool VerifyFixed (bool is_expression);
122 /// This interface denotes an expression which evaluates to a member
123 /// of a struct or a class.
125 public interface IMemberExpr
128 /// The name of this member.
135 /// Whether this is an instance member.
142 /// Whether this is a static member.
149 /// The type which declares this member.
156 /// The instance expression associated with this member, if it's a
157 /// non-static member.
159 Expression InstanceExpression {
165 /// Base class for expressions
167 public abstract class Expression {
168 public ExprClass eclass;
170 protected Location loc;
182 public Location Location {
189 /// Utility wrapper routine for Error, just to beautify the code
191 public void Error (int error, string s)
193 if (!Location.IsNull (loc))
194 Report.Error (error, loc, s);
196 Report.Error (error, s);
200 /// Utility wrapper routine for Warning, just to beautify the code
202 public void Warning (int code, string format, params object[] args)
204 Report.Warning (code, loc, format, args);
207 // Not nice but we have broken hierarchy
208 public virtual void CheckMarshallByRefAccess (Type container) {}
211 /// Tests presence of ObsoleteAttribute and report proper error
213 protected void CheckObsoleteAttribute (Type type)
215 ObsoleteAttribute obsolete_attr = AttributeTester.GetObsoleteAttribute (type);
216 if (obsolete_attr == null)
219 AttributeTester.Report_ObsoleteMessage (obsolete_attr, type.FullName, loc);
222 public static bool IsAccessorAccessible (Type invocation_type, MethodInfo mi, out bool must_do_cs1540_check)
224 MethodAttributes ma = mi.Attributes & MethodAttributes.MemberAccessMask;
226 must_do_cs1540_check = false; // by default we do not check for this
229 // If only accessible to the current class or children
231 if (ma == MethodAttributes.Private) {
232 Type declaring_type = mi.DeclaringType;
234 if (invocation_type != declaring_type)
235 return TypeManager.IsNestedChildOf (invocation_type, declaring_type);
240 // FamAndAssem requires that we not only derivate, but we are on the
243 if (ma == MethodAttributes.FamANDAssem){
244 return (mi.DeclaringType.Assembly != invocation_type.Assembly);
247 // Assembly and FamORAssem succeed if we're in the same assembly.
248 if ((ma == MethodAttributes.Assembly) || (ma == MethodAttributes.FamORAssem)){
249 if (mi.DeclaringType.Assembly == invocation_type.Assembly)
253 // We already know that we aren't in the same assembly.
254 if (ma == MethodAttributes.Assembly)
257 // Family and FamANDAssem require that we derive.
258 if ((ma == MethodAttributes.Family) || (ma == MethodAttributes.FamANDAssem) || (ma == MethodAttributes.FamORAssem)){
259 if (!TypeManager.IsNestedFamilyAccessible (invocation_type, mi.DeclaringType))
262 if (!TypeManager.IsNestedChildOf (invocation_type, mi.DeclaringType))
263 must_do_cs1540_check = true;
272 /// Performs semantic analysis on the Expression
276 /// The Resolve method is invoked to perform the semantic analysis
279 /// The return value is an expression (it can be the
280 /// same expression in some cases) or a new
281 /// expression that better represents this node.
283 /// For example, optimizations of Unary (LiteralInt)
284 /// would return a new LiteralInt with a negated
287 /// If there is an error during semantic analysis,
288 /// then an error should be reported (using Report)
289 /// and a null value should be returned.
291 /// There are two side effects expected from calling
292 /// Resolve(): the the field variable "eclass" should
293 /// be set to any value of the enumeration
294 /// `ExprClass' and the type variable should be set
295 /// to a valid type (this is the type of the
298 public abstract Expression DoResolve (EmitContext ec);
300 public virtual Expression DoResolveLValue (EmitContext ec, Expression right_side)
302 return DoResolve (ec);
306 // This is used if the expression should be resolved as a type or namespace name.
307 // the default implementation fails.
309 public virtual FullNamedExpression ResolveAsTypeStep (EmitContext ec)
315 // This is used to resolve the expression as a type, a null
316 // value will be returned if the expression is not a type
319 public virtual TypeExpr ResolveAsTypeTerminal (EmitContext ec)
321 int errors = Report.Errors;
323 FullNamedExpression fne = ResolveAsTypeStep (ec);
326 if (errors == Report.Errors)
327 Report.Error (246, Location, "Cannot find type '{0}'", ToString ());
331 if (fne.eclass != ExprClass.Type) {
332 if (errors == Report.Errors)
333 Report.Error (118, Location, "'{0}' denotes a '{1}', where a type was expected",
334 fne.FullName, fne.ExprClassName ());
338 TypeExpr te = fne as TypeExpr;
340 if (!te.CheckAccessLevel (ec.DeclSpace)) {
341 Report.Error (122, Location, "'{0}' is inaccessible due to its protection level", te.Name);
349 /// Resolves an expression and performs semantic analysis on it.
353 /// Currently Resolve wraps DoResolve to perform sanity
354 /// checking and assertion checking on what we expect from Resolve.
356 public Expression Resolve (EmitContext ec, ResolveFlags flags)
358 if ((flags & ResolveFlags.MaskExprClass) == ResolveFlags.Type)
359 return ResolveAsTypeStep (ec);
361 bool old_do_flow_analysis = ec.DoFlowAnalysis;
362 if ((flags & ResolveFlags.DisableFlowAnalysis) != 0)
363 ec.DoFlowAnalysis = false;
366 bool intermediate = (flags & ResolveFlags.Intermediate) == ResolveFlags.Intermediate;
367 if (this is SimpleName)
368 e = ((SimpleName) this).DoResolveAllowStatic (ec, intermediate);
373 ec.DoFlowAnalysis = old_do_flow_analysis;
378 if ((e is TypeExpr) || (e is ComposedCast) || (e is Namespace)) {
379 if ((flags & ResolveFlags.Type) == 0) {
380 e.Error_UnexpectedKind (flags, loc);
389 case ExprClass.Namespace:
390 if ((flags & ResolveFlags.VariableOrValue) == 0) {
391 e.Error_UnexpectedKind (flags, loc);
396 case ExprClass.MethodGroup:
397 if (RootContext.Version == LanguageVersion.ISO_1){
398 if ((flags & ResolveFlags.MethodGroup) == 0) {
399 ((MethodGroupExpr) e).ReportUsageError ();
405 case ExprClass.Value:
406 case ExprClass.Variable:
407 case ExprClass.PropertyAccess:
408 case ExprClass.EventAccess:
409 case ExprClass.IndexerAccess:
410 if ((flags & ResolveFlags.VariableOrValue) == 0) {
411 Console.WriteLine ("I got: {0} and {1}", e.GetType (), e);
412 Console.WriteLine ("I am {0} and {1}", this.GetType (), this);
413 FieldInfo fi = ((FieldExpr) e).FieldInfo;
415 Console.WriteLine ("{0} and {1}", fi.DeclaringType, fi.Name);
416 e.Error_UnexpectedKind (flags, loc);
422 throw new Exception ("Expression " + e.GetType () +
423 " ExprClass is Invalid after resolve");
426 if (e.type == null && !(e is Namespace)) {
427 throw new Exception (
428 "Expression " + e.GetType () +
429 " did not set its type after Resolve\n" +
430 "called from: " + this.GetType ());
437 /// Resolves an expression and performs semantic analysis on it.
439 public Expression Resolve (EmitContext ec)
441 return Resolve (ec, ResolveFlags.VariableOrValue);
445 /// Resolves an expression for LValue assignment
449 /// Currently ResolveLValue wraps DoResolveLValue to perform sanity
450 /// checking and assertion checking on what we expect from Resolve
452 public Expression ResolveLValue (EmitContext ec, Expression right_side)
454 Expression e = DoResolveLValue (ec, right_side);
457 if (e is SimpleName){
458 SimpleName s = (SimpleName) e;
459 MemberLookupFailed (ec, null, ec.ContainerType, s.Name,
460 ec.DeclSpace.Name, loc);
464 if (e.eclass == ExprClass.Invalid)
465 throw new Exception ("Expression " + e +
466 " ExprClass is Invalid after resolve");
468 if (e.eclass == ExprClass.MethodGroup) {
469 ((MethodGroupExpr) e).ReportUsageError ();
473 if ((e.type == null) && !(e is ConstructedType))
474 throw new Exception ("Expression " + e +
475 " did not set its type after Resolve");
482 /// Emits the code for the expression
486 /// The Emit method is invoked to generate the code
487 /// for the expression.
489 public abstract void Emit (EmitContext ec);
491 public virtual void EmitBranchable (EmitContext ec, Label target, bool onTrue)
494 ec.ig.Emit (onTrue ? OpCodes.Brtrue : OpCodes.Brfalse, target);
498 /// Protected constructor. Only derivate types should
499 /// be able to be created
502 protected Expression ()
504 eclass = ExprClass.Invalid;
509 /// Returns a literalized version of a literal FieldInfo
513 /// The possible return values are:
514 /// IntConstant, UIntConstant
515 /// LongLiteral, ULongConstant
516 /// FloatConstant, DoubleConstant
519 /// The value returned is already resolved.
521 public static Constant Constantify (object v, Type t)
523 if (t == TypeManager.int32_type)
524 return new IntConstant ((int) v);
525 else if (t == TypeManager.uint32_type)
526 return new UIntConstant ((uint) v);
527 else if (t == TypeManager.int64_type)
528 return new LongConstant ((long) v);
529 else if (t == TypeManager.uint64_type)
530 return new ULongConstant ((ulong) v);
531 else if (t == TypeManager.float_type)
532 return new FloatConstant ((float) v);
533 else if (t == TypeManager.double_type)
534 return new DoubleConstant ((double) v);
535 else if (t == TypeManager.string_type)
536 return new StringConstant ((string) v);
537 else if (t == TypeManager.short_type)
538 return new ShortConstant ((short)v);
539 else if (t == TypeManager.ushort_type)
540 return new UShortConstant ((ushort)v);
541 else if (t == TypeManager.sbyte_type)
542 return new SByteConstant (((sbyte)v));
543 else if (t == TypeManager.byte_type)
544 return new ByteConstant ((byte)v);
545 else if (t == TypeManager.char_type)
546 return new CharConstant ((char)v);
547 else if (t == TypeManager.bool_type)
548 return new BoolConstant ((bool) v);
549 else if (t == TypeManager.decimal_type)
550 return new DecimalConstant ((decimal) v);
551 else if (TypeManager.IsEnumType (t)){
552 Type real_type = TypeManager.TypeToCoreType (v.GetType ());
554 real_type = System.Enum.GetUnderlyingType (real_type);
556 Constant e = Constantify (v, real_type);
558 return new EnumConstant (e, t);
559 } else if (v == null && !TypeManager.IsValueType (t))
560 return NullLiteral.Null;
562 throw new Exception ("Unknown type for constant (" + t +
567 /// Returns a fully formed expression after a MemberLookup
569 public static Expression ExprClassFromMemberInfo (EmitContext ec, MemberInfo mi, Location loc)
572 return new EventExpr ((EventInfo) mi, loc);
573 else if (mi is FieldInfo)
574 return new FieldExpr ((FieldInfo) mi, loc);
575 else if (mi is PropertyInfo)
576 return new PropertyExpr (ec, (PropertyInfo) mi, loc);
577 else if (mi is Type){
578 return new TypeExpression ((System.Type) mi, loc);
584 protected static ArrayList almostMatchedMembers = new ArrayList (4);
587 // FIXME: Probably implement a cache for (t,name,current_access_set)?
589 // This code could use some optimizations, but we need to do some
590 // measurements. For example, we could use a delegate to `flag' when
591 // something can not any longer be a method-group (because it is something
595 // If the return value is an Array, then it is an array of
598 // If the return value is an MemberInfo, it is anything, but a Method
602 // FIXME: When calling MemberLookup inside an `Invocation', we should pass
603 // the arguments here and have MemberLookup return only the methods that
604 // match the argument count/type, unlike we are doing now (we delay this
607 // This is so we can catch correctly attempts to invoke instance methods
608 // from a static body (scan for error 120 in ResolveSimpleName).
611 // FIXME: Potential optimization, have a static ArrayList
614 public static Expression MemberLookup (EmitContext ec, Type queried_type, string name,
615 MemberTypes mt, BindingFlags bf, Location loc)
617 return MemberLookup (ec, ec.ContainerType, null, queried_type, name, mt, bf, loc);
621 // Lookup type `queried_type' for code in class `container_type' with a qualifier of
622 // `qualifier_type' or null to lookup members in the current class.
625 public static Expression MemberLookup (EmitContext ec, Type container_type,
626 Type qualifier_type, Type queried_type,
627 string name, MemberTypes mt,
628 BindingFlags bf, Location loc)
630 almostMatchedMembers.Clear ();
632 MemberInfo [] mi = TypeManager.MemberLookup (
633 container_type, qualifier_type,queried_type, mt, bf, name,
634 almostMatchedMembers);
639 int count = mi.Length;
641 if (mi [0] is MethodBase)
642 return new MethodGroupExpr (mi, loc);
647 return ExprClassFromMemberInfo (ec, mi [0], loc);
650 public const MemberTypes AllMemberTypes =
651 MemberTypes.Constructor |
655 MemberTypes.NestedType |
656 MemberTypes.Property;
658 public const BindingFlags AllBindingFlags =
659 BindingFlags.Public |
660 BindingFlags.Static |
661 BindingFlags.Instance;
663 public static Expression MemberLookup (EmitContext ec, Type queried_type,
664 string name, Location loc)
666 return MemberLookup (ec, ec.ContainerType, null, queried_type, name,
667 AllMemberTypes, AllBindingFlags, loc);
670 public static Expression MemberLookup (EmitContext ec, Type qualifier_type,
671 Type queried_type, string name, Location loc)
673 return MemberLookup (ec, ec.ContainerType, qualifier_type, queried_type,
674 name, AllMemberTypes, AllBindingFlags, loc);
677 public static Expression MethodLookup (EmitContext ec, Type queried_type,
678 string name, Location loc)
680 return MemberLookup (ec, ec.ContainerType, null, queried_type, name,
681 MemberTypes.Method, AllBindingFlags, loc);
685 /// This is a wrapper for MemberLookup that is not used to "probe", but
686 /// to find a final definition. If the final definition is not found, we
687 /// look for private members and display a useful debugging message if we
690 public static Expression MemberLookupFinal (EmitContext ec, Type qualifier_type,
691 Type queried_type, string name,
694 return MemberLookupFinal (ec, qualifier_type, queried_type, name,
695 AllMemberTypes, AllBindingFlags, loc);
698 public static Expression MemberLookupFinal (EmitContext ec, Type qualifier_type,
699 Type queried_type, string name,
700 MemberTypes mt, BindingFlags bf,
705 int errors = Report.Errors;
707 e = MemberLookup (ec, ec.ContainerType, qualifier_type, queried_type,
710 if (e == null && errors == Report.Errors)
711 // No errors were reported by MemberLookup, but there was an error.
712 MemberLookupFailed (ec, qualifier_type, queried_type, name,
718 public static void MemberLookupFailed (EmitContext ec, Type qualifier_type,
719 Type queried_type, string name,
720 string class_name, Location loc)
722 if (almostMatchedMembers.Count != 0) {
723 if (qualifier_type == null) {
724 foreach (MemberInfo m in almostMatchedMembers)
725 Report.Error (38, loc,
726 "Cannot access non-static member `{0}' via nested type `{1}'",
727 TypeManager.GetFullNameSignature (m),
728 TypeManager.CSharpName (ec.ContainerType));
733 if (qualifier_type != ec.ContainerType) {
734 // Although a derived class can access protected members of
735 // its base class it cannot do so through an instance of the
736 // base class (CS1540). If the qualifier_type is a base of the
737 // ec.ContainerType and the lookup succeeds with the latter one,
738 // then we are in this situation.
739 for (int i = 0; i < almostMatchedMembers.Count; ++i) {
740 MemberInfo m = (MemberInfo) almostMatchedMembers [i];
741 for (int j = 0; j < i; ++j) {
742 if (m == almostMatchedMembers [j]) {
750 Report.SymbolRelatedToPreviousError (m);
751 Report.Error (1540, loc,
752 "Cannot access protected member `{0}' via a qualifier of type `{1}';"
753 + " the qualifier must be of type `{2}' (or derived from it)",
754 TypeManager.GetFullNameSignature (m),
755 TypeManager.CSharpName (qualifier_type),
756 TypeManager.CSharpName (ec.ContainerType));
760 almostMatchedMembers.Clear ();
763 MemberInfo[] mi = TypeManager.MemberLookup (queried_type, null, queried_type,
764 AllMemberTypes, AllBindingFlags |
765 BindingFlags.NonPublic, name, null);
768 if (class_name != null)
769 Report.Error (103, loc, "The name `" + name + "' could not be " +
770 "found in `" + class_name + "'");
773 117, loc, "`" + queried_type + "' does not contain a " +
774 "definition for `" + name + "'");
778 if (TypeManager.MemberLookup (queried_type, null, queried_type,
779 AllMemberTypes, AllBindingFlags |
780 BindingFlags.NonPublic, name, null) == null) {
781 if ((mi.Length == 1) && (mi [0] is Type)) {
782 Type t = (Type) mi [0];
784 Report.Error (305, loc,
785 "Using the generic type `{0}' " +
786 "requires {1} type arguments",
787 TypeManager.GetFullName (t),
788 TypeManager.GetNumberOfTypeArguments (t));
793 if (name == ".ctor" && TypeManager.FindMembers (qualifier_type, MemberTypes.Constructor,
794 BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly, null, null).Count == 0)
796 Report.Error (143, loc, String.Format ("The type '{0}' has no constructors defined", TypeManager.CSharpName (queried_type)));
800 if (qualifier_type != null) {
801 Report.Error (122, loc, "'{0}' is inaccessible due to its protection level", TypeManager.CSharpName (qualifier_type) + "." + name);
803 Report.Error (122, loc, "'{0}' is inaccessible due to its protection level", name);
807 static public MemberInfo GetFieldFromEvent (EventExpr event_expr)
809 EventInfo ei = event_expr.EventInfo;
811 return TypeManager.GetPrivateFieldOfEvent (ei);
815 /// Returns an expression that can be used to invoke operator true
816 /// on the expression if it exists.
818 static public StaticCallExpr GetOperatorTrue (EmitContext ec, Expression e, Location loc)
820 return GetOperatorTrueOrFalse (ec, e, true, loc);
824 /// Returns an expression that can be used to invoke operator false
825 /// on the expression if it exists.
827 static public StaticCallExpr GetOperatorFalse (EmitContext ec, Expression e, Location loc)
829 return GetOperatorTrueOrFalse (ec, e, false, loc);
832 static StaticCallExpr GetOperatorTrueOrFalse (EmitContext ec, Expression e, bool is_true, Location loc)
835 Expression operator_group;
837 operator_group = MethodLookup (ec, e.Type, is_true ? "op_True" : "op_False", loc);
838 if (operator_group == null)
841 ArrayList arguments = new ArrayList ();
842 arguments.Add (new Argument (e, Argument.AType.Expression));
843 method = Invocation.OverloadResolve (
844 ec, (MethodGroupExpr) operator_group, arguments, false, loc);
849 return new StaticCallExpr ((MethodInfo) method, arguments, loc);
853 /// Resolves the expression `e' into a boolean expression: either through
854 /// an implicit conversion, or through an `operator true' invocation
856 public static Expression ResolveBoolean (EmitContext ec, Expression e, Location loc)
862 if (e.Type == TypeManager.bool_type)
865 Expression converted = Convert.ImplicitConversion (ec, e, TypeManager.bool_type, new Location (-1));
867 if (converted != null)
871 // If no implicit conversion to bool exists, try using `operator true'
873 Expression operator_true = Expression.GetOperatorTrue (ec, e, loc);
874 if (operator_true == null){
875 Report.Error (31, loc, "Can not convert the expression to a boolean");
878 return operator_true;
881 public string ExprClassName ()
884 case ExprClass.Invalid:
886 case ExprClass.Value:
888 case ExprClass.Variable:
890 case ExprClass.Namespace:
894 case ExprClass.MethodGroup:
895 return "method group";
896 case ExprClass.PropertyAccess:
897 return "property access";
898 case ExprClass.EventAccess:
899 return "event access";
900 case ExprClass.IndexerAccess:
901 return "indexer access";
902 case ExprClass.Nothing:
905 throw new Exception ("Should not happen");
909 /// Reports that we were expecting `expr' to be of class `expected'
911 public void Error_UnexpectedKind (string expected, Location loc)
913 Report.Error (118, loc, "Expression denotes a `" + ExprClassName () +
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 (valid.Count == 0)
933 valid.Add ("unknown");
935 StringBuilder sb = new StringBuilder ();
936 for (int i = 0; i < valid.Count; i++) {
939 else if (i == valid.Count)
941 sb.Append (valid [i]);
944 Error (119, "Expression denotes a `" + ExprClassName () + "' where " +
945 "a `" + sb.ToString () + "' was expected");
948 static public void Error_ConstantValueCannotBeConverted (Location l, string val, Type t)
950 Report.Error (31, l, "Constant value `" + val + "' cannot be converted to " +
951 TypeManager.CSharpName (t));
954 public static void UnsafeError (Location loc)
956 Report.Error (214, loc, "Pointers may only be used in an unsafe context");
960 /// Converts the IntConstant, UIntConstant, LongConstant or
961 /// ULongConstant into the integral target_type. Notice
962 /// that we do not return an `Expression' we do return
963 /// a boxed integral type.
965 /// FIXME: Since I added the new constants, we need to
966 /// also support conversions from CharConstant, ByteConstant,
967 /// SByteConstant, UShortConstant, ShortConstant
969 /// This is used by the switch statement, so the domain
970 /// of work is restricted to the literals above, and the
971 /// targets are int32, uint32, char, byte, sbyte, ushort,
972 /// short, uint64 and int64
974 public static object ConvertIntLiteral (Constant c, Type target_type, Location loc)
976 if (!Convert.ImplicitStandardConversionExists (Convert.ConstantEC, c, target_type)){
977 Convert.Error_CannotImplicitConversion (loc, c.Type, target_type);
983 if (c.Type == target_type)
984 return ((Constant) c).GetValue ();
987 // Make into one of the literals we handle, we dont really care
988 // about this value as we will just return a few limited types
990 if (c is EnumConstant)
991 c = ((EnumConstant)c).WidenToCompilerConstant ();
993 if (c is IntConstant){
994 int v = ((IntConstant) c).Value;
996 if (target_type == TypeManager.uint32_type){
999 } else if (target_type == TypeManager.char_type){
1000 if (v >= Char.MinValue && v <= Char.MaxValue)
1002 } else if (target_type == TypeManager.byte_type){
1003 if (v >= Byte.MinValue && v <= Byte.MaxValue)
1005 } else if (target_type == TypeManager.sbyte_type){
1006 if (v >= SByte.MinValue && v <= SByte.MaxValue)
1008 } else if (target_type == TypeManager.short_type){
1009 if (v >= Int16.MinValue && v <= UInt16.MaxValue)
1011 } else if (target_type == TypeManager.ushort_type){
1012 if (v >= UInt16.MinValue && v <= UInt16.MaxValue)
1014 } else if (target_type == TypeManager.int64_type)
1016 else if (target_type == TypeManager.uint64_type){
1022 } else if (c is UIntConstant){
1023 uint v = ((UIntConstant) c).Value;
1025 if (target_type == TypeManager.int32_type){
1026 if (v <= Int32.MaxValue)
1028 } else if (target_type == TypeManager.char_type){
1029 if (v >= Char.MinValue && v <= Char.MaxValue)
1031 } else if (target_type == TypeManager.byte_type){
1032 if (v <= Byte.MaxValue)
1034 } else if (target_type == TypeManager.sbyte_type){
1035 if (v <= SByte.MaxValue)
1037 } else if (target_type == TypeManager.short_type){
1038 if (v <= UInt16.MaxValue)
1040 } else if (target_type == TypeManager.ushort_type){
1041 if (v <= UInt16.MaxValue)
1043 } else if (target_type == TypeManager.int64_type)
1045 else if (target_type == TypeManager.uint64_type)
1048 } else if (c is LongConstant){
1049 long v = ((LongConstant) c).Value;
1051 if (target_type == TypeManager.int32_type){
1052 if (v >= UInt32.MinValue && v <= UInt32.MaxValue)
1054 } else if (target_type == TypeManager.uint32_type){
1055 if (v >= 0 && v <= UInt32.MaxValue)
1057 } else if (target_type == TypeManager.char_type){
1058 if (v >= Char.MinValue && v <= Char.MaxValue)
1060 } else if (target_type == TypeManager.byte_type){
1061 if (v >= Byte.MinValue && v <= Byte.MaxValue)
1063 } else if (target_type == TypeManager.sbyte_type){
1064 if (v >= SByte.MinValue && v <= SByte.MaxValue)
1066 } else if (target_type == TypeManager.short_type){
1067 if (v >= Int16.MinValue && v <= UInt16.MaxValue)
1069 } else if (target_type == TypeManager.ushort_type){
1070 if (v >= UInt16.MinValue && v <= UInt16.MaxValue)
1072 } else if (target_type == TypeManager.uint64_type){
1077 } else if (c is ULongConstant){
1078 ulong v = ((ULongConstant) c).Value;
1080 if (target_type == TypeManager.int32_type){
1081 if (v <= Int32.MaxValue)
1083 } else if (target_type == TypeManager.uint32_type){
1084 if (v <= UInt32.MaxValue)
1086 } else if (target_type == TypeManager.char_type){
1087 if (v >= Char.MinValue && v <= Char.MaxValue)
1089 } else if (target_type == TypeManager.byte_type){
1090 if (v >= Byte.MinValue && v <= Byte.MaxValue)
1092 } else if (target_type == TypeManager.sbyte_type){
1093 if (v <= (int) SByte.MaxValue)
1095 } else if (target_type == TypeManager.short_type){
1096 if (v <= UInt16.MaxValue)
1098 } else if (target_type == TypeManager.ushort_type){
1099 if (v <= UInt16.MaxValue)
1101 } else if (target_type == TypeManager.int64_type){
1102 if (v <= Int64.MaxValue)
1106 } else if (c is ByteConstant){
1107 byte v = ((ByteConstant) c).Value;
1109 if (target_type == TypeManager.int32_type)
1111 else if (target_type == TypeManager.uint32_type)
1113 else if (target_type == TypeManager.char_type)
1115 else if (target_type == TypeManager.sbyte_type){
1116 if (v <= SByte.MaxValue)
1118 } else if (target_type == TypeManager.short_type)
1120 else if (target_type == TypeManager.ushort_type)
1122 else if (target_type == TypeManager.int64_type)
1124 else if (target_type == TypeManager.uint64_type)
1127 } else if (c is SByteConstant){
1128 sbyte v = ((SByteConstant) c).Value;
1130 if (target_type == TypeManager.int32_type)
1132 else if (target_type == TypeManager.uint32_type){
1135 } else if (target_type == TypeManager.char_type){
1138 } else if (target_type == TypeManager.byte_type){
1141 } else if (target_type == TypeManager.short_type)
1143 else if (target_type == TypeManager.ushort_type){
1146 } else if (target_type == TypeManager.int64_type)
1148 else if (target_type == TypeManager.uint64_type){
1153 } else if (c is ShortConstant){
1154 short v = ((ShortConstant) c).Value;
1156 if (target_type == TypeManager.int32_type){
1158 } else if (target_type == TypeManager.uint32_type){
1161 } else if (target_type == TypeManager.char_type){
1164 } else if (target_type == TypeManager.byte_type){
1165 if (v >= Byte.MinValue && v <= Byte.MaxValue)
1167 } else if (target_type == TypeManager.sbyte_type){
1168 if (v >= SByte.MinValue && v <= SByte.MaxValue)
1170 } else if (target_type == TypeManager.ushort_type){
1173 } else if (target_type == TypeManager.int64_type)
1175 else if (target_type == TypeManager.uint64_type)
1179 } else if (c is UShortConstant){
1180 ushort v = ((UShortConstant) c).Value;
1182 if (target_type == TypeManager.int32_type)
1184 else if (target_type == TypeManager.uint32_type)
1186 else if (target_type == TypeManager.char_type){
1187 if (v >= Char.MinValue && v <= Char.MaxValue)
1189 } else if (target_type == TypeManager.byte_type){
1190 if (v >= Byte.MinValue && v <= Byte.MaxValue)
1192 } else if (target_type == TypeManager.sbyte_type){
1193 if (v <= SByte.MaxValue)
1195 } else if (target_type == TypeManager.short_type){
1196 if (v <= Int16.MaxValue)
1198 } else if (target_type == TypeManager.int64_type)
1200 else if (target_type == TypeManager.uint64_type)
1204 } else if (c is CharConstant){
1205 char v = ((CharConstant) c).Value;
1207 if (target_type == TypeManager.int32_type)
1209 else if (target_type == TypeManager.uint32_type)
1211 else if (target_type == TypeManager.byte_type){
1212 if (v >= Byte.MinValue && v <= Byte.MaxValue)
1214 } else if (target_type == TypeManager.sbyte_type){
1215 if (v <= SByte.MaxValue)
1217 } else if (target_type == TypeManager.short_type){
1218 if (v <= Int16.MaxValue)
1220 } else if (target_type == TypeManager.ushort_type)
1222 else if (target_type == TypeManager.int64_type)
1224 else if (target_type == TypeManager.uint64_type)
1229 Error_ConstantValueCannotBeConverted (loc, s, target_type);
1234 // Load the object from the pointer.
1236 public static void LoadFromPtr (ILGenerator ig, Type t)
1238 if (t == TypeManager.int32_type)
1239 ig.Emit (OpCodes.Ldind_I4);
1240 else if (t == TypeManager.uint32_type)
1241 ig.Emit (OpCodes.Ldind_U4);
1242 else if (t == TypeManager.short_type)
1243 ig.Emit (OpCodes.Ldind_I2);
1244 else if (t == TypeManager.ushort_type)
1245 ig.Emit (OpCodes.Ldind_U2);
1246 else if (t == TypeManager.char_type)
1247 ig.Emit (OpCodes.Ldind_U2);
1248 else if (t == TypeManager.byte_type)
1249 ig.Emit (OpCodes.Ldind_U1);
1250 else if (t == TypeManager.sbyte_type)
1251 ig.Emit (OpCodes.Ldind_I1);
1252 else if (t == TypeManager.uint64_type)
1253 ig.Emit (OpCodes.Ldind_I8);
1254 else if (t == TypeManager.int64_type)
1255 ig.Emit (OpCodes.Ldind_I8);
1256 else if (t == TypeManager.float_type)
1257 ig.Emit (OpCodes.Ldind_R4);
1258 else if (t == TypeManager.double_type)
1259 ig.Emit (OpCodes.Ldind_R8);
1260 else if (t == TypeManager.bool_type)
1261 ig.Emit (OpCodes.Ldind_I1);
1262 else if (t == TypeManager.intptr_type)
1263 ig.Emit (OpCodes.Ldind_I);
1264 else if (TypeManager.IsEnumType (t)) {
1265 if (t == TypeManager.enum_type)
1266 ig.Emit (OpCodes.Ldind_Ref);
1268 LoadFromPtr (ig, TypeManager.EnumToUnderlying (t));
1269 } else if (t.IsValueType || t.IsGenericParameter)
1270 ig.Emit (OpCodes.Ldobj, t);
1271 else if (t.IsPointer)
1272 ig.Emit (OpCodes.Ldind_I);
1274 ig.Emit (OpCodes.Ldind_Ref);
1278 // The stack contains the pointer and the value of type `type'
1280 public static void StoreFromPtr (ILGenerator ig, Type type)
1282 if (TypeManager.IsEnumType (type))
1283 type = TypeManager.EnumToUnderlying (type);
1284 if (type == TypeManager.int32_type || type == TypeManager.uint32_type)
1285 ig.Emit (OpCodes.Stind_I4);
1286 else if (type == TypeManager.int64_type || type == TypeManager.uint64_type)
1287 ig.Emit (OpCodes.Stind_I8);
1288 else if (type == TypeManager.char_type || type == TypeManager.short_type ||
1289 type == TypeManager.ushort_type)
1290 ig.Emit (OpCodes.Stind_I2);
1291 else if (type == TypeManager.float_type)
1292 ig.Emit (OpCodes.Stind_R4);
1293 else if (type == TypeManager.double_type)
1294 ig.Emit (OpCodes.Stind_R8);
1295 else if (type == TypeManager.byte_type || type == TypeManager.sbyte_type ||
1296 type == TypeManager.bool_type)
1297 ig.Emit (OpCodes.Stind_I1);
1298 else if (type == TypeManager.intptr_type)
1299 ig.Emit (OpCodes.Stind_I);
1300 else if (type.IsValueType || type.IsGenericParameter)
1301 ig.Emit (OpCodes.Stobj, type);
1303 ig.Emit (OpCodes.Stind_Ref);
1307 // Returns the size of type `t' if known, otherwise, 0
1309 public static int GetTypeSize (Type t)
1311 t = TypeManager.TypeToCoreType (t);
1312 if (t == TypeManager.int32_type ||
1313 t == TypeManager.uint32_type ||
1314 t == TypeManager.float_type)
1316 else if (t == TypeManager.int64_type ||
1317 t == TypeManager.uint64_type ||
1318 t == TypeManager.double_type)
1320 else if (t == TypeManager.byte_type ||
1321 t == TypeManager.sbyte_type ||
1322 t == TypeManager.bool_type)
1324 else if (t == TypeManager.short_type ||
1325 t == TypeManager.char_type ||
1326 t == TypeManager.ushort_type)
1328 else if (t == TypeManager.decimal_type)
1334 public static void Error_NegativeArrayIndex (Location loc)
1336 Report.Error (248, loc, "Cannot create an array with a negative size");
1340 // Converts `source' to an int, uint, long or ulong.
1342 public Expression ExpressionToArrayArgument (EmitContext ec, Expression source, Location loc)
1346 bool old_checked = ec.CheckState;
1347 ec.CheckState = true;
1349 target = Convert.ImplicitConversion (ec, source, TypeManager.int32_type, loc);
1350 if (target == null){
1351 target = Convert.ImplicitConversion (ec, source, TypeManager.uint32_type, loc);
1352 if (target == null){
1353 target = Convert.ImplicitConversion (ec, source, TypeManager.int64_type, loc);
1354 if (target == null){
1355 target = Convert.ImplicitConversion (ec, source, TypeManager.uint64_type, loc);
1357 Convert.Error_CannotImplicitConversion (loc, source.Type, TypeManager.int32_type);
1361 ec.CheckState = old_checked;
1364 // Only positive constants are allowed at compile time
1366 if (target is Constant){
1367 if (target is IntConstant){
1368 if (((IntConstant) target).Value < 0){
1369 Error_NegativeArrayIndex (loc);
1374 if (target is LongConstant){
1375 if (((LongConstant) target).Value < 0){
1376 Error_NegativeArrayIndex (loc);
1389 /// This is just a base class for expressions that can
1390 /// appear on statements (invocations, object creation,
1391 /// assignments, post/pre increment and decrement). The idea
1392 /// being that they would support an extra Emition interface that
1393 /// does not leave a result on the stack.
1395 public abstract class ExpressionStatement : Expression {
1397 public virtual ExpressionStatement ResolveStatement (EmitContext ec)
1399 Expression e = Resolve (ec);
1403 ExpressionStatement es = e as ExpressionStatement;
1405 Error (201, "Only assignment, call, increment, decrement and new object " +
1406 "expressions can be used as a statement");
1412 /// Requests the expression to be emitted in a `statement'
1413 /// context. This means that no new value is left on the
1414 /// stack after invoking this method (constrasted with
1415 /// Emit that will always leave a value on the stack).
1417 public abstract void EmitStatement (EmitContext ec);
1421 /// This kind of cast is used to encapsulate the child
1422 /// whose type is child.Type into an expression that is
1423 /// reported to return "return_type". This is used to encapsulate
1424 /// expressions which have compatible types, but need to be dealt
1425 /// at higher levels with.
1427 /// For example, a "byte" expression could be encapsulated in one
1428 /// of these as an "unsigned int". The type for the expression
1429 /// would be "unsigned int".
1432 public class EmptyCast : Expression {
1433 protected Expression child;
1435 public Expression Child {
1441 public EmptyCast (Expression child, Type return_type)
1443 eclass = child.eclass;
1448 public override Expression DoResolve (EmitContext ec)
1450 // This should never be invoked, we are born in fully
1451 // initialized state.
1456 public override void Emit (EmitContext ec)
1463 // We need to special case this since an empty cast of
1464 // a NullLiteral is still a Constant
1466 public class NullCast : Constant {
1467 protected Expression child;
1469 public NullCast (Expression child, Type return_type)
1471 eclass = child.eclass;
1476 override public string AsString ()
1481 public override object GetValue ()
1486 public override Expression DoResolve (EmitContext ec)
1488 // This should never be invoked, we are born in fully
1489 // initialized state.
1494 public override void Emit (EmitContext ec)
1499 public override bool IsNegative {
1508 /// This class is used to wrap literals which belong inside Enums
1510 public class EnumConstant : Constant {
1511 public Constant Child;
1513 public EnumConstant (Constant child, Type enum_type)
1515 eclass = child.eclass;
1520 public override Expression DoResolve (EmitContext ec)
1522 // This should never be invoked, we are born in fully
1523 // initialized state.
1528 public override void Emit (EmitContext ec)
1533 public override object GetValue ()
1535 return Child.GetValue ();
1538 public object GetValueAsEnumType ()
1540 return System.Enum.ToObject (type, Child.GetValue ());
1544 // Converts from one of the valid underlying types for an enumeration
1545 // (int32, uint32, int64, uint64, short, ushort, byte, sbyte) to
1546 // one of the internal compiler literals: Int/UInt/Long/ULong Literals.
1548 public Constant WidenToCompilerConstant ()
1550 Type t = TypeManager.EnumToUnderlying (Child.Type);
1551 object v = ((Constant) Child).GetValue ();;
1553 if (t == TypeManager.int32_type)
1554 return new IntConstant ((int) v);
1555 if (t == TypeManager.uint32_type)
1556 return new UIntConstant ((uint) v);
1557 if (t == TypeManager.int64_type)
1558 return new LongConstant ((long) v);
1559 if (t == TypeManager.uint64_type)
1560 return new ULongConstant ((ulong) v);
1561 if (t == TypeManager.short_type)
1562 return new ShortConstant ((short) v);
1563 if (t == TypeManager.ushort_type)
1564 return new UShortConstant ((ushort) v);
1565 if (t == TypeManager.byte_type)
1566 return new ByteConstant ((byte) v);
1567 if (t == TypeManager.sbyte_type)
1568 return new SByteConstant ((sbyte) v);
1570 throw new Exception ("Invalid enumeration underlying type: " + t);
1574 // Extracts the value in the enumeration on its native representation
1576 public object GetPlainValue ()
1578 Type t = TypeManager.EnumToUnderlying (Child.Type);
1579 object v = ((Constant) Child).GetValue ();;
1581 if (t == TypeManager.int32_type)
1583 if (t == TypeManager.uint32_type)
1585 if (t == TypeManager.int64_type)
1587 if (t == TypeManager.uint64_type)
1589 if (t == TypeManager.short_type)
1591 if (t == TypeManager.ushort_type)
1593 if (t == TypeManager.byte_type)
1595 if (t == TypeManager.sbyte_type)
1601 public override string AsString ()
1603 return Child.AsString ();
1606 public override DoubleConstant ConvertToDouble ()
1608 return Child.ConvertToDouble ();
1611 public override FloatConstant ConvertToFloat ()
1613 return Child.ConvertToFloat ();
1616 public override ULongConstant ConvertToULong ()
1618 return Child.ConvertToULong ();
1621 public override LongConstant ConvertToLong ()
1623 return Child.ConvertToLong ();
1626 public override UIntConstant ConvertToUInt ()
1628 return Child.ConvertToUInt ();
1631 public override IntConstant ConvertToInt ()
1633 return Child.ConvertToInt ();
1636 public override bool IsZeroInteger {
1637 get { return Child.IsZeroInteger; }
1640 public override bool IsNegative {
1642 return Child.IsNegative;
1648 /// This kind of cast is used to encapsulate Value Types in objects.
1650 /// The effect of it is to box the value type emitted by the previous
1653 public class BoxedCast : EmptyCast {
1655 public BoxedCast (Expression expr)
1656 : base (expr, TypeManager.object_type)
1658 eclass = ExprClass.Value;
1661 public BoxedCast (Expression expr, Type target_type)
1662 : base (expr, target_type)
1664 eclass = ExprClass.Value;
1667 public override Expression DoResolve (EmitContext ec)
1669 // This should never be invoked, we are born in fully
1670 // initialized state.
1675 public override void Emit (EmitContext ec)
1679 ec.ig.Emit (OpCodes.Box, child.Type);
1683 public class UnboxCast : EmptyCast {
1684 public UnboxCast (Expression expr, Type return_type)
1685 : base (expr, return_type)
1689 public override Expression DoResolve (EmitContext ec)
1691 // This should never be invoked, we are born in fully
1692 // initialized state.
1697 public override void Emit (EmitContext ec)
1700 ILGenerator ig = ec.ig;
1703 if (t.IsGenericParameter)
1704 ig.Emit (OpCodes.Unbox_Any, t);
1706 ig.Emit (OpCodes.Unbox, t);
1708 LoadFromPtr (ig, t);
1714 /// This is used to perform explicit numeric conversions.
1716 /// Explicit numeric conversions might trigger exceptions in a checked
1717 /// context, so they should generate the conv.ovf opcodes instead of
1720 public class ConvCast : EmptyCast {
1721 public enum Mode : byte {
1722 I1_U1, I1_U2, I1_U4, I1_U8, I1_CH,
1724 I2_I1, I2_U1, I2_U2, I2_U4, I2_U8, I2_CH,
1725 U2_I1, U2_U1, U2_I2, U2_CH,
1726 I4_I1, I4_U1, I4_I2, I4_U2, I4_U4, I4_U8, I4_CH,
1727 U4_I1, U4_U1, U4_I2, U4_U2, U4_I4, U4_CH,
1728 I8_I1, I8_U1, I8_I2, I8_U2, I8_I4, I8_U4, I8_U8, I8_CH,
1729 U8_I1, U8_U1, U8_I2, U8_U2, U8_I4, U8_U4, U8_I8, U8_CH,
1730 CH_I1, CH_U1, CH_I2,
1731 R4_I1, R4_U1, R4_I2, R4_U2, R4_I4, R4_U4, R4_I8, R4_U8, R4_CH,
1732 R8_I1, R8_U1, R8_I2, R8_U2, R8_I4, R8_U4, R8_I8, R8_U8, R8_CH, R8_R4
1738 public ConvCast (EmitContext ec, Expression child, Type return_type, Mode m)
1739 : base (child, return_type)
1741 checked_state = ec.CheckState;
1745 public override Expression DoResolve (EmitContext ec)
1747 // This should never be invoked, we are born in fully
1748 // initialized state.
1753 public override string ToString ()
1755 return String.Format ("ConvCast ({0}, {1})", mode, child);
1758 public override void Emit (EmitContext ec)
1760 ILGenerator ig = ec.ig;
1766 case Mode.I1_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1767 case Mode.I1_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1768 case Mode.I1_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1769 case Mode.I1_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1770 case Mode.I1_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1772 case Mode.U1_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1773 case Mode.U1_CH: /* nothing */ break;
1775 case Mode.I2_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1776 case Mode.I2_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1777 case Mode.I2_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1778 case Mode.I2_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1779 case Mode.I2_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1780 case Mode.I2_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1782 case Mode.U2_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1783 case Mode.U2_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
1784 case Mode.U2_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
1785 case Mode.U2_CH: /* nothing */ break;
1787 case Mode.I4_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1788 case Mode.I4_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1789 case Mode.I4_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
1790 case Mode.I4_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1791 case Mode.I4_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1792 case Mode.I4_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1793 case Mode.I4_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1795 case Mode.U4_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1796 case Mode.U4_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
1797 case Mode.U4_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
1798 case Mode.U4_U2: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
1799 case Mode.U4_I4: ig.Emit (OpCodes.Conv_Ovf_I4_Un); break;
1800 case Mode.U4_CH: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
1802 case Mode.I8_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1803 case Mode.I8_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1804 case Mode.I8_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
1805 case Mode.I8_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1806 case Mode.I8_I4: ig.Emit (OpCodes.Conv_Ovf_I4); break;
1807 case Mode.I8_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1808 case Mode.I8_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1809 case Mode.I8_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1811 case Mode.U8_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1812 case Mode.U8_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
1813 case Mode.U8_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
1814 case Mode.U8_U2: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
1815 case Mode.U8_I4: ig.Emit (OpCodes.Conv_Ovf_I4_Un); break;
1816 case Mode.U8_U4: ig.Emit (OpCodes.Conv_Ovf_U4_Un); break;
1817 case Mode.U8_I8: ig.Emit (OpCodes.Conv_Ovf_I8_Un); break;
1818 case Mode.U8_CH: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
1820 case Mode.CH_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1821 case Mode.CH_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
1822 case Mode.CH_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
1824 case Mode.R4_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1825 case Mode.R4_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1826 case Mode.R4_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
1827 case Mode.R4_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1828 case Mode.R4_I4: ig.Emit (OpCodes.Conv_Ovf_I4); break;
1829 case Mode.R4_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1830 case Mode.R4_I8: ig.Emit (OpCodes.Conv_Ovf_I8); break;
1831 case Mode.R4_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1832 case Mode.R4_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1834 case Mode.R8_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1835 case Mode.R8_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1836 case Mode.R8_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
1837 case Mode.R8_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1838 case Mode.R8_I4: ig.Emit (OpCodes.Conv_Ovf_I4); break;
1839 case Mode.R8_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1840 case Mode.R8_I8: ig.Emit (OpCodes.Conv_Ovf_I8); break;
1841 case Mode.R8_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1842 case Mode.R8_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1843 case Mode.R8_R4: ig.Emit (OpCodes.Conv_R4); break;
1847 case Mode.I1_U1: ig.Emit (OpCodes.Conv_U1); break;
1848 case Mode.I1_U2: ig.Emit (OpCodes.Conv_U2); break;
1849 case Mode.I1_U4: ig.Emit (OpCodes.Conv_U4); break;
1850 case Mode.I1_U8: ig.Emit (OpCodes.Conv_I8); break;
1851 case Mode.I1_CH: ig.Emit (OpCodes.Conv_U2); break;
1853 case Mode.U1_I1: ig.Emit (OpCodes.Conv_I1); break;
1854 case Mode.U1_CH: ig.Emit (OpCodes.Conv_U2); break;
1856 case Mode.I2_I1: ig.Emit (OpCodes.Conv_I1); break;
1857 case Mode.I2_U1: ig.Emit (OpCodes.Conv_U1); break;
1858 case Mode.I2_U2: ig.Emit (OpCodes.Conv_U2); break;
1859 case Mode.I2_U4: ig.Emit (OpCodes.Conv_U4); break;
1860 case Mode.I2_U8: ig.Emit (OpCodes.Conv_I8); break;
1861 case Mode.I2_CH: ig.Emit (OpCodes.Conv_U2); break;
1863 case Mode.U2_I1: ig.Emit (OpCodes.Conv_I1); break;
1864 case Mode.U2_U1: ig.Emit (OpCodes.Conv_U1); break;
1865 case Mode.U2_I2: ig.Emit (OpCodes.Conv_I2); break;
1866 case Mode.U2_CH: /* nothing */ break;
1868 case Mode.I4_I1: ig.Emit (OpCodes.Conv_I1); break;
1869 case Mode.I4_U1: ig.Emit (OpCodes.Conv_U1); break;
1870 case Mode.I4_I2: ig.Emit (OpCodes.Conv_I2); break;
1871 case Mode.I4_U4: /* nothing */ break;
1872 case Mode.I4_U2: ig.Emit (OpCodes.Conv_U2); break;
1873 case Mode.I4_U8: ig.Emit (OpCodes.Conv_I8); break;
1874 case Mode.I4_CH: ig.Emit (OpCodes.Conv_U2); break;
1876 case Mode.U4_I1: ig.Emit (OpCodes.Conv_I1); break;
1877 case Mode.U4_U1: ig.Emit (OpCodes.Conv_U1); break;
1878 case Mode.U4_I2: ig.Emit (OpCodes.Conv_I2); break;
1879 case Mode.U4_U2: ig.Emit (OpCodes.Conv_U2); break;
1880 case Mode.U4_I4: /* nothing */ break;
1881 case Mode.U4_CH: ig.Emit (OpCodes.Conv_U2); break;
1883 case Mode.I8_I1: ig.Emit (OpCodes.Conv_I1); break;
1884 case Mode.I8_U1: ig.Emit (OpCodes.Conv_U1); break;
1885 case Mode.I8_I2: ig.Emit (OpCodes.Conv_I2); break;
1886 case Mode.I8_U2: ig.Emit (OpCodes.Conv_U2); break;
1887 case Mode.I8_I4: ig.Emit (OpCodes.Conv_I4); break;
1888 case Mode.I8_U4: ig.Emit (OpCodes.Conv_U4); break;
1889 case Mode.I8_U8: /* nothing */ break;
1890 case Mode.I8_CH: ig.Emit (OpCodes.Conv_U2); break;
1892 case Mode.U8_I1: ig.Emit (OpCodes.Conv_I1); break;
1893 case Mode.U8_U1: ig.Emit (OpCodes.Conv_U1); break;
1894 case Mode.U8_I2: ig.Emit (OpCodes.Conv_I2); break;
1895 case Mode.U8_U2: ig.Emit (OpCodes.Conv_U2); break;
1896 case Mode.U8_I4: ig.Emit (OpCodes.Conv_I4); break;
1897 case Mode.U8_U4: ig.Emit (OpCodes.Conv_U4); break;
1898 case Mode.U8_I8: /* nothing */ break;
1899 case Mode.U8_CH: ig.Emit (OpCodes.Conv_U2); break;
1901 case Mode.CH_I1: ig.Emit (OpCodes.Conv_I1); break;
1902 case Mode.CH_U1: ig.Emit (OpCodes.Conv_U1); break;
1903 case Mode.CH_I2: ig.Emit (OpCodes.Conv_I2); break;
1905 case Mode.R4_I1: ig.Emit (OpCodes.Conv_I1); break;
1906 case Mode.R4_U1: ig.Emit (OpCodes.Conv_U1); break;
1907 case Mode.R4_I2: ig.Emit (OpCodes.Conv_I2); break;
1908 case Mode.R4_U2: ig.Emit (OpCodes.Conv_U2); break;
1909 case Mode.R4_I4: ig.Emit (OpCodes.Conv_I4); break;
1910 case Mode.R4_U4: ig.Emit (OpCodes.Conv_U4); break;
1911 case Mode.R4_I8: ig.Emit (OpCodes.Conv_I8); break;
1912 case Mode.R4_U8: ig.Emit (OpCodes.Conv_U8); break;
1913 case Mode.R4_CH: ig.Emit (OpCodes.Conv_U2); break;
1915 case Mode.R8_I1: ig.Emit (OpCodes.Conv_I1); break;
1916 case Mode.R8_U1: ig.Emit (OpCodes.Conv_U1); break;
1917 case Mode.R8_I2: ig.Emit (OpCodes.Conv_I2); break;
1918 case Mode.R8_U2: ig.Emit (OpCodes.Conv_U2); break;
1919 case Mode.R8_I4: ig.Emit (OpCodes.Conv_I4); break;
1920 case Mode.R8_U4: ig.Emit (OpCodes.Conv_U4); break;
1921 case Mode.R8_I8: ig.Emit (OpCodes.Conv_I8); break;
1922 case Mode.R8_U8: ig.Emit (OpCodes.Conv_U8); break;
1923 case Mode.R8_CH: ig.Emit (OpCodes.Conv_U2); break;
1924 case Mode.R8_R4: ig.Emit (OpCodes.Conv_R4); break;
1930 public class OpcodeCast : EmptyCast {
1934 public OpcodeCast (Expression child, Type return_type, OpCode op)
1935 : base (child, return_type)
1939 second_valid = false;
1942 public OpcodeCast (Expression child, Type return_type, OpCode op, OpCode op2)
1943 : base (child, return_type)
1948 second_valid = true;
1951 public override Expression DoResolve (EmitContext ec)
1953 // This should never be invoked, we are born in fully
1954 // initialized state.
1959 public override void Emit (EmitContext ec)
1970 /// This kind of cast is used to encapsulate a child and cast it
1971 /// to the class requested
1973 public class ClassCast : EmptyCast {
1974 public ClassCast (Expression child, Type return_type)
1975 : base (child, return_type)
1980 public override Expression DoResolve (EmitContext ec)
1982 // This should never be invoked, we are born in fully
1983 // initialized state.
1988 public override void Emit (EmitContext ec)
1992 if (child.Type.IsGenericParameter)
1993 ec.ig.Emit (OpCodes.Box, child.Type);
1995 if (type.IsGenericParameter)
1996 ec.ig.Emit (OpCodes.Unbox_Any, type);
1998 ec.ig.Emit (OpCodes.Castclass, type);
2003 /// SimpleName expressions are formed of a single word and only happen at the beginning
2004 /// of a dotted-name.
2006 public class SimpleName : Expression {
2008 public readonly TypeArguments Arguments;
2010 public SimpleName (string name, Location l)
2016 public SimpleName (string name, TypeArguments args, Location l)
2023 public static void Error_ObjectRefRequired (EmitContext ec, Location l, string name)
2025 if (ec.IsFieldInitializer)
2028 "A field initializer cannot reference the non-static field, " +
2029 "method or property `"+name+"'");
2033 "An object reference is required " +
2034 "for the non-static field `"+name+"'");
2038 // Checks whether we are trying to access an instance
2039 // property, method or field from a static body.
2041 Expression MemberStaticCheck (EmitContext ec, Expression e)
2043 if (e is IMemberExpr){
2044 IMemberExpr member = (IMemberExpr) e;
2046 if (!member.IsStatic){
2047 Error_ObjectRefRequired (ec, loc, Name);
2055 public override Expression DoResolve (EmitContext ec)
2057 return SimpleNameResolve (ec, null, false, false);
2060 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
2062 return SimpleNameResolve (ec, right_side, false, false);
2066 public Expression DoResolveAllowStatic (EmitContext ec, bool intermediate)
2068 return SimpleNameResolve (ec, null, true, intermediate);
2071 public override FullNamedExpression ResolveAsTypeStep (EmitContext ec)
2073 DeclSpace ds = ec.DeclSpace;
2074 FullNamedExpression dt;
2076 dt = ds.LookupGeneric (Name, loc);
2078 return dt.ResolveAsTypeStep (ec);
2080 int errors = Report.Errors;
2081 dt = ec.ResolvingTypeTree
2082 ? ds.FindType (loc, Name)
2083 : ds.LookupType (Name, true, loc);
2084 if (Report.Errors != errors)
2090 Expression SimpleNameResolve (EmitContext ec, Expression right_side,
2091 bool allow_static, bool intermediate)
2093 Expression e = DoSimpleNameResolve (ec, right_side, allow_static, intermediate);
2097 Block current_block = ec.CurrentBlock;
2098 if (current_block != null){
2099 if (current_block.IsVariableNameUsedInChildBlock (Name)) {
2100 Report.Error (135, Location,
2101 "'{0}' has a different meaning in a child block", Name);
2106 if (e.Type != null && e.Type.IsPointer && !ec.InUnsafe) {
2115 /// 7.5.2: Simple Names.
2117 /// Local Variables and Parameters are handled at
2118 /// parse time, so they never occur as SimpleNames.
2120 /// The `allow_static' flag is used by MemberAccess only
2121 /// and it is used to inform us that it is ok for us to
2122 /// avoid the static check, because MemberAccess might end
2123 /// up resolving the Name as a Type name and the access as
2124 /// a static type access.
2126 /// ie: Type Type; .... { Type.GetType (""); }
2128 /// Type is both an instance variable and a Type; Type.GetType
2129 /// is the static method not an instance method of type.
2131 Expression DoSimpleNameResolve (EmitContext ec, Expression right_side, bool allow_static, bool intermediate)
2133 Expression e = null;
2136 // Stage 1: Performed by the parser (binding to locals or parameters).
2138 Block current_block = ec.CurrentBlock;
2139 if (current_block != null){
2140 LocalInfo vi = current_block.GetLocalInfo (Name);
2144 var = new LocalVariableReference (ec.CurrentBlock, Name, loc);
2146 if (right_side != null)
2147 return var.ResolveLValue (ec, right_side);
2149 return var.Resolve (ec);
2152 ParameterReference pref = current_block.GetParameterReference (Name, loc);
2154 if (right_side != null)
2155 return pref.ResolveLValue (ec, right_side);
2157 return pref.Resolve (ec);
2162 // Stage 2: Lookup members
2165 DeclSpace lookup_ds = ec.DeclSpace;
2166 Type almost_matched_type = null;
2167 ArrayList almost_matched = null;
2169 if (lookup_ds.TypeBuilder == null)
2172 e = MemberLookup (ec, lookup_ds.TypeBuilder, Name, loc);
2176 if (almost_matched == null && almostMatchedMembers.Count > 0) {
2177 almost_matched_type = lookup_ds.TypeBuilder;
2178 almost_matched = (ArrayList) almostMatchedMembers.Clone ();
2181 lookup_ds =lookup_ds.Parent;
2182 } while (lookup_ds != null);
2184 if (e == null && ec.ContainerType != null)
2185 e = MemberLookup (ec, ec.ContainerType, Name, loc);
2188 if (almost_matched == null && almostMatchedMembers.Count > 0) {
2189 almost_matched_type = ec.ContainerType;
2190 almost_matched = (ArrayList) almostMatchedMembers.Clone ();
2192 e = ResolveAsTypeStep (ec);
2196 if (almost_matched != null)
2197 almostMatchedMembers = almost_matched;
2198 if (almost_matched_type == null)
2199 almost_matched_type = ec.ContainerType;
2200 MemberLookupFailed (ec, null, almost_matched_type, ((SimpleName) this).Name, ec.DeclSpace.Name, loc);
2207 if (e is IMemberExpr) {
2208 e = MemberAccess.ResolveMemberAccess (ec, e, null, loc, this);
2212 IMemberExpr me = e as IMemberExpr;
2216 if (Arguments != null) {
2217 MethodGroupExpr mg = me as MethodGroupExpr;
2221 return mg.ResolveGeneric (ec, Arguments);
2224 // This fails if ResolveMemberAccess() was unable to decide whether
2225 // it's a field or a type of the same name.
2227 if (!me.IsStatic && (me.InstanceExpression == null))
2231 TypeManager.IsNestedFamilyAccessible (me.InstanceExpression.Type, me.DeclaringType) &&
2232 me.InstanceExpression.Type != me.DeclaringType &&
2233 !TypeManager.IsFamilyAccessible (me.InstanceExpression.Type, me.DeclaringType) &&
2234 (!intermediate || !MemberAccess.IdenticalNameAndTypeName (ec, this, e, loc))) {
2235 Error (38, "Cannot access nonstatic member `" + me.Name + "' of " +
2236 "outer type `" + me.DeclaringType + "' via nested type `" +
2237 me.InstanceExpression.Type + "'");
2241 return (right_side != null)
2242 ? e.DoResolveLValue (ec, right_side)
2246 if (ec.IsStatic || ec.IsFieldInitializer){
2250 return MemberStaticCheck (ec, e);
2255 public override void Emit (EmitContext ec)
2258 // If this is ever reached, then we failed to
2259 // find the name as a namespace
2262 Error (103, "The name `" + Name +
2263 "' does not exist in the class `" +
2264 ec.DeclSpace.Name + "'");
2267 public override string ToString ()
2274 /// Represents a namespace or a type. The name of the class was inspired by
2275 /// section 10.8.1 (Fully Qualified Names).
2277 public abstract class FullNamedExpression : Expression {
2278 public abstract string FullName {
2284 /// Fully resolved expression that evaluates to a type
2286 public abstract class TypeExpr : FullNamedExpression {
2287 override public FullNamedExpression ResolveAsTypeStep (EmitContext ec)
2289 TypeExpr t = DoResolveAsTypeStep (ec);
2293 eclass = ExprClass.Type;
2297 override public Expression DoResolve (EmitContext ec)
2299 return ResolveAsTypeTerminal (ec);
2302 override public void Emit (EmitContext ec)
2304 throw new Exception ("Should never be called");
2307 public virtual bool CheckAccessLevel (DeclSpace ds)
2309 return ds.CheckAccessLevel (Type);
2312 public virtual bool AsAccessible (DeclSpace ds, int flags)
2314 return ds.AsAccessible (Type, flags);
2317 public virtual bool IsClass {
2318 get { return Type.IsClass; }
2321 public virtual bool IsValueType {
2322 get { return Type.IsValueType; }
2325 public virtual bool IsInterface {
2326 get { return Type.IsInterface; }
2329 public virtual bool IsSealed {
2330 get { return Type.IsSealed; }
2333 public virtual bool CanInheritFrom ()
2335 if (Type == TypeManager.enum_type ||
2336 (Type == TypeManager.value_type && RootContext.StdLib) ||
2337 Type == TypeManager.multicast_delegate_type ||
2338 Type == TypeManager.delegate_type ||
2339 Type == TypeManager.array_type)
2345 public virtual bool IsAttribute {
2347 return Type == TypeManager.attribute_type ||
2348 Type.IsSubclassOf (TypeManager.attribute_type);
2352 protected abstract TypeExpr DoResolveAsTypeStep (EmitContext ec);
2354 public virtual Type ResolveType (EmitContext ec)
2356 TypeExpr t = ResolveAsTypeTerminal (ec);
2363 public abstract string Name {
2367 public override bool Equals (object obj)
2369 TypeExpr tobj = obj as TypeExpr;
2373 return Type == tobj.Type;
2376 public override int GetHashCode ()
2378 return Type.GetHashCode ();
2381 public override string ToString ()
2387 public class TypeExpression : TypeExpr {
2388 public TypeExpression (Type t, Location l)
2391 eclass = ExprClass.Type;
2395 protected override TypeExpr DoResolveAsTypeStep (EmitContext ec)
2400 public override string Name {
2402 return Type.ToString ();
2406 public override string FullName {
2408 return Type.FullName != null ? Type.FullName : Type.Name;
2414 /// Used to create types from a fully qualified name. These are just used
2415 /// by the parser to setup the core types. A TypeLookupExpression is always
2416 /// classified as a type.
2418 public class TypeLookupExpression : TypeExpr {
2421 public TypeLookupExpression (string name)
2426 protected override TypeExpr DoResolveAsTypeStep (EmitContext ec)
2429 FullNamedExpression t = ec.DeclSpace.LookupType (name, false, Location.Null);
2432 if (!(t is TypeExpr))
2434 type = ((TypeExpr) t).ResolveType (ec);
2440 public override string Name {
2446 public override string FullName {
2454 /// Represents an "unbound generic type", ie. typeof (Foo<>).
2457 public class UnboundTypeExpression : TypeLookupExpression {
2458 public UnboundTypeExpression (string name)
2463 public class TypeAliasExpression : TypeExpr {
2464 FullNamedExpression alias;
2469 public TypeAliasExpression (FullNamedExpression alias, TypeArguments args, Location l)
2475 eclass = ExprClass.Type;
2477 name = alias.FullName + "<" + args.ToString () + ">";
2479 name = alias.FullName;
2482 public override string Name {
2483 get { return alias.FullName; }
2486 public override string FullName {
2487 get { return name; }
2490 protected override TypeExpr DoResolveAsTypeStep (EmitContext ec)
2492 texpr = alias.ResolveAsTypeTerminal (ec);
2496 Type type = texpr.Type;
2497 int num_args = TypeManager.GetNumberOfTypeArguments (type);
2500 if (num_args == 0) {
2501 Report.Error (308, loc,
2502 "The non-generic type `{0}' cannot " +
2503 "be used with type arguments.",
2504 TypeManager.CSharpName (type));
2508 ConstructedType ctype = new ConstructedType (type, args, loc);
2509 return ctype.ResolveAsTypeTerminal (ec);
2510 } else if (num_args > 0) {
2511 Report.Error (305, loc,
2512 "Using the generic type `{0}' " +
2513 "requires {1} type arguments",
2514 TypeManager.GetFullName (type), num_args);
2518 return new TypeExpression (type, loc);
2521 public override bool CheckAccessLevel (DeclSpace ds)
2523 return texpr.CheckAccessLevel (ds);
2526 public override bool AsAccessible (DeclSpace ds, int flags)
2528 return texpr.AsAccessible (ds, flags);
2531 public override bool IsClass {
2532 get { return texpr.IsClass; }
2535 public override bool IsValueType {
2536 get { return texpr.IsValueType; }
2539 public override bool IsInterface {
2540 get { return texpr.IsInterface; }
2543 public override bool IsSealed {
2544 get { return texpr.IsSealed; }
2547 public override bool IsAttribute {
2548 get { return texpr.IsAttribute; }
2553 /// MethodGroup Expression.
2555 /// This is a fully resolved expression that evaluates to a type
2557 public class MethodGroupExpr : Expression, IMemberExpr {
2558 public MethodBase [] Methods;
2559 Expression instance_expression = null;
2560 bool is_explicit_impl = false;
2561 bool has_type_arguments = false;
2562 bool identical_type_name = false;
2565 public MethodGroupExpr (MemberInfo [] mi, Location l)
2567 Methods = new MethodBase [mi.Length];
2568 mi.CopyTo (Methods, 0);
2569 eclass = ExprClass.MethodGroup;
2570 type = TypeManager.object_type;
2574 public MethodGroupExpr (ArrayList list, Location l)
2576 Methods = new MethodBase [list.Count];
2579 list.CopyTo (Methods, 0);
2581 foreach (MemberInfo m in list){
2582 if (!(m is MethodBase)){
2583 Console.WriteLine ("Name " + m.Name);
2584 Console.WriteLine ("Found a: " + m.GetType ().FullName);
2591 eclass = ExprClass.MethodGroup;
2592 type = TypeManager.object_type;
2595 public Type DeclaringType {
2598 // We assume that the top-level type is in the end
2600 return Methods [Methods.Length - 1].DeclaringType;
2601 //return Methods [0].DeclaringType;
2606 // `A method group may have associated an instance expression'
2608 public Expression InstanceExpression {
2610 return instance_expression;
2614 instance_expression = value;
2618 public bool IsExplicitImpl {
2620 return is_explicit_impl;
2624 is_explicit_impl = value;
2628 public bool HasTypeArguments {
2630 return has_type_arguments;
2634 has_type_arguments = value;
2638 public bool IdenticalTypeName {
2640 return identical_type_name;
2644 identical_type_name = value;
2648 public bool IsBase {
2657 public string Name {
2659 //return Methods [0].Name;
2660 return Methods [Methods.Length - 1].Name;
2664 public bool IsInstance {
2666 foreach (MethodBase mb in Methods)
2674 public bool IsStatic {
2676 foreach (MethodBase mb in Methods)
2684 override public Expression DoResolve (EmitContext ec)
2687 instance_expression = null;
2689 if (instance_expression != null) {
2690 instance_expression = instance_expression.DoResolve (ec);
2691 if (instance_expression == null)
2698 public void ReportUsageError ()
2700 Report.Error (654, loc, "Method `" + DeclaringType + "." +
2701 Name + "()' is referenced without parentheses");
2704 override public void Emit (EmitContext ec)
2706 ReportUsageError ();
2709 bool RemoveMethods (bool keep_static)
2711 ArrayList smethods = new ArrayList ();
2713 foreach (MethodBase mb in Methods){
2714 if (mb.IsStatic == keep_static)
2718 if (smethods.Count == 0)
2721 Methods = new MethodBase [smethods.Count];
2722 smethods.CopyTo (Methods, 0);
2728 /// Removes any instance methods from the MethodGroup, returns
2729 /// false if the resulting set is empty.
2731 public bool RemoveInstanceMethods ()
2733 return RemoveMethods (true);
2737 /// Removes any static methods from the MethodGroup, returns
2738 /// false if the resulting set is empty.
2740 public bool RemoveStaticMethods ()
2742 return RemoveMethods (false);
2745 public Expression ResolveGeneric (EmitContext ec, TypeArguments args)
2747 if (args.Resolve (ec) == false)
2750 Type[] atypes = args.Arguments;
2752 int first_count = 0;
2753 MethodInfo first = null;
2755 ArrayList list = new ArrayList ();
2756 foreach (MethodBase mb in Methods) {
2757 MethodInfo mi = mb as MethodInfo;
2758 if ((mi == null) || !mi.HasGenericParameters)
2761 Type[] gen_params = mi.GetGenericArguments ();
2763 if (first == null) {
2765 first_count = gen_params.Length;
2768 if (gen_params.Length != atypes.Length)
2771 list.Add (mi.BindGenericParameters (atypes));
2774 if (list.Count > 0) {
2775 MethodGroupExpr new_mg = new MethodGroupExpr (list, Location);
2776 new_mg.InstanceExpression = InstanceExpression;
2777 new_mg.HasTypeArguments = true;
2783 305, loc, "Using the generic method `{0}' " +
2784 "requires {1} type arguments", Name,
2788 308, loc, "The non-generic method `{0}' " +
2789 "cannot be used with type arguments", Name);
2796 /// Fully resolved expression that evaluates to a Field
2798 public class FieldExpr : Expression, IAssignMethod, IMemoryLocation, IMemberExpr, IVariable {
2799 public readonly FieldInfo FieldInfo;
2800 Expression instance_expr;
2801 VariableInfo variable_info;
2803 LocalTemporary temp;
2805 bool is_field_initializer;
2807 public FieldExpr (FieldInfo fi, Location l)
2810 eclass = ExprClass.Variable;
2811 type = TypeManager.TypeToCoreType (fi.FieldType);
2815 public string Name {
2817 return FieldInfo.Name;
2821 public bool IsInstance {
2823 return !FieldInfo.IsStatic;
2827 public bool IsStatic {
2829 return FieldInfo.IsStatic;
2833 public Type DeclaringType {
2835 return FieldInfo.DeclaringType;
2839 public Expression InstanceExpression {
2841 return instance_expr;
2845 instance_expr = value;
2849 public bool IsFieldInitializer {
2851 return is_field_initializer;
2855 is_field_initializer = value;
2859 public VariableInfo VariableInfo {
2861 return variable_info;
2865 override public Expression DoResolve (EmitContext ec)
2867 if (!FieldInfo.IsStatic){
2868 if (instance_expr == null){
2870 // This can happen when referencing an instance field using
2871 // a fully qualified type expression: TypeName.InstanceField = xxx
2873 SimpleName.Error_ObjectRefRequired (ec, loc, FieldInfo.Name);
2877 // Resolve the field's instance expression while flow analysis is turned
2878 // off: when accessing a field "a.b", we must check whether the field
2879 // "a.b" is initialized, not whether the whole struct "a" is initialized.
2880 instance_expr = instance_expr.Resolve (ec, ResolveFlags.VariableOrValue |
2881 ResolveFlags.DisableFlowAnalysis);
2882 if (instance_expr == null)
2886 ObsoleteAttribute oa;
2887 FieldBase f = TypeManager.GetField (FieldInfo);
2889 oa = f.GetObsoleteAttribute (f.Parent);
2891 AttributeTester.Report_ObsoleteMessage (oa, f.GetSignatureForError (), loc);
2892 // To be sure that type is external because we do not register generated fields
2893 } else if (!(FieldInfo.DeclaringType is TypeBuilder)) {
2894 oa = AttributeTester.GetMemberObsoleteAttribute (FieldInfo);
2896 AttributeTester.Report_ObsoleteMessage (oa, TypeManager.GetFullNameSignature (FieldInfo), loc);
2899 if (ec.CurrentAnonymousMethod != null){
2900 if (!FieldInfo.IsStatic){
2901 if (ec.TypeContainer is Struct){
2902 Report.Error (1673, loc, "Can not reference instance variables in anonymous methods hosted in structs");
2905 ec.CaptureField (this);
2909 // If the instance expression is a local variable or parameter.
2910 IVariable var = instance_expr as IVariable;
2911 if ((var == null) || (var.VariableInfo == null))
2914 VariableInfo vi = var.VariableInfo;
2915 if (!vi.IsFieldAssigned (ec, FieldInfo.Name, loc))
2918 variable_info = vi.GetSubStruct (FieldInfo.Name);
2922 void Report_AssignToReadonly (bool is_instance)
2927 msg = "Readonly field can not be assigned outside " +
2928 "of constructor or variable initializer";
2930 msg = "A static readonly field can only be assigned in " +
2931 "a static constructor";
2933 Report.Error (is_instance ? 191 : 198, loc, msg);
2936 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
2938 IVariable var = instance_expr as IVariable;
2939 if ((var != null) && (var.VariableInfo != null))
2940 var.VariableInfo.SetFieldAssigned (ec, FieldInfo.Name);
2942 Expression e = DoResolve (ec);
2947 if (!FieldInfo.IsStatic && (instance_expr.Type.IsValueType && !(instance_expr is IMemoryLocation))) {
2948 // FIXME: Provide better error reporting.
2949 Error (1612, "Cannot modify expression because it is not a variable.");
2953 if (!FieldInfo.IsInitOnly)
2956 FieldBase fb = TypeManager.GetField (FieldInfo);
2961 // InitOnly fields can only be assigned in constructors
2964 if (ec.IsConstructor){
2965 if (IsStatic && !ec.IsStatic)
2966 Report_AssignToReadonly (false);
2969 if (!is_field_initializer &&
2970 (ec.TypeContainer.CurrentType != null))
2971 ctype = ec.TypeContainer.CurrentType;
2973 ctype = ec.ContainerType;
2975 if (TypeManager.IsEqual (ctype, FieldInfo.DeclaringType))
2979 Report_AssignToReadonly (!IsStatic);
2984 public override void CheckMarshallByRefAccess (Type container)
2986 if (!IsStatic && Type.IsValueType && !container.IsSubclassOf (TypeManager.mbr_type) && DeclaringType.IsSubclassOf (TypeManager.mbr_type)) {
2987 Report.SymbolRelatedToPreviousError (DeclaringType);
2988 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);
2992 public bool VerifyFixed (bool is_expression)
2994 IVariable variable = instance_expr as IVariable;
2995 if ((variable == null) || !variable.VerifyFixed (true))
3001 public void Emit (EmitContext ec, bool leave_copy)
3003 ILGenerator ig = ec.ig;
3004 bool is_volatile = false;
3006 if (FieldInfo is FieldBuilder){
3007 FieldBase f = TypeManager.GetField (FieldInfo);
3009 if ((f.ModFlags & Modifiers.VOLATILE) != 0)
3012 f.status |= Field.Status.USED;
3016 if (FieldInfo.IsStatic){
3018 ig.Emit (OpCodes.Volatile);
3020 ig.Emit (OpCodes.Ldsfld, FieldInfo);
3026 ig.Emit (OpCodes.Volatile);
3028 ig.Emit (OpCodes.Ldfld, FieldInfo);
3032 ec.ig.Emit (OpCodes.Dup);
3033 if (!FieldInfo.IsStatic) {
3034 temp = new LocalTemporary (ec, this.Type);
3040 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
3042 FieldAttributes fa = FieldInfo.Attributes;
3043 bool is_static = (fa & FieldAttributes.Static) != 0;
3044 bool is_readonly = (fa & FieldAttributes.InitOnly) != 0;
3045 ILGenerator ig = ec.ig;
3046 prepared = prepare_for_load;
3048 if (is_readonly && !ec.IsConstructor){
3049 Report_AssignToReadonly (!is_static);
3055 if (prepare_for_load)
3056 ig.Emit (OpCodes.Dup);
3061 ec.ig.Emit (OpCodes.Dup);
3062 if (!FieldInfo.IsStatic) {
3063 temp = new LocalTemporary (ec, this.Type);
3068 if (FieldInfo is FieldBuilder){
3069 FieldBase f = TypeManager.GetField (FieldInfo);
3071 if ((f.ModFlags & Modifiers.VOLATILE) != 0)
3072 ig.Emit (OpCodes.Volatile);
3074 f.status |= Field.Status.ASSIGNED;
3079 ig.Emit (OpCodes.Stsfld, FieldInfo);
3081 ig.Emit (OpCodes.Stfld, FieldInfo);
3087 void EmitInstance (EmitContext ec)
3089 if (instance_expr.Type.IsValueType) {
3090 if (instance_expr is IMemoryLocation) {
3091 ((IMemoryLocation) instance_expr).AddressOf (ec, AddressOp.LoadStore);
3093 LocalTemporary t = new LocalTemporary (ec, instance_expr.Type);
3094 instance_expr.Emit (ec);
3096 t.AddressOf (ec, AddressOp.Store);
3099 instance_expr.Emit (ec);
3102 public override void Emit (EmitContext ec)
3107 public void AddressOf (EmitContext ec, AddressOp mode)
3109 ILGenerator ig = ec.ig;
3111 if (FieldInfo is FieldBuilder){
3112 FieldBase f = TypeManager.GetField (FieldInfo);
3114 if ((f.ModFlags & Modifiers.VOLATILE) != 0){
3115 Error (676, "volatile variable: can not take its address, or pass as ref/out parameter");
3119 if ((mode & AddressOp.Store) != 0)
3120 f.status |= Field.Status.ASSIGNED;
3121 if ((mode & AddressOp.Load) != 0)
3122 f.status |= Field.Status.USED;
3127 // Handle initonly fields specially: make a copy and then
3128 // get the address of the copy.
3131 if (FieldInfo.IsInitOnly){
3133 if (ec.IsConstructor){
3134 if (FieldInfo.IsStatic){
3146 local = ig.DeclareLocal (type);
3147 ig.Emit (OpCodes.Stloc, local);
3148 ig.Emit (OpCodes.Ldloca, local);
3153 if (FieldInfo.IsStatic){
3154 ig.Emit (OpCodes.Ldsflda, FieldInfo);
3157 ig.Emit (OpCodes.Ldflda, FieldInfo);
3163 // A FieldExpr whose address can not be taken
3165 public class FieldExprNoAddress : FieldExpr, IMemoryLocation {
3166 public FieldExprNoAddress (FieldInfo fi, Location loc) : base (fi, loc)
3170 public new void AddressOf (EmitContext ec, AddressOp mode)
3172 Report.Error (-215, "Report this: Taking the address of a remapped parameter not supported");
3177 /// Expression that evaluates to a Property. The Assign class
3178 /// might set the `Value' expression if we are in an assignment.
3180 /// This is not an LValue because we need to re-write the expression, we
3181 /// can not take data from the stack and store it.
3183 public class PropertyExpr : ExpressionStatement, IAssignMethod, IMemberExpr {
3184 public readonly PropertyInfo PropertyInfo;
3187 // This is set externally by the `BaseAccess' class
3190 MethodInfo getter, setter;
3193 Expression instance_expr;
3194 LocalTemporary temp;
3197 internal static PtrHashtable AccessorTable = new PtrHashtable ();
3199 public PropertyExpr (EmitContext ec, PropertyInfo pi, Location l)
3202 eclass = ExprClass.PropertyAccess;
3206 type = TypeManager.TypeToCoreType (pi.PropertyType);
3208 ResolveAccessors (ec);
3211 public string Name {
3213 return PropertyInfo.Name;
3217 public bool IsInstance {
3223 public bool IsStatic {
3229 public Type DeclaringType {
3231 return PropertyInfo.DeclaringType;
3236 // The instance expression associated with this expression
3238 public Expression InstanceExpression {
3240 instance_expr = value;
3244 return instance_expr;
3248 public bool VerifyAssignable ()
3250 if (setter == null) {
3251 Report.Error (200, loc,
3252 "The property `" + PropertyInfo.Name +
3253 "' can not be assigned to, as it has not set accessor");
3260 void FindAccessors (Type invocation_type)
3262 BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic |
3263 BindingFlags.Static | BindingFlags.Instance |
3264 BindingFlags.DeclaredOnly;
3266 Type current = PropertyInfo.DeclaringType;
3267 for (; current != null; current = current.BaseType) {
3268 MemberInfo[] group = TypeManager.MemberLookup (
3269 invocation_type, invocation_type, current,
3270 MemberTypes.Property, flags, PropertyInfo.Name, null);
3275 if (group.Length != 1)
3276 // Oooops, can this ever happen ?
3279 PropertyInfo pi = (PropertyInfo) group [0];
3282 getter = pi.GetGetMethod (true);
3285 setter = pi.GetSetMethod (true);
3287 MethodInfo accessor = getter != null ? getter : setter;
3289 if (!accessor.IsVirtual)
3295 // We also perform the permission checking here, as the PropertyInfo does not
3296 // hold the information for the accessibility of its setter/getter
3298 void ResolveAccessors (EmitContext ec)
3300 FindAccessors (ec.ContainerType);
3302 if (getter != null) {
3303 AccessorTable [getter] = PropertyInfo;
3304 is_static = getter.IsStatic;
3307 if (setter != null) {
3308 AccessorTable [setter] = PropertyInfo;
3309 is_static = setter.IsStatic;
3313 bool InstanceResolve (EmitContext ec, bool must_do_cs1540_check)
3315 if ((instance_expr == null) && ec.IsStatic && !is_static) {
3316 SimpleName.Error_ObjectRefRequired (ec, loc, PropertyInfo.Name);
3320 if (instance_expr != null) {
3321 instance_expr = instance_expr.DoResolve (ec);
3322 if (instance_expr == null)
3325 instance_expr.CheckMarshallByRefAccess (ec.ContainerType);
3328 if (must_do_cs1540_check && (instance_expr != null)) {
3329 if ((instance_expr.Type != ec.ContainerType) &&
3330 ec.ContainerType.IsSubclassOf (instance_expr.Type)) {
3331 Report.Error (1540, loc, "Cannot access protected member `" +
3332 PropertyInfo.DeclaringType + "." + PropertyInfo.Name +
3333 "' via a qualifier of type `" +
3334 TypeManager.CSharpName (instance_expr.Type) +
3335 "'; the qualifier must be of type `" +
3336 TypeManager.CSharpName (ec.ContainerType) +
3337 "' (or derived from it)");
3345 override public Expression DoResolve (EmitContext ec)
3347 if (getter != null){
3348 if (TypeManager.GetArgumentTypes (getter).Length != 0){
3350 117, loc, "`{0}' does not contain a " +
3351 "definition for `{1}'.", getter.DeclaringType,
3357 if (getter == null){
3359 // The following condition happens if the PropertyExpr was
3360 // created, but is invalid (ie, the property is inaccessible),
3361 // and we did not want to embed the knowledge about this in
3362 // the caller routine. This only avoids double error reporting.
3367 Report.Error (154, loc,
3368 "The property `" + PropertyInfo.Name +
3369 "' can not be used in " +
3370 "this context because it lacks a get accessor");
3374 bool must_do_cs1540_check;
3375 if (!IsAccessorAccessible (ec.ContainerType, getter, out must_do_cs1540_check)) {
3376 Report.Error (122, loc, "'{0}.get' is inaccessible due to its protection level", PropertyInfo.Name);
3380 if (!InstanceResolve (ec, must_do_cs1540_check))
3384 // Only base will allow this invocation to happen.
3386 if (IsBase && getter.IsAbstract){
3387 Report.Error (205, loc, "Cannot call an abstract base property: " +
3388 PropertyInfo.DeclaringType + "." +PropertyInfo.Name);
3395 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
3397 if (setter == null){
3399 // The following condition happens if the PropertyExpr was
3400 // created, but is invalid (ie, the property is inaccessible),
3401 // and we did not want to embed the knowledge about this in
3402 // the caller routine. This only avoids double error reporting.
3407 Report.Error (154, loc,
3408 "The property `" + PropertyInfo.Name +
3409 "' can not be used in " +
3410 "this context because it lacks a set accessor");
3414 if (TypeManager.GetArgumentTypes (setter).Length != 1){
3416 117, loc, "`{0}' does not contain a " +
3417 "definition for `{1}'.", getter.DeclaringType,
3422 bool must_do_cs1540_check;
3423 if (!IsAccessorAccessible (ec.ContainerType, setter, out must_do_cs1540_check)) {
3424 Report.Error (122, loc, "'{0}.set' is inaccessible due to its protection level", PropertyInfo.Name);
3428 if (!InstanceResolve (ec, must_do_cs1540_check))
3432 // Only base will allow this invocation to happen.
3434 if (IsBase && setter.IsAbstract){
3435 Report.Error (205, loc, "Cannot call an abstract base property: " +
3436 PropertyInfo.DeclaringType + "." +PropertyInfo.Name);
3441 // Check that we are not making changes to a temporary memory location
3443 if (instance_expr != null && instance_expr.Type.IsValueType && !(instance_expr is IMemoryLocation)) {
3444 // FIXME: Provide better error reporting.
3445 Error (1612, "Cannot modify expression because it is not a variable.");
3454 public override void Emit (EmitContext ec)
3459 void EmitInstance (EmitContext ec)
3464 if (instance_expr.Type.IsValueType) {
3465 if (instance_expr is IMemoryLocation) {
3466 ((IMemoryLocation) instance_expr).AddressOf (ec, AddressOp.LoadStore);
3468 LocalTemporary t = new LocalTemporary (ec, instance_expr.Type);
3469 instance_expr.Emit (ec);
3471 t.AddressOf (ec, AddressOp.Store);
3474 instance_expr.Emit (ec);
3477 ec.ig.Emit (OpCodes.Dup);
3481 public void Emit (EmitContext ec, bool leave_copy)
3487 // Special case: length of single dimension array property is turned into ldlen
3489 if ((getter == TypeManager.system_int_array_get_length) ||
3490 (getter == TypeManager.int_array_get_length)){
3491 Type iet = instance_expr.Type;
3494 // System.Array.Length can be called, but the Type does not
3495 // support invoking GetArrayRank, so test for that case first
3497 if (iet != TypeManager.array_type && (iet.GetArrayRank () == 1)) {
3498 ec.ig.Emit (OpCodes.Ldlen);
3499 ec.ig.Emit (OpCodes.Conv_I4);
3504 Invocation.EmitCall (ec, IsBase, IsStatic, new EmptyAddressOf (), getter, null, loc);
3509 ec.ig.Emit (OpCodes.Dup);
3511 temp = new LocalTemporary (ec, this.Type);
3517 // Implements the IAssignMethod interface for assignments
3519 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
3521 prepared = prepare_for_load;
3527 ec.ig.Emit (OpCodes.Dup);
3529 temp = new LocalTemporary (ec, this.Type);
3534 ArrayList args = new ArrayList (1);
3535 args.Add (new Argument (new EmptyAddressOf (), Argument.AType.Expression));
3537 Invocation.EmitCall (ec, IsBase, IsStatic, new EmptyAddressOf (), setter, args, loc);
3543 override public void EmitStatement (EmitContext ec)
3546 ec.ig.Emit (OpCodes.Pop);
3551 /// Fully resolved expression that evaluates to an Event
3553 public class EventExpr : Expression, IMemberExpr {
3554 public readonly EventInfo EventInfo;
3555 Expression instance_expr;
3558 MethodInfo add_accessor, remove_accessor;
3560 public EventExpr (EventInfo ei, Location loc)
3564 eclass = ExprClass.EventAccess;
3566 add_accessor = TypeManager.GetAddMethod (ei);
3567 remove_accessor = TypeManager.GetRemoveMethod (ei);
3569 if (add_accessor.IsStatic || remove_accessor.IsStatic)
3572 if (EventInfo is MyEventBuilder){
3573 MyEventBuilder eb = (MyEventBuilder) EventInfo;
3574 type = eb.EventType;
3577 type = EventInfo.EventHandlerType;
3580 public string Name {
3582 return EventInfo.Name;
3586 public bool IsInstance {
3592 public bool IsStatic {
3598 public Type DeclaringType {
3600 return EventInfo.DeclaringType;
3604 public Expression InstanceExpression {
3606 return instance_expr;
3610 instance_expr = value;
3614 bool InstanceResolve (EmitContext ec, bool must_do_cs1540_check)
3616 if ((instance_expr == null) && ec.IsStatic && !is_static) {
3617 SimpleName.Error_ObjectRefRequired (ec, loc, EventInfo.Name);
3621 if (instance_expr != null) {
3622 instance_expr = instance_expr.DoResolve (ec);
3623 if (instance_expr == null)
3628 // This is using the same mechanism as the CS1540 check in PropertyExpr.
3629 // However, in the Event case, we reported a CS0122 instead.
3631 if (must_do_cs1540_check && (instance_expr != null)) {
3632 if ((instance_expr.Type != ec.ContainerType) &&
3633 ec.ContainerType.IsSubclassOf (instance_expr.Type)) {
3634 Report.Error (122, loc, "'{0}' is inaccessible due to its protection level",
3635 DeclaringType.Name + "." + EventInfo.Name);
3644 public override Expression DoResolve (EmitContext ec)
3646 if (instance_expr != null) {
3647 instance_expr = instance_expr.DoResolve (ec);
3648 if (instance_expr == null)
3652 bool must_do_cs1540_check;
3653 if (!(IsAccessorAccessible (ec.ContainerType, add_accessor, out must_do_cs1540_check)
3654 && IsAccessorAccessible (ec.ContainerType, remove_accessor, out must_do_cs1540_check))) {
3656 Report.Error (122, loc, "'{0}' is inaccessible due to its protection level",
3657 DeclaringType.Name + "." + EventInfo.Name);
3661 if (!InstanceResolve (ec, must_do_cs1540_check))
3667 public override void Emit (EmitContext ec)
3669 if (instance_expr is This)
3670 Report.Error (79, loc, "The event `{0}' can only appear on the left hand side of += or -=, try calling the actual delegate", Name);
3672 Report.Error (70, loc, "The event `{0}' can only appear on the left hand side of += or -= "+
3673 "(except on the defining type)", Name);
3676 public void EmitAddOrRemove (EmitContext ec, Expression source)
3678 BinaryDelegate source_del = (BinaryDelegate) source;
3679 Expression handler = source_del.Right;
3681 Argument arg = new Argument (handler, Argument.AType.Expression);
3682 ArrayList args = new ArrayList ();
3686 if (source_del.IsAddition)
3687 Invocation.EmitCall (
3688 ec, false, IsStatic, instance_expr, add_accessor, args, loc);
3690 Invocation.EmitCall (
3691 ec, false, IsStatic, instance_expr, remove_accessor, args, loc);