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 Expression 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 Expression GetOperatorFalse (EmitContext ec, Expression e, Location loc)
829 return GetOperatorTrueOrFalse (ec, e, false, loc);
832 static Expression GetOperatorTrueOrFalse (EmitContext ec, Expression e, bool is_true, Location loc)
835 Expression operator_group;
837 if (TypeManager.IsNullableType (e.Type))
838 return new Nullable.OperatorTrueOrFalse (e, is_true, loc).Resolve (ec);
840 operator_group = MethodLookup (ec, e.Type, is_true ? "op_True" : "op_False", loc);
841 if (operator_group == null)
844 ArrayList arguments = new ArrayList ();
845 arguments.Add (new Argument (e, Argument.AType.Expression));
846 method = Invocation.OverloadResolve (
847 ec, (MethodGroupExpr) operator_group, arguments, false, loc);
852 return new StaticCallExpr ((MethodInfo) method, arguments, loc);
856 /// Resolves the expression `e' into a boolean expression: either through
857 /// an implicit conversion, or through an `operator true' invocation
859 public static Expression ResolveBoolean (EmitContext ec, Expression e, Location loc)
865 if (e.Type == TypeManager.bool_type)
868 Expression converted = Convert.WideningConversion (ec, e, TypeManager.bool_type, new Location (-1));
870 if (converted != null)
874 // If no implicit conversion to bool exists, try using `operator true'
876 Expression operator_true = Expression.GetOperatorTrue (ec, e, loc);
877 if (operator_true == null){
878 Report.Error (31, loc, "Can not convert the expression to a boolean");
881 return operator_true;
884 public string ExprClassName ()
887 case ExprClass.Invalid:
889 case ExprClass.Value:
891 case ExprClass.Variable:
893 case ExprClass.Namespace:
897 case ExprClass.MethodGroup:
898 return "method group";
899 case ExprClass.PropertyAccess:
900 return "property access";
901 case ExprClass.EventAccess:
902 return "event access";
903 case ExprClass.IndexerAccess:
904 return "indexer access";
905 case ExprClass.Nothing:
908 throw new Exception ("Should not happen");
912 /// Reports that we were expecting `expr' to be of class `expected'
914 public void Error_UnexpectedKind (string expected, Location loc)
916 Report.Error (118, loc, "Expression denotes a `" + ExprClassName () +
917 "' where a `" + expected + "' was expected");
920 public void Error_UnexpectedKind (ResolveFlags flags, Location loc)
922 ArrayList valid = new ArrayList (10);
924 if ((flags & ResolveFlags.VariableOrValue) != 0) {
925 valid.Add ("variable");
929 if ((flags & ResolveFlags.Type) != 0)
932 if ((flags & ResolveFlags.MethodGroup) != 0)
933 valid.Add ("method group");
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 Report.Error (119, loc, "Expression denotes a `" + ExprClassName () + "' where " +
948 "a `" + sb.ToString () + "' was expected");
951 static public void Error_ConstantValueCannotBeConverted (Location l, string val, Type t)
953 Report.Error (31, l, "Constant value `" + val + "' cannot be converted to " +
954 TypeManager.CSharpName (t));
957 public static void UnsafeError (Location loc)
959 Report.Error (214, loc, "Pointers may only be used in an unsafe context");
963 /// Converts the IntConstant, UIntConstant, LongConstant or
964 /// ULongConstant into the integral target_type. Notice
965 /// that we do not return an `Expression' we do return
966 /// a boxed integral type.
968 /// FIXME: Since I added the new constants, we need to
969 /// also support conversions from CharConstant, ByteConstant,
970 /// SByteConstant, UShortConstant, ShortConstant
972 /// This is used by the switch statement, so the domain
973 /// of work is restricted to the literals above, and the
974 /// targets are int32, uint32, char, byte, sbyte, ushort,
975 /// short, uint64 and int64
977 public static object ConvertIntLiteral (Constant c, Type target_type, Location loc)
979 if (!Convert.WideningStandardConversionExists (Convert.ConstantEC, c, target_type)){
980 Convert.Error_CannotWideningConversion (loc, c.Type, target_type);
986 if (c.Type == target_type)
987 return ((Constant) c).GetValue ();
990 // Make into one of the literals we handle, we dont really care
991 // about this value as we will just return a few limited types
993 if (c is EnumConstant)
994 c = ((EnumConstant)c).WidenToCompilerConstant ();
996 if (c is IntConstant){
997 int v = ((IntConstant) c).Value;
999 if (target_type == TypeManager.uint32_type){
1002 } else if (target_type == TypeManager.char_type){
1003 if (v >= Char.MinValue && v <= Char.MaxValue)
1005 } else if (target_type == TypeManager.byte_type){
1006 if (v >= Byte.MinValue && v <= Byte.MaxValue)
1008 } else if (target_type == TypeManager.sbyte_type){
1009 if (v >= SByte.MinValue && v <= SByte.MaxValue)
1011 } else if (target_type == TypeManager.short_type){
1012 if (v >= Int16.MinValue && v <= UInt16.MaxValue)
1014 } else if (target_type == TypeManager.ushort_type){
1015 if (v >= UInt16.MinValue && v <= UInt16.MaxValue)
1017 } else if (target_type == TypeManager.int64_type)
1019 else if (target_type == TypeManager.uint64_type){
1025 } else if (c is UIntConstant){
1026 uint v = ((UIntConstant) c).Value;
1028 if (target_type == TypeManager.int32_type){
1029 if (v <= Int32.MaxValue)
1031 } else if (target_type == TypeManager.char_type){
1032 if (v >= Char.MinValue && v <= Char.MaxValue)
1034 } else if (target_type == TypeManager.byte_type){
1035 if (v <= Byte.MaxValue)
1037 } else if (target_type == TypeManager.sbyte_type){
1038 if (v <= SByte.MaxValue)
1040 } else if (target_type == TypeManager.short_type){
1041 if (v <= UInt16.MaxValue)
1043 } else if (target_type == TypeManager.ushort_type){
1044 if (v <= UInt16.MaxValue)
1046 } else if (target_type == TypeManager.int64_type)
1048 else if (target_type == TypeManager.uint64_type)
1051 } else if (c is LongConstant){
1052 long v = ((LongConstant) c).Value;
1054 if (target_type == TypeManager.int32_type){
1055 if (v >= UInt32.MinValue && v <= UInt32.MaxValue)
1057 } else if (target_type == TypeManager.uint32_type){
1058 if (v >= 0 && v <= UInt32.MaxValue)
1060 } else if (target_type == TypeManager.char_type){
1061 if (v >= Char.MinValue && v <= Char.MaxValue)
1063 } else if (target_type == TypeManager.byte_type){
1064 if (v >= Byte.MinValue && v <= Byte.MaxValue)
1066 } else if (target_type == TypeManager.sbyte_type){
1067 if (v >= SByte.MinValue && v <= SByte.MaxValue)
1069 } else if (target_type == TypeManager.short_type){
1070 if (v >= Int16.MinValue && v <= UInt16.MaxValue)
1072 } else if (target_type == TypeManager.ushort_type){
1073 if (v >= UInt16.MinValue && v <= UInt16.MaxValue)
1075 } else if (target_type == TypeManager.uint64_type){
1080 } else if (c is ULongConstant){
1081 ulong v = ((ULongConstant) c).Value;
1083 if (target_type == TypeManager.int32_type){
1084 if (v <= Int32.MaxValue)
1086 } else if (target_type == TypeManager.uint32_type){
1087 if (v <= UInt32.MaxValue)
1089 } else if (target_type == TypeManager.char_type){
1090 if (v >= Char.MinValue && v <= Char.MaxValue)
1092 } else if (target_type == TypeManager.byte_type){
1093 if (v >= Byte.MinValue && v <= Byte.MaxValue)
1095 } else if (target_type == TypeManager.sbyte_type){
1096 if (v <= (int) SByte.MaxValue)
1098 } else if (target_type == TypeManager.short_type){
1099 if (v <= UInt16.MaxValue)
1101 } else if (target_type == TypeManager.ushort_type){
1102 if (v <= UInt16.MaxValue)
1104 } else if (target_type == TypeManager.int64_type){
1105 if (v <= Int64.MaxValue)
1109 } else if (c is ByteConstant){
1110 byte v = ((ByteConstant) c).Value;
1112 if (target_type == TypeManager.int32_type)
1114 else if (target_type == TypeManager.uint32_type)
1116 else if (target_type == TypeManager.char_type)
1118 else if (target_type == TypeManager.sbyte_type){
1119 if (v <= SByte.MaxValue)
1121 } else if (target_type == TypeManager.short_type)
1123 else if (target_type == TypeManager.ushort_type)
1125 else if (target_type == TypeManager.int64_type)
1127 else if (target_type == TypeManager.uint64_type)
1130 } else if (c is SByteConstant){
1131 sbyte v = ((SByteConstant) c).Value;
1133 if (target_type == TypeManager.int32_type)
1135 else if (target_type == TypeManager.uint32_type){
1138 } else if (target_type == TypeManager.char_type){
1141 } else if (target_type == TypeManager.byte_type){
1144 } else if (target_type == TypeManager.short_type)
1146 else if (target_type == TypeManager.ushort_type){
1149 } else if (target_type == TypeManager.int64_type)
1151 else if (target_type == TypeManager.uint64_type){
1156 } else if (c is ShortConstant){
1157 short v = ((ShortConstant) c).Value;
1159 if (target_type == TypeManager.int32_type){
1161 } else if (target_type == TypeManager.uint32_type){
1164 } else if (target_type == TypeManager.char_type){
1167 } else if (target_type == TypeManager.byte_type){
1168 if (v >= Byte.MinValue && v <= Byte.MaxValue)
1170 } else if (target_type == TypeManager.sbyte_type){
1171 if (v >= SByte.MinValue && v <= SByte.MaxValue)
1173 } else if (target_type == TypeManager.ushort_type){
1176 } else if (target_type == TypeManager.int64_type)
1178 else if (target_type == TypeManager.uint64_type)
1182 } else if (c is UShortConstant){
1183 ushort v = ((UShortConstant) c).Value;
1185 if (target_type == TypeManager.int32_type)
1187 else if (target_type == TypeManager.uint32_type)
1189 else if (target_type == TypeManager.char_type){
1190 if (v >= Char.MinValue && v <= Char.MaxValue)
1192 } else if (target_type == TypeManager.byte_type){
1193 if (v >= Byte.MinValue && v <= Byte.MaxValue)
1195 } else if (target_type == TypeManager.sbyte_type){
1196 if (v <= SByte.MaxValue)
1198 } else if (target_type == TypeManager.short_type){
1199 if (v <= Int16.MaxValue)
1201 } else if (target_type == TypeManager.int64_type)
1203 else if (target_type == TypeManager.uint64_type)
1207 } else if (c is CharConstant){
1208 char v = ((CharConstant) c).Value;
1210 if (target_type == TypeManager.int32_type)
1212 else if (target_type == TypeManager.uint32_type)
1214 else if (target_type == TypeManager.byte_type){
1215 if (v >= Byte.MinValue && v <= Byte.MaxValue)
1217 } else if (target_type == TypeManager.sbyte_type){
1218 if (v <= SByte.MaxValue)
1220 } else if (target_type == TypeManager.short_type){
1221 if (v <= Int16.MaxValue)
1223 } else if (target_type == TypeManager.ushort_type)
1225 else if (target_type == TypeManager.int64_type)
1227 else if (target_type == TypeManager.uint64_type)
1232 Error_ConstantValueCannotBeConverted (loc, s, target_type);
1237 // Load the object from the pointer.
1239 public static void LoadFromPtr (ILGenerator ig, Type t)
1241 if (t == TypeManager.int32_type)
1242 ig.Emit (OpCodes.Ldind_I4);
1243 else if (t == TypeManager.uint32_type)
1244 ig.Emit (OpCodes.Ldind_U4);
1245 else if (t == TypeManager.short_type)
1246 ig.Emit (OpCodes.Ldind_I2);
1247 else if (t == TypeManager.ushort_type)
1248 ig.Emit (OpCodes.Ldind_U2);
1249 else if (t == TypeManager.char_type)
1250 ig.Emit (OpCodes.Ldind_U2);
1251 else if (t == TypeManager.byte_type)
1252 ig.Emit (OpCodes.Ldind_U1);
1253 else if (t == TypeManager.sbyte_type)
1254 ig.Emit (OpCodes.Ldind_I1);
1255 else if (t == TypeManager.uint64_type)
1256 ig.Emit (OpCodes.Ldind_I8);
1257 else if (t == TypeManager.int64_type)
1258 ig.Emit (OpCodes.Ldind_I8);
1259 else if (t == TypeManager.float_type)
1260 ig.Emit (OpCodes.Ldind_R4);
1261 else if (t == TypeManager.double_type)
1262 ig.Emit (OpCodes.Ldind_R8);
1263 else if (t == TypeManager.bool_type)
1264 ig.Emit (OpCodes.Ldind_I1);
1265 else if (t == TypeManager.intptr_type)
1266 ig.Emit (OpCodes.Ldind_I);
1267 else if (TypeManager.IsEnumType (t)) {
1268 if (t == TypeManager.enum_type)
1269 ig.Emit (OpCodes.Ldind_Ref);
1271 LoadFromPtr (ig, TypeManager.EnumToUnderlying (t));
1272 } else if (t.IsValueType || t.IsGenericParameter)
1273 ig.Emit (OpCodes.Ldobj, t);
1274 else if (t.IsPointer)
1275 ig.Emit (OpCodes.Ldind_I);
1277 ig.Emit (OpCodes.Ldind_Ref);
1281 // The stack contains the pointer and the value of type `type'
1283 public static void StoreFromPtr (ILGenerator ig, Type type)
1285 if (TypeManager.IsEnumType (type))
1286 type = TypeManager.EnumToUnderlying (type);
1287 if (type == TypeManager.int32_type || type == TypeManager.uint32_type)
1288 ig.Emit (OpCodes.Stind_I4);
1289 else if (type == TypeManager.int64_type || type == TypeManager.uint64_type)
1290 ig.Emit (OpCodes.Stind_I8);
1291 else if (type == TypeManager.char_type || type == TypeManager.short_type ||
1292 type == TypeManager.ushort_type)
1293 ig.Emit (OpCodes.Stind_I2);
1294 else if (type == TypeManager.float_type)
1295 ig.Emit (OpCodes.Stind_R4);
1296 else if (type == TypeManager.double_type)
1297 ig.Emit (OpCodes.Stind_R8);
1298 else if (type == TypeManager.byte_type || type == TypeManager.sbyte_type ||
1299 type == TypeManager.bool_type)
1300 ig.Emit (OpCodes.Stind_I1);
1301 else if (type == TypeManager.intptr_type)
1302 ig.Emit (OpCodes.Stind_I);
1303 else if (type.IsValueType || type.IsGenericParameter)
1304 ig.Emit (OpCodes.Stobj, type);
1306 ig.Emit (OpCodes.Stind_Ref);
1310 // Returns the size of type `t' if known, otherwise, 0
1312 public static int GetTypeSize (Type t)
1314 t = TypeManager.TypeToCoreType (t);
1315 if (t == TypeManager.int32_type ||
1316 t == TypeManager.uint32_type ||
1317 t == TypeManager.float_type)
1319 else if (t == TypeManager.int64_type ||
1320 t == TypeManager.uint64_type ||
1321 t == TypeManager.double_type)
1323 else if (t == TypeManager.byte_type ||
1324 t == TypeManager.sbyte_type ||
1325 t == TypeManager.bool_type)
1327 else if (t == TypeManager.short_type ||
1328 t == TypeManager.char_type ||
1329 t == TypeManager.ushort_type)
1331 else if (t == TypeManager.decimal_type)
1337 public static void Error_NegativeArrayIndex (Location loc)
1339 Report.Error (248, loc, "Cannot create an array with a negative size");
1344 /// Converts a String to an equivalent SimpleName or a
1345 /// MemberAccess expression
1348 public static Expression StringToExpression (string name, Location loc)
1354 Expression expr = null;
1356 pos = name.IndexOf('.');
1359 left = name.Substring (0, pos);
1360 right = name.Substring (pos + 1);
1363 expr = new SimpleName (left, loc);
1365 expr = new MemberAccess (expr, left, loc);
1368 pos = name.IndexOf('.');
1372 return new SimpleName (name, loc);
1374 return new MemberAccess (expr, name, loc);
1379 // Converts `source' to an int, uint, long or ulong.
1381 public Expression ExpressionToArrayArgument (EmitContext ec, Expression source, Location loc)
1385 bool old_checked = ec.CheckState;
1386 ec.CheckState = true;
1388 target = Convert.WideningConversion (ec, source, TypeManager.int32_type, loc);
1389 if (target == null){
1390 target = Convert.WideningConversion (ec, source, TypeManager.uint32_type, loc);
1391 if (target == null){
1392 target = Convert.WideningConversion (ec, source, TypeManager.int64_type, loc);
1393 if (target == null){
1394 target = Convert.WideningConversion (ec, source, TypeManager.uint64_type, loc);
1396 Convert.Error_CannotWideningConversion (loc, source.Type, TypeManager.int32_type);
1400 ec.CheckState = old_checked;
1403 // Only positive constants are allowed at compile time
1405 if (target is Constant){
1406 if (target is IntConstant){
1407 if (((IntConstant) target).Value < 0){
1408 Error_NegativeArrayIndex (loc);
1413 if (target is LongConstant){
1414 if (((LongConstant) target).Value < 0){
1415 Error_NegativeArrayIndex (loc);
1428 /// This is just a base class for expressions that can
1429 /// appear on statements (invocations, object creation,
1430 /// assignments, post/pre increment and decrement). The idea
1431 /// being that they would support an extra Emition interface that
1432 /// does not leave a result on the stack.
1434 public abstract class ExpressionStatement : Expression {
1436 public virtual ExpressionStatement ResolveStatement (EmitContext ec)
1438 Expression e = Resolve (ec);
1442 ExpressionStatement es = e as ExpressionStatement;
1444 Error (201, "Only assignment, call, increment, decrement and new object " +
1445 "expressions can be used as a statement");
1451 /// Requests the expression to be emitted in a `statement'
1452 /// context. This means that no new value is left on the
1453 /// stack after invoking this method (constrasted with
1454 /// Emit that will always leave a value on the stack).
1456 public abstract void EmitStatement (EmitContext ec);
1460 /// This kind of cast is used to encapsulate the child
1461 /// whose type is child.Type into an expression that is
1462 /// reported to return "return_type". This is used to encapsulate
1463 /// expressions which have compatible types, but need to be dealt
1464 /// at higher levels with.
1466 /// For example, a "byte" expression could be encapsulated in one
1467 /// of these as an "unsigned int". The type for the expression
1468 /// would be "unsigned int".
1471 public class EmptyCast : Expression {
1472 protected Expression child;
1474 public Expression Child {
1480 public EmptyCast (Expression child, Type return_type)
1482 eclass = child.eclass;
1487 public override Expression DoResolve (EmitContext ec)
1489 // This should never be invoked, we are born in fully
1490 // initialized state.
1495 public override void Emit (EmitContext ec)
1503 /// HelperMethodInvocation of methods or delegates. Used by the
1504 /// VB.NET compiler specifically to emit calls to the
1505 /// Microsoft.VisualBasic.CompilerServices helper routines
1508 public class HelperMethodInvocation : Expression
1513 public HelperMethodInvocation (EmitContext ec, Location l, Type return_type, MethodInfo method, params Expression [] exprs)
1515 args = new ArrayList ();
1516 foreach (Expression expr in exprs)
1517 args.Add (new Argument (expr, Argument.AType.Expression));
1521 this.method = method;
1523 eclass = ExprClass.Value;
1526 public override Expression DoResolve (EmitContext ec)
1531 public override void Emit (EmitContext ec)
1533 Invocation.EmitArguments (ec, method, args, false, null);
1534 ec.ig.Emit (OpCodes.Call, method);
1539 /// Implicit Creation of types. Used by the VB.NET compiler
1540 /// (in the context of Type Conversions) to emit calls to the
1541 /// appropriate constructors available in the core libraries.
1544 public class ImplicitNew : Expression
1548 public ImplicitNew (EmitContext ec, string ns, string name, Location l, params Expression [] exprs)
1550 name = ns + "." + name;
1551 ArrayList args = new ArrayList ();
1553 foreach (Expression expr in exprs)
1554 args.Add (new Argument (expr, Argument.AType.Expression));
1556 child = new New (StringToExpression (name, l), args, l).Resolve (ec);
1559 public override Expression DoResolve (EmitContext ec)
1561 // This should never be invoked, we are born in fully
1562 // initialized state.
1567 public override void Emit (EmitContext ec)
1574 // We need to special case this since an empty cast of
1575 // a NullLiteral is still a Constant
1577 public class NullCast : Constant {
1578 protected Expression child;
1580 public NullCast (Expression child, Type return_type)
1582 eclass = child.eclass;
1587 override public string AsString ()
1592 public override object GetValue ()
1597 public override Expression DoResolve (EmitContext ec)
1599 // This should never be invoked, we are born in fully
1600 // initialized state.
1605 public override void Emit (EmitContext ec)
1607 if (!type.IsValueType)
1610 // VB.NET allows Nothing to be converted to any value type
1612 ILGenerator ig = ec.ig;
1614 ig.Emit (OpCodes.Ldtoken, type);
1615 ig.Emit (OpCodes.Call, TypeManager.system_type_get_type_from_handle);
1616 ig.Emit (OpCodes.Call, TypeManager.activator_create_instance);
1617 ig.Emit (OpCodes.Unbox, type);
1618 ig.Emit (OpCodes.Ldobj, type);
1622 public override bool IsNegative {
1631 /// This class is used to wrap literals which belong inside Enums
1633 public class EnumConstant : Constant {
1634 public Constant Child;
1636 public EnumConstant (Constant child, Type enum_type)
1638 eclass = child.eclass;
1643 public override Expression DoResolve (EmitContext ec)
1645 // This should never be invoked, we are born in fully
1646 // initialized state.
1651 public override void Emit (EmitContext ec)
1656 public override object GetValue ()
1658 return Child.GetValue ();
1661 public object GetValueAsEnumType ()
1663 return System.Enum.ToObject (type, Child.GetValue ());
1667 // Converts from one of the valid underlying types for an enumeration
1668 // (int32, uint32, int64, uint64, short, ushort, byte, sbyte) to
1669 // one of the internal compiler literals: Int/UInt/Long/ULong Literals.
1671 public Constant WidenToCompilerConstant ()
1673 Type t = TypeManager.EnumToUnderlying (Child.Type);
1674 object v = ((Constant) Child).GetValue ();;
1676 if (t == TypeManager.int32_type)
1677 return new IntConstant ((int) v);
1678 if (t == TypeManager.uint32_type)
1679 return new UIntConstant ((uint) v);
1680 if (t == TypeManager.int64_type)
1681 return new LongConstant ((long) v);
1682 if (t == TypeManager.uint64_type)
1683 return new ULongConstant ((ulong) v);
1684 if (t == TypeManager.short_type)
1685 return new ShortConstant ((short) v);
1686 if (t == TypeManager.ushort_type)
1687 return new UShortConstant ((ushort) v);
1688 if (t == TypeManager.byte_type)
1689 return new ByteConstant ((byte) v);
1690 if (t == TypeManager.sbyte_type)
1691 return new SByteConstant ((sbyte) v);
1693 throw new Exception ("Invalid enumeration underlying type: " + t);
1697 // Extracts the value in the enumeration on its native representation
1699 public object GetPlainValue ()
1701 Type t = TypeManager.EnumToUnderlying (Child.Type);
1702 object v = ((Constant) Child).GetValue ();;
1704 if (t == TypeManager.int32_type)
1706 if (t == TypeManager.uint32_type)
1708 if (t == TypeManager.int64_type)
1710 if (t == TypeManager.uint64_type)
1712 if (t == TypeManager.short_type)
1714 if (t == TypeManager.ushort_type)
1716 if (t == TypeManager.byte_type)
1718 if (t == TypeManager.sbyte_type)
1724 public override string AsString ()
1726 return Child.AsString ();
1729 public override DoubleConstant ConvertToDouble ()
1731 return Child.ConvertToDouble ();
1734 public override FloatConstant ConvertToFloat ()
1736 return Child.ConvertToFloat ();
1739 public override ULongConstant ConvertToULong ()
1741 return Child.ConvertToULong ();
1744 public override LongConstant ConvertToLong ()
1746 return Child.ConvertToLong ();
1749 public override UIntConstant ConvertToUInt ()
1751 return Child.ConvertToUInt ();
1754 public override IntConstant ConvertToInt ()
1756 return Child.ConvertToInt ();
1759 public override bool IsZeroInteger {
1760 get { return Child.IsZeroInteger; }
1763 public override bool IsNegative {
1765 return Child.IsNegative;
1771 /// This kind of cast is used to encapsulate Value Types in objects.
1773 /// The effect of it is to box the value type emitted by the previous
1776 public class BoxedCast : EmptyCast {
1778 public BoxedCast (Expression expr)
1779 : base (expr, TypeManager.object_type)
1781 eclass = ExprClass.Value;
1784 public BoxedCast (Expression expr, Type target_type)
1785 : base (expr, target_type)
1787 eclass = ExprClass.Value;
1790 public override Expression DoResolve (EmitContext ec)
1792 // This should never be invoked, we are born in fully
1793 // initialized state.
1798 public override void Emit (EmitContext ec)
1802 ec.ig.Emit (OpCodes.Box, child.Type);
1806 public class UnboxCast : EmptyCast {
1807 public UnboxCast (Expression expr, Type return_type)
1808 : base (expr, return_type)
1812 public override Expression DoResolve (EmitContext ec)
1814 // This should never be invoked, we are born in fully
1815 // initialized state.
1820 public override void Emit (EmitContext ec)
1823 ILGenerator ig = ec.ig;
1826 if (t.IsGenericParameter)
1827 ig.Emit (OpCodes.Unbox_Any, t);
1829 ig.Emit (OpCodes.Unbox, t);
1831 LoadFromPtr (ig, t);
1837 /// This is used to perform explicit numeric conversions.
1839 /// Explicit numeric conversions might trigger exceptions in a checked
1840 /// context, so they should generate the conv.ovf opcodes instead of
1843 public class ConvCast : EmptyCast {
1844 public enum Mode : byte {
1845 I1_U1, I1_U2, I1_U4, I1_U8, I1_CH,
1847 I2_I1, I2_U1, I2_U2, I2_U4, I2_U8, I2_CH,
1848 U2_I1, U2_U1, U2_I2, U2_CH,
1849 I4_I1, I4_U1, I4_I2, I4_U2, I4_U4, I4_U8, I4_CH,
1850 U4_I1, U4_U1, U4_I2, U4_U2, U4_I4, U4_CH,
1851 I8_I1, I8_U1, I8_I2, I8_U2, I8_I4, I8_U4, I8_U8, I8_CH,
1852 U8_I1, U8_U1, U8_I2, U8_U2, U8_I4, U8_U4, U8_I8, U8_CH,
1853 CH_I1, CH_U1, CH_I2,
1854 R4_I1, R4_U1, R4_I2, R4_U2, R4_I4, R4_U4, R4_I8, R4_U8, R4_CH,
1855 R8_I1, R8_U1, R8_I2, R8_U2, R8_I4, R8_U4, R8_I8, R8_U8, R8_CH, R8_R4
1861 public ConvCast (EmitContext ec, Expression child, Type return_type, Mode m)
1862 : base (child, return_type)
1864 checked_state = ec.CheckState;
1868 public override Expression DoResolve (EmitContext ec)
1870 // This should never be invoked, we are born in fully
1871 // initialized state.
1876 public override string ToString ()
1878 return String.Format ("ConvCast ({0}, {1})", mode, child);
1881 public override void Emit (EmitContext ec)
1883 ILGenerator ig = ec.ig;
1889 case Mode.I1_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1890 case Mode.I1_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1891 case Mode.I1_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1892 case Mode.I1_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1893 case Mode.I1_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1895 case Mode.U1_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1896 case Mode.U1_CH: /* nothing */ break;
1898 case Mode.I2_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1899 case Mode.I2_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1900 case Mode.I2_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1901 case Mode.I2_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1902 case Mode.I2_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1903 case Mode.I2_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1905 case Mode.U2_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1906 case Mode.U2_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
1907 case Mode.U2_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
1908 case Mode.U2_CH: /* nothing */ break;
1910 case Mode.I4_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1911 case Mode.I4_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1912 case Mode.I4_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
1913 case Mode.I4_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1914 case Mode.I4_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1915 case Mode.I4_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1916 case Mode.I4_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1918 case Mode.U4_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1919 case Mode.U4_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
1920 case Mode.U4_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
1921 case Mode.U4_U2: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
1922 case Mode.U4_I4: ig.Emit (OpCodes.Conv_Ovf_I4_Un); break;
1923 case Mode.U4_CH: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
1925 case Mode.I8_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1926 case Mode.I8_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1927 case Mode.I8_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
1928 case Mode.I8_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1929 case Mode.I8_I4: ig.Emit (OpCodes.Conv_Ovf_I4); break;
1930 case Mode.I8_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1931 case Mode.I8_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1932 case Mode.I8_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1934 case Mode.U8_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1935 case Mode.U8_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
1936 case Mode.U8_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
1937 case Mode.U8_U2: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
1938 case Mode.U8_I4: ig.Emit (OpCodes.Conv_Ovf_I4_Un); break;
1939 case Mode.U8_U4: ig.Emit (OpCodes.Conv_Ovf_U4_Un); break;
1940 case Mode.U8_I8: ig.Emit (OpCodes.Conv_Ovf_I8_Un); break;
1941 case Mode.U8_CH: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
1943 case Mode.CH_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1944 case Mode.CH_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
1945 case Mode.CH_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
1947 case Mode.R4_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1948 case Mode.R4_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1949 case Mode.R4_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
1950 case Mode.R4_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1951 case Mode.R4_I4: ig.Emit (OpCodes.Conv_Ovf_I4); break;
1952 case Mode.R4_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1953 case Mode.R4_I8: ig.Emit (OpCodes.Conv_Ovf_I8); break;
1954 case Mode.R4_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1955 case Mode.R4_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1957 case Mode.R8_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1958 case Mode.R8_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1959 case Mode.R8_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
1960 case Mode.R8_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1961 case Mode.R8_I4: ig.Emit (OpCodes.Conv_Ovf_I4); break;
1962 case Mode.R8_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1963 case Mode.R8_I8: ig.Emit (OpCodes.Conv_Ovf_I8); break;
1964 case Mode.R8_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1965 case Mode.R8_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1966 case Mode.R8_R4: ig.Emit (OpCodes.Conv_R4); break;
1970 case Mode.I1_U1: ig.Emit (OpCodes.Conv_U1); break;
1971 case Mode.I1_U2: ig.Emit (OpCodes.Conv_U2); break;
1972 case Mode.I1_U4: ig.Emit (OpCodes.Conv_U4); break;
1973 case Mode.I1_U8: ig.Emit (OpCodes.Conv_I8); break;
1974 case Mode.I1_CH: ig.Emit (OpCodes.Conv_U2); break;
1976 case Mode.U1_I1: ig.Emit (OpCodes.Conv_I1); break;
1977 case Mode.U1_CH: ig.Emit (OpCodes.Conv_U2); break;
1979 case Mode.I2_I1: ig.Emit (OpCodes.Conv_I1); break;
1980 case Mode.I2_U1: ig.Emit (OpCodes.Conv_U1); break;
1981 case Mode.I2_U2: ig.Emit (OpCodes.Conv_U2); break;
1982 case Mode.I2_U4: ig.Emit (OpCodes.Conv_U4); break;
1983 case Mode.I2_U8: ig.Emit (OpCodes.Conv_I8); break;
1984 case Mode.I2_CH: ig.Emit (OpCodes.Conv_U2); break;
1986 case Mode.U2_I1: ig.Emit (OpCodes.Conv_I1); break;
1987 case Mode.U2_U1: ig.Emit (OpCodes.Conv_U1); break;
1988 case Mode.U2_I2: ig.Emit (OpCodes.Conv_I2); break;
1989 case Mode.U2_CH: /* nothing */ break;
1991 case Mode.I4_I1: ig.Emit (OpCodes.Conv_I1); break;
1992 case Mode.I4_U1: ig.Emit (OpCodes.Conv_U1); break;
1993 case Mode.I4_I2: ig.Emit (OpCodes.Conv_I2); break;
1994 case Mode.I4_U4: /* nothing */ break;
1995 case Mode.I4_U2: ig.Emit (OpCodes.Conv_U2); break;
1996 case Mode.I4_U8: ig.Emit (OpCodes.Conv_I8); break;
1997 case Mode.I4_CH: ig.Emit (OpCodes.Conv_U2); break;
1999 case Mode.U4_I1: ig.Emit (OpCodes.Conv_I1); break;
2000 case Mode.U4_U1: ig.Emit (OpCodes.Conv_U1); break;
2001 case Mode.U4_I2: ig.Emit (OpCodes.Conv_I2); break;
2002 case Mode.U4_U2: ig.Emit (OpCodes.Conv_U2); break;
2003 case Mode.U4_I4: /* nothing */ break;
2004 case Mode.U4_CH: ig.Emit (OpCodes.Conv_U2); break;
2006 case Mode.I8_I1: ig.Emit (OpCodes.Conv_I1); break;
2007 case Mode.I8_U1: ig.Emit (OpCodes.Conv_U1); break;
2008 case Mode.I8_I2: ig.Emit (OpCodes.Conv_I2); break;
2009 case Mode.I8_U2: ig.Emit (OpCodes.Conv_U2); break;
2010 case Mode.I8_I4: ig.Emit (OpCodes.Conv_I4); break;
2011 case Mode.I8_U4: ig.Emit (OpCodes.Conv_U4); break;
2012 case Mode.I8_U8: /* nothing */ break;
2013 case Mode.I8_CH: ig.Emit (OpCodes.Conv_U2); break;
2015 case Mode.U8_I1: ig.Emit (OpCodes.Conv_I1); break;
2016 case Mode.U8_U1: ig.Emit (OpCodes.Conv_U1); break;
2017 case Mode.U8_I2: ig.Emit (OpCodes.Conv_I2); break;
2018 case Mode.U8_U2: ig.Emit (OpCodes.Conv_U2); break;
2019 case Mode.U8_I4: ig.Emit (OpCodes.Conv_I4); break;
2020 case Mode.U8_U4: ig.Emit (OpCodes.Conv_U4); break;
2021 case Mode.U8_I8: /* nothing */ break;
2022 case Mode.U8_CH: ig.Emit (OpCodes.Conv_U2); break;
2024 case Mode.CH_I1: ig.Emit (OpCodes.Conv_I1); break;
2025 case Mode.CH_U1: ig.Emit (OpCodes.Conv_U1); break;
2026 case Mode.CH_I2: ig.Emit (OpCodes.Conv_I2); break;
2028 case Mode.R4_I1: ig.Emit (OpCodes.Conv_I1); break;
2029 case Mode.R4_U1: ig.Emit (OpCodes.Conv_U1); break;
2030 case Mode.R4_I2: ig.Emit (OpCodes.Conv_I2); break;
2031 case Mode.R4_U2: ig.Emit (OpCodes.Conv_U2); break;
2032 case Mode.R4_I4: ig.Emit (OpCodes.Conv_I4); break;
2033 case Mode.R4_U4: ig.Emit (OpCodes.Conv_U4); break;
2034 case Mode.R4_I8: ig.Emit (OpCodes.Conv_I8); break;
2035 case Mode.R4_U8: ig.Emit (OpCodes.Conv_U8); break;
2036 case Mode.R4_CH: ig.Emit (OpCodes.Conv_U2); break;
2038 case Mode.R8_I1: ig.Emit (OpCodes.Conv_I1); break;
2039 case Mode.R8_U1: ig.Emit (OpCodes.Conv_U1); break;
2040 case Mode.R8_I2: ig.Emit (OpCodes.Conv_I2); break;
2041 case Mode.R8_U2: ig.Emit (OpCodes.Conv_U2); break;
2042 case Mode.R8_I4: ig.Emit (OpCodes.Conv_I4); break;
2043 case Mode.R8_U4: ig.Emit (OpCodes.Conv_U4); break;
2044 case Mode.R8_I8: ig.Emit (OpCodes.Conv_I8); break;
2045 case Mode.R8_U8: ig.Emit (OpCodes.Conv_U8); break;
2046 case Mode.R8_CH: ig.Emit (OpCodes.Conv_U2); break;
2047 case Mode.R8_R4: ig.Emit (OpCodes.Conv_R4); break;
2053 public class OpcodeCast : EmptyCast {
2057 public OpcodeCast (Expression child, Type return_type, OpCode op)
2058 : base (child, return_type)
2062 second_valid = false;
2065 public OpcodeCast (Expression child, Type return_type, OpCode op, OpCode op2)
2066 : base (child, return_type)
2071 second_valid = true;
2074 public override Expression DoResolve (EmitContext ec)
2076 // This should never be invoked, we are born in fully
2077 // initialized state.
2082 public override void Emit (EmitContext ec)
2093 /// This kind of cast is used to encapsulate a child and cast it
2094 /// to the class requested
2096 public class ClassCast : EmptyCast {
2097 public ClassCast (Expression child, Type return_type)
2098 : base (child, return_type)
2103 public override Expression DoResolve (EmitContext ec)
2105 // This should never be invoked, we are born in fully
2106 // initialized state.
2111 public override void Emit (EmitContext ec)
2115 if (child.Type.IsGenericParameter)
2116 ec.ig.Emit (OpCodes.Box, child.Type);
2118 if (type.IsGenericParameter)
2119 ec.ig.Emit (OpCodes.Unbox_Any, type);
2121 ec.ig.Emit (OpCodes.Castclass, type);
2128 public class BooleanToNumericCast : EmptyCast {
2131 public BooleanToNumericCast (Expression child, Type return_type, OpCode op)
2132 : base (child, return_type)
2138 public override Expression DoResolve (EmitContext ec)
2140 // This should never be invoked, we are born in fully
2141 // initialized state.
2146 public override void Emit (EmitContext ec)
2149 ec.ig.Emit (OpCodes.Ldc_I4_0);
2150 ec.ig.Emit (OpCodes.Cgt_Un);
2151 ec.ig.Emit (OpCodes.Neg);
2159 public class NumericToBooleanCast : EmptyCast {
2163 public NumericToBooleanCast (Expression child, Type src_type)
2164 : base (child, TypeManager.bool_type)
2167 expr_type = src_type;
2170 public override Expression DoResolve (EmitContext ec)
2172 // This should never be invoked, we are born in fully
2173 // initialized state.
2178 public override void Emit (EmitContext ec)
2182 if (expr_type == TypeManager.byte_type ||
2183 expr_type == TypeManager.short_type ||
2184 expr_type == TypeManager.int32_type) {
2185 ec.ig.Emit (OpCodes.Ldc_I4_0);
2186 ec.ig.Emit (OpCodes.Cgt_Un);
2190 if (expr_type == TypeManager.int64_type) {
2191 ec.ig.Emit (OpCodes.Ldc_I8, (long) 0);
2192 ec.ig.Emit (OpCodes.Cgt_Un);
2196 if (expr_type == TypeManager.float_type)
2197 ec.ig.Emit (OpCodes.Ldc_R4, (float) 0);
2198 else if (expr_type == TypeManager.double_type)
2199 ec.ig.Emit (OpCodes.Ldc_R8, (double) 0);
2201 ec.ig.Emit (OpCodes.Ceq);
2202 ec.ig.Emit (OpCodes.Ldc_I4_0);
2203 ec.ig.Emit (OpCodes.Ceq);
2210 public class FloatingToFixedCast : ConvCast {
2211 public FloatingToFixedCast (EmitContext ec, Expression child, Type return_type, Mode mode)
2212 : base (ec, new HelperMethodInvocation (ec, child.Location, TypeManager.double_type, TypeManager.math_round_double,
2213 (child.Type == TypeManager.float_type) ?
2214 new OpcodeCast (child, TypeManager.double_type, OpCodes.Conv_R8) : child),
2222 /// SimpleName expressions are formed of a single word and only happen at the beginning
2223 /// of a dotted-name.
2225 public class SimpleName : Expression {
2227 public readonly TypeArguments Arguments;
2229 public SimpleName (string name, Location l)
2235 public SimpleName (string name, TypeArguments args, Location l)
2242 public static void Error_ObjectRefRequired (EmitContext ec, Location l, string name)
2244 if (ec.IsFieldInitializer)
2247 "A field initializer cannot reference the non-static field, " +
2248 "method or property `"+name+"'");
2252 "An object reference is required " +
2253 "for the non-static field `"+name+"'");
2257 // Checks whether we are trying to access an instance
2258 // property, method or field from a static body.
2260 Expression MemberStaticCheck (EmitContext ec, Expression e)
2262 if (e is IMemberExpr){
2263 IMemberExpr member = (IMemberExpr) e;
2265 if (!member.IsStatic){
2266 Error_ObjectRefRequired (ec, loc, Name);
2274 public override Expression DoResolve (EmitContext ec)
2276 return SimpleNameResolve (ec, null, false, false);
2279 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
2281 return SimpleNameResolve (ec, right_side, false, false);
2285 public Expression DoResolveAllowStatic (EmitContext ec, bool intermediate)
2287 return SimpleNameResolve (ec, null, true, intermediate);
2290 public override FullNamedExpression ResolveAsTypeStep (EmitContext ec)
2292 DeclSpace ds = ec.DeclSpace;
2293 FullNamedExpression dt;
2295 dt = ds.LookupGeneric (Name, loc);
2297 return dt.ResolveAsTypeStep (ec);
2299 int errors = Report.Errors;
2300 dt = ec.ResolvingTypeTree
2301 ? ds.FindType (loc, Name)
2302 : ds.LookupType (Name, true, loc);
2303 if (Report.Errors != errors)
2309 Expression SimpleNameResolve (EmitContext ec, Expression right_side,
2310 bool allow_static, bool intermediate)
2312 Expression e = DoSimpleNameResolve (ec, right_side, allow_static, intermediate);
2316 Block current_block = ec.CurrentBlock;
2317 if (current_block != null){
2318 if (current_block.IsVariableNameUsedInChildBlock (Name)) {
2319 Report.Error (135, Location,
2320 "'{0}' has a different meaning in a child block", Name);
2325 if (e.Type != null && e.Type.IsPointer && !ec.InUnsafe) {
2334 /// 7.5.2: Simple Names.
2336 /// Local Variables and Parameters are handled at
2337 /// parse time, so they never occur as SimpleNames.
2339 /// The `allow_static' flag is used by MemberAccess only
2340 /// and it is used to inform us that it is ok for us to
2341 /// avoid the static check, because MemberAccess might end
2342 /// up resolving the Name as a Type name and the access as
2343 /// a static type access.
2345 /// ie: Type Type; .... { Type.GetType (""); }
2347 /// Type is both an instance variable and a Type; Type.GetType
2348 /// is the static method not an instance method of type.
2350 Expression DoSimpleNameResolve (EmitContext ec, Expression right_side, bool allow_static, bool intermediate)
2352 Expression e = null;
2355 // Stage 1: Performed by the parser (binding to locals or parameters).
2357 Block current_block = ec.CurrentBlock;
2358 if (current_block != null){
2359 LocalInfo vi = current_block.GetLocalInfo (Name);
2363 var = new LocalVariableReference (ec.CurrentBlock, Name, loc);
2365 if (right_side != null)
2366 return var.ResolveLValue (ec, right_side);
2368 return var.Resolve (ec);
2371 ParameterReference pref = current_block.GetParameterReference (Name, loc);
2373 if (right_side != null)
2374 return pref.ResolveLValue (ec, right_side);
2376 return pref.Resolve (ec);
2381 // Stage 2: Lookup members
2384 DeclSpace lookup_ds = ec.DeclSpace;
2385 Type almost_matched_type = null;
2386 ArrayList almost_matched = null;
2388 if (lookup_ds.TypeBuilder == null)
2391 e = MemberLookup (ec, lookup_ds.TypeBuilder, Name, loc);
2395 if (almost_matched == null && almostMatchedMembers.Count > 0) {
2396 almost_matched_type = lookup_ds.TypeBuilder;
2397 almost_matched = (ArrayList) almostMatchedMembers.Clone ();
2400 lookup_ds =lookup_ds.Parent;
2401 } while (lookup_ds != null);
2403 if (e == null && ec.ContainerType != null)
2404 e = MemberLookup (ec, ec.ContainerType, Name, loc);
2407 if (almost_matched == null && almostMatchedMembers.Count > 0) {
2408 almost_matched_type = ec.ContainerType;
2409 almost_matched = (ArrayList) almostMatchedMembers.Clone ();
2411 e = ResolveAsTypeStep (ec);
2415 if (almost_matched != null)
2416 almostMatchedMembers = almost_matched;
2417 if (almost_matched_type == null)
2418 almost_matched_type = ec.ContainerType;
2419 MemberLookupFailed (ec, null, almost_matched_type, ((SimpleName) this).Name, ec.DeclSpace.Name, loc);
2426 if (e is IMemberExpr) {
2427 e = MemberAccess.ResolveMemberAccess (ec, e, null, loc, this);
2431 IMemberExpr me = e as IMemberExpr;
2435 if (Arguments != null) {
2436 MethodGroupExpr mg = me as MethodGroupExpr;
2440 return mg.ResolveGeneric (ec, Arguments);
2443 // This fails if ResolveMemberAccess() was unable to decide whether
2444 // it's a field or a type of the same name.
2446 if (!me.IsStatic && (me.InstanceExpression == null))
2450 TypeManager.IsNestedFamilyAccessible (me.InstanceExpression.Type, me.DeclaringType) &&
2451 me.InstanceExpression.Type != me.DeclaringType &&
2452 !TypeManager.IsFamilyAccessible (me.InstanceExpression.Type, me.DeclaringType) &&
2453 (!intermediate || !MemberAccess.IdenticalNameAndTypeName (ec, this, e, loc))) {
2454 Error (38, "Cannot access nonstatic member `" + me.Name + "' of " +
2455 "outer type `" + me.DeclaringType + "' via nested type `" +
2456 me.InstanceExpression.Type + "'");
2460 return (right_side != null)
2461 ? e.DoResolveLValue (ec, right_side)
2465 if (ec.IsStatic || ec.IsFieldInitializer){
2469 return MemberStaticCheck (ec, e);
2474 public override void Emit (EmitContext ec)
2477 // If this is ever reached, then we failed to
2478 // find the name as a namespace
2481 Error (103, "The name `" + Name +
2482 "' does not exist in the class `" +
2483 ec.DeclSpace.Name + "'");
2486 public override string ToString ()
2493 /// Represents a namespace or a type. The name of the class was inspired by
2494 /// section 10.8.1 (Fully Qualified Names).
2496 public abstract class FullNamedExpression : Expression {
2497 public override FullNamedExpression ResolveAsTypeStep (EmitContext ec)
2502 public abstract string FullName {
2508 /// Fully resolved expression that evaluates to a type
2510 public abstract class TypeExpr : FullNamedExpression {
2511 override public FullNamedExpression ResolveAsTypeStep (EmitContext ec)
2513 TypeExpr t = DoResolveAsTypeStep (ec);
2517 eclass = ExprClass.Type;
2521 override public Expression DoResolve (EmitContext ec)
2523 return ResolveAsTypeTerminal (ec);
2526 override public void Emit (EmitContext ec)
2528 throw new Exception ("Should never be called");
2531 public virtual bool CheckAccessLevel (DeclSpace ds)
2533 return ds.CheckAccessLevel (Type);
2536 public virtual bool AsAccessible (DeclSpace ds, int flags)
2538 return ds.AsAccessible (Type, flags);
2541 public virtual bool IsClass {
2542 get { return Type.IsClass; }
2545 public virtual bool IsValueType {
2546 get { return Type.IsValueType; }
2549 public virtual bool IsInterface {
2550 get { return Type.IsInterface; }
2553 public virtual bool IsSealed {
2554 get { return Type.IsSealed; }
2557 public virtual bool CanInheritFrom ()
2559 if (Type == TypeManager.enum_type ||
2560 (Type == TypeManager.value_type && RootContext.StdLib) ||
2561 Type == TypeManager.multicast_delegate_type ||
2562 Type == TypeManager.delegate_type ||
2563 Type == TypeManager.array_type)
2569 public virtual bool IsAttribute {
2571 return Type == TypeManager.attribute_type ||
2572 Type.IsSubclassOf (TypeManager.attribute_type);
2576 protected abstract TypeExpr DoResolveAsTypeStep (EmitContext ec);
2578 public virtual Type ResolveType (EmitContext ec)
2580 TypeExpr t = ResolveAsTypeTerminal (ec);
2587 public abstract string Name {
2591 public override bool Equals (object obj)
2593 TypeExpr tobj = obj as TypeExpr;
2597 return Type == tobj.Type;
2600 public override int GetHashCode ()
2602 return Type.GetHashCode ();
2605 public override string ToString ()
2611 public class TypeExpression : TypeExpr {
2612 public TypeExpression (Type t, Location l)
2615 eclass = ExprClass.Type;
2619 protected override TypeExpr DoResolveAsTypeStep (EmitContext ec)
2624 public override string Name {
2626 return Type.ToString ();
2630 public override string FullName {
2632 return Type.FullName != null ? Type.FullName : Type.Name;
2638 /// Used to create types from a fully qualified name. These are just used
2639 /// by the parser to setup the core types. A TypeLookupExpression is always
2640 /// classified as a type.
2642 public class TypeLookupExpression : TypeExpr {
2645 public TypeLookupExpression (string name)
2650 protected override TypeExpr DoResolveAsTypeStep (EmitContext ec)
2653 FullNamedExpression t = ec.DeclSpace.LookupType (name, false, Location.Null);
2656 if (!(t is TypeExpr))
2658 type = ((TypeExpr) t).ResolveType (ec);
2664 public override string Name {
2670 public override string FullName {
2678 /// Represents an "unbound generic type", ie. typeof (Foo<>).
2681 public class UnboundTypeExpression : TypeLookupExpression {
2682 public UnboundTypeExpression (string name)
2687 public class TypeAliasExpression : TypeExpr {
2688 FullNamedExpression alias;
2693 public TypeAliasExpression (FullNamedExpression alias, TypeArguments args, Location l)
2699 eclass = ExprClass.Type;
2701 name = alias.FullName + "<" + args.ToString () + ">";
2703 name = alias.FullName;
2706 public override string Name {
2707 get { return alias.FullName; }
2710 public override string FullName {
2711 get { return name; }
2714 protected override TypeExpr DoResolveAsTypeStep (EmitContext ec)
2716 texpr = alias.ResolveAsTypeTerminal (ec);
2720 Type type = texpr.Type;
2721 int num_args = TypeManager.GetNumberOfTypeArguments (type);
2724 if (num_args == 0) {
2725 Report.Error (308, loc,
2726 "The non-generic type `{0}' cannot " +
2727 "be used with type arguments.",
2728 TypeManager.CSharpName (type));
2732 ConstructedType ctype = new ConstructedType (type, args, loc);
2733 return ctype.ResolveAsTypeTerminal (ec);
2734 } else if (num_args > 0) {
2735 Report.Error (305, loc,
2736 "Using the generic type `{0}' " +
2737 "requires {1} type arguments",
2738 TypeManager.GetFullName (type), num_args);
2742 return new TypeExpression (type, loc);
2745 public override bool CheckAccessLevel (DeclSpace ds)
2747 return texpr.CheckAccessLevel (ds);
2750 public override bool AsAccessible (DeclSpace ds, int flags)
2752 return texpr.AsAccessible (ds, flags);
2755 public override bool IsClass {
2756 get { return texpr.IsClass; }
2759 public override bool IsValueType {
2760 get { return texpr.IsValueType; }
2763 public override bool IsInterface {
2764 get { return texpr.IsInterface; }
2767 public override bool IsSealed {
2768 get { return texpr.IsSealed; }
2771 public override bool IsAttribute {
2772 get { return texpr.IsAttribute; }
2777 /// MethodGroup Expression.
2779 /// This is a fully resolved expression that evaluates to a type
2781 public class MethodGroupExpr : Expression, IMemberExpr {
2782 public MethodBase [] Methods;
2783 Expression instance_expression = null;
2784 bool is_explicit_impl = false;
2785 bool has_type_arguments = false;
2786 bool identical_type_name = false;
2789 public MethodGroupExpr (MemberInfo [] mi, Location l)
2791 Methods = new MethodBase [mi.Length];
2792 mi.CopyTo (Methods, 0);
2793 eclass = ExprClass.MethodGroup;
2794 type = TypeManager.object_type;
2798 public MethodGroupExpr (ArrayList list, Location l)
2800 Methods = new MethodBase [list.Count];
2803 list.CopyTo (Methods, 0);
2805 foreach (MemberInfo m in list){
2806 if (!(m is MethodBase)){
2807 Console.WriteLine ("Name " + m.Name);
2808 Console.WriteLine ("Found a: " + m.GetType ().FullName);
2815 eclass = ExprClass.MethodGroup;
2816 type = TypeManager.object_type;
2819 public Type DeclaringType {
2822 // We assume that the top-level type is in the end
2824 return Methods [Methods.Length - 1].DeclaringType;
2825 //return Methods [0].DeclaringType;
2830 // `A method group may have associated an instance expression'
2832 public Expression InstanceExpression {
2834 return instance_expression;
2838 instance_expression = value;
2842 public bool IsExplicitImpl {
2844 return is_explicit_impl;
2848 is_explicit_impl = value;
2852 public bool HasTypeArguments {
2854 return has_type_arguments;
2858 has_type_arguments = value;
2862 public bool IdenticalTypeName {
2864 return identical_type_name;
2868 identical_type_name = value;
2872 public bool IsBase {
2881 public string Name {
2883 //return Methods [0].Name;
2884 return Methods [Methods.Length - 1].Name;
2888 public bool IsInstance {
2890 foreach (MethodBase mb in Methods)
2898 public bool IsStatic {
2900 foreach (MethodBase mb in Methods)
2908 override public Expression DoResolve (EmitContext ec)
2911 instance_expression = null;
2913 if (instance_expression != null) {
2914 instance_expression = instance_expression.DoResolve (ec);
2915 if (instance_expression == null)
2922 public void ReportUsageError ()
2924 Report.Error (654, loc, "Method `" + DeclaringType + "." +
2925 Name + "()' is referenced without parentheses");
2928 override public void Emit (EmitContext ec)
2930 ReportUsageError ();
2933 bool RemoveMethods (bool keep_static)
2935 ArrayList smethods = new ArrayList ();
2937 foreach (MethodBase mb in Methods){
2938 if (mb.IsStatic == keep_static)
2942 if (smethods.Count == 0)
2945 Methods = new MethodBase [smethods.Count];
2946 smethods.CopyTo (Methods, 0);
2952 /// Removes any instance methods from the MethodGroup, returns
2953 /// false if the resulting set is empty.
2955 public bool RemoveInstanceMethods ()
2957 return RemoveMethods (true);
2961 /// Removes any static methods from the MethodGroup, returns
2962 /// false if the resulting set is empty.
2964 public bool RemoveStaticMethods ()
2966 return RemoveMethods (false);
2969 public Expression ResolveGeneric (EmitContext ec, TypeArguments args)
2971 if (args.Resolve (ec) == false)
2974 Type[] atypes = args.Arguments;
2976 int first_count = 0;
2977 MethodInfo first = null;
2979 ArrayList list = new ArrayList ();
2980 foreach (MethodBase mb in Methods) {
2981 MethodInfo mi = mb as MethodInfo;
2982 if ((mi == null) || !mi.HasGenericParameters)
2985 Type[] gen_params = mi.GetGenericArguments ();
2987 if (first == null) {
2989 first_count = gen_params.Length;
2992 if (gen_params.Length != atypes.Length)
2995 list.Add (mi.BindGenericParameters (atypes));
2998 if (list.Count > 0) {
2999 MethodGroupExpr new_mg = new MethodGroupExpr (list, Location);
3000 new_mg.InstanceExpression = InstanceExpression;
3001 new_mg.HasTypeArguments = true;
3007 305, loc, "Using the generic method `{0}' " +
3008 "requires {1} type arguments", Name,
3012 308, loc, "The non-generic method `{0}' " +
3013 "cannot be used with type arguments", Name);
3020 /// Fully resolved expression that evaluates to a Field
3022 public class FieldExpr : Expression, IAssignMethod, IMemoryLocation, IMemberExpr, IVariable {
3023 public readonly FieldInfo FieldInfo;
3024 Expression instance_expr;
3025 VariableInfo variable_info;
3027 LocalTemporary temp;
3029 bool is_field_initializer;
3031 public FieldExpr (FieldInfo fi, Location l)
3034 eclass = ExprClass.Variable;
3035 type = TypeManager.TypeToCoreType (fi.FieldType);
3039 public string Name {
3041 return FieldInfo.Name;
3045 public bool IsInstance {
3047 return !FieldInfo.IsStatic;
3051 public bool IsStatic {
3053 return FieldInfo.IsStatic;
3057 public Type DeclaringType {
3059 return FieldInfo.DeclaringType;
3063 public Expression InstanceExpression {
3065 return instance_expr;
3069 instance_expr = value;
3073 public bool IsFieldInitializer {
3075 return is_field_initializer;
3079 is_field_initializer = value;
3083 public VariableInfo VariableInfo {
3085 return variable_info;
3089 override public Expression DoResolve (EmitContext ec)
3091 if (!FieldInfo.IsStatic){
3092 if (instance_expr == null){
3094 // This can happen when referencing an instance field using
3095 // a fully qualified type expression: TypeName.InstanceField = xxx
3097 SimpleName.Error_ObjectRefRequired (ec, loc, FieldInfo.Name);
3101 // Resolve the field's instance expression while flow analysis is turned
3102 // off: when accessing a field "a.b", we must check whether the field
3103 // "a.b" is initialized, not whether the whole struct "a" is initialized.
3104 instance_expr = instance_expr.Resolve (ec, ResolveFlags.VariableOrValue |
3105 ResolveFlags.DisableFlowAnalysis);
3106 if (instance_expr == null)
3110 ObsoleteAttribute oa;
3111 FieldBase f = TypeManager.GetField (FieldInfo);
3113 oa = f.GetObsoleteAttribute (f.Parent);
3115 AttributeTester.Report_ObsoleteMessage (oa, f.GetSignatureForError (), loc);
3116 // To be sure that type is external because we do not register generated fields
3117 } else if (!(FieldInfo.DeclaringType is TypeBuilder)) {
3118 oa = AttributeTester.GetMemberObsoleteAttribute (FieldInfo);
3120 AttributeTester.Report_ObsoleteMessage (oa, TypeManager.GetFullNameSignature (FieldInfo), loc);
3123 if (ec.CurrentAnonymousMethod != null){
3124 if (!FieldInfo.IsStatic){
3125 if (ec.TypeContainer is Struct){
3126 Report.Error (1673, loc, "Can not reference instance variables in anonymous methods hosted in structs");
3129 ec.CaptureField (this);
3133 // If the instance expression is a local variable or parameter.
3134 IVariable var = instance_expr as IVariable;
3135 if ((var == null) || (var.VariableInfo == null))
3138 VariableInfo vi = var.VariableInfo;
3139 if (!vi.IsFieldAssigned (ec, FieldInfo.Name, loc))
3142 variable_info = vi.GetSubStruct (FieldInfo.Name);
3146 void Report_AssignToReadonly (bool is_instance)
3151 msg = "Readonly field can not be assigned outside " +
3152 "of constructor or variable initializer";
3154 msg = "A static readonly field can only be assigned in " +
3155 "a static constructor";
3157 Report.Error (is_instance ? 191 : 198, loc, msg);
3160 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
3162 IVariable var = instance_expr as IVariable;
3163 if ((var != null) && (var.VariableInfo != null))
3164 var.VariableInfo.SetFieldAssigned (ec, FieldInfo.Name);
3166 Expression e = DoResolve (ec);
3171 if (!FieldInfo.IsStatic && (instance_expr.Type.IsValueType && !(instance_expr is IMemoryLocation))) {
3172 // FIXME: Provide better error reporting.
3173 Error (1612, "Cannot modify expression because it is not a variable.");
3177 if (!FieldInfo.IsInitOnly)
3180 FieldBase fb = TypeManager.GetField (FieldInfo);
3185 // InitOnly fields can only be assigned in constructors
3188 if (ec.IsConstructor){
3189 if (IsStatic && !ec.IsStatic)
3190 Report_AssignToReadonly (false);
3193 if (!is_field_initializer &&
3194 (ec.TypeContainer.CurrentType != null))
3195 ctype = ec.TypeContainer.CurrentType;
3197 ctype = ec.ContainerType;
3199 if (TypeManager.IsEqual (ctype, FieldInfo.DeclaringType))
3203 Report_AssignToReadonly (!IsStatic);
3208 public override void CheckMarshallByRefAccess (Type container)
3210 if (!IsStatic && Type.IsValueType && !container.IsSubclassOf (TypeManager.mbr_type) && DeclaringType.IsSubclassOf (TypeManager.mbr_type)) {
3211 Report.SymbolRelatedToPreviousError (DeclaringType);
3212 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);
3216 public bool VerifyFixed (bool is_expression)
3218 IVariable variable = instance_expr as IVariable;
3219 if ((variable == null) || !variable.VerifyFixed (true))
3225 public void Emit (EmitContext ec, bool leave_copy)
3227 ILGenerator ig = ec.ig;
3228 bool is_volatile = false;
3230 if (FieldInfo is FieldBuilder){
3231 FieldBase f = TypeManager.GetField (FieldInfo);
3233 if ((f.ModFlags & Modifiers.VOLATILE) != 0)
3236 f.status |= Field.Status.USED;
3240 if (FieldInfo.IsStatic){
3242 ig.Emit (OpCodes.Volatile);
3244 ig.Emit (OpCodes.Ldsfld, FieldInfo);
3250 ig.Emit (OpCodes.Volatile);
3252 ig.Emit (OpCodes.Ldfld, FieldInfo);
3256 ec.ig.Emit (OpCodes.Dup);
3257 if (!FieldInfo.IsStatic) {
3258 temp = new LocalTemporary (ec, this.Type);
3264 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
3266 FieldAttributes fa = FieldInfo.Attributes;
3267 bool is_static = (fa & FieldAttributes.Static) != 0;
3268 bool is_readonly = (fa & FieldAttributes.InitOnly) != 0;
3269 ILGenerator ig = ec.ig;
3270 prepared = prepare_for_load;
3272 if (is_readonly && !ec.IsConstructor){
3273 Report_AssignToReadonly (!is_static);
3279 if (prepare_for_load)
3280 ig.Emit (OpCodes.Dup);
3285 ec.ig.Emit (OpCodes.Dup);
3286 if (!FieldInfo.IsStatic) {
3287 temp = new LocalTemporary (ec, this.Type);
3292 if (FieldInfo is FieldBuilder){
3293 FieldBase f = TypeManager.GetField (FieldInfo);
3295 if ((f.ModFlags & Modifiers.VOLATILE) != 0)
3296 ig.Emit (OpCodes.Volatile);
3298 f.status |= Field.Status.ASSIGNED;
3303 ig.Emit (OpCodes.Stsfld, FieldInfo);
3305 ig.Emit (OpCodes.Stfld, FieldInfo);
3311 void EmitInstance (EmitContext ec)
3313 if (instance_expr.Type.IsValueType) {
3314 if (instance_expr is IMemoryLocation) {
3315 ((IMemoryLocation) instance_expr).AddressOf (ec, AddressOp.LoadStore);
3317 LocalTemporary t = new LocalTemporary (ec, instance_expr.Type);
3318 instance_expr.Emit (ec);
3320 t.AddressOf (ec, AddressOp.Store);
3323 instance_expr.Emit (ec);
3326 public override void Emit (EmitContext ec)
3331 public void AddressOf (EmitContext ec, AddressOp mode)
3333 ILGenerator ig = ec.ig;
3335 if (FieldInfo is FieldBuilder){
3336 FieldBase f = TypeManager.GetField (FieldInfo);
3338 if ((f.ModFlags & Modifiers.VOLATILE) != 0){
3339 Error (676, "volatile variable: can not take its address, or pass as ref/out parameter");
3343 if ((mode & AddressOp.Store) != 0)
3344 f.status |= Field.Status.ASSIGNED;
3345 if ((mode & AddressOp.Load) != 0)
3346 f.status |= Field.Status.USED;
3351 // Handle initonly fields specially: make a copy and then
3352 // get the address of the copy.
3355 if (FieldInfo.IsInitOnly){
3357 if (ec.IsConstructor){
3358 if (FieldInfo.IsStatic){
3370 local = ig.DeclareLocal (type);
3371 ig.Emit (OpCodes.Stloc, local);
3372 ig.Emit (OpCodes.Ldloca, local);
3377 if (FieldInfo.IsStatic){
3378 ig.Emit (OpCodes.Ldsflda, FieldInfo);
3381 ig.Emit (OpCodes.Ldflda, FieldInfo);
3387 // A FieldExpr whose address can not be taken
3389 public class FieldExprNoAddress : FieldExpr, IMemoryLocation {
3390 public FieldExprNoAddress (FieldInfo fi, Location loc) : base (fi, loc)
3394 public new void AddressOf (EmitContext ec, AddressOp mode)
3396 Report.Error (-215, "Report this: Taking the address of a remapped parameter not supported");
3401 /// Expression that evaluates to a Property. The Assign class
3402 /// might set the `Value' expression if we are in an assignment.
3404 /// This is not an LValue because we need to re-write the expression, we
3405 /// can not take data from the stack and store it.
3407 public class PropertyExpr : ExpressionStatement, IAssignMethod, IMemberExpr {
3408 public readonly PropertyInfo PropertyInfo;
3411 // This is set externally by the `BaseAccess' class
3414 MethodInfo getter, setter;
3417 Expression instance_expr;
3418 LocalTemporary temp;
3421 internal static PtrHashtable AccessorTable = new PtrHashtable ();
3423 public PropertyExpr (EmitContext ec, PropertyInfo pi, Location l)
3426 eclass = ExprClass.PropertyAccess;
3430 type = TypeManager.TypeToCoreType (pi.PropertyType);
3432 ResolveAccessors (ec);
3435 public string Name {
3437 return PropertyInfo.Name;
3441 public bool IsInstance {
3447 public bool IsStatic {
3453 public Type DeclaringType {
3455 return PropertyInfo.DeclaringType;
3460 // The instance expression associated with this expression
3462 public Expression InstanceExpression {
3464 instance_expr = value;
3468 return instance_expr;
3472 public bool VerifyAssignable ()
3474 if (setter == null) {
3475 Report.Error (200, loc,
3476 "The property `" + PropertyInfo.Name +
3477 "' can not be assigned to, as it has not set accessor");
3484 void FindAccessors (Type invocation_type)
3486 BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic |
3487 BindingFlags.Static | BindingFlags.Instance |
3488 BindingFlags.DeclaredOnly;
3490 Type current = PropertyInfo.DeclaringType;
3491 for (; current != null; current = current.BaseType) {
3492 MemberInfo[] group = TypeManager.MemberLookup (
3493 invocation_type, invocation_type, current,
3494 MemberTypes.Property, flags, PropertyInfo.Name, null);
3499 if (group.Length != 1)
3500 // Oooops, can this ever happen ?
3503 PropertyInfo pi = (PropertyInfo) group [0];
3506 getter = pi.GetGetMethod (true);
3509 setter = pi.GetSetMethod (true);
3511 MethodInfo accessor = getter != null ? getter : setter;
3513 if (!accessor.IsVirtual)
3519 // We also perform the permission checking here, as the PropertyInfo does not
3520 // hold the information for the accessibility of its setter/getter
3522 void ResolveAccessors (EmitContext ec)
3524 FindAccessors (ec.ContainerType);
3526 if (getter != null) {
3527 AccessorTable [getter] = PropertyInfo;
3528 is_static = getter.IsStatic;
3531 if (setter != null) {
3532 AccessorTable [setter] = PropertyInfo;
3533 is_static = setter.IsStatic;
3537 bool InstanceResolve (EmitContext ec, bool must_do_cs1540_check)
3539 if ((instance_expr == null) && ec.IsStatic && !is_static) {
3540 SimpleName.Error_ObjectRefRequired (ec, loc, PropertyInfo.Name);
3544 if (instance_expr != null) {
3545 instance_expr = instance_expr.DoResolve (ec);
3546 if (instance_expr == null)
3549 instance_expr.CheckMarshallByRefAccess (ec.ContainerType);
3552 if (must_do_cs1540_check && (instance_expr != null)) {
3553 if ((instance_expr.Type != ec.ContainerType) &&
3554 ec.ContainerType.IsSubclassOf (instance_expr.Type)) {
3555 Report.Error (1540, loc, "Cannot access protected member `" +
3556 PropertyInfo.DeclaringType + "." + PropertyInfo.Name +
3557 "' via a qualifier of type `" +
3558 TypeManager.CSharpName (instance_expr.Type) +
3559 "'; the qualifier must be of type `" +
3560 TypeManager.CSharpName (ec.ContainerType) +
3561 "' (or derived from it)");
3569 override public Expression DoResolve (EmitContext ec)
3571 if (getter != null){
3572 if (TypeManager.GetArgumentTypes (getter).Length != 0){
3574 117, loc, "`{0}' does not contain a " +
3575 "definition for `{1}'.", getter.DeclaringType,
3581 if (getter == null){
3583 // The following condition happens if the PropertyExpr was
3584 // created, but is invalid (ie, the property is inaccessible),
3585 // and we did not want to embed the knowledge about this in
3586 // the caller routine. This only avoids double error reporting.
3591 Report.Error (154, loc,
3592 "The property `" + PropertyInfo.Name +
3593 "' can not be used in " +
3594 "this context because it lacks a get accessor");
3598 bool must_do_cs1540_check;
3599 if (!IsAccessorAccessible (ec.ContainerType, getter, out must_do_cs1540_check)) {
3600 Report.Error (122, loc, "'{0}.get' is inaccessible due to its protection level", PropertyInfo.Name);
3604 if (!InstanceResolve (ec, must_do_cs1540_check))
3608 // Only base will allow this invocation to happen.
3610 if (IsBase && getter.IsAbstract){
3611 Report.Error (205, loc, "Cannot call an abstract base property: " +
3612 PropertyInfo.DeclaringType + "." +PropertyInfo.Name);
3619 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
3621 if (setter == null){
3623 // The following condition happens if the PropertyExpr was
3624 // created, but is invalid (ie, the property is inaccessible),
3625 // and we did not want to embed the knowledge about this in
3626 // the caller routine. This only avoids double error reporting.
3631 Report.Error (154, loc,
3632 "The property `" + PropertyInfo.Name +
3633 "' can not be used in " +
3634 "this context because it lacks a set accessor");
3638 if (TypeManager.GetArgumentTypes (setter).Length != 1){
3640 117, loc, "`{0}' does not contain a " +
3641 "definition for `{1}'.", getter.DeclaringType,
3646 bool must_do_cs1540_check;
3647 if (!IsAccessorAccessible (ec.ContainerType, setter, out must_do_cs1540_check)) {
3648 Report.Error (122, loc, "'{0}.set' is inaccessible due to its protection level", PropertyInfo.Name);
3652 if (!InstanceResolve (ec, must_do_cs1540_check))
3656 // Only base will allow this invocation to happen.
3658 if (IsBase && setter.IsAbstract){
3659 Report.Error (205, loc, "Cannot call an abstract base property: " +
3660 PropertyInfo.DeclaringType + "." +PropertyInfo.Name);
3665 // Check that we are not making changes to a temporary memory location
3667 if (instance_expr != null && instance_expr.Type.IsValueType && !(instance_expr is IMemoryLocation)) {
3668 // FIXME: Provide better error reporting.
3669 Error (1612, "Cannot modify expression because it is not a variable.");
3678 public override void Emit (EmitContext ec)
3683 void EmitInstance (EmitContext ec)
3688 if (instance_expr.Type.IsValueType) {
3689 if (instance_expr is IMemoryLocation) {
3690 ((IMemoryLocation) instance_expr).AddressOf (ec, AddressOp.LoadStore);
3692 LocalTemporary t = new LocalTemporary (ec, instance_expr.Type);
3693 instance_expr.Emit (ec);
3695 t.AddressOf (ec, AddressOp.Store);
3698 instance_expr.Emit (ec);
3701 ec.ig.Emit (OpCodes.Dup);
3705 public void Emit (EmitContext ec, bool leave_copy)
3711 // Special case: length of single dimension array property is turned into ldlen
3713 if ((getter == TypeManager.system_int_array_get_length) ||
3714 (getter == TypeManager.int_array_get_length)){
3715 Type iet = instance_expr.Type;
3718 // System.Array.Length can be called, but the Type does not
3719 // support invoking GetArrayRank, so test for that case first
3721 if (iet != TypeManager.array_type && (iet.GetArrayRank () == 1)) {
3722 ec.ig.Emit (OpCodes.Ldlen);
3723 ec.ig.Emit (OpCodes.Conv_I4);
3728 Invocation.EmitCall (ec, IsBase, IsStatic, new EmptyAddressOf (), getter, null, loc);
3733 ec.ig.Emit (OpCodes.Dup);
3735 temp = new LocalTemporary (ec, this.Type);
3741 // Implements the IAssignMethod interface for assignments
3743 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
3745 prepared = prepare_for_load;
3751 ec.ig.Emit (OpCodes.Dup);
3753 temp = new LocalTemporary (ec, this.Type);
3758 ArrayList args = new ArrayList (1);
3759 args.Add (new Argument (new EmptyAddressOf (), Argument.AType.Expression));
3761 Invocation.EmitCall (ec, IsBase, IsStatic, new EmptyAddressOf (), setter, args, loc);
3767 override public void EmitStatement (EmitContext ec)
3770 ec.ig.Emit (OpCodes.Pop);
3775 /// Fully resolved expression that evaluates to an Event
3777 public class EventExpr : Expression, IMemberExpr {
3778 public readonly EventInfo EventInfo;
3779 Expression instance_expr;
3782 MethodInfo add_accessor, remove_accessor;
3784 public EventExpr (EventInfo ei, Location loc)
3788 eclass = ExprClass.EventAccess;
3790 add_accessor = TypeManager.GetAddMethod (ei);
3791 remove_accessor = TypeManager.GetRemoveMethod (ei);
3793 if (add_accessor.IsStatic || remove_accessor.IsStatic)
3796 if (EventInfo is MyEventBuilder){
3797 MyEventBuilder eb = (MyEventBuilder) EventInfo;
3798 type = eb.EventType;
3801 type = EventInfo.EventHandlerType;
3804 public string Name {
3806 return EventInfo.Name;
3810 public bool IsInstance {
3816 public bool IsStatic {
3822 public Type DeclaringType {
3824 return EventInfo.DeclaringType;
3828 public Expression InstanceExpression {
3830 return instance_expr;
3834 instance_expr = value;
3838 bool InstanceResolve (EmitContext ec, bool must_do_cs1540_check)
3840 if ((instance_expr == null) && ec.IsStatic && !is_static) {
3841 SimpleName.Error_ObjectRefRequired (ec, loc, EventInfo.Name);
3845 if (instance_expr != null) {
3846 instance_expr = instance_expr.DoResolve (ec);
3847 if (instance_expr == null)
3852 // This is using the same mechanism as the CS1540 check in PropertyExpr.
3853 // However, in the Event case, we reported a CS0122 instead.
3855 if (must_do_cs1540_check && (instance_expr != null)) {
3856 if ((instance_expr.Type != ec.ContainerType) &&
3857 ec.ContainerType.IsSubclassOf (instance_expr.Type)) {
3858 Report.Error (122, loc, "'{0}' is inaccessible due to its protection level",
3859 DeclaringType.Name + "." + EventInfo.Name);
3868 public override Expression DoResolve (EmitContext ec)
3870 if (instance_expr != null) {
3871 instance_expr = instance_expr.DoResolve (ec);
3872 if (instance_expr == null)
3876 bool must_do_cs1540_check;
3877 if (!(IsAccessorAccessible (ec.ContainerType, add_accessor, out must_do_cs1540_check)
3878 && IsAccessorAccessible (ec.ContainerType, remove_accessor, out must_do_cs1540_check))) {
3880 Report.Error (122, loc, "'{0}' is inaccessible due to its protection level",
3881 DeclaringType.Name + "." + EventInfo.Name);
3885 if (!InstanceResolve (ec, must_do_cs1540_check))
3891 public override void Emit (EmitContext ec)
3893 if (instance_expr is This)
3894 Report.Error (79, loc, "The event `{0}' can only appear on the left hand side of += or -=, try calling the actual delegate", Name);
3896 Report.Error (70, loc, "The event `{0}' can only appear on the left hand side of += or -= "+
3897 "(except on the defining type)", Name);
3900 public void EmitAddOrRemove (EmitContext ec, Expression source)
3902 BinaryDelegate source_del = (BinaryDelegate) source;
3903 Expression handler = source_del.Right;
3905 Argument arg = new Argument (handler, Argument.AType.Expression);
3906 ArrayList args = new ArrayList ();
3910 if (source_del.IsAddition)
3911 Invocation.EmitCall (
3912 ec, false, IsStatic, instance_expr, add_accessor, args, loc);
3914 Invocation.EmitCall (
3915 ec, false, IsStatic, instance_expr, remove_accessor, args, loc);