2 // ecore.cs: Core of the Expression representation for the intermediate tree.
5 // Miguel de Icaza (miguel@ximian.com)
7 // (C) 2001, 2002, 2003 Ximian, Inc.
11 namespace Mono.CSharp {
13 using System.Collections;
14 using System.Diagnostics;
15 using System.Reflection;
16 using System.Reflection.Emit;
20 /// The ExprClass class contains the is used to pass the
21 /// classification of an expression (value, variable, namespace,
22 /// type, method group, property access, event access, indexer access,
25 public enum ExprClass : byte {
40 /// This is used to tell Resolve in which types of expressions we're
44 public enum ResolveFlags {
45 // Returns Value, Variable, PropertyAccess, EventAccess or IndexerAccess.
48 // Returns a type expression.
51 // Returns a method group.
54 // Allows SimpleNames to be returned.
55 // This is used by MemberAccess to construct long names that can not be
56 // partially resolved (namespace-qualified names for example).
59 // Mask of all the expression class flags.
62 // Disable control flow analysis while resolving the expression.
63 // This is used when resolving the instance expression of a field expression.
64 DisableFlowAnalysis = 16,
66 // Set if this is resolving the first part of a MemberAccess.
71 // This is just as a hint to AddressOf of what will be done with the
74 public enum AddressOp {
81 /// This interface is implemented by variables
83 public interface IMemoryLocation {
85 /// The AddressOf method should generate code that loads
86 /// the address of the object and leaves it on the stack.
88 /// The `mode' argument is used to notify the expression
89 /// of whether this will be used to read from the address or
90 /// write to the address.
92 /// This is just a hint that can be used to provide good error
93 /// reporting, and should have no other side effects.
95 void AddressOf (EmitContext ec, AddressOp mode);
99 /// We are either a namespace or a type.
100 /// If we're a type, `IsType' is true and we may use `Type' to get
101 /// a TypeExpr representing that type.
103 public interface IAlias {
112 TypeExpr ResolveAsType (EmitContext ec);
116 /// This interface is implemented by variables
118 public interface IVariable {
119 VariableInfo VariableInfo {
123 bool VerifyFixed (bool is_expression);
127 /// This interface denotes an expression which evaluates to a member
128 /// of a struct or a class.
130 public interface IMemberExpr
133 /// The name of this member.
140 /// Whether this is an instance member.
147 /// Whether this is a static member.
154 /// The type which declares this member.
161 /// The instance expression associated with this member, if it's a
162 /// non-static member.
164 Expression InstanceExpression {
170 /// Base class for expressions
172 public abstract class Expression {
173 public ExprClass eclass;
175 protected Location loc;
187 public Location Location {
194 /// Utility wrapper routine for Error, just to beautify the code
196 public void Error (int error, string s)
198 if (!Location.IsNull (loc))
199 Report.Error (error, loc, s);
201 Report.Error (error, s);
205 /// Utility wrapper routine for Warning, just to beautify the code
207 public void Warning (int code, string format, params object[] args)
209 Report.Warning (code, loc, format, args);
212 // Not nice but we have broken hierarchy
213 public virtual void CheckMarshallByRefAccess (Type container) {}
216 /// Tests presence of ObsoleteAttribute and report proper error
218 protected void CheckObsoleteAttribute (Type type)
220 ObsoleteAttribute obsolete_attr = AttributeTester.GetObsoleteAttribute (type);
221 if (obsolete_attr == null)
224 AttributeTester.Report_ObsoleteMessage (obsolete_attr, type.FullName, loc);
228 /// Performs semantic analysis on the Expression
232 /// The Resolve method is invoked to perform the semantic analysis
235 /// The return value is an expression (it can be the
236 /// same expression in some cases) or a new
237 /// expression that better represents this node.
239 /// For example, optimizations of Unary (LiteralInt)
240 /// would return a new LiteralInt with a negated
243 /// If there is an error during semantic analysis,
244 /// then an error should be reported (using Report)
245 /// and a null value should be returned.
247 /// There are two side effects expected from calling
248 /// Resolve(): the the field variable "eclass" should
249 /// be set to any value of the enumeration
250 /// `ExprClass' and the type variable should be set
251 /// to a valid type (this is the type of the
254 public abstract Expression DoResolve (EmitContext ec);
256 public virtual Expression DoResolveLValue (EmitContext ec, Expression right_side)
258 return DoResolve (ec);
262 // This is used if the expression should be resolved as a type.
263 // the default implementation fails. Use this method in
264 // those participants in the SimpleName chain system.
266 public virtual Expression ResolveAsTypeStep (EmitContext ec)
272 // This is used to resolve the expression as a type, a null
273 // value will be returned if the expression is not a type
276 public virtual TypeExpr ResolveAsTypeTerminal (EmitContext ec)
278 int errors = Report.Errors;
280 TypeExpr te = ResolveAsTypeStep (ec) as TypeExpr;
282 if ((te == null) || (te.eclass != ExprClass.Type) || (te.Type == null)) {
283 if (errors == Report.Errors)
284 Report.Error (246, Location, "Cannot find type '{0}'", ToString ());
288 if (!te.CheckAccessLevel (ec.DeclSpace)) {
289 Report.Error (122, Location, "'{0}' is inaccessible due to its protection level", te.Name);
297 /// Resolves an expression and performs semantic analysis on it.
301 /// Currently Resolve wraps DoResolve to perform sanity
302 /// checking and assertion checking on what we expect from Resolve.
304 public Expression Resolve (EmitContext ec, ResolveFlags flags)
306 if ((flags & ResolveFlags.MaskExprClass) == ResolveFlags.Type)
307 return ResolveAsTypeStep (ec);
309 bool old_do_flow_analysis = ec.DoFlowAnalysis;
310 if ((flags & ResolveFlags.DisableFlowAnalysis) != 0)
311 ec.DoFlowAnalysis = false;
314 bool intermediate = (flags & ResolveFlags.Intermediate) == ResolveFlags.Intermediate;
315 if (this is SimpleName)
316 e = ((SimpleName) this).DoResolveAllowStatic (ec, intermediate);
321 ec.DoFlowAnalysis = old_do_flow_analysis;
326 if (e is SimpleName){
327 SimpleName s = (SimpleName) e;
329 if ((flags & ResolveFlags.SimpleName) == 0) {
330 MemberLookupFailed (ec, null, ec.ContainerType, s.Name,
331 ec.DeclSpace.Name, loc);
338 if ((e is TypeExpr) || (e is ComposedCast)) {
339 if ((flags & ResolveFlags.Type) == 0) {
340 e.Error_UnexpectedKind (flags, loc);
349 if ((flags & ResolveFlags.VariableOrValue) == 0) {
350 e.Error_UnexpectedKind (flags, loc);
355 case ExprClass.MethodGroup:
356 if (RootContext.Version == LanguageVersion.ISO_1){
357 if ((flags & ResolveFlags.MethodGroup) == 0) {
358 ((MethodGroupExpr) e).ReportUsageError ();
364 case ExprClass.Value:
365 case ExprClass.Variable:
366 case ExprClass.PropertyAccess:
367 case ExprClass.EventAccess:
368 case ExprClass.IndexerAccess:
369 if ((flags & ResolveFlags.VariableOrValue) == 0) {
370 Console.WriteLine ("I got: {0} and {1}", e.GetType (), e);
371 Console.WriteLine ("I am {0} and {1}", this.GetType (), this);
372 FieldInfo fi = ((FieldExpr) e).FieldInfo;
374 Console.WriteLine ("{0} and {1}", fi.DeclaringType, fi.Name);
375 e.Error_UnexpectedKind (flags, loc);
381 throw new Exception ("Expression " + e.GetType () +
382 " ExprClass is Invalid after resolve");
386 throw new Exception (
387 "Expression " + e.GetType () +
388 " did not set its type after Resolve\n" +
389 "called from: " + this.GetType ());
395 /// Resolves an expression and performs semantic analysis on it.
397 public Expression Resolve (EmitContext ec)
399 return Resolve (ec, ResolveFlags.VariableOrValue);
403 /// Resolves an expression for LValue assignment
407 /// Currently ResolveLValue wraps DoResolveLValue to perform sanity
408 /// checking and assertion checking on what we expect from Resolve
410 public Expression ResolveLValue (EmitContext ec, Expression right_side)
412 Expression e = DoResolveLValue (ec, right_side);
415 if (e is SimpleName){
416 SimpleName s = (SimpleName) e;
417 MemberLookupFailed (ec, null, ec.ContainerType, s.Name,
418 ec.DeclSpace.Name, loc);
422 if (e.eclass == ExprClass.Invalid)
423 throw new Exception ("Expression " + e +
424 " ExprClass is Invalid after resolve");
426 if (e.eclass == ExprClass.MethodGroup) {
427 ((MethodGroupExpr) e).ReportUsageError ();
431 if ((e.type == null) && !(e is ConstructedType))
432 throw new Exception ("Expression " + e +
433 " did not set its type after Resolve");
440 /// Emits the code for the expression
444 /// The Emit method is invoked to generate the code
445 /// for the expression.
447 public abstract void Emit (EmitContext ec);
449 public virtual void EmitBranchable (EmitContext ec, Label target, bool onTrue)
452 ec.ig.Emit (onTrue ? OpCodes.Brtrue : OpCodes.Brfalse, target);
456 /// Protected constructor. Only derivate types should
457 /// be able to be created
460 protected Expression ()
462 eclass = ExprClass.Invalid;
467 /// Returns a literalized version of a literal FieldInfo
471 /// The possible return values are:
472 /// IntConstant, UIntConstant
473 /// LongLiteral, ULongConstant
474 /// FloatConstant, DoubleConstant
477 /// The value returned is already resolved.
479 public static Constant Constantify (object v, Type t)
481 if (t == TypeManager.int32_type)
482 return new IntConstant ((int) v);
483 else if (t == TypeManager.uint32_type)
484 return new UIntConstant ((uint) v);
485 else if (t == TypeManager.int64_type)
486 return new LongConstant ((long) v);
487 else if (t == TypeManager.uint64_type)
488 return new ULongConstant ((ulong) v);
489 else if (t == TypeManager.float_type)
490 return new FloatConstant ((float) v);
491 else if (t == TypeManager.double_type)
492 return new DoubleConstant ((double) v);
493 else if (t == TypeManager.string_type)
494 return new StringConstant ((string) v);
495 else if (t == TypeManager.short_type)
496 return new ShortConstant ((short)v);
497 else if (t == TypeManager.ushort_type)
498 return new UShortConstant ((ushort)v);
499 else if (t == TypeManager.sbyte_type)
500 return new SByteConstant (((sbyte)v));
501 else if (t == TypeManager.byte_type)
502 return new ByteConstant ((byte)v);
503 else if (t == TypeManager.char_type)
504 return new CharConstant ((char)v);
505 else if (t == TypeManager.bool_type)
506 return new BoolConstant ((bool) v);
507 else if (t == TypeManager.decimal_type)
508 return new DecimalConstant ((decimal) v);
509 else if (TypeManager.IsEnumType (t)){
510 Type real_type = TypeManager.TypeToCoreType (v.GetType ());
512 real_type = System.Enum.GetUnderlyingType (real_type);
514 Constant e = Constantify (v, real_type);
516 return new EnumConstant (e, t);
517 } else if (v == null && !TypeManager.IsValueType (t))
518 return NullLiteral.Null;
520 throw new Exception ("Unknown type for constant (" + t +
525 /// Returns a fully formed expression after a MemberLookup
527 public static Expression ExprClassFromMemberInfo (EmitContext ec, MemberInfo mi, Location loc)
530 return new EventExpr ((EventInfo) mi, loc);
531 else if (mi is FieldInfo)
532 return new FieldExpr ((FieldInfo) mi, loc);
533 else if (mi is PropertyInfo)
534 return new PropertyExpr (ec, (PropertyInfo) mi, loc);
535 else if (mi is Type){
536 return new TypeExpression ((System.Type) mi, loc);
543 private static ArrayList almostMatchedMembers = new ArrayList (4);
546 // FIXME: Probably implement a cache for (t,name,current_access_set)?
548 // This code could use some optimizations, but we need to do some
549 // measurements. For example, we could use a delegate to `flag' when
550 // something can not any longer be a method-group (because it is something
554 // If the return value is an Array, then it is an array of
557 // If the return value is an MemberInfo, it is anything, but a Method
561 // FIXME: When calling MemberLookup inside an `Invocation', we should pass
562 // the arguments here and have MemberLookup return only the methods that
563 // match the argument count/type, unlike we are doing now (we delay this
566 // This is so we can catch correctly attempts to invoke instance methods
567 // from a static body (scan for error 120 in ResolveSimpleName).
570 // FIXME: Potential optimization, have a static ArrayList
573 public static Expression MemberLookup (EmitContext ec, Type queried_type, string name,
574 MemberTypes mt, BindingFlags bf, Location loc)
576 return MemberLookup (ec, ec.ContainerType, null, queried_type, name, mt, bf, loc);
580 // Lookup type `queried_type' for code in class `container_type' with a qualifier of
581 // `qualifier_type' or null to lookup members in the current class.
584 public static Expression MemberLookup (EmitContext ec, Type container_type,
585 Type qualifier_type, Type queried_type,
586 string name, MemberTypes mt,
587 BindingFlags bf, Location loc)
589 almostMatchedMembers.Clear ();
591 MemberInfo [] mi = TypeManager.MemberLookup (
592 container_type, qualifier_type,queried_type, mt, bf, name,
593 almostMatchedMembers);
598 int count = mi.Length;
600 if (mi [0] is MethodBase)
601 return new MethodGroupExpr (mi, loc);
606 return ExprClassFromMemberInfo (ec, mi [0], loc);
609 public const MemberTypes AllMemberTypes =
610 MemberTypes.Constructor |
614 MemberTypes.NestedType |
615 MemberTypes.Property;
617 public const BindingFlags AllBindingFlags =
618 BindingFlags.Public |
619 BindingFlags.Static |
620 BindingFlags.Instance;
622 public static Expression MemberLookup (EmitContext ec, Type queried_type,
623 string name, Location loc)
625 return MemberLookup (ec, ec.ContainerType, null, queried_type, name,
626 AllMemberTypes, AllBindingFlags, loc);
629 public static Expression MemberLookup (EmitContext ec, Type qualifier_type,
630 Type queried_type, string name, Location loc)
632 return MemberLookup (ec, ec.ContainerType, qualifier_type, queried_type,
633 name, AllMemberTypes, AllBindingFlags, loc);
636 public static Expression MethodLookup (EmitContext ec, Type queried_type,
637 string name, Location loc)
639 return MemberLookup (ec, ec.ContainerType, null, queried_type, name,
640 MemberTypes.Method, AllBindingFlags, loc);
644 /// This is a wrapper for MemberLookup that is not used to "probe", but
645 /// to find a final definition. If the final definition is not found, we
646 /// look for private members and display a useful debugging message if we
649 public static Expression MemberLookupFinal (EmitContext ec, Type qualifier_type,
650 Type queried_type, string name,
653 return MemberLookupFinal (ec, qualifier_type, queried_type, name,
654 AllMemberTypes, AllBindingFlags, loc);
657 public static Expression MemberLookupFinal (EmitContext ec, Type qualifier_type,
658 Type queried_type, string name,
659 MemberTypes mt, BindingFlags bf,
664 int errors = Report.Errors;
666 e = MemberLookup (ec, ec.ContainerType, qualifier_type, queried_type,
669 if (e == null && errors == Report.Errors)
670 // No errors were reported by MemberLookup, but there was an error.
671 MemberLookupFailed (ec, qualifier_type, queried_type, name,
677 public static void MemberLookupFailed (EmitContext ec, Type qualifier_type,
678 Type queried_type, string name,
679 string class_name, Location loc)
681 if (almostMatchedMembers.Count != 0) {
682 if (qualifier_type == null) {
683 foreach (MemberInfo m in almostMatchedMembers)
684 Report.Error (38, loc,
685 "Cannot access non-static member `{0}' via nested type `{1}'",
686 TypeManager.GetFullNameSignature (m),
687 TypeManager.CSharpName (ec.ContainerType));
692 if (qualifier_type != ec.ContainerType) {
693 // Although a derived class can access protected members of
694 // its base class it cannot do so through an instance of the
695 // base class (CS1540). If the qualifier_type is a parent of the
696 // ec.ContainerType and the lookup succeeds with the latter one,
697 // then we are in this situation.
698 foreach (MemberInfo m in almostMatchedMembers)
699 Report.Error (1540, loc,
700 "Cannot access protected member `{0}' via a qualifier of type `{1}';"
701 + " the qualifier must be of type `{2}' (or derived from it)",
702 TypeManager.GetFullNameSignature (m),
703 TypeManager.CSharpName (qualifier_type),
704 TypeManager.CSharpName (ec.ContainerType));
707 almostMatchedMembers.Clear ();
710 MemberInfo[] mi = TypeManager.MemberLookup (queried_type, null, queried_type,
711 AllMemberTypes, AllBindingFlags |
712 BindingFlags.NonPublic, name, null);
715 if (class_name != null)
716 Report.Error (103, loc, "The name `" + name + "' could not be " +
717 "found in `" + class_name + "'");
720 117, loc, "`" + queried_type + "' does not contain a " +
721 "definition for `" + name + "'");
725 if (TypeManager.MemberLookup (queried_type, null, queried_type,
726 AllMemberTypes, AllBindingFlags |
727 BindingFlags.NonPublic, name, null) == null) {
728 if ((mi.Length == 1) && (mi [0] is Type)) {
729 Type t = (Type) mi [0];
731 Report.Error (305, loc,
732 "Using the generic type `{0}' " +
733 "requires {1} type arguments",
734 TypeManager.GetFullName (t),
735 TypeManager.GetNumberOfTypeArguments (t));
742 if (qualifier_type != null)
743 Report.Error (122, loc, "'{0}' is inaccessible due to its protection level", TypeManager.CSharpName (qualifier_type) + "." + name);
744 else if (name == ".ctor") {
745 Report.Error (143, loc, String.Format ("The type {0} has no constructors defined",
746 TypeManager.CSharpName (queried_type)));
748 Report.Error (122, loc, "'{0}' is inaccessible due to its protection level", name);
752 static public MemberInfo GetFieldFromEvent (EventExpr event_expr)
754 EventInfo ei = event_expr.EventInfo;
756 return TypeManager.GetPrivateFieldOfEvent (ei);
760 /// Returns an expression that can be used to invoke operator true
761 /// on the expression if it exists.
763 static public StaticCallExpr GetOperatorTrue (EmitContext ec, Expression e, Location loc)
765 return GetOperatorTrueOrFalse (ec, e, true, loc);
769 /// Returns an expression that can be used to invoke operator false
770 /// on the expression if it exists.
772 static public StaticCallExpr GetOperatorFalse (EmitContext ec, Expression e, Location loc)
774 return GetOperatorTrueOrFalse (ec, e, false, loc);
777 static StaticCallExpr GetOperatorTrueOrFalse (EmitContext ec, Expression e, bool is_true, Location loc)
780 Expression operator_group;
782 operator_group = MethodLookup (ec, e.Type, is_true ? "op_True" : "op_False", loc);
783 if (operator_group == null)
786 ArrayList arguments = new ArrayList ();
787 arguments.Add (new Argument (e, Argument.AType.Expression));
788 method = Invocation.OverloadResolve (
789 ec, (MethodGroupExpr) operator_group, arguments, false, loc);
794 return new StaticCallExpr ((MethodInfo) method, arguments, loc);
798 /// Resolves the expression `e' into a boolean expression: either through
799 /// an implicit conversion, or through an `operator true' invocation
801 public static Expression ResolveBoolean (EmitContext ec, Expression e, Location loc)
807 Expression converted = e;
808 if (e.Type != TypeManager.bool_type)
809 converted = Convert.ImplicitConversion (ec, e, TypeManager.bool_type, new Location (-1));
812 // If no implicit conversion to bool exists, try using `operator true'
814 if (converted == null){
815 Expression operator_true = Expression.GetOperatorTrue (ec, e, loc);
816 if (operator_true == null){
818 31, loc, "Can not convert the expression to a boolean");
828 static string ExprClassName (ExprClass c)
831 case ExprClass.Invalid:
833 case ExprClass.Value:
835 case ExprClass.Variable:
837 case ExprClass.Namespace:
841 case ExprClass.MethodGroup:
842 return "method group";
843 case ExprClass.PropertyAccess:
844 return "property access";
845 case ExprClass.EventAccess:
846 return "event access";
847 case ExprClass.IndexerAccess:
848 return "indexer access";
849 case ExprClass.Nothing:
852 throw new Exception ("Should not happen");
856 /// Reports that we were expecting `expr' to be of class `expected'
858 public void Error_UnexpectedKind (string expected, Location loc)
860 string kind = "Unknown";
862 kind = ExprClassName (eclass);
864 Report.Error (118, loc, "Expression denotes a `" + kind +
865 "' where a `" + expected + "' was expected");
868 public void Error_UnexpectedKind (ResolveFlags flags, Location loc)
870 ArrayList valid = new ArrayList (10);
872 if ((flags & ResolveFlags.VariableOrValue) != 0) {
873 valid.Add ("variable");
877 if ((flags & ResolveFlags.Type) != 0)
880 if ((flags & ResolveFlags.MethodGroup) != 0)
881 valid.Add ("method group");
883 if ((flags & ResolveFlags.SimpleName) != 0)
884 valid.Add ("simple name");
886 if (valid.Count == 0)
887 valid.Add ("unknown");
889 StringBuilder sb = new StringBuilder ();
890 for (int i = 0; i < valid.Count; i++) {
893 else if (i == valid.Count)
895 sb.Append (valid [i]);
898 string kind = ExprClassName (eclass);
900 Error (119, "Expression denotes a `" + kind + "' where " +
901 "a `" + sb.ToString () + "' was expected");
904 static public void Error_ConstantValueCannotBeConverted (Location l, string val, Type t)
906 Report.Error (31, l, "Constant value `" + val + "' cannot be converted to " +
907 TypeManager.CSharpName (t));
910 public static void UnsafeError (Location loc)
912 Report.Error (214, loc, "Pointers may only be used in an unsafe context");
916 /// Converts the IntConstant, UIntConstant, LongConstant or
917 /// ULongConstant into the integral target_type. Notice
918 /// that we do not return an `Expression' we do return
919 /// a boxed integral type.
921 /// FIXME: Since I added the new constants, we need to
922 /// also support conversions from CharConstant, ByteConstant,
923 /// SByteConstant, UShortConstant, ShortConstant
925 /// This is used by the switch statement, so the domain
926 /// of work is restricted to the literals above, and the
927 /// targets are int32, uint32, char, byte, sbyte, ushort,
928 /// short, uint64 and int64
930 public static object ConvertIntLiteral (Constant c, Type target_type, Location loc)
932 if (!Convert.ImplicitStandardConversionExists (Convert.ConstantEC, c, target_type)){
933 Convert.Error_CannotImplicitConversion (loc, c.Type, target_type);
939 if (c.Type == target_type)
940 return ((Constant) c).GetValue ();
943 // Make into one of the literals we handle, we dont really care
944 // about this value as we will just return a few limited types
946 if (c is EnumConstant)
947 c = ((EnumConstant)c).WidenToCompilerConstant ();
949 if (c is IntConstant){
950 int v = ((IntConstant) c).Value;
952 if (target_type == TypeManager.uint32_type){
955 } else if (target_type == TypeManager.char_type){
956 if (v >= Char.MinValue && v <= Char.MaxValue)
958 } else if (target_type == TypeManager.byte_type){
959 if (v >= Byte.MinValue && v <= Byte.MaxValue)
961 } else if (target_type == TypeManager.sbyte_type){
962 if (v >= SByte.MinValue && v <= SByte.MaxValue)
964 } else if (target_type == TypeManager.short_type){
965 if (v >= Int16.MinValue && v <= UInt16.MaxValue)
967 } else if (target_type == TypeManager.ushort_type){
968 if (v >= UInt16.MinValue && v <= UInt16.MaxValue)
970 } else if (target_type == TypeManager.int64_type)
972 else if (target_type == TypeManager.uint64_type){
978 } else if (c is UIntConstant){
979 uint v = ((UIntConstant) c).Value;
981 if (target_type == TypeManager.int32_type){
982 if (v <= Int32.MaxValue)
984 } else if (target_type == TypeManager.char_type){
985 if (v >= Char.MinValue && v <= Char.MaxValue)
987 } else if (target_type == TypeManager.byte_type){
988 if (v <= Byte.MaxValue)
990 } else if (target_type == TypeManager.sbyte_type){
991 if (v <= SByte.MaxValue)
993 } else if (target_type == TypeManager.short_type){
994 if (v <= UInt16.MaxValue)
996 } else if (target_type == TypeManager.ushort_type){
997 if (v <= UInt16.MaxValue)
999 } else if (target_type == TypeManager.int64_type)
1001 else if (target_type == TypeManager.uint64_type)
1004 } else if (c is LongConstant){
1005 long v = ((LongConstant) c).Value;
1007 if (target_type == TypeManager.int32_type){
1008 if (v >= UInt32.MinValue && v <= UInt32.MaxValue)
1010 } else if (target_type == TypeManager.uint32_type){
1011 if (v >= 0 && v <= UInt32.MaxValue)
1013 } else if (target_type == TypeManager.char_type){
1014 if (v >= Char.MinValue && v <= Char.MaxValue)
1016 } else if (target_type == TypeManager.byte_type){
1017 if (v >= Byte.MinValue && v <= Byte.MaxValue)
1019 } else if (target_type == TypeManager.sbyte_type){
1020 if (v >= SByte.MinValue && v <= SByte.MaxValue)
1022 } else if (target_type == TypeManager.short_type){
1023 if (v >= Int16.MinValue && v <= UInt16.MaxValue)
1025 } else if (target_type == TypeManager.ushort_type){
1026 if (v >= UInt16.MinValue && v <= UInt16.MaxValue)
1028 } else if (target_type == TypeManager.uint64_type){
1033 } else if (c is ULongConstant){
1034 ulong v = ((ULongConstant) c).Value;
1036 if (target_type == TypeManager.int32_type){
1037 if (v <= Int32.MaxValue)
1039 } else if (target_type == TypeManager.uint32_type){
1040 if (v <= UInt32.MaxValue)
1042 } else if (target_type == TypeManager.char_type){
1043 if (v >= Char.MinValue && v <= Char.MaxValue)
1045 } else if (target_type == TypeManager.byte_type){
1046 if (v >= Byte.MinValue && v <= Byte.MaxValue)
1048 } else if (target_type == TypeManager.sbyte_type){
1049 if (v <= (int) SByte.MaxValue)
1051 } else if (target_type == TypeManager.short_type){
1052 if (v <= UInt16.MaxValue)
1054 } else if (target_type == TypeManager.ushort_type){
1055 if (v <= UInt16.MaxValue)
1057 } else if (target_type == TypeManager.int64_type){
1058 if (v <= Int64.MaxValue)
1062 } else if (c is ByteConstant){
1063 byte v = ((ByteConstant) c).Value;
1065 if (target_type == TypeManager.int32_type)
1067 else if (target_type == TypeManager.uint32_type)
1069 else if (target_type == TypeManager.char_type)
1071 else if (target_type == TypeManager.sbyte_type){
1072 if (v <= SByte.MaxValue)
1074 } else if (target_type == TypeManager.short_type)
1076 else if (target_type == TypeManager.ushort_type)
1078 else if (target_type == TypeManager.int64_type)
1080 else if (target_type == TypeManager.uint64_type)
1083 } else if (c is SByteConstant){
1084 sbyte v = ((SByteConstant) c).Value;
1086 if (target_type == TypeManager.int32_type)
1088 else if (target_type == TypeManager.uint32_type){
1091 } else if (target_type == TypeManager.char_type){
1094 } else if (target_type == TypeManager.byte_type){
1097 } else if (target_type == TypeManager.short_type)
1099 else if (target_type == TypeManager.ushort_type){
1102 } else if (target_type == TypeManager.int64_type)
1104 else if (target_type == TypeManager.uint64_type){
1109 } else if (c is ShortConstant){
1110 short v = ((ShortConstant) c).Value;
1112 if (target_type == TypeManager.int32_type){
1114 } else if (target_type == TypeManager.uint32_type){
1117 } else if (target_type == TypeManager.char_type){
1120 } else if (target_type == TypeManager.byte_type){
1121 if (v >= Byte.MinValue && v <= Byte.MaxValue)
1123 } else if (target_type == TypeManager.sbyte_type){
1124 if (v >= SByte.MinValue && v <= SByte.MaxValue)
1126 } else if (target_type == TypeManager.ushort_type){
1129 } else if (target_type == TypeManager.int64_type)
1131 else if (target_type == TypeManager.uint64_type)
1135 } else if (c is UShortConstant){
1136 ushort v = ((UShortConstant) c).Value;
1138 if (target_type == TypeManager.int32_type)
1140 else if (target_type == TypeManager.uint32_type)
1142 else if (target_type == TypeManager.char_type){
1143 if (v >= Char.MinValue && v <= Char.MaxValue)
1145 } else if (target_type == TypeManager.byte_type){
1146 if (v >= Byte.MinValue && v <= Byte.MaxValue)
1148 } else if (target_type == TypeManager.sbyte_type){
1149 if (v <= SByte.MaxValue)
1151 } else if (target_type == TypeManager.short_type){
1152 if (v <= Int16.MaxValue)
1154 } else if (target_type == TypeManager.int64_type)
1156 else if (target_type == TypeManager.uint64_type)
1160 } else if (c is CharConstant){
1161 char v = ((CharConstant) c).Value;
1163 if (target_type == TypeManager.int32_type)
1165 else if (target_type == TypeManager.uint32_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.MaxValue)
1173 } else if (target_type == TypeManager.short_type){
1174 if (v <= Int16.MaxValue)
1176 } else if (target_type == TypeManager.ushort_type)
1178 else if (target_type == TypeManager.int64_type)
1180 else if (target_type == TypeManager.uint64_type)
1185 Error_ConstantValueCannotBeConverted (loc, s, target_type);
1190 // Load the object from the pointer.
1192 public static void LoadFromPtr (ILGenerator ig, Type t)
1194 if (t == TypeManager.int32_type)
1195 ig.Emit (OpCodes.Ldind_I4);
1196 else if (t == TypeManager.uint32_type)
1197 ig.Emit (OpCodes.Ldind_U4);
1198 else if (t == TypeManager.short_type)
1199 ig.Emit (OpCodes.Ldind_I2);
1200 else if (t == TypeManager.ushort_type)
1201 ig.Emit (OpCodes.Ldind_U2);
1202 else if (t == TypeManager.char_type)
1203 ig.Emit (OpCodes.Ldind_U2);
1204 else if (t == TypeManager.byte_type)
1205 ig.Emit (OpCodes.Ldind_U1);
1206 else if (t == TypeManager.sbyte_type)
1207 ig.Emit (OpCodes.Ldind_I1);
1208 else if (t == TypeManager.uint64_type)
1209 ig.Emit (OpCodes.Ldind_I8);
1210 else if (t == TypeManager.int64_type)
1211 ig.Emit (OpCodes.Ldind_I8);
1212 else if (t == TypeManager.float_type)
1213 ig.Emit (OpCodes.Ldind_R4);
1214 else if (t == TypeManager.double_type)
1215 ig.Emit (OpCodes.Ldind_R8);
1216 else if (t == TypeManager.bool_type)
1217 ig.Emit (OpCodes.Ldind_I1);
1218 else if (t == TypeManager.intptr_type)
1219 ig.Emit (OpCodes.Ldind_I);
1220 else if (TypeManager.IsEnumType (t)) {
1221 if (t == TypeManager.enum_type)
1222 ig.Emit (OpCodes.Ldind_Ref);
1224 LoadFromPtr (ig, TypeManager.EnumToUnderlying (t));
1225 } else if (t.IsValueType || t.IsGenericParameter)
1226 ig.Emit (OpCodes.Ldobj, t);
1227 else if (t.IsPointer)
1228 ig.Emit (OpCodes.Ldind_I);
1230 ig.Emit (OpCodes.Ldind_Ref);
1234 // The stack contains the pointer and the value of type `type'
1236 public static void StoreFromPtr (ILGenerator ig, Type type)
1238 if (TypeManager.IsEnumType (type))
1239 type = TypeManager.EnumToUnderlying (type);
1240 if (type == TypeManager.int32_type || type == TypeManager.uint32_type)
1241 ig.Emit (OpCodes.Stind_I4);
1242 else if (type == TypeManager.int64_type || type == TypeManager.uint64_type)
1243 ig.Emit (OpCodes.Stind_I8);
1244 else if (type == TypeManager.char_type || type == TypeManager.short_type ||
1245 type == TypeManager.ushort_type)
1246 ig.Emit (OpCodes.Stind_I2);
1247 else if (type == TypeManager.float_type)
1248 ig.Emit (OpCodes.Stind_R4);
1249 else if (type == TypeManager.double_type)
1250 ig.Emit (OpCodes.Stind_R8);
1251 else if (type == TypeManager.byte_type || type == TypeManager.sbyte_type ||
1252 type == TypeManager.bool_type)
1253 ig.Emit (OpCodes.Stind_I1);
1254 else if (type == TypeManager.intptr_type)
1255 ig.Emit (OpCodes.Stind_I);
1256 else if (type.IsValueType || type.IsGenericParameter)
1257 ig.Emit (OpCodes.Stobj, type);
1259 ig.Emit (OpCodes.Stind_Ref);
1263 // Returns the size of type `t' if known, otherwise, 0
1265 public static int GetTypeSize (Type t)
1267 t = TypeManager.TypeToCoreType (t);
1268 if (t == TypeManager.int32_type ||
1269 t == TypeManager.uint32_type ||
1270 t == TypeManager.float_type)
1272 else if (t == TypeManager.int64_type ||
1273 t == TypeManager.uint64_type ||
1274 t == TypeManager.double_type)
1276 else if (t == TypeManager.byte_type ||
1277 t == TypeManager.sbyte_type ||
1278 t == TypeManager.bool_type)
1280 else if (t == TypeManager.short_type ||
1281 t == TypeManager.char_type ||
1282 t == TypeManager.ushort_type)
1284 else if (t == TypeManager.decimal_type)
1290 public static void Error_NegativeArrayIndex (Location loc)
1292 Report.Error (248, loc, "Cannot create an array with a negative size");
1296 // Converts `source' to an int, uint, long or ulong.
1298 public Expression ExpressionToArrayArgument (EmitContext ec, Expression source, Location loc)
1302 bool old_checked = ec.CheckState;
1303 ec.CheckState = true;
1305 target = Convert.ImplicitConversion (ec, source, TypeManager.int32_type, loc);
1306 if (target == null){
1307 target = Convert.ImplicitConversion (ec, source, TypeManager.uint32_type, loc);
1308 if (target == null){
1309 target = Convert.ImplicitConversion (ec, source, TypeManager.int64_type, loc);
1310 if (target == null){
1311 target = Convert.ImplicitConversion (ec, source, TypeManager.uint64_type, loc);
1313 Convert.Error_CannotImplicitConversion (loc, source.Type, TypeManager.int32_type);
1317 ec.CheckState = old_checked;
1320 // Only positive constants are allowed at compile time
1322 if (target is Constant){
1323 if (target is IntConstant){
1324 if (((IntConstant) target).Value < 0){
1325 Error_NegativeArrayIndex (loc);
1330 if (target is LongConstant){
1331 if (((LongConstant) target).Value < 0){
1332 Error_NegativeArrayIndex (loc);
1345 /// This is just a base class for expressions that can
1346 /// appear on statements (invocations, object creation,
1347 /// assignments, post/pre increment and decrement). The idea
1348 /// being that they would support an extra Emition interface that
1349 /// does not leave a result on the stack.
1351 public abstract class ExpressionStatement : Expression {
1353 public virtual ExpressionStatement ResolveStatement (EmitContext ec)
1355 Expression e = Resolve (ec);
1359 ExpressionStatement es = e as ExpressionStatement;
1361 Error (201, "Only assignment, call, increment, decrement and new object " +
1362 "expressions can be used as a statement");
1368 /// Requests the expression to be emitted in a `statement'
1369 /// context. This means that no new value is left on the
1370 /// stack after invoking this method (constrasted with
1371 /// Emit that will always leave a value on the stack).
1373 public abstract void EmitStatement (EmitContext ec);
1377 /// This kind of cast is used to encapsulate the child
1378 /// whose type is child.Type into an expression that is
1379 /// reported to return "return_type". This is used to encapsulate
1380 /// expressions which have compatible types, but need to be dealt
1381 /// at higher levels with.
1383 /// For example, a "byte" expression could be encapsulated in one
1384 /// of these as an "unsigned int". The type for the expression
1385 /// would be "unsigned int".
1388 public class EmptyCast : Expression {
1389 protected Expression child;
1391 public Expression Child {
1397 public EmptyCast (Expression child, Type return_type)
1399 eclass = child.eclass;
1404 public override Expression DoResolve (EmitContext ec)
1406 // This should never be invoked, we are born in fully
1407 // initialized state.
1412 public override void Emit (EmitContext ec)
1419 // We need to special case this since an empty cast of
1420 // a NullLiteral is still a Constant
1422 public class NullCast : Constant {
1423 protected Expression child;
1425 public NullCast (Expression child, Type return_type)
1427 eclass = child.eclass;
1432 override public string AsString ()
1437 public override object GetValue ()
1442 public override Expression DoResolve (EmitContext ec)
1444 // This should never be invoked, we are born in fully
1445 // initialized state.
1450 public override void Emit (EmitContext ec)
1455 public override bool IsNegative {
1464 /// This class is used to wrap literals which belong inside Enums
1466 public class EnumConstant : Constant {
1467 public Constant Child;
1469 public EnumConstant (Constant child, Type enum_type)
1471 eclass = child.eclass;
1476 public override Expression DoResolve (EmitContext ec)
1478 // This should never be invoked, we are born in fully
1479 // initialized state.
1484 public override void Emit (EmitContext ec)
1489 public override object GetValue ()
1491 return Child.GetValue ();
1494 public object GetValueAsEnumType ()
1496 return System.Enum.ToObject (type, Child.GetValue ());
1500 // Converts from one of the valid underlying types for an enumeration
1501 // (int32, uint32, int64, uint64, short, ushort, byte, sbyte) to
1502 // one of the internal compiler literals: Int/UInt/Long/ULong Literals.
1504 public Constant WidenToCompilerConstant ()
1506 Type t = TypeManager.EnumToUnderlying (Child.Type);
1507 object v = ((Constant) Child).GetValue ();;
1509 if (t == TypeManager.int32_type)
1510 return new IntConstant ((int) v);
1511 if (t == TypeManager.uint32_type)
1512 return new UIntConstant ((uint) v);
1513 if (t == TypeManager.int64_type)
1514 return new LongConstant ((long) v);
1515 if (t == TypeManager.uint64_type)
1516 return new ULongConstant ((ulong) v);
1517 if (t == TypeManager.short_type)
1518 return new ShortConstant ((short) v);
1519 if (t == TypeManager.ushort_type)
1520 return new UShortConstant ((ushort) v);
1521 if (t == TypeManager.byte_type)
1522 return new ByteConstant ((byte) v);
1523 if (t == TypeManager.sbyte_type)
1524 return new SByteConstant ((sbyte) v);
1526 throw new Exception ("Invalid enumeration underlying type: " + t);
1530 // Extracts the value in the enumeration on its native representation
1532 public object GetPlainValue ()
1534 Type t = TypeManager.EnumToUnderlying (Child.Type);
1535 object v = ((Constant) Child).GetValue ();;
1537 if (t == TypeManager.int32_type)
1539 if (t == TypeManager.uint32_type)
1541 if (t == TypeManager.int64_type)
1543 if (t == TypeManager.uint64_type)
1545 if (t == TypeManager.short_type)
1547 if (t == TypeManager.ushort_type)
1549 if (t == TypeManager.byte_type)
1551 if (t == TypeManager.sbyte_type)
1557 public override string AsString ()
1559 return Child.AsString ();
1562 public override DoubleConstant ConvertToDouble ()
1564 return Child.ConvertToDouble ();
1567 public override FloatConstant ConvertToFloat ()
1569 return Child.ConvertToFloat ();
1572 public override ULongConstant ConvertToULong ()
1574 return Child.ConvertToULong ();
1577 public override LongConstant ConvertToLong ()
1579 return Child.ConvertToLong ();
1582 public override UIntConstant ConvertToUInt ()
1584 return Child.ConvertToUInt ();
1587 public override IntConstant ConvertToInt ()
1589 return Child.ConvertToInt ();
1592 public override bool IsZeroInteger {
1593 get { return Child.IsZeroInteger; }
1596 public override bool IsNegative {
1598 return Child.IsNegative;
1604 /// This kind of cast is used to encapsulate Value Types in objects.
1606 /// The effect of it is to box the value type emitted by the previous
1609 public class BoxedCast : EmptyCast {
1611 public BoxedCast (Expression expr)
1612 : base (expr, TypeManager.object_type)
1614 eclass = ExprClass.Value;
1617 public BoxedCast (Expression expr, Type target_type)
1618 : base (expr, target_type)
1620 eclass = ExprClass.Value;
1623 public override Expression DoResolve (EmitContext ec)
1625 // This should never be invoked, we are born in fully
1626 // initialized state.
1631 public override void Emit (EmitContext ec)
1635 ec.ig.Emit (OpCodes.Box, child.Type);
1639 public class UnboxCast : EmptyCast {
1640 public UnboxCast (Expression expr, Type return_type)
1641 : base (expr, return_type)
1645 public override Expression DoResolve (EmitContext ec)
1647 // This should never be invoked, we are born in fully
1648 // initialized state.
1653 public override void Emit (EmitContext ec)
1656 ILGenerator ig = ec.ig;
1659 if (t.IsGenericParameter)
1660 ig.Emit (OpCodes.Unbox_Any, t);
1662 ig.Emit (OpCodes.Unbox, t);
1664 LoadFromPtr (ig, t);
1670 /// This is used to perform explicit numeric conversions.
1672 /// Explicit numeric conversions might trigger exceptions in a checked
1673 /// context, so they should generate the conv.ovf opcodes instead of
1676 public class ConvCast : EmptyCast {
1677 public enum Mode : byte {
1678 I1_U1, I1_U2, I1_U4, I1_U8, I1_CH,
1680 I2_I1, I2_U1, I2_U2, I2_U4, I2_U8, I2_CH,
1681 U2_I1, U2_U1, U2_I2, U2_CH,
1682 I4_I1, I4_U1, I4_I2, I4_U2, I4_U4, I4_U8, I4_CH,
1683 U4_I1, U4_U1, U4_I2, U4_U2, U4_I4, U4_CH,
1684 I8_I1, I8_U1, I8_I2, I8_U2, I8_I4, I8_U4, I8_U8, I8_CH,
1685 U8_I1, U8_U1, U8_I2, U8_U2, U8_I4, U8_U4, U8_I8, U8_CH,
1686 CH_I1, CH_U1, CH_I2,
1687 R4_I1, R4_U1, R4_I2, R4_U2, R4_I4, R4_U4, R4_I8, R4_U8, R4_CH,
1688 R8_I1, R8_U1, R8_I2, R8_U2, R8_I4, R8_U4, R8_I8, R8_U8, R8_CH, R8_R4
1694 public ConvCast (EmitContext ec, Expression child, Type return_type, Mode m)
1695 : base (child, return_type)
1697 checked_state = ec.CheckState;
1701 public override Expression DoResolve (EmitContext ec)
1703 // This should never be invoked, we are born in fully
1704 // initialized state.
1709 public override string ToString ()
1711 return String.Format ("ConvCast ({0}, {1})", mode, child);
1714 public override void Emit (EmitContext ec)
1716 ILGenerator ig = ec.ig;
1722 case Mode.I1_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1723 case Mode.I1_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1724 case Mode.I1_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1725 case Mode.I1_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1726 case Mode.I1_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1728 case Mode.U1_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1729 case Mode.U1_CH: /* nothing */ break;
1731 case Mode.I2_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1732 case Mode.I2_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1733 case Mode.I2_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1734 case Mode.I2_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1735 case Mode.I2_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1736 case Mode.I2_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1738 case Mode.U2_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1739 case Mode.U2_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
1740 case Mode.U2_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
1741 case Mode.U2_CH: /* nothing */ break;
1743 case Mode.I4_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1744 case Mode.I4_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1745 case Mode.I4_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
1746 case Mode.I4_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1747 case Mode.I4_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1748 case Mode.I4_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1749 case Mode.I4_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1751 case Mode.U4_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1752 case Mode.U4_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
1753 case Mode.U4_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
1754 case Mode.U4_U2: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
1755 case Mode.U4_I4: ig.Emit (OpCodes.Conv_Ovf_I4_Un); break;
1756 case Mode.U4_CH: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
1758 case Mode.I8_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1759 case Mode.I8_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1760 case Mode.I8_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
1761 case Mode.I8_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1762 case Mode.I8_I4: ig.Emit (OpCodes.Conv_Ovf_I4); break;
1763 case Mode.I8_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1764 case Mode.I8_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1765 case Mode.I8_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1767 case Mode.U8_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1768 case Mode.U8_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
1769 case Mode.U8_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
1770 case Mode.U8_U2: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
1771 case Mode.U8_I4: ig.Emit (OpCodes.Conv_Ovf_I4_Un); break;
1772 case Mode.U8_U4: ig.Emit (OpCodes.Conv_Ovf_U4_Un); break;
1773 case Mode.U8_I8: ig.Emit (OpCodes.Conv_Ovf_I8_Un); break;
1774 case Mode.U8_CH: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
1776 case Mode.CH_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1777 case Mode.CH_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
1778 case Mode.CH_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
1780 case Mode.R4_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1781 case Mode.R4_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1782 case Mode.R4_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
1783 case Mode.R4_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1784 case Mode.R4_I4: ig.Emit (OpCodes.Conv_Ovf_I4); break;
1785 case Mode.R4_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1786 case Mode.R4_I8: ig.Emit (OpCodes.Conv_Ovf_I8); break;
1787 case Mode.R4_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1788 case Mode.R4_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1790 case Mode.R8_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1791 case Mode.R8_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1792 case Mode.R8_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
1793 case Mode.R8_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1794 case Mode.R8_I4: ig.Emit (OpCodes.Conv_Ovf_I4); break;
1795 case Mode.R8_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1796 case Mode.R8_I8: ig.Emit (OpCodes.Conv_Ovf_I8); break;
1797 case Mode.R8_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1798 case Mode.R8_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1799 case Mode.R8_R4: ig.Emit (OpCodes.Conv_R4); break;
1803 case Mode.I1_U1: ig.Emit (OpCodes.Conv_U1); break;
1804 case Mode.I1_U2: ig.Emit (OpCodes.Conv_U2); break;
1805 case Mode.I1_U4: ig.Emit (OpCodes.Conv_U4); break;
1806 case Mode.I1_U8: ig.Emit (OpCodes.Conv_I8); break;
1807 case Mode.I1_CH: ig.Emit (OpCodes.Conv_U2); break;
1809 case Mode.U1_I1: ig.Emit (OpCodes.Conv_I1); break;
1810 case Mode.U1_CH: ig.Emit (OpCodes.Conv_U2); break;
1812 case Mode.I2_I1: ig.Emit (OpCodes.Conv_I1); break;
1813 case Mode.I2_U1: ig.Emit (OpCodes.Conv_U1); break;
1814 case Mode.I2_U2: ig.Emit (OpCodes.Conv_U2); break;
1815 case Mode.I2_U4: ig.Emit (OpCodes.Conv_U4); break;
1816 case Mode.I2_U8: ig.Emit (OpCodes.Conv_I8); break;
1817 case Mode.I2_CH: ig.Emit (OpCodes.Conv_U2); break;
1819 case Mode.U2_I1: ig.Emit (OpCodes.Conv_I1); break;
1820 case Mode.U2_U1: ig.Emit (OpCodes.Conv_U1); break;
1821 case Mode.U2_I2: ig.Emit (OpCodes.Conv_I2); break;
1822 case Mode.U2_CH: /* nothing */ break;
1824 case Mode.I4_I1: ig.Emit (OpCodes.Conv_I1); break;
1825 case Mode.I4_U1: ig.Emit (OpCodes.Conv_U1); break;
1826 case Mode.I4_I2: ig.Emit (OpCodes.Conv_I2); break;
1827 case Mode.I4_U4: /* nothing */ break;
1828 case Mode.I4_U2: ig.Emit (OpCodes.Conv_U2); break;
1829 case Mode.I4_U8: ig.Emit (OpCodes.Conv_I8); break;
1830 case Mode.I4_CH: ig.Emit (OpCodes.Conv_U2); break;
1832 case Mode.U4_I1: ig.Emit (OpCodes.Conv_I1); break;
1833 case Mode.U4_U1: ig.Emit (OpCodes.Conv_U1); break;
1834 case Mode.U4_I2: ig.Emit (OpCodes.Conv_I2); break;
1835 case Mode.U4_U2: ig.Emit (OpCodes.Conv_U2); break;
1836 case Mode.U4_I4: /* nothing */ break;
1837 case Mode.U4_CH: ig.Emit (OpCodes.Conv_U2); break;
1839 case Mode.I8_I1: ig.Emit (OpCodes.Conv_I1); break;
1840 case Mode.I8_U1: ig.Emit (OpCodes.Conv_U1); break;
1841 case Mode.I8_I2: ig.Emit (OpCodes.Conv_I2); break;
1842 case Mode.I8_U2: ig.Emit (OpCodes.Conv_U2); break;
1843 case Mode.I8_I4: ig.Emit (OpCodes.Conv_I4); break;
1844 case Mode.I8_U4: ig.Emit (OpCodes.Conv_U4); break;
1845 case Mode.I8_U8: /* nothing */ break;
1846 case Mode.I8_CH: ig.Emit (OpCodes.Conv_U2); break;
1848 case Mode.U8_I1: ig.Emit (OpCodes.Conv_I1); break;
1849 case Mode.U8_U1: ig.Emit (OpCodes.Conv_U1); break;
1850 case Mode.U8_I2: ig.Emit (OpCodes.Conv_I2); break;
1851 case Mode.U8_U2: ig.Emit (OpCodes.Conv_U2); break;
1852 case Mode.U8_I4: ig.Emit (OpCodes.Conv_I4); break;
1853 case Mode.U8_U4: ig.Emit (OpCodes.Conv_U4); break;
1854 case Mode.U8_I8: /* nothing */ break;
1855 case Mode.U8_CH: ig.Emit (OpCodes.Conv_U2); break;
1857 case Mode.CH_I1: ig.Emit (OpCodes.Conv_I1); break;
1858 case Mode.CH_U1: ig.Emit (OpCodes.Conv_U1); break;
1859 case Mode.CH_I2: ig.Emit (OpCodes.Conv_I2); break;
1861 case Mode.R4_I1: ig.Emit (OpCodes.Conv_I1); break;
1862 case Mode.R4_U1: ig.Emit (OpCodes.Conv_U1); break;
1863 case Mode.R4_I2: ig.Emit (OpCodes.Conv_I2); break;
1864 case Mode.R4_U2: ig.Emit (OpCodes.Conv_U2); break;
1865 case Mode.R4_I4: ig.Emit (OpCodes.Conv_I4); break;
1866 case Mode.R4_U4: ig.Emit (OpCodes.Conv_U4); break;
1867 case Mode.R4_I8: ig.Emit (OpCodes.Conv_I8); break;
1868 case Mode.R4_U8: ig.Emit (OpCodes.Conv_U8); break;
1869 case Mode.R4_CH: ig.Emit (OpCodes.Conv_U2); break;
1871 case Mode.R8_I1: ig.Emit (OpCodes.Conv_I1); break;
1872 case Mode.R8_U1: ig.Emit (OpCodes.Conv_U1); break;
1873 case Mode.R8_I2: ig.Emit (OpCodes.Conv_I2); break;
1874 case Mode.R8_U2: ig.Emit (OpCodes.Conv_U2); break;
1875 case Mode.R8_I4: ig.Emit (OpCodes.Conv_I4); break;
1876 case Mode.R8_U4: ig.Emit (OpCodes.Conv_U4); break;
1877 case Mode.R8_I8: ig.Emit (OpCodes.Conv_I8); break;
1878 case Mode.R8_U8: ig.Emit (OpCodes.Conv_U8); break;
1879 case Mode.R8_CH: ig.Emit (OpCodes.Conv_U2); break;
1880 case Mode.R8_R4: ig.Emit (OpCodes.Conv_R4); break;
1886 public class OpcodeCast : EmptyCast {
1890 public OpcodeCast (Expression child, Type return_type, OpCode op)
1891 : base (child, return_type)
1895 second_valid = false;
1898 public OpcodeCast (Expression child, Type return_type, OpCode op, OpCode op2)
1899 : base (child, return_type)
1904 second_valid = true;
1907 public override Expression DoResolve (EmitContext ec)
1909 // This should never be invoked, we are born in fully
1910 // initialized state.
1915 public override void Emit (EmitContext ec)
1926 /// This kind of cast is used to encapsulate a child and cast it
1927 /// to the class requested
1929 public class ClassCast : EmptyCast {
1930 public ClassCast (Expression child, Type return_type)
1931 : base (child, return_type)
1936 public override Expression DoResolve (EmitContext ec)
1938 // This should never be invoked, we are born in fully
1939 // initialized state.
1944 public override void Emit (EmitContext ec)
1948 if (child.Type.IsGenericParameter)
1949 ec.ig.Emit (OpCodes.Box, child.Type);
1951 if (type.IsGenericParameter)
1952 ec.ig.Emit (OpCodes.Unbox_Any, type);
1954 ec.ig.Emit (OpCodes.Castclass, type);
1959 /// SimpleName expressions are initially formed of a single
1960 /// word and it only happens at the beginning of the expression.
1964 /// The expression will try to be bound to a Field, a Method
1965 /// group or a Property. If those fail we pass the name to our
1966 /// caller and the SimpleName is compounded to perform a type
1967 /// lookup. The idea behind this process is that we want to avoid
1968 /// creating a namespace map from the assemblies, as that requires
1969 /// the GetExportedTypes function to be called and a hashtable to
1970 /// be constructed which reduces startup time. If later we find
1971 /// that this is slower, we should create a `NamespaceExpr' expression
1972 /// that fully participates in the resolution process.
1974 /// For example `System.Console.WriteLine' is decomposed into
1975 /// MemberAccess (MemberAccess (SimpleName ("System"), "Console"), "WriteLine")
1977 /// The first SimpleName wont produce a match on its own, so it will
1979 /// MemberAccess (SimpleName ("System.Console"), "WriteLine").
1981 /// System.Console will produce a TypeExpr match.
1983 /// The downside of this is that we might be hitting `LookupType' too many
1984 /// times with this scheme.
1986 public class SimpleName : Expression {
1988 public readonly TypeArguments Arguments;
1991 // If true, then we are a simple name, not composed with a ".
1995 public SimpleName (string a, string b, Location l)
1997 Name = String.Concat (a, ".", b);
2002 public SimpleName (string name, Location l)
2009 public SimpleName (string name, TypeArguments args, Location l)
2017 public static void Error_ObjectRefRequired (EmitContext ec, Location l, string name)
2019 if (ec.IsFieldInitializer)
2022 "A field initializer cannot reference the non-static field, " +
2023 "method or property `"+name+"'");
2027 "An object reference is required " +
2028 "for the non-static field `"+name+"'");
2032 // Checks whether we are trying to access an instance
2033 // property, method or field from a static body.
2035 Expression MemberStaticCheck (EmitContext ec, Expression e)
2037 if (e is IMemberExpr){
2038 IMemberExpr member = (IMemberExpr) e;
2040 if (!member.IsStatic){
2041 Error_ObjectRefRequired (ec, loc, Name);
2049 public override Expression DoResolve (EmitContext ec)
2051 return SimpleNameResolve (ec, null, false, false);
2054 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
2056 return SimpleNameResolve (ec, right_side, false, false);
2060 public Expression DoResolveAllowStatic (EmitContext ec, bool intermediate)
2062 return SimpleNameResolve (ec, null, true, intermediate);
2065 public override Expression ResolveAsTypeStep (EmitContext ec)
2067 DeclSpace ds = ec.DeclSpace;
2068 NamespaceEntry ns = ds.NamespaceEntry;
2073 // Since we are cheating: we only do the Alias lookup for
2074 // namespaces if the name does not include any dots in it
2076 if (ns != null && is_base)
2077 alias_value = ns.LookupAlias (Name);
2081 TypeParameterExpr generic_type = ds.LookupGeneric (Name, loc);
2082 if (generic_type != null)
2083 return generic_type.ResolveAsTypeTerminal (ec);
2085 if (ec.ResolvingTypeTree){
2086 int errors = Report.Errors;
2087 Type dt = ds.FindType (loc, Name);
2089 if (Report.Errors != errors)
2093 return new TypeExpression (dt, loc);
2095 if (alias_value != null){
2096 if (alias_value.IsType)
2097 return alias_value.ResolveAsType (ec);
2098 if ((t = RootContext.LookupType (ds, alias_value.Name, true, loc)) != null)
2099 return new TypeExpression (t, loc);
2103 if ((t = RootContext.LookupType (ds, Name, true, loc)) != null)
2104 return new TypeExpression (t, loc);
2106 if (alias_value != null) {
2107 if (alias_value.IsType)
2108 return alias_value.ResolveAsType (ec);
2109 if ((t = RootContext.LookupType (ds, alias_value.Name, true, loc)) != null)
2110 return new TypeExpression (t, loc);
2112 // we have alias value, but it isn't Type, so try if it's namespace
2113 return new SimpleName (alias_value.Name, loc);
2116 // No match, maybe our parent can compose us
2117 // into something meaningful.
2121 Expression SimpleNameResolve (EmitContext ec, Expression right_side,
2122 bool allow_static, bool intermediate)
2124 Expression e = DoSimpleNameResolve (ec, right_side, allow_static, intermediate);
2128 Block current_block = ec.CurrentBlock;
2129 if (current_block != null){
2130 //LocalInfo vi = current_block.GetLocalInfo (Name);
2132 current_block.IsVariableNameUsedInChildBlock(Name)) {
2133 Report.Error (135, Location,
2134 "'{0}' has a different meaning in a " +
2135 "child block", Name);
2140 if (e.Type != null && e.Type.IsPointer && !ec.InUnsafe) {
2149 /// 7.5.2: Simple Names.
2151 /// Local Variables and Parameters are handled at
2152 /// parse time, so they never occur as SimpleNames.
2154 /// The `allow_static' flag is used by MemberAccess only
2155 /// and it is used to inform us that it is ok for us to
2156 /// avoid the static check, because MemberAccess might end
2157 /// up resolving the Name as a Type name and the access as
2158 /// a static type access.
2160 /// ie: Type Type; .... { Type.GetType (""); }
2162 /// Type is both an instance variable and a Type; Type.GetType
2163 /// is the static method not an instance method of type.
2165 Expression DoSimpleNameResolve (EmitContext ec, Expression right_side, bool allow_static, bool intermediate)
2167 Expression e = null;
2170 // Stage 1: Performed by the parser (binding to locals or parameters).
2172 Block current_block = ec.CurrentBlock;
2173 if (current_block != null){
2174 LocalInfo vi = current_block.GetLocalInfo (Name);
2178 var = new LocalVariableReference (ec.CurrentBlock, Name, loc);
2180 if (right_side != null)
2181 return var.ResolveLValue (ec, right_side);
2183 return var.Resolve (ec);
2186 ParameterReference pref = current_block.GetParameterReference (Name, loc);
2188 if (right_side != null)
2189 return pref.ResolveLValue (ec, right_side);
2191 return pref.Resolve (ec);
2196 // Stage 2: Lookup members
2199 DeclSpace lookup_ds = ec.DeclSpace;
2201 if (lookup_ds.TypeBuilder == null)
2204 e = MemberLookup (ec, lookup_ds.TypeBuilder, Name, loc);
2208 lookup_ds =lookup_ds.Parent;
2209 } while (lookup_ds != null);
2211 if (e == null && ec.ContainerType != null)
2212 e = MemberLookup (ec, ec.ContainerType, Name, loc);
2216 // Since we are cheating (is_base is our hint
2217 // that we are the beginning of the name): we
2218 // only do the Alias lookup for namespaces if
2219 // the name does not include any dots in it
2221 NamespaceEntry ns = ec.DeclSpace.NamespaceEntry;
2222 if (is_base && ns != null){
2223 IAlias alias_value = ns.LookupAlias (Name);
2224 if (alias_value != null){
2225 if (alias_value.IsType)
2226 return alias_value.ResolveAsType (ec);
2228 Name = alias_value.Name;
2231 if ((t = TypeManager.LookupType (Name)) != null)
2232 return new TypeExpression (t, loc);
2234 // No match, maybe our parent can compose us
2235 // into something meaningful.
2240 return ResolveAsTypeStep (ec);
2246 if (e is IMemberExpr) {
2247 e = MemberAccess.ResolveMemberAccess (ec, e, null, loc, this);
2251 IMemberExpr me = e as IMemberExpr;
2255 if (Arguments != null) {
2256 MethodGroupExpr mg = me as MethodGroupExpr;
2260 return mg.ResolveGeneric (ec, Arguments);
2263 // This fails if ResolveMemberAccess() was unable to decide whether
2264 // it's a field or a type of the same name.
2266 if (!me.IsStatic && (me.InstanceExpression == null))
2270 TypeManager.IsNestedFamilyAccessible (me.InstanceExpression.Type, me.DeclaringType) &&
2271 me.InstanceExpression.Type != me.DeclaringType &&
2272 !TypeManager.IsFamilyAccessible (me.InstanceExpression.Type, me.DeclaringType) &&
2273 (!intermediate || !MemberAccess.IdenticalNameAndTypeName (ec, this, e, loc))) {
2274 Error (38, "Cannot access nonstatic member `" + me.Name + "' of " +
2275 "outer type `" + me.DeclaringType + "' via nested type `" +
2276 me.InstanceExpression.Type + "'");
2280 return (right_side != null)
2281 ? e.DoResolveLValue (ec, right_side)
2285 if (ec.IsStatic || ec.IsFieldInitializer){
2289 return MemberStaticCheck (ec, e);
2294 public override void Emit (EmitContext ec)
2297 // If this is ever reached, then we failed to
2298 // find the name as a namespace
2301 Error (103, "The name `" + Name +
2302 "' does not exist in the class `" +
2303 ec.DeclSpace.Name + "'");
2306 public override string ToString ()
2313 /// Fully resolved expression that evaluates to a type
2315 public abstract class TypeExpr : Expression, IAlias {
2316 override public Expression ResolveAsTypeStep (EmitContext ec)
2318 TypeExpr t = DoResolveAsTypeStep (ec);
2322 eclass = ExprClass.Type;
2326 override public Expression DoResolve (EmitContext ec)
2328 return ResolveAsTypeTerminal (ec);
2331 override public void Emit (EmitContext ec)
2333 throw new Exception ("Should never be called");
2336 public virtual bool CheckAccessLevel (DeclSpace ds)
2338 return ds.CheckAccessLevel (Type);
2341 public virtual bool AsAccessible (DeclSpace ds, int flags)
2343 return ds.AsAccessible (Type, flags);
2346 public virtual bool IsClass {
2347 get { return Type.IsClass; }
2350 public virtual bool IsValueType {
2351 get { return Type.IsValueType; }
2354 public virtual bool IsInterface {
2355 get { return Type.IsInterface; }
2358 public virtual bool IsSealed {
2359 get { return Type.IsSealed; }
2362 public virtual bool CanInheritFrom ()
2364 if (Type == TypeManager.enum_type ||
2365 (Type == TypeManager.value_type && RootContext.StdLib) ||
2366 Type == TypeManager.multicast_delegate_type ||
2367 Type == TypeManager.delegate_type ||
2368 Type == TypeManager.array_type)
2374 public virtual bool IsAttribute {
2376 return Type == TypeManager.attribute_type ||
2377 Type.IsSubclassOf (TypeManager.attribute_type);
2381 protected abstract TypeExpr DoResolveAsTypeStep (EmitContext ec);
2383 public abstract string Name {
2387 public override bool Equals (object obj)
2389 TypeExpr tobj = obj as TypeExpr;
2393 return Type == tobj.Type;
2396 public override int GetHashCode ()
2398 return Type.GetHashCode ();
2401 public override string ToString ()
2406 bool IAlias.IsType {
2407 get { return true; }
2410 TypeExpr IAlias.ResolveAsType (EmitContext ec)
2412 return ResolveAsTypeTerminal (ec);
2416 public class TypeExpression : TypeExpr, IAlias {
2417 public TypeExpression (Type t, Location l)
2420 eclass = ExprClass.Type;
2424 protected override TypeExpr DoResolveAsTypeStep (EmitContext ec)
2429 public override string Name {
2431 return Type.ToString ();
2435 string IAlias.Name {
2437 return Type.FullName != null ? Type.FullName : Type.Name;
2443 /// Used to create types from a fully qualified name. These are just used
2444 /// by the parser to setup the core types. A TypeLookupExpression is always
2445 /// classified as a type.
2447 public class TypeLookupExpression : TypeExpr {
2450 public TypeLookupExpression (string name)
2455 protected override TypeExpr DoResolveAsTypeStep (EmitContext ec)
2458 type = RootContext.LookupType (
2459 ec.DeclSpace, name, false, Location.Null);
2467 public override string Name {
2475 /// Represents an "unbound generic type", ie. typeof (Foo<>).
2478 public class UnboundTypeExpression : TypeLookupExpression {
2479 public UnboundTypeExpression (string name)
2484 public class TypeAliasExpression : TypeExpr, IAlias {
2490 public TypeAliasExpression (IAlias alias, TypeArguments args, Location l)
2496 eclass = ExprClass.Type;
2498 name = alias.Name + "<" + args.ToString () + ">";
2503 public override string Name {
2504 get { return name; }
2507 protected override TypeExpr DoResolveAsTypeStep (EmitContext ec)
2509 texpr = alias.ResolveAsType (ec);
2513 Type type = texpr.Type;
2514 int num_args = TypeManager.GetNumberOfTypeArguments (type);
2517 if (num_args == 0) {
2518 Report.Error (308, loc,
2519 "The non-generic type `{0}' cannot " +
2520 "be used with type arguments.",
2521 TypeManager.CSharpName (type));
2525 ConstructedType ctype = new ConstructedType (type, args, loc);
2526 return ctype.ResolveAsTypeTerminal (ec);
2527 } else if (num_args > 0) {
2528 Report.Error (305, loc,
2529 "Using the generic type `{0}' " +
2530 "requires {1} type arguments",
2531 TypeManager.GetFullName (type), num_args);
2535 return new TypeExpression (type, loc);
2538 public override bool CheckAccessLevel (DeclSpace ds)
2540 return texpr.CheckAccessLevel (ds);
2543 public override bool AsAccessible (DeclSpace ds, int flags)
2545 return texpr.AsAccessible (ds, flags);
2548 public override bool IsClass {
2549 get { return texpr.IsClass; }
2552 public override bool IsValueType {
2553 get { return texpr.IsValueType; }
2556 public override bool IsInterface {
2557 get { return texpr.IsInterface; }
2560 public override bool IsSealed {
2561 get { return texpr.IsSealed; }
2564 public override bool IsAttribute {
2565 get { return texpr.IsAttribute; }
2570 /// MethodGroup Expression.
2572 /// This is a fully resolved expression that evaluates to a type
2574 public class MethodGroupExpr : Expression, IMemberExpr {
2575 public MethodBase [] Methods;
2576 Expression instance_expression = null;
2577 bool is_explicit_impl = false;
2578 bool has_type_arguments = false;
2579 bool identical_type_name = false;
2582 public MethodGroupExpr (MemberInfo [] mi, Location l)
2584 Methods = new MethodBase [mi.Length];
2585 mi.CopyTo (Methods, 0);
2586 eclass = ExprClass.MethodGroup;
2587 type = TypeManager.object_type;
2591 public MethodGroupExpr (ArrayList list, Location l)
2593 Methods = new MethodBase [list.Count];
2596 list.CopyTo (Methods, 0);
2598 foreach (MemberInfo m in list){
2599 if (!(m is MethodBase)){
2600 Console.WriteLine ("Name " + m.Name);
2601 Console.WriteLine ("Found a: " + m.GetType ().FullName);
2608 eclass = ExprClass.MethodGroup;
2609 type = TypeManager.object_type;
2612 public Type DeclaringType {
2615 // We assume that the top-level type is in the end
2617 return Methods [Methods.Length - 1].DeclaringType;
2618 //return Methods [0].DeclaringType;
2623 // `A method group may have associated an instance expression'
2625 public Expression InstanceExpression {
2627 return instance_expression;
2631 instance_expression = value;
2635 public bool IsExplicitImpl {
2637 return is_explicit_impl;
2641 is_explicit_impl = value;
2645 public bool HasTypeArguments {
2647 return has_type_arguments;
2651 has_type_arguments = value;
2655 public bool IdenticalTypeName {
2657 return identical_type_name;
2661 identical_type_name = value;
2665 public bool IsBase {
2674 public string Name {
2676 //return Methods [0].Name;
2677 return Methods [Methods.Length - 1].Name;
2681 public bool IsInstance {
2683 foreach (MethodBase mb in Methods)
2691 public bool IsStatic {
2693 foreach (MethodBase mb in Methods)
2701 override public Expression DoResolve (EmitContext ec)
2704 instance_expression = null;
2706 if (instance_expression != null) {
2707 instance_expression = instance_expression.DoResolve (ec);
2708 if (instance_expression == null)
2715 public void ReportUsageError ()
2717 Report.Error (654, loc, "Method `" + DeclaringType + "." +
2718 Name + "()' is referenced without parentheses");
2721 override public void Emit (EmitContext ec)
2723 ReportUsageError ();
2726 bool RemoveMethods (bool keep_static)
2728 ArrayList smethods = new ArrayList ();
2730 foreach (MethodBase mb in Methods){
2731 if (mb.IsStatic == keep_static)
2735 if (smethods.Count == 0)
2738 Methods = new MethodBase [smethods.Count];
2739 smethods.CopyTo (Methods, 0);
2745 /// Removes any instance methods from the MethodGroup, returns
2746 /// false if the resulting set is empty.
2748 public bool RemoveInstanceMethods ()
2750 return RemoveMethods (true);
2754 /// Removes any static methods from the MethodGroup, returns
2755 /// false if the resulting set is empty.
2757 public bool RemoveStaticMethods ()
2759 return RemoveMethods (false);
2762 public Expression ResolveGeneric (EmitContext ec, TypeArguments args)
2764 if (args.Resolve (ec) == false)
2767 Type[] atypes = args.Arguments;
2769 int first_count = 0;
2770 MethodInfo first = null;
2772 ArrayList list = new ArrayList ();
2773 foreach (MethodBase mb in Methods) {
2774 MethodInfo mi = mb as MethodInfo;
2775 if ((mi == null) || !mi.HasGenericParameters)
2778 Type[] gen_params = mi.GetGenericArguments ();
2780 if (first == null) {
2782 first_count = gen_params.Length;
2785 if (gen_params.Length != atypes.Length)
2788 list.Add (mi.BindGenericParameters (atypes));
2791 if (list.Count > 0) {
2792 MethodGroupExpr new_mg = new MethodGroupExpr (list, Location);
2793 new_mg.InstanceExpression = InstanceExpression;
2794 new_mg.HasTypeArguments = true;
2800 305, loc, "Using the generic method `{0}' " +
2801 "requires {1} type arguments", Name,
2805 308, loc, "The non-generic method `{0}' " +
2806 "cannot be used with type arguments", Name);
2813 /// Fully resolved expression that evaluates to a Field
2815 public class FieldExpr : Expression, IAssignMethod, IMemoryLocation, IMemberExpr, IVariable {
2816 public readonly FieldInfo FieldInfo;
2817 Expression instance_expr;
2818 VariableInfo variable_info;
2820 LocalTemporary temp;
2822 bool is_field_initializer;
2824 public FieldExpr (FieldInfo fi, Location l)
2827 eclass = ExprClass.Variable;
2828 type = TypeManager.TypeToCoreType (fi.FieldType);
2832 public string Name {
2834 return FieldInfo.Name;
2838 public bool IsInstance {
2840 return !FieldInfo.IsStatic;
2844 public bool IsStatic {
2846 return FieldInfo.IsStatic;
2850 public Type DeclaringType {
2852 return FieldInfo.DeclaringType;
2856 public Expression InstanceExpression {
2858 return instance_expr;
2862 instance_expr = value;
2866 public bool IsFieldInitializer {
2868 return is_field_initializer;
2872 is_field_initializer = value;
2876 public VariableInfo VariableInfo {
2878 return variable_info;
2882 override public Expression DoResolve (EmitContext ec)
2884 if (!FieldInfo.IsStatic){
2885 if (instance_expr == null){
2887 // This can happen when referencing an instance field using
2888 // a fully qualified type expression: TypeName.InstanceField = xxx
2890 SimpleName.Error_ObjectRefRequired (ec, loc, FieldInfo.Name);
2894 // Resolve the field's instance expression while flow analysis is turned
2895 // off: when accessing a field "a.b", we must check whether the field
2896 // "a.b" is initialized, not whether the whole struct "a" is initialized.
2897 instance_expr = instance_expr.Resolve (ec, ResolveFlags.VariableOrValue |
2898 ResolveFlags.DisableFlowAnalysis);
2899 if (instance_expr == null)
2903 ObsoleteAttribute oa;
2904 FieldBase f = TypeManager.GetField (FieldInfo);
2906 oa = f.GetObsoleteAttribute (f.Parent);
2908 AttributeTester.Report_ObsoleteMessage (oa, f.GetSignatureForError (), loc);
2909 // To be sure that type is external because we do not register generated fields
2910 } else if (!(FieldInfo.DeclaringType is TypeBuilder)) {
2911 oa = AttributeTester.GetMemberObsoleteAttribute (FieldInfo);
2913 AttributeTester.Report_ObsoleteMessage (oa, TypeManager.GetFullNameSignature (FieldInfo), loc);
2916 if (ec.CurrentAnonymousMethod != null){
2917 if (!FieldInfo.IsStatic){
2918 if (ec.TypeContainer is Struct){
2919 Report.Error (1673, loc, "Can not reference instance variables in anonymous methods hosted in structs");
2922 ec.CaptureField (this);
2926 // If the instance expression is a local variable or parameter.
2927 IVariable var = instance_expr as IVariable;
2928 if ((var == null) || (var.VariableInfo == null))
2931 VariableInfo vi = var.VariableInfo;
2932 if (!vi.IsFieldAssigned (ec, FieldInfo.Name, loc))
2935 variable_info = vi.GetSubStruct (FieldInfo.Name);
2939 void Report_AssignToReadonly (bool is_instance)
2944 msg = "Readonly field can not be assigned outside " +
2945 "of constructor or variable initializer";
2947 msg = "A static readonly field can only be assigned in " +
2948 "a static constructor";
2950 Report.Error (is_instance ? 191 : 198, loc, msg);
2953 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
2955 IVariable var = instance_expr as IVariable;
2956 if ((var != null) && (var.VariableInfo != null))
2957 var.VariableInfo.SetFieldAssigned (ec, FieldInfo.Name);
2959 Expression e = DoResolve (ec);
2964 if (!FieldInfo.IsStatic && (instance_expr.Type.IsValueType && !(instance_expr is IMemoryLocation))) {
2965 // FIXME: Provide better error reporting.
2966 Error (1612, "Cannot modify expression because it is not a variable.");
2970 if (!FieldInfo.IsInitOnly)
2973 FieldBase fb = TypeManager.GetField (FieldInfo);
2978 // InitOnly fields can only be assigned in constructors
2981 if (ec.IsConstructor){
2982 if (IsStatic && !ec.IsStatic)
2983 Report_AssignToReadonly (false);
2986 if (!is_field_initializer &&
2987 (ec.TypeContainer.CurrentType != null))
2988 ctype = ec.TypeContainer.CurrentType;
2990 ctype = ec.ContainerType;
2992 if (TypeManager.IsEqual (ctype, FieldInfo.DeclaringType))
2996 Report_AssignToReadonly (!IsStatic);
3001 public override void CheckMarshallByRefAccess (Type container)
3003 if (!IsStatic && Type.IsValueType && !container.IsSubclassOf (TypeManager.mbr_type) && DeclaringType.IsSubclassOf (TypeManager.mbr_type)) {
3004 Report.SymbolRelatedToPreviousError (DeclaringType);
3005 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);
3009 public bool VerifyFixed (bool is_expression)
3011 IVariable variable = instance_expr as IVariable;
3012 if ((variable == null) || !variable.VerifyFixed (true))
3018 public void Emit (EmitContext ec, bool leave_copy)
3020 ILGenerator ig = ec.ig;
3021 bool is_volatile = false;
3023 if (FieldInfo is FieldBuilder){
3024 FieldBase f = TypeManager.GetField (FieldInfo);
3026 if ((f.ModFlags & Modifiers.VOLATILE) != 0)
3029 f.status |= Field.Status.USED;
3033 if (FieldInfo.IsStatic){
3035 ig.Emit (OpCodes.Volatile);
3037 ig.Emit (OpCodes.Ldsfld, FieldInfo);
3043 ig.Emit (OpCodes.Volatile);
3045 ig.Emit (OpCodes.Ldfld, FieldInfo);
3049 ec.ig.Emit (OpCodes.Dup);
3050 if (!FieldInfo.IsStatic) {
3051 temp = new LocalTemporary (ec, this.Type);
3057 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
3059 FieldAttributes fa = FieldInfo.Attributes;
3060 bool is_static = (fa & FieldAttributes.Static) != 0;
3061 bool is_readonly = (fa & FieldAttributes.InitOnly) != 0;
3062 ILGenerator ig = ec.ig;
3063 prepared = prepare_for_load;
3065 if (is_readonly && !ec.IsConstructor){
3066 Report_AssignToReadonly (!is_static);
3072 if (prepare_for_load)
3073 ig.Emit (OpCodes.Dup);
3078 ec.ig.Emit (OpCodes.Dup);
3079 if (!FieldInfo.IsStatic) {
3080 temp = new LocalTemporary (ec, this.Type);
3085 if (FieldInfo is FieldBuilder){
3086 FieldBase f = TypeManager.GetField (FieldInfo);
3088 if ((f.ModFlags & Modifiers.VOLATILE) != 0)
3089 ig.Emit (OpCodes.Volatile);
3091 f.status |= Field.Status.ASSIGNED;
3096 ig.Emit (OpCodes.Stsfld, FieldInfo);
3098 ig.Emit (OpCodes.Stfld, FieldInfo);
3104 void EmitInstance (EmitContext ec)
3106 if (instance_expr.Type.IsValueType) {
3107 if (instance_expr is IMemoryLocation) {
3108 ((IMemoryLocation) instance_expr).AddressOf (ec, AddressOp.LoadStore);
3110 LocalTemporary t = new LocalTemporary (ec, instance_expr.Type);
3111 instance_expr.Emit (ec);
3113 t.AddressOf (ec, AddressOp.Store);
3116 instance_expr.Emit (ec);
3119 public override void Emit (EmitContext ec)
3124 public void AddressOf (EmitContext ec, AddressOp mode)
3126 ILGenerator ig = ec.ig;
3128 if (FieldInfo is FieldBuilder){
3129 FieldBase f = TypeManager.GetField (FieldInfo);
3131 if ((f.ModFlags & Modifiers.VOLATILE) != 0){
3132 Error (676, "volatile variable: can not take its address, or pass as ref/out parameter");
3136 if ((mode & AddressOp.Store) != 0)
3137 f.status |= Field.Status.ASSIGNED;
3138 if ((mode & AddressOp.Load) != 0)
3139 f.status |= Field.Status.USED;
3144 // Handle initonly fields specially: make a copy and then
3145 // get the address of the copy.
3148 if (FieldInfo.IsInitOnly){
3150 if (ec.IsConstructor){
3151 if (FieldInfo.IsStatic){
3163 local = ig.DeclareLocal (type);
3164 ig.Emit (OpCodes.Stloc, local);
3165 ig.Emit (OpCodes.Ldloca, local);
3170 if (FieldInfo.IsStatic){
3171 ig.Emit (OpCodes.Ldsflda, FieldInfo);
3174 ig.Emit (OpCodes.Ldflda, FieldInfo);
3180 // A FieldExpr whose address can not be taken
3182 public class FieldExprNoAddress : FieldExpr, IMemoryLocation {
3183 public FieldExprNoAddress (FieldInfo fi, Location loc) : base (fi, loc)
3187 public new void AddressOf (EmitContext ec, AddressOp mode)
3189 Report.Error (-215, "Report this: Taking the address of a remapped parameter not supported");
3194 /// Expression that evaluates to a Property. The Assign class
3195 /// might set the `Value' expression if we are in an assignment.
3197 /// This is not an LValue because we need to re-write the expression, we
3198 /// can not take data from the stack and store it.
3200 public class PropertyExpr : ExpressionStatement, IAssignMethod, IMemberExpr {
3201 public readonly PropertyInfo PropertyInfo;
3204 // This is set externally by the `BaseAccess' class
3207 MethodInfo getter, setter;
3209 bool must_do_cs1540_check;
3211 Expression instance_expr;
3212 LocalTemporary temp;
3215 public PropertyExpr (EmitContext ec, PropertyInfo pi, Location l)
3218 eclass = ExprClass.PropertyAccess;
3222 type = TypeManager.TypeToCoreType (pi.PropertyType);
3224 ResolveAccessors (ec);
3227 public string Name {
3229 return PropertyInfo.Name;
3233 public bool IsInstance {
3239 public bool IsStatic {
3245 public Type DeclaringType {
3247 return PropertyInfo.DeclaringType;
3252 // The instance expression associated with this expression
3254 public Expression InstanceExpression {
3256 instance_expr = value;
3260 return instance_expr;
3264 public bool VerifyAssignable ()
3266 if (setter == null) {
3267 Report.Error (200, loc,
3268 "The property `" + PropertyInfo.Name +
3269 "' can not be assigned to, as it has not set accessor");
3276 void FindAccessors (Type invocation_type)
3278 BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic |
3279 BindingFlags.Static | BindingFlags.Instance |
3280 BindingFlags.DeclaredOnly;
3282 Type current = PropertyInfo.DeclaringType;
3283 for (; current != null; current = current.BaseType) {
3284 MemberInfo[] group = TypeManager.MemberLookup (
3285 invocation_type, invocation_type, current,
3286 MemberTypes.Property, flags, PropertyInfo.Name, null);
3291 if (group.Length != 1)
3292 // Oooops, can this ever happen ?
3295 PropertyInfo pi = (PropertyInfo) group [0];
3298 getter = pi.GetGetMethod (true);;
3301 setter = pi.GetSetMethod (true);;
3303 MethodInfo accessor = getter != null ? getter : setter;
3305 if (!accessor.IsVirtual)
3310 bool IsAccessorAccessible (Type invocation_type, MethodInfo mi)
3312 MethodAttributes ma = mi.Attributes & MethodAttributes.MemberAccessMask;
3315 // If only accessible to the current class or children
3317 if (ma == MethodAttributes.Private) {
3318 Type declaring_type = mi.DeclaringType;
3320 if (invocation_type != declaring_type)
3321 return TypeManager.IsNestedFamilyAccessible (invocation_type, declaring_type);
3326 // FamAndAssem requires that we not only derivate, but we are on the
3329 if (ma == MethodAttributes.FamANDAssem){
3330 return (mi.DeclaringType.Assembly != invocation_type.Assembly);
3333 // Assembly and FamORAssem succeed if we're in the same assembly.
3334 if ((ma == MethodAttributes.Assembly) || (ma == MethodAttributes.FamORAssem)){
3335 if (mi.DeclaringType.Assembly == invocation_type.Assembly)
3339 // We already know that we aren't in the same assembly.
3340 if (ma == MethodAttributes.Assembly)
3343 // Family and FamANDAssem require that we derive.
3344 if ((ma == MethodAttributes.Family) || (ma == MethodAttributes.FamANDAssem) || (ma == MethodAttributes.FamORAssem)){
3345 if (!TypeManager.IsNestedFamilyAccessible (invocation_type, mi.DeclaringType))
3348 if (!TypeManager.IsNestedChildOf (invocation_type, mi.DeclaringType))
3349 must_do_cs1540_check = true;
3359 // We also perform the permission checking here, as the PropertyInfo does not
3360 // hold the information for the accessibility of its setter/getter
3362 void ResolveAccessors (EmitContext ec)
3364 FindAccessors (ec.ContainerType);
3366 is_static = getter != null ? getter.IsStatic : setter.IsStatic;
3369 bool InstanceResolve (EmitContext ec)
3371 if ((instance_expr == null) && ec.IsStatic && !is_static) {
3372 SimpleName.Error_ObjectRefRequired (ec, loc, PropertyInfo.Name);
3376 if (instance_expr != null) {
3377 instance_expr = instance_expr.DoResolve (ec);
3378 if (instance_expr == null)
3381 instance_expr.CheckMarshallByRefAccess (ec.ContainerType);
3384 if (must_do_cs1540_check && (instance_expr != null)) {
3385 if ((instance_expr.Type != ec.ContainerType) &&
3386 ec.ContainerType.IsSubclassOf (instance_expr.Type)) {
3387 Report.Error (1540, loc, "Cannot access protected member `" +
3388 PropertyInfo.DeclaringType + "." + PropertyInfo.Name +
3389 "' via a qualifier of type `" +
3390 TypeManager.CSharpName (instance_expr.Type) +
3391 "'; the qualifier must be of type `" +
3392 TypeManager.CSharpName (ec.ContainerType) +
3393 "' (or derived from it)");
3401 override public Expression DoResolve (EmitContext ec)
3403 if (getter != null){
3404 if (TypeManager.GetArgumentTypes (getter).Length != 0){
3406 117, loc, "`{0}' does not contain a " +
3407 "definition for `{1}'.", getter.DeclaringType,
3413 if (getter == null){
3415 // The following condition happens if the PropertyExpr was
3416 // created, but is invalid (ie, the property is inaccessible),
3417 // and we did not want to embed the knowledge about this in
3418 // the caller routine. This only avoids double error reporting.
3423 Report.Error (154, loc,
3424 "The property `" + PropertyInfo.Name +
3425 "' can not be used in " +
3426 "this context because it lacks a get accessor");
3430 if (!IsAccessorAccessible (ec.ContainerType, getter)) {
3431 Report.Error (122, loc, "'{0}.get' is inaccessible due to its protection level", PropertyInfo.Name);
3435 if (!InstanceResolve (ec))
3439 // Only base will allow this invocation to happen.
3441 if (IsBase && getter.IsAbstract){
3442 Report.Error (205, loc, "Cannot call an abstract base property: " +
3443 PropertyInfo.DeclaringType + "." +PropertyInfo.Name);
3450 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
3452 if (setter == null){
3454 // The following condition happens if the PropertyExpr was
3455 // created, but is invalid (ie, the property is inaccessible),
3456 // and we did not want to embed the knowledge about this in
3457 // the caller routine. This only avoids double error reporting.
3462 Report.Error (154, loc,
3463 "The property `" + PropertyInfo.Name +
3464 "' can not be used in " +
3465 "this context because it lacks a set accessor");
3469 if (TypeManager.GetArgumentTypes (setter).Length != 1){
3471 117, loc, "`{0}' does not contain a " +
3472 "definition for `{1}'.", getter.DeclaringType,
3477 if (!IsAccessorAccessible (ec.ContainerType, setter)) {
3478 Report.Error (122, loc, "'{0}.set' is inaccessible due to its protection level", PropertyInfo.Name);
3482 if (!InstanceResolve (ec))
3486 // Only base will allow this invocation to happen.
3488 if (IsBase && setter.IsAbstract){
3489 Report.Error (205, loc, "Cannot call an abstract base property: " +
3490 PropertyInfo.DeclaringType + "." +PropertyInfo.Name);
3495 // Check that we are not making changes to a temporary memory location
3497 if (instance_expr != null && instance_expr.Type.IsValueType && !(instance_expr is IMemoryLocation)) {
3498 // FIXME: Provide better error reporting.
3499 Error (1612, "Cannot modify expression because it is not a variable.");
3508 public override void Emit (EmitContext ec)
3513 void EmitInstance (EmitContext ec)
3518 if (instance_expr.Type.IsValueType) {
3519 if (instance_expr is IMemoryLocation) {
3520 ((IMemoryLocation) instance_expr).AddressOf (ec, AddressOp.LoadStore);
3522 LocalTemporary t = new LocalTemporary (ec, instance_expr.Type);
3523 instance_expr.Emit (ec);
3525 t.AddressOf (ec, AddressOp.Store);
3528 instance_expr.Emit (ec);
3531 ec.ig.Emit (OpCodes.Dup);
3535 public void Emit (EmitContext ec, bool leave_copy)
3541 // Special case: length of single dimension array property is turned into ldlen
3543 if ((getter == TypeManager.system_int_array_get_length) ||
3544 (getter == TypeManager.int_array_get_length)){
3545 Type iet = instance_expr.Type;
3548 // System.Array.Length can be called, but the Type does not
3549 // support invoking GetArrayRank, so test for that case first
3551 if (iet != TypeManager.array_type && (iet.GetArrayRank () == 1)) {
3552 ec.ig.Emit (OpCodes.Ldlen);
3553 ec.ig.Emit (OpCodes.Conv_I4);
3558 Invocation.EmitCall (ec, IsBase, IsStatic, new EmptyAddressOf (), getter, null, loc);
3563 ec.ig.Emit (OpCodes.Dup);
3565 temp = new LocalTemporary (ec, this.Type);
3571 // Implements the IAssignMethod interface for assignments
3573 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
3575 prepared = prepare_for_load;
3581 ec.ig.Emit (OpCodes.Dup);
3583 temp = new LocalTemporary (ec, this.Type);
3588 ArrayList args = new ArrayList (1);
3589 args.Add (new Argument (new EmptyAddressOf (), Argument.AType.Expression));
3591 Invocation.EmitCall (ec, IsBase, IsStatic, new EmptyAddressOf (), setter, args, loc);
3597 override public void EmitStatement (EmitContext ec)
3600 ec.ig.Emit (OpCodes.Pop);
3605 /// Fully resolved expression that evaluates to an Event
3607 public class EventExpr : Expression, IMemberExpr {
3608 public readonly EventInfo EventInfo;
3609 Expression instance_expr;
3612 MethodInfo add_accessor, remove_accessor;
3614 public EventExpr (EventInfo ei, Location loc)
3618 eclass = ExprClass.EventAccess;
3620 add_accessor = TypeManager.GetAddMethod (ei);
3621 remove_accessor = TypeManager.GetRemoveMethod (ei);
3623 if (add_accessor.IsStatic || remove_accessor.IsStatic)
3626 if (EventInfo is MyEventBuilder){
3627 MyEventBuilder eb = (MyEventBuilder) EventInfo;
3628 type = eb.EventType;
3631 type = EventInfo.EventHandlerType;
3634 public string Name {
3636 return EventInfo.Name;
3640 public bool IsInstance {
3646 public bool IsStatic {
3652 public Type DeclaringType {
3654 return EventInfo.DeclaringType;
3658 public Expression InstanceExpression {
3660 return instance_expr;
3664 instance_expr = value;
3668 public override Expression DoResolve (EmitContext ec)
3670 if (instance_expr != null) {
3671 instance_expr = instance_expr.DoResolve (ec);
3672 if (instance_expr == null)
3680 public override void Emit (EmitContext ec)
3682 if (instance_expr is This)
3683 Report.Error (79, loc, "The event `{0}' can only appear on the left hand side of += or -=, try calling the actual delegate");
3685 Report.Error (70, loc, "The event `{0}' can only appear on the left hand side of += or -= "+
3686 "(except on the defining type)", Name);
3689 public void EmitAddOrRemove (EmitContext ec, Expression source)
3691 BinaryDelegate source_del = (BinaryDelegate) source;
3692 Expression handler = source_del.Right;
3694 Argument arg = new Argument (handler, Argument.AType.Expression);
3695 ArrayList args = new ArrayList ();
3699 if (source_del.IsAddition)
3700 Invocation.EmitCall (
3701 ec, false, IsStatic, instance_expr, add_accessor, args, loc);
3703 Invocation.EmitCall (
3704 ec, false, IsStatic, instance_expr, remove_accessor, args, loc);