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
68 // This is just as a hint to AddressOf of what will be done with the
71 public enum AddressOp {
78 /// This interface is implemented by variables
80 public interface IMemoryLocation {
82 /// The AddressOf method should generate code that loads
83 /// the address of the object and leaves it on the stack.
85 /// The `mode' argument is used to notify the expression
86 /// of whether this will be used to read from the address or
87 /// write to the address.
89 /// This is just a hint that can be used to provide good error
90 /// reporting, and should have no other side effects.
92 void AddressOf (EmitContext ec, AddressOp mode);
96 /// We are either a namespace or a type.
97 /// If we're a type, `IsType' is true and we may use `Type' to get
98 /// a TypeExpr representing that type.
100 public interface IAlias {
115 /// This interface is implemented by variables
117 public interface IVariable {
118 VariableInfo VariableInfo {
122 bool VerifyFixed (bool is_expression);
126 /// This interface denotes an expression which evaluates to a member
127 /// of a struct or a class.
129 public interface IMemberExpr
132 /// The name of this member.
139 /// Whether this is an instance member.
146 /// Whether this is a static member.
153 /// The type which declares this member.
160 /// The instance expression associated with this member, if it's a
161 /// non-static member.
163 Expression InstanceExpression {
169 /// Base class for expressions
171 public abstract class Expression {
172 public ExprClass eclass;
174 protected Location loc;
186 public Location Location {
193 /// Utility wrapper routine for Error, just to beautify the code
195 public void Error (int error, string s)
197 if (!Location.IsNull (loc))
198 Report.Error (error, loc, s);
200 Report.Error (error, s);
204 /// Utility wrapper routine for Warning, just to beautify the code
206 public void Warning (int warning, string s)
208 if (!Location.IsNull (loc))
209 Report.Warning (warning, loc, s);
211 Report.Warning (warning, s);
215 /// Utility wrapper routine for Warning, only prints the warning if
216 /// warnings of level `level' are enabled.
218 public void Warning (int warning, int level, string s)
220 if (level <= RootContext.WarningLevel)
221 Warning (warning, s);
225 /// Tests presence of ObsoleteAttribute and report proper error
227 protected void CheckObsoleteAttribute (Type type)
229 ObsoleteAttribute obsolete_attr = AttributeTester.GetObsoleteAttribute (type);
230 if (obsolete_attr == null)
233 AttributeTester.Report_ObsoleteMessage (obsolete_attr, type.FullName, loc);
237 /// Performs semantic analysis on the Expression
241 /// The Resolve method is invoked to perform the semantic analysis
244 /// The return value is an expression (it can be the
245 /// same expression in some cases) or a new
246 /// expression that better represents this node.
248 /// For example, optimizations of Unary (LiteralInt)
249 /// would return a new LiteralInt with a negated
252 /// If there is an error during semantic analysis,
253 /// then an error should be reported (using Report)
254 /// and a null value should be returned.
256 /// There are two side effects expected from calling
257 /// Resolve(): the the field variable "eclass" should
258 /// be set to any value of the enumeration
259 /// `ExprClass' and the type variable should be set
260 /// to a valid type (this is the type of the
263 public abstract Expression DoResolve (EmitContext ec);
265 public virtual Expression DoResolveLValue (EmitContext ec, Expression right_side)
267 return DoResolve (ec);
271 // This is used if the expression should be resolved as a type.
272 // the default implementation fails. Use this method in
273 // those participants in the SimpleName chain system.
275 public virtual Expression ResolveAsTypeStep (EmitContext ec)
281 // This is used to resolve the expression as a type, a null
282 // value will be returned if the expression is not a type
285 public TypeExpr ResolveAsTypeTerminal (EmitContext ec)
287 return ResolveAsTypeStep (ec) as TypeExpr;
291 /// Resolves an expression and performs semantic analysis on it.
295 /// Currently Resolve wraps DoResolve to perform sanity
296 /// checking and assertion checking on what we expect from Resolve.
298 public Expression Resolve (EmitContext ec, ResolveFlags flags)
300 if ((flags & ResolveFlags.MaskExprClass) == ResolveFlags.Type)
301 return ResolveAsTypeStep (ec);
303 bool old_do_flow_analysis = ec.DoFlowAnalysis;
304 if ((flags & ResolveFlags.DisableFlowAnalysis) != 0)
305 ec.DoFlowAnalysis = false;
308 if (this is SimpleName)
309 e = ((SimpleName) this).DoResolveAllowStatic (ec);
313 ec.DoFlowAnalysis = old_do_flow_analysis;
318 if (e is SimpleName){
319 SimpleName s = (SimpleName) e;
321 if ((flags & ResolveFlags.SimpleName) == 0) {
322 MemberLookupFailed (ec, null, ec.ContainerType, s.Name,
323 ec.DeclSpace.Name, loc);
330 if ((e is TypeExpr) || (e is ComposedCast)) {
331 if ((flags & ResolveFlags.Type) == 0) {
332 e.Error_UnexpectedKind (flags);
341 if ((flags & ResolveFlags.VariableOrValue) == 0) {
342 e.Error_UnexpectedKind (flags);
347 case ExprClass.MethodGroup:
348 if (!RootContext.V2){
349 if ((flags & ResolveFlags.MethodGroup) == 0) {
350 ((MethodGroupExpr) e).ReportUsageError ();
356 case ExprClass.Value:
357 case ExprClass.Variable:
358 case ExprClass.PropertyAccess:
359 case ExprClass.EventAccess:
360 case ExprClass.IndexerAccess:
361 if ((flags & ResolveFlags.VariableOrValue) == 0) {
362 Console.WriteLine ("I got: {0} and {1}", e.GetType (), e);
363 Console.WriteLine ("I am {0} and {1}", this.GetType (), this);
364 FieldInfo fi = ((FieldExpr) e).FieldInfo;
366 Console.WriteLine ("{0} and {1}", fi.DeclaringType, fi.Name);
367 e.Error_UnexpectedKind (flags);
373 throw new Exception ("Expression " + e.GetType () +
374 " ExprClass is Invalid after resolve");
378 throw new Exception (
379 "Expression " + e.GetType () +
380 " did not set its type after Resolve\n" +
381 "called from: " + this.GetType ());
387 /// Resolves an expression and performs semantic analysis on it.
389 public Expression Resolve (EmitContext ec)
391 return Resolve (ec, ResolveFlags.VariableOrValue);
395 /// Resolves an expression for LValue assignment
399 /// Currently ResolveLValue wraps DoResolveLValue to perform sanity
400 /// checking and assertion checking on what we expect from Resolve
402 public Expression ResolveLValue (EmitContext ec, Expression right_side)
404 Expression e = DoResolveLValue (ec, right_side);
407 if (e is SimpleName){
408 SimpleName s = (SimpleName) e;
409 MemberLookupFailed (ec, null, ec.ContainerType, s.Name,
410 ec.DeclSpace.Name, loc);
414 if (e.eclass == ExprClass.Invalid)
415 throw new Exception ("Expression " + e +
416 " ExprClass is Invalid after resolve");
418 if (e.eclass == ExprClass.MethodGroup) {
419 ((MethodGroupExpr) e).ReportUsageError ();
423 if ((e.type == null) && !(e is ConstructedType))
424 throw new Exception ("Expression " + e +
425 " did not set its type after Resolve");
432 /// Emits the code for the expression
436 /// The Emit method is invoked to generate the code
437 /// for the expression.
439 public abstract void Emit (EmitContext ec);
441 public virtual void EmitBranchable (EmitContext ec, Label target, bool onTrue)
444 ec.ig.Emit (onTrue ? OpCodes.Brtrue : OpCodes.Brfalse, target);
448 /// Protected constructor. Only derivate types should
449 /// be able to be created
452 protected Expression ()
454 eclass = ExprClass.Invalid;
459 /// Returns a literalized version of a literal FieldInfo
463 /// The possible return values are:
464 /// IntConstant, UIntConstant
465 /// LongLiteral, ULongConstant
466 /// FloatConstant, DoubleConstant
469 /// The value returned is already resolved.
471 public static Constant Constantify (object v, Type t)
473 if (t == TypeManager.int32_type)
474 return new IntConstant ((int) v);
475 else if (t == TypeManager.uint32_type)
476 return new UIntConstant ((uint) v);
477 else if (t == TypeManager.int64_type)
478 return new LongConstant ((long) v);
479 else if (t == TypeManager.uint64_type)
480 return new ULongConstant ((ulong) v);
481 else if (t == TypeManager.float_type)
482 return new FloatConstant ((float) v);
483 else if (t == TypeManager.double_type)
484 return new DoubleConstant ((double) v);
485 else if (t == TypeManager.string_type)
486 return new StringConstant ((string) v);
487 else if (t == TypeManager.short_type)
488 return new ShortConstant ((short)v);
489 else if (t == TypeManager.ushort_type)
490 return new UShortConstant ((ushort)v);
491 else if (t == TypeManager.sbyte_type)
492 return new SByteConstant (((sbyte)v));
493 else if (t == TypeManager.byte_type)
494 return new ByteConstant ((byte)v);
495 else if (t == TypeManager.char_type)
496 return new CharConstant ((char)v);
497 else if (t == TypeManager.bool_type)
498 return new BoolConstant ((bool) v);
499 else if (TypeManager.IsEnumType (t)){
500 Type real_type = TypeManager.TypeToCoreType (v.GetType ());
502 real_type = real_type.UnderlyingSystemType;
504 Constant e = Constantify (v, real_type);
506 return new EnumConstant (e, t);
508 throw new Exception ("Unknown type for constant (" + t +
513 /// Returns a fully formed expression after a MemberLookup
515 public static Expression ExprClassFromMemberInfo (EmitContext ec, MemberInfo mi, Location loc)
518 return new EventExpr ((EventInfo) mi, loc);
519 else if (mi is FieldInfo)
520 return new FieldExpr ((FieldInfo) mi, loc);
521 else if (mi is PropertyInfo)
522 return new PropertyExpr (ec, (PropertyInfo) mi, loc);
523 else if (mi is Type){
524 return new TypeExpression ((System.Type) mi, loc);
531 private static ArrayList almostMatchedMembers = new ArrayList (4);
534 // FIXME: Probably implement a cache for (t,name,current_access_set)?
536 // This code could use some optimizations, but we need to do some
537 // measurements. For example, we could use a delegate to `flag' when
538 // something can not any longer be a method-group (because it is something
542 // If the return value is an Array, then it is an array of
545 // If the return value is an MemberInfo, it is anything, but a Method
549 // FIXME: When calling MemberLookup inside an `Invocation', we should pass
550 // the arguments here and have MemberLookup return only the methods that
551 // match the argument count/type, unlike we are doing now (we delay this
554 // This is so we can catch correctly attempts to invoke instance methods
555 // from a static body (scan for error 120 in ResolveSimpleName).
558 // FIXME: Potential optimization, have a static ArrayList
561 public static Expression MemberLookup (EmitContext ec, Type queried_type, string name,
562 MemberTypes mt, BindingFlags bf, Location loc)
564 return MemberLookup (ec, ec.ContainerType, null, queried_type, name, mt, bf, loc);
568 // Lookup type `queried_type' for code in class `container_type' with a qualifier of
569 // `qualifier_type' or null to lookup members in the current class.
572 public static Expression MemberLookup (EmitContext ec, Type container_type,
573 Type qualifier_type, Type queried_type,
574 string name, MemberTypes mt,
575 BindingFlags bf, Location loc)
577 almostMatchedMembers.Clear ();
579 MemberInfo [] mi = TypeManager.MemberLookup (
580 container_type, qualifier_type,queried_type, mt, bf, name,
581 almostMatchedMembers);
586 int count = mi.Length;
588 if (mi [0] is MethodBase)
589 return new MethodGroupExpr (mi, loc);
594 return ExprClassFromMemberInfo (ec, mi [0], loc);
597 public const MemberTypes AllMemberTypes =
598 MemberTypes.Constructor |
602 MemberTypes.NestedType |
603 MemberTypes.Property;
605 public const BindingFlags AllBindingFlags =
606 BindingFlags.Public |
607 BindingFlags.Static |
608 BindingFlags.Instance;
610 public static Expression MemberLookup (EmitContext ec, Type queried_type,
611 string name, Location loc)
613 return MemberLookup (ec, ec.ContainerType, null, queried_type, name,
614 AllMemberTypes, AllBindingFlags, loc);
617 public static Expression MemberLookup (EmitContext ec, Type qualifier_type,
618 Type queried_type, string name, Location loc)
620 return MemberLookup (ec, ec.ContainerType, qualifier_type, queried_type,
621 name, AllMemberTypes, AllBindingFlags, loc);
624 public static Expression MethodLookup (EmitContext ec, Type queried_type,
625 string name, Location loc)
627 return MemberLookup (ec, ec.ContainerType, null, queried_type, name,
628 MemberTypes.Method, AllBindingFlags, loc);
632 /// This is a wrapper for MemberLookup that is not used to "probe", but
633 /// to find a final definition. If the final definition is not found, we
634 /// look for private members and display a useful debugging message if we
637 public static Expression MemberLookupFinal (EmitContext ec, Type qualifier_type,
638 Type queried_type, string name,
641 return MemberLookupFinal (ec, qualifier_type, queried_type, name,
642 AllMemberTypes, AllBindingFlags, loc);
645 public static Expression MemberLookupFinal (EmitContext ec, Type qualifier_type,
646 Type queried_type, string name,
647 MemberTypes mt, BindingFlags bf,
652 int errors = Report.Errors;
654 e = MemberLookup (ec, ec.ContainerType, qualifier_type, queried_type,
657 if (e == null && errors == Report.Errors)
658 // No errors were reported by MemberLookup, but there was an error.
659 MemberLookupFailed (ec, qualifier_type, queried_type, name,
665 public static void MemberLookupFailed (EmitContext ec, Type qualifier_type,
666 Type queried_type, string name,
667 string class_name, Location loc)
669 if (almostMatchedMembers.Count != 0) {
670 if (qualifier_type == null) {
671 foreach (MemberInfo m in almostMatchedMembers)
672 Report.Error (38, loc,
673 "Cannot access non-static member `{0}' via nested type `{1}'",
674 TypeManager.GetFullNameSignature (m),
675 TypeManager.CSharpName (ec.ContainerType));
680 if (qualifier_type != ec.ContainerType) {
681 // Although a derived class can access protected members of
682 // its base class it cannot do so through an instance of the
683 // base class (CS1540). If the qualifier_type is a parent of the
684 // ec.ContainerType and the lookup succeeds with the latter one,
685 // then we are in this situation.
686 foreach (MemberInfo m in almostMatchedMembers)
687 Report.Error (1540, loc,
688 "Cannot access protected member `{0}' via a qualifier of type `{1}';"
689 + " the qualifier must be of type `{2}' (or derived from it)",
690 TypeManager.GetFullNameSignature (m),
691 TypeManager.CSharpName (qualifier_type),
692 TypeManager.CSharpName (ec.ContainerType));
695 almostMatchedMembers.Clear ();
698 MemberInfo[] mi = TypeManager.MemberLookup (queried_type, null, queried_type,
699 AllMemberTypes, AllBindingFlags |
700 BindingFlags.NonPublic, name, null);
703 if (class_name != null)
704 Report.Error (103, loc, "The name `" + name + "' could not be " +
705 "found in `" + class_name + "'");
708 117, loc, "`" + queried_type + "' does not contain a " +
709 "definition for `" + name + "'");
713 if (TypeManager.MemberLookup (queried_type, null, queried_type,
714 AllMemberTypes, AllBindingFlags |
715 BindingFlags.NonPublic, name, null) == null) {
716 if ((mi.Length == 1) && (mi [0] is Type)) {
717 Type t = (Type) mi [0];
719 Report.Error (305, loc,
720 "Using the generic type `{0}' " +
721 "requires {1} type arguments",
722 TypeManager.GetFullName (t),
723 TypeManager.GetNumberOfTypeArguments (t));
730 if (qualifier_type != null)
731 Report.Error_T (122, loc, TypeManager.CSharpName (qualifier_type) + "." + name);
732 else if (name == ".ctor") {
733 Report.Error (143, loc, String.Format ("The type {0} has no constructors defined",
734 TypeManager.CSharpName (queried_type)));
736 Report.Error_T (122, loc, name);
740 static public MemberInfo GetFieldFromEvent (EventExpr event_expr)
742 EventInfo ei = event_expr.EventInfo;
744 return TypeManager.GetPrivateFieldOfEvent (ei);
748 /// Returns an expression that can be used to invoke operator true
749 /// on the expression if it exists.
751 static public StaticCallExpr GetOperatorTrue (EmitContext ec, Expression e, Location loc)
753 return GetOperatorTrueOrFalse (ec, e, true, loc);
757 /// Returns an expression that can be used to invoke operator false
758 /// on the expression if it exists.
760 static public StaticCallExpr GetOperatorFalse (EmitContext ec, Expression e, Location loc)
762 return GetOperatorTrueOrFalse (ec, e, false, loc);
765 static StaticCallExpr GetOperatorTrueOrFalse (EmitContext ec, Expression e, bool is_true, Location loc)
768 Expression operator_group;
770 operator_group = MethodLookup (ec, e.Type, is_true ? "op_True" : "op_False", loc);
771 if (operator_group == null)
774 ArrayList arguments = new ArrayList ();
775 arguments.Add (new Argument (e, Argument.AType.Expression));
776 method = Invocation.OverloadResolve (
777 ec, (MethodGroupExpr) operator_group, arguments, false, loc);
782 return new StaticCallExpr ((MethodInfo) method, arguments, loc);
786 /// Resolves the expression `e' into a boolean expression: either through
787 /// an implicit conversion, or through an `operator true' invocation
789 public static Expression ResolveBoolean (EmitContext ec, Expression e, Location loc)
795 Expression converted = e;
796 if (e.Type != TypeManager.bool_type)
797 converted = Convert.ImplicitConversion (ec, e, TypeManager.bool_type, new Location (-1));
800 // If no implicit conversion to bool exists, try using `operator true'
802 if (converted == null){
803 Expression operator_true = Expression.GetOperatorTrue (ec, e, loc);
804 if (operator_true == null){
806 31, loc, "Can not convert the expression to a boolean");
816 static string ExprClassName (ExprClass c)
819 case ExprClass.Invalid:
821 case ExprClass.Value:
823 case ExprClass.Variable:
825 case ExprClass.Namespace:
829 case ExprClass.MethodGroup:
830 return "method group";
831 case ExprClass.PropertyAccess:
832 return "property access";
833 case ExprClass.EventAccess:
834 return "event access";
835 case ExprClass.IndexerAccess:
836 return "indexer access";
837 case ExprClass.Nothing:
840 throw new Exception ("Should not happen");
844 /// Reports that we were expecting `expr' to be of class `expected'
846 public void Error_UnexpectedKind (string expected)
848 string kind = "Unknown";
850 kind = ExprClassName (eclass);
852 Error (118, "Expression denotes a `" + kind +
853 "' where a `" + expected + "' was expected");
856 public void Error_UnexpectedKind (ResolveFlags flags)
858 ArrayList valid = new ArrayList (10);
860 if ((flags & ResolveFlags.VariableOrValue) != 0) {
861 valid.Add ("variable");
865 if ((flags & ResolveFlags.Type) != 0)
868 if ((flags & ResolveFlags.MethodGroup) != 0)
869 valid.Add ("method group");
871 if ((flags & ResolveFlags.SimpleName) != 0)
872 valid.Add ("simple name");
874 if (valid.Count == 0)
875 valid.Add ("unknown");
877 StringBuilder sb = new StringBuilder ();
878 for (int i = 0; i < valid.Count; i++) {
881 else if (i == valid.Count)
883 sb.Append (valid [i]);
886 string kind = ExprClassName (eclass);
888 Error (119, "Expression denotes a `" + kind + "' where " +
889 "a `" + sb.ToString () + "' was expected");
892 static public void Error_ConstantValueCannotBeConverted (Location l, string val, Type t)
894 Report.Error (31, l, "Constant value `" + val + "' cannot be converted to " +
895 TypeManager.CSharpName (t));
898 public static void UnsafeError (Location loc)
900 Report.Error (214, loc, "Pointers may only be used in an unsafe context");
904 /// Converts the IntConstant, UIntConstant, LongConstant or
905 /// ULongConstant into the integral target_type. Notice
906 /// that we do not return an `Expression' we do return
907 /// a boxed integral type.
909 /// FIXME: Since I added the new constants, we need to
910 /// also support conversions from CharConstant, ByteConstant,
911 /// SByteConstant, UShortConstant, ShortConstant
913 /// This is used by the switch statement, so the domain
914 /// of work is restricted to the literals above, and the
915 /// targets are int32, uint32, char, byte, sbyte, ushort,
916 /// short, uint64 and int64
918 public static object ConvertIntLiteral (Constant c, Type target_type, Location loc)
920 if (!Convert.ImplicitStandardConversionExists (c, target_type)){
921 Convert.Error_CannotImplicitConversion (loc, c.Type, target_type);
927 if (c.Type == target_type)
928 return ((Constant) c).GetValue ();
931 // Make into one of the literals we handle, we dont really care
932 // about this value as we will just return a few limited types
934 if (c is EnumConstant)
935 c = ((EnumConstant)c).WidenToCompilerConstant ();
937 if (c is IntConstant){
938 int v = ((IntConstant) c).Value;
940 if (target_type == TypeManager.uint32_type){
943 } else if (target_type == TypeManager.char_type){
944 if (v >= Char.MinValue && v <= Char.MaxValue)
946 } else if (target_type == TypeManager.byte_type){
947 if (v >= Byte.MinValue && v <= Byte.MaxValue)
949 } else if (target_type == TypeManager.sbyte_type){
950 if (v >= SByte.MinValue && v <= SByte.MaxValue)
952 } else if (target_type == TypeManager.short_type){
953 if (v >= Int16.MinValue && v <= UInt16.MaxValue)
955 } else if (target_type == TypeManager.ushort_type){
956 if (v >= UInt16.MinValue && v <= UInt16.MaxValue)
958 } else if (target_type == TypeManager.int64_type)
960 else if (target_type == TypeManager.uint64_type){
966 } else if (c is UIntConstant){
967 uint v = ((UIntConstant) c).Value;
969 if (target_type == TypeManager.int32_type){
970 if (v <= Int32.MaxValue)
972 } else if (target_type == TypeManager.char_type){
973 if (v >= Char.MinValue && v <= Char.MaxValue)
975 } else if (target_type == TypeManager.byte_type){
976 if (v <= Byte.MaxValue)
978 } else if (target_type == TypeManager.sbyte_type){
979 if (v <= SByte.MaxValue)
981 } else if (target_type == TypeManager.short_type){
982 if (v <= UInt16.MaxValue)
984 } else if (target_type == TypeManager.ushort_type){
985 if (v <= UInt16.MaxValue)
987 } else if (target_type == TypeManager.int64_type)
989 else if (target_type == TypeManager.uint64_type)
992 } else if (c is LongConstant){
993 long v = ((LongConstant) c).Value;
995 if (target_type == TypeManager.int32_type){
996 if (v >= UInt32.MinValue && v <= UInt32.MaxValue)
998 } else if (target_type == TypeManager.uint32_type){
999 if (v >= 0 && v <= UInt32.MaxValue)
1001 } else if (target_type == TypeManager.char_type){
1002 if (v >= Char.MinValue && v <= Char.MaxValue)
1004 } else if (target_type == TypeManager.byte_type){
1005 if (v >= Byte.MinValue && v <= Byte.MaxValue)
1007 } else if (target_type == TypeManager.sbyte_type){
1008 if (v >= SByte.MinValue && v <= SByte.MaxValue)
1010 } else if (target_type == TypeManager.short_type){
1011 if (v >= Int16.MinValue && v <= UInt16.MaxValue)
1013 } else if (target_type == TypeManager.ushort_type){
1014 if (v >= UInt16.MinValue && v <= UInt16.MaxValue)
1016 } else if (target_type == TypeManager.uint64_type){
1021 } else if (c is ULongConstant){
1022 ulong v = ((ULongConstant) c).Value;
1024 if (target_type == TypeManager.int32_type){
1025 if (v <= Int32.MaxValue)
1027 } else if (target_type == TypeManager.uint32_type){
1028 if (v <= UInt32.MaxValue)
1030 } else if (target_type == TypeManager.char_type){
1031 if (v >= Char.MinValue && v <= Char.MaxValue)
1033 } else if (target_type == TypeManager.byte_type){
1034 if (v >= Byte.MinValue && v <= Byte.MaxValue)
1036 } else if (target_type == TypeManager.sbyte_type){
1037 if (v <= (int) SByte.MaxValue)
1039 } else if (target_type == TypeManager.short_type){
1040 if (v <= UInt16.MaxValue)
1042 } else if (target_type == TypeManager.ushort_type){
1043 if (v <= UInt16.MaxValue)
1045 } else if (target_type == TypeManager.int64_type){
1046 if (v <= Int64.MaxValue)
1050 } else if (c is ByteConstant){
1051 byte v = ((ByteConstant) c).Value;
1053 if (target_type == TypeManager.int32_type)
1055 else if (target_type == TypeManager.uint32_type)
1057 else if (target_type == TypeManager.char_type)
1059 else if (target_type == TypeManager.sbyte_type){
1060 if (v <= SByte.MaxValue)
1062 } else if (target_type == TypeManager.short_type)
1064 else if (target_type == TypeManager.ushort_type)
1066 else if (target_type == TypeManager.int64_type)
1068 else if (target_type == TypeManager.uint64_type)
1071 } else if (c is SByteConstant){
1072 sbyte v = ((SByteConstant) c).Value;
1074 if (target_type == TypeManager.int32_type)
1076 else if (target_type == TypeManager.uint32_type){
1079 } else if (target_type == TypeManager.char_type){
1082 } else if (target_type == TypeManager.byte_type){
1085 } else if (target_type == TypeManager.short_type)
1087 else if (target_type == TypeManager.ushort_type){
1090 } else if (target_type == TypeManager.int64_type)
1092 else if (target_type == TypeManager.uint64_type){
1097 } else if (c is ShortConstant){
1098 short v = ((ShortConstant) c).Value;
1100 if (target_type == TypeManager.int32_type){
1102 } else if (target_type == TypeManager.uint32_type){
1105 } else if (target_type == TypeManager.char_type){
1108 } else if (target_type == TypeManager.byte_type){
1109 if (v >= Byte.MinValue && v <= Byte.MaxValue)
1111 } else if (target_type == TypeManager.sbyte_type){
1112 if (v >= SByte.MinValue && v <= SByte.MaxValue)
1114 } else if (target_type == TypeManager.ushort_type){
1117 } else if (target_type == TypeManager.int64_type)
1119 else if (target_type == TypeManager.uint64_type)
1123 } else if (c is UShortConstant){
1124 ushort v = ((UShortConstant) c).Value;
1126 if (target_type == TypeManager.int32_type)
1128 else if (target_type == TypeManager.uint32_type)
1130 else if (target_type == TypeManager.char_type){
1131 if (v >= Char.MinValue && v <= Char.MaxValue)
1133 } else if (target_type == TypeManager.byte_type){
1134 if (v >= Byte.MinValue && v <= Byte.MaxValue)
1136 } else if (target_type == TypeManager.sbyte_type){
1137 if (v <= SByte.MaxValue)
1139 } else if (target_type == TypeManager.short_type){
1140 if (v <= Int16.MaxValue)
1142 } else if (target_type == TypeManager.int64_type)
1144 else if (target_type == TypeManager.uint64_type)
1148 } else if (c is CharConstant){
1149 char v = ((CharConstant) c).Value;
1151 if (target_type == TypeManager.int32_type)
1153 else if (target_type == TypeManager.uint32_type)
1155 else if (target_type == TypeManager.byte_type){
1156 if (v >= Byte.MinValue && v <= Byte.MaxValue)
1158 } else if (target_type == TypeManager.sbyte_type){
1159 if (v <= SByte.MaxValue)
1161 } else if (target_type == TypeManager.short_type){
1162 if (v <= Int16.MaxValue)
1164 } else if (target_type == TypeManager.ushort_type)
1166 else if (target_type == TypeManager.int64_type)
1168 else if (target_type == TypeManager.uint64_type)
1173 Error_ConstantValueCannotBeConverted (loc, s, target_type);
1178 // Load the object from the pointer.
1180 public static void LoadFromPtr (ILGenerator ig, Type t)
1182 if (t == TypeManager.int32_type)
1183 ig.Emit (OpCodes.Ldind_I4);
1184 else if (t == TypeManager.uint32_type)
1185 ig.Emit (OpCodes.Ldind_U4);
1186 else if (t == TypeManager.short_type)
1187 ig.Emit (OpCodes.Ldind_I2);
1188 else if (t == TypeManager.ushort_type)
1189 ig.Emit (OpCodes.Ldind_U2);
1190 else if (t == TypeManager.char_type)
1191 ig.Emit (OpCodes.Ldind_U2);
1192 else if (t == TypeManager.byte_type)
1193 ig.Emit (OpCodes.Ldind_U1);
1194 else if (t == TypeManager.sbyte_type)
1195 ig.Emit (OpCodes.Ldind_I1);
1196 else if (t == TypeManager.uint64_type)
1197 ig.Emit (OpCodes.Ldind_I8);
1198 else if (t == TypeManager.int64_type)
1199 ig.Emit (OpCodes.Ldind_I8);
1200 else if (t == TypeManager.float_type)
1201 ig.Emit (OpCodes.Ldind_R4);
1202 else if (t == TypeManager.double_type)
1203 ig.Emit (OpCodes.Ldind_R8);
1204 else if (t == TypeManager.bool_type)
1205 ig.Emit (OpCodes.Ldind_I1);
1206 else if (t == TypeManager.intptr_type)
1207 ig.Emit (OpCodes.Ldind_I);
1208 else if (TypeManager.IsEnumType (t)) {
1209 if (t == TypeManager.enum_type)
1210 ig.Emit (OpCodes.Ldind_Ref);
1212 LoadFromPtr (ig, TypeManager.EnumToUnderlying (t));
1213 } else if (t.IsValueType)
1214 ig.Emit (OpCodes.Ldobj, t);
1215 else if (t.IsPointer)
1216 ig.Emit (OpCodes.Ldind_I);
1218 ig.Emit (OpCodes.Ldind_Ref);
1222 // The stack contains the pointer and the value of type `type'
1224 public static void StoreFromPtr (ILGenerator ig, Type type)
1226 if (TypeManager.IsEnumType (type))
1227 type = TypeManager.EnumToUnderlying (type);
1228 if (type == TypeManager.int32_type || type == TypeManager.uint32_type)
1229 ig.Emit (OpCodes.Stind_I4);
1230 else if (type == TypeManager.int64_type || type == TypeManager.uint64_type)
1231 ig.Emit (OpCodes.Stind_I8);
1232 else if (type == TypeManager.char_type || type == TypeManager.short_type ||
1233 type == TypeManager.ushort_type)
1234 ig.Emit (OpCodes.Stind_I2);
1235 else if (type == TypeManager.float_type)
1236 ig.Emit (OpCodes.Stind_R4);
1237 else if (type == TypeManager.double_type)
1238 ig.Emit (OpCodes.Stind_R8);
1239 else if (type == TypeManager.byte_type || type == TypeManager.sbyte_type ||
1240 type == TypeManager.bool_type)
1241 ig.Emit (OpCodes.Stind_I1);
1242 else if (type == TypeManager.intptr_type)
1243 ig.Emit (OpCodes.Stind_I);
1244 else if (type.IsValueType)
1245 ig.Emit (OpCodes.Stobj, type);
1247 ig.Emit (OpCodes.Stind_Ref);
1251 // Returns the size of type `t' if known, otherwise, 0
1253 public static int GetTypeSize (Type t)
1255 t = TypeManager.TypeToCoreType (t);
1256 if (t == TypeManager.int32_type ||
1257 t == TypeManager.uint32_type ||
1258 t == TypeManager.float_type)
1260 else if (t == TypeManager.int64_type ||
1261 t == TypeManager.uint64_type ||
1262 t == TypeManager.double_type)
1264 else if (t == TypeManager.byte_type ||
1265 t == TypeManager.sbyte_type ||
1266 t == TypeManager.bool_type)
1268 else if (t == TypeManager.short_type ||
1269 t == TypeManager.char_type ||
1270 t == TypeManager.ushort_type)
1272 else if (t == TypeManager.decimal_type)
1279 // Default implementation of IAssignMethod.CacheTemporaries
1281 public virtual void CacheTemporaries (EmitContext ec)
1285 static void Error_NegativeArrayIndex (Location loc)
1287 Report.Error (284, loc, "Can not create array with a negative size");
1291 // Converts `source' to an int, uint, long or ulong.
1293 public Expression ExpressionToArrayArgument (EmitContext ec, Expression source, Location loc)
1297 bool old_checked = ec.CheckState;
1298 ec.CheckState = true;
1300 target = Convert.ImplicitConversion (ec, source, TypeManager.int32_type, loc);
1301 if (target == null){
1302 target = Convert.ImplicitConversion (ec, source, TypeManager.uint32_type, loc);
1303 if (target == null){
1304 target = Convert.ImplicitConversion (ec, source, TypeManager.int64_type, loc);
1305 if (target == null){
1306 target = Convert.ImplicitConversion (ec, source, TypeManager.uint64_type, loc);
1308 Convert.Error_CannotImplicitConversion (loc, source.Type, TypeManager.int32_type);
1312 ec.CheckState = old_checked;
1315 // Only positive constants are allowed at compile time
1317 if (target is Constant){
1318 if (target is IntConstant){
1319 if (((IntConstant) target).Value < 0){
1320 Error_NegativeArrayIndex (loc);
1325 if (target is LongConstant){
1326 if (((LongConstant) target).Value < 0){
1327 Error_NegativeArrayIndex (loc);
1340 /// This is just a base class for expressions that can
1341 /// appear on statements (invocations, object creation,
1342 /// assignments, post/pre increment and decrement). The idea
1343 /// being that they would support an extra Emition interface that
1344 /// does not leave a result on the stack.
1346 public abstract class ExpressionStatement : Expression {
1348 public virtual ExpressionStatement ResolveStatement (EmitContext ec)
1350 Expression e = Resolve (ec);
1354 ExpressionStatement es = e as ExpressionStatement;
1356 Error (201, "Only assignment, call, increment, decrement and new object " +
1357 "expressions can be used as a statement");
1363 /// Requests the expression to be emitted in a `statement'
1364 /// context. This means that no new value is left on the
1365 /// stack after invoking this method (constrasted with
1366 /// Emit that will always leave a value on the stack).
1368 public abstract void EmitStatement (EmitContext ec);
1372 /// This kind of cast is used to encapsulate the child
1373 /// whose type is child.Type into an expression that is
1374 /// reported to return "return_type". This is used to encapsulate
1375 /// expressions which have compatible types, but need to be dealt
1376 /// at higher levels with.
1378 /// For example, a "byte" expression could be encapsulated in one
1379 /// of these as an "unsigned int". The type for the expression
1380 /// would be "unsigned int".
1383 public class EmptyCast : Expression {
1384 protected Expression child;
1386 public Expression Child {
1392 public EmptyCast (Expression child, Type return_type)
1394 eclass = child.eclass;
1399 public override Expression DoResolve (EmitContext ec)
1401 // This should never be invoked, we are born in fully
1402 // initialized state.
1407 public override void Emit (EmitContext ec)
1414 // We need to special case this since an empty cast of
1415 // a NullLiteral is still a Constant
1417 public class NullCast : Constant {
1418 protected Expression child;
1420 public NullCast (Expression child, Type return_type)
1422 eclass = child.eclass;
1427 override public string AsString ()
1432 public override object GetValue ()
1437 public override Expression DoResolve (EmitContext ec)
1439 // This should never be invoked, we are born in fully
1440 // initialized state.
1445 public override void Emit (EmitContext ec)
1453 /// This class is used to wrap literals which belong inside Enums
1455 public class EnumConstant : Constant {
1456 public Constant Child;
1458 public EnumConstant (Constant child, Type enum_type)
1460 eclass = child.eclass;
1465 public override Expression DoResolve (EmitContext ec)
1467 // This should never be invoked, we are born in fully
1468 // initialized state.
1473 public override void Emit (EmitContext ec)
1478 public override object GetValue ()
1480 return Child.GetValue ();
1484 // Converts from one of the valid underlying types for an enumeration
1485 // (int32, uint32, int64, uint64, short, ushort, byte, sbyte) to
1486 // one of the internal compiler literals: Int/UInt/Long/ULong Literals.
1488 public Constant WidenToCompilerConstant ()
1490 Type t = TypeManager.EnumToUnderlying (Child.Type);
1491 object v = ((Constant) Child).GetValue ();;
1493 if (t == TypeManager.int32_type)
1494 return new IntConstant ((int) v);
1495 if (t == TypeManager.uint32_type)
1496 return new UIntConstant ((uint) v);
1497 if (t == TypeManager.int64_type)
1498 return new LongConstant ((long) v);
1499 if (t == TypeManager.uint64_type)
1500 return new ULongConstant ((ulong) v);
1501 if (t == TypeManager.short_type)
1502 return new ShortConstant ((short) v);
1503 if (t == TypeManager.ushort_type)
1504 return new UShortConstant ((ushort) v);
1505 if (t == TypeManager.byte_type)
1506 return new ByteConstant ((byte) v);
1507 if (t == TypeManager.sbyte_type)
1508 return new SByteConstant ((sbyte) v);
1510 throw new Exception ("Invalid enumeration underlying type: " + t);
1514 // Extracts the value in the enumeration on its native representation
1516 public object GetPlainValue ()
1518 Type t = TypeManager.EnumToUnderlying (Child.Type);
1519 object v = ((Constant) Child).GetValue ();;
1521 if (t == TypeManager.int32_type)
1523 if (t == TypeManager.uint32_type)
1525 if (t == TypeManager.int64_type)
1527 if (t == TypeManager.uint64_type)
1529 if (t == TypeManager.short_type)
1531 if (t == TypeManager.ushort_type)
1533 if (t == TypeManager.byte_type)
1535 if (t == TypeManager.sbyte_type)
1541 public override string AsString ()
1543 return Child.AsString ();
1546 public override DoubleConstant ConvertToDouble ()
1548 return Child.ConvertToDouble ();
1551 public override FloatConstant ConvertToFloat ()
1553 return Child.ConvertToFloat ();
1556 public override ULongConstant ConvertToULong ()
1558 return Child.ConvertToULong ();
1561 public override LongConstant ConvertToLong ()
1563 return Child.ConvertToLong ();
1566 public override UIntConstant ConvertToUInt ()
1568 return Child.ConvertToUInt ();
1571 public override IntConstant ConvertToInt ()
1573 return Child.ConvertToInt ();
1576 public override bool IsZeroInteger {
1577 get { return Child.IsZeroInteger; }
1582 /// This kind of cast is used to encapsulate Value Types in objects.
1584 /// The effect of it is to box the value type emitted by the previous
1587 public class BoxedCast : EmptyCast {
1589 public BoxedCast (Expression expr)
1590 : base (expr, TypeManager.object_type)
1592 eclass = ExprClass.Value;
1595 public BoxedCast (Expression expr, Type target_type)
1596 : base (expr, target_type)
1598 eclass = ExprClass.Value;
1601 public override Expression DoResolve (EmitContext ec)
1603 // This should never be invoked, we are born in fully
1604 // initialized state.
1609 public override void Emit (EmitContext ec)
1613 ec.ig.Emit (OpCodes.Box, child.Type);
1617 public class UnboxCast : EmptyCast {
1618 public UnboxCast (Expression expr, Type return_type)
1619 : base (expr, return_type)
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)
1634 ILGenerator ig = ec.ig;
1637 if (t.IsGenericParameter)
1638 ig.Emit (OpCodes.Unbox_Any, t);
1640 ig.Emit (OpCodes.Unbox, t);
1642 LoadFromPtr (ig, t);
1648 /// This is used to perform explicit numeric conversions.
1650 /// Explicit numeric conversions might trigger exceptions in a checked
1651 /// context, so they should generate the conv.ovf opcodes instead of
1654 public class ConvCast : EmptyCast {
1655 public enum Mode : byte {
1656 I1_U1, I1_U2, I1_U4, I1_U8, I1_CH,
1658 I2_I1, I2_U1, I2_U2, I2_U4, I2_U8, I2_CH,
1659 U2_I1, U2_U1, U2_I2, U2_CH,
1660 I4_I1, I4_U1, I4_I2, I4_U2, I4_U4, I4_U8, I4_CH,
1661 U4_I1, U4_U1, U4_I2, U4_U2, U4_I4, U4_CH,
1662 I8_I1, I8_U1, I8_I2, I8_U2, I8_I4, I8_U4, I8_U8, I8_CH,
1663 U8_I1, U8_U1, U8_I2, U8_U2, U8_I4, U8_U4, U8_I8, U8_CH,
1664 CH_I1, CH_U1, CH_I2,
1665 R4_I1, R4_U1, R4_I2, R4_U2, R4_I4, R4_U4, R4_I8, R4_U8, R4_CH,
1666 R8_I1, R8_U1, R8_I2, R8_U2, R8_I4, R8_U4, R8_I8, R8_U8, R8_CH, R8_R4
1672 public ConvCast (EmitContext ec, Expression child, Type return_type, Mode m)
1673 : base (child, return_type)
1675 checked_state = ec.CheckState;
1679 public override Expression DoResolve (EmitContext ec)
1681 // This should never be invoked, we are born in fully
1682 // initialized state.
1687 public override string ToString ()
1689 return String.Format ("ConvCast ({0}, {1})", mode, child);
1692 public override void Emit (EmitContext ec)
1694 ILGenerator ig = ec.ig;
1700 case Mode.I1_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1701 case Mode.I1_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1702 case Mode.I1_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1703 case Mode.I1_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1704 case Mode.I1_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1706 case Mode.U1_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1707 case Mode.U1_CH: /* nothing */ break;
1709 case Mode.I2_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1710 case Mode.I2_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1711 case Mode.I2_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1712 case Mode.I2_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1713 case Mode.I2_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1714 case Mode.I2_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1716 case Mode.U2_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1717 case Mode.U2_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
1718 case Mode.U2_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
1719 case Mode.U2_CH: /* nothing */ break;
1721 case Mode.I4_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1722 case Mode.I4_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1723 case Mode.I4_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
1724 case Mode.I4_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1725 case Mode.I4_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1726 case Mode.I4_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1727 case Mode.I4_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1729 case Mode.U4_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1730 case Mode.U4_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
1731 case Mode.U4_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
1732 case Mode.U4_U2: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
1733 case Mode.U4_I4: ig.Emit (OpCodes.Conv_Ovf_I4_Un); break;
1734 case Mode.U4_CH: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
1736 case Mode.I8_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1737 case Mode.I8_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1738 case Mode.I8_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
1739 case Mode.I8_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1740 case Mode.I8_I4: ig.Emit (OpCodes.Conv_Ovf_I4); break;
1741 case Mode.I8_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1742 case Mode.I8_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1743 case Mode.I8_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1745 case Mode.U8_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1746 case Mode.U8_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
1747 case Mode.U8_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
1748 case Mode.U8_U2: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
1749 case Mode.U8_I4: ig.Emit (OpCodes.Conv_Ovf_I4_Un); break;
1750 case Mode.U8_U4: ig.Emit (OpCodes.Conv_Ovf_U4_Un); break;
1751 case Mode.U8_I8: ig.Emit (OpCodes.Conv_Ovf_I8_Un); break;
1752 case Mode.U8_CH: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
1754 case Mode.CH_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1755 case Mode.CH_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
1756 case Mode.CH_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
1758 case Mode.R4_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1759 case Mode.R4_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1760 case Mode.R4_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
1761 case Mode.R4_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1762 case Mode.R4_I4: ig.Emit (OpCodes.Conv_Ovf_I4); break;
1763 case Mode.R4_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1764 case Mode.R4_I8: ig.Emit (OpCodes.Conv_Ovf_I8); break;
1765 case Mode.R4_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1766 case Mode.R4_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1768 case Mode.R8_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1769 case Mode.R8_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1770 case Mode.R8_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
1771 case Mode.R8_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1772 case Mode.R8_I4: ig.Emit (OpCodes.Conv_Ovf_I4); break;
1773 case Mode.R8_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1774 case Mode.R8_I8: ig.Emit (OpCodes.Conv_Ovf_I8); break;
1775 case Mode.R8_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1776 case Mode.R8_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1777 case Mode.R8_R4: ig.Emit (OpCodes.Conv_R4); break;
1781 case Mode.I1_U1: ig.Emit (OpCodes.Conv_U1); break;
1782 case Mode.I1_U2: ig.Emit (OpCodes.Conv_U2); break;
1783 case Mode.I1_U4: ig.Emit (OpCodes.Conv_U4); break;
1784 case Mode.I1_U8: ig.Emit (OpCodes.Conv_I8); break;
1785 case Mode.I1_CH: ig.Emit (OpCodes.Conv_U2); break;
1787 case Mode.U1_I1: ig.Emit (OpCodes.Conv_I1); break;
1788 case Mode.U1_CH: ig.Emit (OpCodes.Conv_U2); break;
1790 case Mode.I2_I1: ig.Emit (OpCodes.Conv_I1); break;
1791 case Mode.I2_U1: ig.Emit (OpCodes.Conv_U1); break;
1792 case Mode.I2_U2: ig.Emit (OpCodes.Conv_U2); break;
1793 case Mode.I2_U4: ig.Emit (OpCodes.Conv_U4); break;
1794 case Mode.I2_U8: ig.Emit (OpCodes.Conv_I8); break;
1795 case Mode.I2_CH: ig.Emit (OpCodes.Conv_U2); break;
1797 case Mode.U2_I1: ig.Emit (OpCodes.Conv_I1); break;
1798 case Mode.U2_U1: ig.Emit (OpCodes.Conv_U1); break;
1799 case Mode.U2_I2: ig.Emit (OpCodes.Conv_I2); break;
1800 case Mode.U2_CH: /* nothing */ break;
1802 case Mode.I4_I1: ig.Emit (OpCodes.Conv_I1); break;
1803 case Mode.I4_U1: ig.Emit (OpCodes.Conv_U1); break;
1804 case Mode.I4_I2: ig.Emit (OpCodes.Conv_I2); break;
1805 case Mode.I4_U4: /* nothing */ break;
1806 case Mode.I4_U2: ig.Emit (OpCodes.Conv_U2); break;
1807 case Mode.I4_U8: ig.Emit (OpCodes.Conv_I8); break;
1808 case Mode.I4_CH: ig.Emit (OpCodes.Conv_U2); break;
1810 case Mode.U4_I1: ig.Emit (OpCodes.Conv_I1); break;
1811 case Mode.U4_U1: ig.Emit (OpCodes.Conv_U1); break;
1812 case Mode.U4_I2: ig.Emit (OpCodes.Conv_I2); break;
1813 case Mode.U4_U2: ig.Emit (OpCodes.Conv_U2); break;
1814 case Mode.U4_I4: /* nothing */ break;
1815 case Mode.U4_CH: ig.Emit (OpCodes.Conv_U2); break;
1817 case Mode.I8_I1: ig.Emit (OpCodes.Conv_I1); break;
1818 case Mode.I8_U1: ig.Emit (OpCodes.Conv_U1); break;
1819 case Mode.I8_I2: ig.Emit (OpCodes.Conv_I2); break;
1820 case Mode.I8_U2: ig.Emit (OpCodes.Conv_U2); break;
1821 case Mode.I8_I4: ig.Emit (OpCodes.Conv_I4); break;
1822 case Mode.I8_U4: ig.Emit (OpCodes.Conv_U4); break;
1823 case Mode.I8_U8: /* nothing */ break;
1824 case Mode.I8_CH: ig.Emit (OpCodes.Conv_U2); break;
1826 case Mode.U8_I1: ig.Emit (OpCodes.Conv_I1); break;
1827 case Mode.U8_U1: ig.Emit (OpCodes.Conv_U1); break;
1828 case Mode.U8_I2: ig.Emit (OpCodes.Conv_I2); break;
1829 case Mode.U8_U2: ig.Emit (OpCodes.Conv_U2); break;
1830 case Mode.U8_I4: ig.Emit (OpCodes.Conv_I4); break;
1831 case Mode.U8_U4: ig.Emit (OpCodes.Conv_U4); break;
1832 case Mode.U8_I8: /* nothing */ break;
1833 case Mode.U8_CH: ig.Emit (OpCodes.Conv_U2); break;
1835 case Mode.CH_I1: ig.Emit (OpCodes.Conv_I1); break;
1836 case Mode.CH_U1: ig.Emit (OpCodes.Conv_U1); break;
1837 case Mode.CH_I2: ig.Emit (OpCodes.Conv_I2); break;
1839 case Mode.R4_I1: ig.Emit (OpCodes.Conv_I1); break;
1840 case Mode.R4_U1: ig.Emit (OpCodes.Conv_U1); break;
1841 case Mode.R4_I2: ig.Emit (OpCodes.Conv_I2); break;
1842 case Mode.R4_U2: ig.Emit (OpCodes.Conv_U2); break;
1843 case Mode.R4_I4: ig.Emit (OpCodes.Conv_I4); break;
1844 case Mode.R4_U4: ig.Emit (OpCodes.Conv_U4); break;
1845 case Mode.R4_I8: ig.Emit (OpCodes.Conv_I8); break;
1846 case Mode.R4_U8: ig.Emit (OpCodes.Conv_U8); break;
1847 case Mode.R4_CH: ig.Emit (OpCodes.Conv_U2); break;
1849 case Mode.R8_I1: ig.Emit (OpCodes.Conv_I1); break;
1850 case Mode.R8_U1: ig.Emit (OpCodes.Conv_U1); break;
1851 case Mode.R8_I2: ig.Emit (OpCodes.Conv_I2); break;
1852 case Mode.R8_U2: ig.Emit (OpCodes.Conv_U2); break;
1853 case Mode.R8_I4: ig.Emit (OpCodes.Conv_I4); break;
1854 case Mode.R8_U4: ig.Emit (OpCodes.Conv_U4); break;
1855 case Mode.R8_I8: ig.Emit (OpCodes.Conv_I8); break;
1856 case Mode.R8_U8: ig.Emit (OpCodes.Conv_U8); break;
1857 case Mode.R8_CH: ig.Emit (OpCodes.Conv_U2); break;
1858 case Mode.R8_R4: ig.Emit (OpCodes.Conv_R4); break;
1864 public class OpcodeCast : EmptyCast {
1868 public OpcodeCast (Expression child, Type return_type, OpCode op)
1869 : base (child, return_type)
1873 second_valid = false;
1876 public OpcodeCast (Expression child, Type return_type, OpCode op, OpCode op2)
1877 : base (child, return_type)
1882 second_valid = true;
1885 public override Expression DoResolve (EmitContext ec)
1887 // This should never be invoked, we are born in fully
1888 // initialized state.
1893 public override void Emit (EmitContext ec)
1904 /// This kind of cast is used to encapsulate a child and cast it
1905 /// to the class requested
1907 public class ClassCast : EmptyCast {
1908 public ClassCast (Expression child, Type return_type)
1909 : base (child, return_type)
1914 public override Expression DoResolve (EmitContext ec)
1916 // This should never be invoked, we are born in fully
1917 // initialized state.
1922 public override void Emit (EmitContext ec)
1926 if (child.Type.IsGenericParameter)
1927 ec.ig.Emit (OpCodes.Box, child.Type);
1929 if (type.IsGenericParameter)
1930 ec.ig.Emit (OpCodes.Unbox_Any, type);
1932 ec.ig.Emit (OpCodes.Castclass, type);
1937 /// SimpleName expressions are initially formed of a single
1938 /// word and it only happens at the beginning of the expression.
1942 /// The expression will try to be bound to a Field, a Method
1943 /// group or a Property. If those fail we pass the name to our
1944 /// caller and the SimpleName is compounded to perform a type
1945 /// lookup. The idea behind this process is that we want to avoid
1946 /// creating a namespace map from the assemblies, as that requires
1947 /// the GetExportedTypes function to be called and a hashtable to
1948 /// be constructed which reduces startup time. If later we find
1949 /// that this is slower, we should create a `NamespaceExpr' expression
1950 /// that fully participates in the resolution process.
1952 /// For example `System.Console.WriteLine' is decomposed into
1953 /// MemberAccess (MemberAccess (SimpleName ("System"), "Console"), "WriteLine")
1955 /// The first SimpleName wont produce a match on its own, so it will
1957 /// MemberAccess (SimpleName ("System.Console"), "WriteLine").
1959 /// System.Console will produce a TypeExpr match.
1961 /// The downside of this is that we might be hitting `LookupType' too many
1962 /// times with this scheme.
1964 public class SimpleName : Expression {
1966 public readonly TypeArguments Arguments;
1969 // If true, then we are a simple name, not composed with a ".
1973 public SimpleName (string a, string b, Location l)
1975 Name = String.Concat (a, ".", b);
1980 public SimpleName (string name, Location l)
1987 public SimpleName (string name, TypeArguments args, Location l)
1995 public static void Error_ObjectRefRequired (EmitContext ec, Location l, string name)
1997 if (ec.IsFieldInitializer)
2000 "A field initializer cannot reference the non-static field, " +
2001 "method or property `"+name+"'");
2005 "An object reference is required " +
2006 "for the non-static field `"+name+"'");
2010 // Checks whether we are trying to access an instance
2011 // property, method or field from a static body.
2013 Expression MemberStaticCheck (EmitContext ec, Expression e)
2015 if (e is IMemberExpr){
2016 IMemberExpr member = (IMemberExpr) e;
2018 if (!member.IsStatic){
2019 Error_ObjectRefRequired (ec, loc, Name);
2027 public override Expression DoResolve (EmitContext ec)
2029 return SimpleNameResolve (ec, null, false);
2032 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
2034 return SimpleNameResolve (ec, right_side, false);
2038 public Expression DoResolveAllowStatic (EmitContext ec)
2040 return SimpleNameResolve (ec, null, true);
2043 public override Expression ResolveAsTypeStep (EmitContext ec)
2045 DeclSpace ds = ec.DeclSpace;
2046 NamespaceEntry ns = ds.NamespaceEntry;
2051 // Since we are cheating: we only do the Alias lookup for
2052 // namespaces if the name does not include any dots in it
2054 if (ns != null && is_base)
2055 alias_value = ns.LookupAlias (Name);
2059 TypeParameterExpr generic_type = ds.LookupGeneric (Name, loc);
2060 if (generic_type != null)
2061 return generic_type.ResolveAsTypeTerminal (ec);
2063 if (ec.ResolvingTypeTree){
2064 int errors = Report.Errors;
2065 Type dt = ds.FindType (loc, Name);
2067 if (Report.Errors != errors)
2071 return new TypeExpression (dt, loc);
2073 if (alias_value != null){
2074 if (alias_value.IsType)
2075 return alias_value.Type;
2076 if ((t = RootContext.LookupType (ds, alias_value.Name, true, loc)) != null)
2082 // First, the using aliases
2084 if (alias_value != null){
2085 if (alias_value.IsType)
2086 return alias_value.Type;
2087 if ((t = RootContext.LookupType (ds, alias_value.Name, true, loc)) != null)
2090 // we have alias value, but it isn't Type, so try if it's namespace
2091 return new SimpleName (alias_value.Name, loc);
2095 // Stage 2: Lookup up if we are an alias to a type
2099 if ((t = RootContext.LookupType (ds, Name, true, loc)) != null)
2102 // No match, maybe our parent can compose us
2103 // into something meaningful.
2107 Expression SimpleNameResolve (EmitContext ec, Expression right_side,
2110 Expression e = DoSimpleNameResolve (ec, right_side, allow_static);
2114 Block current_block = ec.CurrentBlock;
2115 if (current_block != null){
2116 LocalInfo vi = current_block.GetLocalInfo (Name);
2118 current_block.IsVariableNameUsedInChildBlock(Name)) {
2119 Report.Error (135, Location,
2120 "'{0}' has a different meaning in a " +
2121 "child block", Name);
2126 if (e.Type != null && e.Type.IsPointer && !ec.InUnsafe) {
2135 /// 7.5.2: Simple Names.
2137 /// Local Variables and Parameters are handled at
2138 /// parse time, so they never occur as SimpleNames.
2140 /// The `allow_static' flag is used by MemberAccess only
2141 /// and it is used to inform us that it is ok for us to
2142 /// avoid the static check, because MemberAccess might end
2143 /// up resolving the Name as a Type name and the access as
2144 /// a static type access.
2146 /// ie: Type Type; .... { Type.GetType (""); }
2148 /// Type is both an instance variable and a Type; Type.GetType
2149 /// is the static method not an instance method of type.
2151 Expression DoSimpleNameResolve (EmitContext ec, Expression right_side, bool allow_static)
2153 Expression e = null;
2156 // Stage 1: Performed by the parser (binding to locals or parameters).
2158 Block current_block = ec.CurrentBlock;
2159 if (current_block != null){
2160 LocalInfo vi = current_block.GetLocalInfo (Name);
2164 var = new LocalVariableReference (ec.CurrentBlock, Name, loc);
2166 if (right_side != null)
2167 return var.ResolveLValue (ec, right_side);
2169 return var.Resolve (ec);
2173 Parameter par = null;
2174 Parameters pars = current_block.Parameters;
2176 par = pars.GetParameterByName (Name, out idx);
2179 ParameterReference param;
2181 param = new ParameterReference (pars, current_block, idx, Name, loc);
2183 if (right_side != null)
2184 return param.ResolveLValue (ec, right_side);
2186 return param.Resolve (ec);
2191 // Stage 2: Lookup members
2194 DeclSpace lookup_ds = ec.DeclSpace;
2196 if (lookup_ds.TypeBuilder == null)
2199 e = MemberLookup (ec, lookup_ds.TypeBuilder, Name, loc);
2203 lookup_ds =lookup_ds.Parent;
2204 } while (lookup_ds != null);
2206 if (e == null && ec.ContainerType != null)
2207 e = MemberLookup (ec, ec.ContainerType, Name, loc);
2211 // Since we are cheating (is_base is our hint
2212 // that we are the beginning of the name): we
2213 // only do the Alias lookup for namespaces if
2214 // the name does not include any dots in it
2216 NamespaceEntry ns = ec.DeclSpace.NamespaceEntry;
2217 if (is_base && ns != null){
2218 IAlias alias_value = ns.LookupAlias (Name);
2219 if (alias_value != null){
2220 if (alias_value.IsType)
2221 return alias_value.Type;
2223 Name = alias_value.Name;
2226 if ((t = TypeManager.LookupType (Name)) != null)
2227 return new TypeExpression (t, loc);
2229 // No match, maybe our parent can compose us
2230 // into something meaningful.
2235 return ResolveAsTypeStep (ec);
2241 if (e is IMemberExpr) {
2242 e = MemberAccess.ResolveMemberAccess (ec, e, null, loc, this);
2246 IMemberExpr me = e as IMemberExpr;
2250 if (Arguments != null) {
2251 MethodGroupExpr mg = me as MethodGroupExpr;
2255 return mg.ResolveGeneric (ec, Arguments);
2258 // This fails if ResolveMemberAccess() was unable to decide whether
2259 // it's a field or a type of the same name.
2260 if (!me.IsStatic && (me.InstanceExpression == null))
2264 TypeManager.IsNestedChildOf (me.InstanceExpression.Type, me.DeclaringType) &&
2265 !me.InstanceExpression.Type.IsSubclassOf (me.DeclaringType)) {
2266 Error (38, "Cannot access nonstatic member `" + me.Name + "' of " +
2267 "outer type `" + me.DeclaringType + "' via nested type `" +
2268 me.InstanceExpression.Type + "'");
2272 if (right_side != null)
2273 e = e.DoResolveLValue (ec, right_side);
2275 e = e.DoResolve (ec);
2280 if (ec.IsStatic || ec.IsFieldInitializer){
2284 return MemberStaticCheck (ec, e);
2289 public override void Emit (EmitContext ec)
2292 // If this is ever reached, then we failed to
2293 // find the name as a namespace
2296 Error (103, "The name `" + Name +
2297 "' does not exist in the class `" +
2298 ec.DeclSpace.Name + "'");
2301 public override string ToString ()
2308 /// Fully resolved expression that evaluates to a type
2310 public abstract class TypeExpr : Expression, IAlias {
2311 override public Expression ResolveAsTypeStep (EmitContext ec)
2313 TypeExpr t = DoResolveAsTypeStep (ec);
2317 eclass = ExprClass.Type;
2321 override public Expression DoResolve (EmitContext ec)
2323 return ResolveAsTypeTerminal (ec);
2326 override public void Emit (EmitContext ec)
2328 throw new Exception ("Should never be called");
2331 public virtual bool CheckAccessLevel (DeclSpace ds)
2333 return ds.CheckAccessLevel (Type);
2336 public virtual bool AsAccessible (DeclSpace ds, int flags)
2338 return ds.AsAccessible (Type, flags);
2341 public virtual bool IsClass {
2342 get { return Type.IsClass; }
2345 public virtual bool IsValueType {
2346 get { return Type.IsValueType; }
2349 public virtual bool IsInterface {
2350 get { return Type.IsInterface; }
2353 public virtual bool IsSealed {
2354 get { return Type.IsSealed; }
2357 public virtual bool CanInheritFrom ()
2359 if (Type == TypeManager.enum_type ||
2360 (Type == TypeManager.value_type && RootContext.StdLib) ||
2361 Type == TypeManager.multicast_delegate_type ||
2362 Type == TypeManager.delegate_type ||
2363 Type == TypeManager.array_type)
2369 public virtual bool IsAttribute {
2371 return Type == TypeManager.attribute_type ||
2372 Type.IsSubclassOf (TypeManager.attribute_type);
2376 public virtual TypeExpr[] GetInterfaces ()
2378 return TypeManager.GetInterfaces (Type);
2381 public abstract TypeExpr DoResolveAsTypeStep (EmitContext ec);
2383 public virtual Type ResolveType (EmitContext ec)
2385 TypeExpr t = ResolveAsTypeTerminal (ec);
2392 public abstract string Name {
2396 public override bool Equals (object obj)
2398 TypeExpr tobj = obj as TypeExpr;
2402 return Type == tobj.Type;
2405 public override int GetHashCode ()
2407 return Type.GetHashCode ();
2410 public override string ToString ()
2415 bool IAlias.IsType {
2416 get { return true; }
2419 TypeExpr IAlias.Type {
2426 public class TypeExpression : TypeExpr, IAlias {
2427 public TypeExpression (Type t, Location l)
2430 eclass = ExprClass.Type;
2434 public override TypeExpr DoResolveAsTypeStep (EmitContext ec)
2439 public override string Name {
2441 return Type.ToString ();
2445 string IAlias.Name {
2447 return Type.FullName != null ? Type.FullName : Type.Name;
2453 /// Used to create types from a fully qualified name. These are just used
2454 /// by the parser to setup the core types. A TypeLookupExpression is always
2455 /// classified as a type.
2457 public class TypeLookupExpression : TypeExpr {
2460 public TypeLookupExpression (string name)
2465 public override TypeExpr DoResolveAsTypeStep (EmitContext ec)
2468 TypeExpr texpr = RootContext.LookupType (
2469 ec.DeclSpace, name, false, Location.Null);
2473 type = texpr.ResolveType (ec);
2481 public override string Name {
2488 public class TypeAliasExpression : TypeExpr, IAlias {
2493 public TypeAliasExpression (TypeExpr texpr, TypeArguments args, Location l)
2497 loc = texpr.Location;
2499 eclass = ExprClass.Type;
2501 name = texpr.Name + "<" + args.ToString () + ">";
2506 public override string Name {
2507 get { return name; }
2510 public override TypeExpr DoResolveAsTypeStep (EmitContext ec)
2512 Type type = texpr.ResolveType (ec);
2516 int num_args = TypeManager.GetNumberOfTypeArguments (type);
2519 if (num_args == 0) {
2520 Report.Error (308, loc,
2521 "The non-generic type `{0}' cannot " +
2522 "be used with type arguments.",
2523 TypeManager.CSharpName (type));
2527 ConstructedType ctype = new ConstructedType (type, args, loc);
2528 return ctype.ResolveAsTypeTerminal (ec);
2529 } else if (num_args > 0) {
2530 Report.Error (305, loc,
2531 "Using the generic type `{0}' " +
2532 "requires {1} type arguments",
2533 TypeManager.GetFullName (type), num_args);
2537 return new TypeExpression (type, loc);
2540 public override Type ResolveType (EmitContext ec)
2542 TypeExpr t = ResolveAsTypeTerminal (ec);
2546 type = t.ResolveType (ec);
2550 public override bool CheckAccessLevel (DeclSpace ds)
2552 return texpr.CheckAccessLevel (ds);
2555 public override bool AsAccessible (DeclSpace ds, int flags)
2557 return texpr.AsAccessible (ds, flags);
2560 public override bool IsClass {
2561 get { return texpr.IsClass; }
2564 public override bool IsValueType {
2565 get { return texpr.IsValueType; }
2568 public override bool IsInterface {
2569 get { return texpr.IsInterface; }
2572 public override bool IsSealed {
2573 get { return texpr.IsSealed; }
2576 public override bool IsAttribute {
2577 get { return texpr.IsAttribute; }
2582 /// MethodGroup Expression.
2584 /// This is a fully resolved expression that evaluates to a type
2586 public class MethodGroupExpr : Expression, IMemberExpr {
2587 public MethodBase [] Methods;
2588 Expression instance_expression = null;
2589 bool is_explicit_impl = false;
2590 bool has_type_arguments = false;
2591 bool identical_type_name = false;
2593 public MethodGroupExpr (MemberInfo [] mi, Location l)
2595 Methods = new MethodBase [mi.Length];
2596 mi.CopyTo (Methods, 0);
2597 eclass = ExprClass.MethodGroup;
2598 type = TypeManager.object_type;
2602 public MethodGroupExpr (ArrayList list, Location l)
2604 Methods = new MethodBase [list.Count];
2607 list.CopyTo (Methods, 0);
2609 foreach (MemberInfo m in list){
2610 if (!(m is MethodBase)){
2611 Console.WriteLine ("Name " + m.Name);
2612 Console.WriteLine ("Found a: " + m.GetType ().FullName);
2619 eclass = ExprClass.MethodGroup;
2620 type = TypeManager.object_type;
2623 public Type DeclaringType {
2626 // We assume that the top-level type is in the end
2628 return Methods [Methods.Length - 1].DeclaringType;
2629 //return Methods [0].DeclaringType;
2634 // `A method group may have associated an instance expression'
2636 public Expression InstanceExpression {
2638 return instance_expression;
2642 instance_expression = value;
2646 public bool IsExplicitImpl {
2648 return is_explicit_impl;
2652 is_explicit_impl = value;
2656 public bool HasTypeArguments {
2658 return has_type_arguments;
2662 has_type_arguments = value;
2666 public bool IdenticalTypeName {
2668 return identical_type_name;
2672 identical_type_name = value;
2676 public string Name {
2678 return TypeManager.CSharpSignature (
2679 Methods [Methods.Length - 1]);
2683 public bool IsInstance {
2685 foreach (MethodBase mb in Methods)
2693 public bool IsStatic {
2695 foreach (MethodBase mb in Methods)
2703 override public Expression DoResolve (EmitContext ec)
2706 instance_expression = null;
2708 if (instance_expression != null) {
2709 instance_expression = instance_expression.DoResolve (ec);
2710 if (instance_expression == null)
2717 public void ReportUsageError ()
2719 Report.Error (654, loc, "Method `" + DeclaringType + "." +
2720 Name + "()' is referenced without parentheses");
2723 override public void Emit (EmitContext ec)
2725 ReportUsageError ();
2728 bool RemoveMethods (bool keep_static)
2730 ArrayList smethods = new ArrayList ();
2732 foreach (MethodBase mb in Methods){
2733 if (mb.IsStatic == keep_static)
2737 if (smethods.Count == 0)
2740 Methods = new MethodBase [smethods.Count];
2741 smethods.CopyTo (Methods, 0);
2747 /// Removes any instance methods from the MethodGroup, returns
2748 /// false if the resulting set is empty.
2750 public bool RemoveInstanceMethods ()
2752 return RemoveMethods (true);
2756 /// Removes any static methods from the MethodGroup, returns
2757 /// false if the resulting set is empty.
2759 public bool RemoveStaticMethods ()
2761 return RemoveMethods (false);
2764 public Expression ResolveGeneric (EmitContext ec, TypeArguments args)
2766 if (args.Resolve (ec) == false)
2769 Type[] atypes = args.Arguments;
2771 int first_count = 0;
2772 MethodInfo first = null;
2774 ArrayList list = new ArrayList ();
2775 foreach (MethodBase mb in Methods) {
2776 MethodInfo mi = mb as MethodInfo;
2777 if ((mi == null) || !mi.HasGenericParameters)
2780 Type[] gen_params = mi.GetGenericArguments ();
2782 if (first == null) {
2784 first_count = gen_params.Length;
2787 if (gen_params.Length != atypes.Length)
2790 list.Add (mi.BindGenericParameters (atypes));
2793 if (list.Count > 0) {
2794 MethodGroupExpr new_mg = new MethodGroupExpr (list, Location);
2795 new_mg.InstanceExpression = InstanceExpression;
2796 new_mg.HasTypeArguments = true;
2802 305, loc, "Using the generic method `{0}' " +
2803 "requires {1} type arguments", Name,
2807 308, loc, "The non-generic method `{0}' " +
2808 "cannot be used with type arguments", Name);
2815 /// Fully resolved expression that evaluates to a Field
2817 public class FieldExpr : Expression, IAssignMethod, IMemoryLocation, IMemberExpr, IVariable {
2818 public readonly FieldInfo FieldInfo;
2819 Expression instance_expr;
2820 VariableInfo variable_info;
2822 LocalTemporary temporary;
2823 IMemoryLocation instance_ml;
2824 bool have_temporary;
2826 public FieldExpr (FieldInfo fi, Location l)
2829 eclass = ExprClass.Variable;
2830 type = TypeManager.TypeToCoreType (fi.FieldType);
2834 public string Name {
2836 return FieldInfo.Name;
2840 public bool IsInstance {
2842 return !FieldInfo.IsStatic;
2846 public bool IsStatic {
2848 return FieldInfo.IsStatic;
2852 public Type DeclaringType {
2854 return FieldInfo.DeclaringType;
2858 public Expression InstanceExpression {
2860 return instance_expr;
2864 instance_expr = value;
2868 public VariableInfo VariableInfo {
2870 return variable_info;
2874 override public Expression DoResolve (EmitContext ec)
2876 if (!FieldInfo.IsStatic){
2877 if (instance_expr == null){
2879 // This can happen when referencing an instance field using
2880 // a fully qualified type expression: TypeName.InstanceField = xxx
2882 SimpleName.Error_ObjectRefRequired (ec, loc, FieldInfo.Name);
2886 // Resolve the field's instance expression while flow analysis is turned
2887 // off: when accessing a field "a.b", we must check whether the field
2888 // "a.b" is initialized, not whether the whole struct "a" is initialized.
2889 instance_expr = instance_expr.Resolve (ec, ResolveFlags.VariableOrValue |
2890 ResolveFlags.DisableFlowAnalysis);
2891 if (instance_expr == null)
2895 ObsoleteAttribute oa;
2896 FieldBase f = TypeManager.GetField (FieldInfo);
2898 oa = f.GetObsoleteAttribute (ec.DeclSpace);
2900 AttributeTester.Report_ObsoleteMessage (oa, f.GetSignatureForError (), loc);
2901 // To be sure that type is external because we do not register generated fields
2902 } else if (!(FieldInfo.DeclaringType is TypeBuilder)) {
2903 oa = AttributeTester.GetMemberObsoleteAttribute (FieldInfo);
2905 AttributeTester.Report_ObsoleteMessage (oa, TypeManager.GetFullNameSignature (FieldInfo), loc);
2908 // If the instance expression is a local variable or parameter.
2909 IVariable var = instance_expr as IVariable;
2910 if ((var == null) || (var.VariableInfo == null))
2913 VariableInfo vi = var.VariableInfo;
2914 if (!vi.IsFieldAssigned (ec, FieldInfo.Name, loc))
2917 variable_info = vi.GetSubStruct (FieldInfo.Name);
2921 void Report_AssignToReadonly (bool is_instance)
2926 msg = "Readonly field can not be assigned outside " +
2927 "of constructor or variable initializer";
2929 msg = "A static readonly field can only be assigned in " +
2930 "a static constructor";
2932 Report.Error (is_instance ? 191 : 198, loc, msg);
2935 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
2937 IVariable var = instance_expr as IVariable;
2938 if ((var != null) && (var.VariableInfo != null))
2939 var.VariableInfo.SetFieldAssigned (ec, FieldInfo.Name);
2941 Expression e = DoResolve (ec);
2946 if (!FieldInfo.IsStatic && (instance_expr.Type.IsValueType && !(instance_expr is IMemoryLocation))) {
2947 // FIXME: Provide better error reporting.
2948 Error (1612, "Cannot modify expression because it is not a variable.");
2952 if (!FieldInfo.IsInitOnly)
2955 FieldBase fb = TypeManager.GetField (FieldInfo);
2960 // InitOnly fields can only be assigned in constructors
2963 if (ec.IsConstructor){
2964 if (IsStatic && !ec.IsStatic)
2965 Report_AssignToReadonly (false);
2968 if (ec.TypeContainer.CurrentType != null)
2969 ctype = ec.TypeContainer.CurrentType.ResolveType (ec);
2971 ctype = ec.ContainerType;
2973 if (TypeManager.IsEqual (ctype, FieldInfo.DeclaringType))
2977 Report_AssignToReadonly (true);
2982 public bool VerifyFixed (bool is_expression)
2984 IVariable variable = instance_expr as IVariable;
2985 if ((variable == null) || !variable.VerifyFixed (true))
2991 public override void CacheTemporaries (EmitContext ec)
2993 if (!FieldInfo.IsStatic && (temporary == null))
2994 temporary = new LocalTemporary (ec, instance_expr.Type);
2997 void EmitInstance (EmitContext ec)
2999 if (instance_expr.Type.IsValueType)
3000 CacheTemporaries (ec);
3002 if ((temporary == null) || have_temporary)
3005 if (instance_expr.Type.IsValueType) {
3006 instance_ml = instance_expr as IMemoryLocation;
3007 if (instance_ml == null) {
3008 instance_expr.Emit (ec);
3009 temporary.Store (ec);
3010 instance_ml = temporary;
3013 instance_expr.Emit (ec);
3014 temporary.Store (ec);
3017 have_temporary = true;
3020 override public void Emit (EmitContext ec)
3022 ILGenerator ig = ec.ig;
3023 bool is_volatile = false;
3025 if (FieldInfo is FieldBuilder){
3026 FieldBase f = TypeManager.GetField (FieldInfo);
3028 if ((f.ModFlags & Modifiers.VOLATILE) != 0)
3031 f.status |= Field.Status.USED;
3035 if (FieldInfo.IsStatic){
3037 ig.Emit (OpCodes.Volatile);
3039 ig.Emit (OpCodes.Ldsfld, FieldInfo);
3044 if (instance_ml != null)
3045 instance_ml.AddressOf (ec, AddressOp.Load);
3046 else if (temporary != null)
3047 temporary.Emit (ec);
3049 instance_expr.Emit (ec);
3052 ig.Emit (OpCodes.Volatile);
3054 ig.Emit (OpCodes.Ldfld, FieldInfo);
3057 public void EmitAssign (EmitContext ec, Expression source)
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;
3064 if (is_readonly && !ec.IsConstructor){
3065 Report_AssignToReadonly (!is_static);
3071 if (instance_ml != null)
3072 instance_ml.AddressOf (ec, AddressOp.Store);
3073 else if (temporary != null)
3074 temporary.Emit (ec);
3076 instance_expr.Emit (ec);
3081 if (FieldInfo is FieldBuilder){
3082 FieldBase f = TypeManager.GetField (FieldInfo);
3084 if ((f.ModFlags & Modifiers.VOLATILE) != 0)
3085 ig.Emit (OpCodes.Volatile);
3087 f.status |= Field.Status.ASSIGNED;
3092 ig.Emit (OpCodes.Stsfld, FieldInfo);
3094 ig.Emit (OpCodes.Stfld, FieldInfo);
3097 public void AddressOf (EmitContext ec, AddressOp mode)
3099 ILGenerator ig = ec.ig;
3101 if (FieldInfo is FieldBuilder){
3102 FieldBase f = TypeManager.GetField (FieldInfo);
3104 if ((f.ModFlags & Modifiers.VOLATILE) != 0){
3105 Error (676, "volatile variable: can not take its address, or pass as ref/out parameter");
3109 if ((mode & AddressOp.Store) != 0)
3110 f.status |= Field.Status.ASSIGNED;
3111 if ((mode & AddressOp.Load) != 0)
3112 f.status |= Field.Status.USED;
3117 // Handle initonly fields specially: make a copy and then
3118 // get the address of the copy.
3121 if (FieldInfo.IsInitOnly){
3123 if (ec.IsConstructor){
3124 if (FieldInfo.IsStatic){
3136 local = ig.DeclareLocal (type);
3137 ig.Emit (OpCodes.Stloc, local);
3138 ig.Emit (OpCodes.Ldloca, local);
3143 if (FieldInfo.IsStatic){
3144 ig.Emit (OpCodes.Ldsflda, FieldInfo);
3147 // In the case of `This', we call the AddressOf method, which will
3148 // only load the pointer, and not perform an Ldobj immediately after
3149 // the value has been loaded into the stack.
3152 if (instance_ml != null)
3153 instance_ml.AddressOf (ec, AddressOp.LoadStore);
3154 else if (temporary != null)
3155 temporary.Emit (ec);
3156 else if (instance_expr is This)
3157 ((This)instance_expr).AddressOf (ec, AddressOp.LoadStore);
3159 instance_expr.Emit (ec);
3160 ig.Emit (OpCodes.Ldflda, FieldInfo);
3166 // A FieldExpr whose address can not be taken
3168 public class FieldExprNoAddress : FieldExpr, IMemoryLocation {
3169 public FieldExprNoAddress (FieldInfo fi, Location loc) : base (fi, loc)
3173 public new void AddressOf (EmitContext ec, AddressOp mode)
3175 Report.Error (-215, "Report this: Taking the address of a remapped parameter not supported");
3180 /// Expression that evaluates to a Property. The Assign class
3181 /// might set the `Value' expression if we are in an assignment.
3183 /// This is not an LValue because we need to re-write the expression, we
3184 /// can not take data from the stack and store it.
3186 public class PropertyExpr : ExpressionStatement, IAssignMethod, IMemberExpr {
3187 public readonly PropertyInfo PropertyInfo;
3190 // This is set externally by the `BaseAccess' class
3193 MethodInfo getter, setter;
3195 bool must_do_cs1540_check;
3197 Expression instance_expr;
3198 LocalTemporary temporary;
3199 bool have_temporary;
3201 public PropertyExpr (EmitContext ec, PropertyInfo pi, Location l)
3204 eclass = ExprClass.PropertyAccess;
3208 type = TypeManager.TypeToCoreType (pi.PropertyType);
3210 ResolveAccessors (ec);
3213 public string Name {
3215 return PropertyInfo.Name;
3219 public bool IsInstance {
3225 public bool IsStatic {
3231 public Type DeclaringType {
3233 return PropertyInfo.DeclaringType;
3238 // The instance expression associated with this expression
3240 public Expression InstanceExpression {
3242 instance_expr = value;
3246 return instance_expr;
3250 public bool VerifyAssignable ()
3252 if (setter == null) {
3253 Report.Error (200, loc,
3254 "The property `" + PropertyInfo.Name +
3255 "' can not be assigned to, as it has not set accessor");
3262 MethodInfo FindAccessor (Type invocation_type, bool is_set)
3264 BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic |
3265 BindingFlags.Static | BindingFlags.Instance |
3266 BindingFlags.DeclaredOnly;
3268 Type current = PropertyInfo.DeclaringType;
3269 for (; current != null; current = current.BaseType) {
3270 MemberInfo[] group = TypeManager.MemberLookup (
3271 invocation_type, invocation_type, current,
3272 MemberTypes.Property, flags, PropertyInfo.Name, null);
3277 if (group.Length != 1)
3278 // Oooops, can this ever happen ?
3281 PropertyInfo pi = (PropertyInfo) group [0];
3283 MethodInfo get = pi.GetGetMethod (true);
3284 MethodInfo set = pi.GetSetMethod (true);
3294 MethodInfo accessor = get != null ? get : set;
3295 if (accessor == null)
3297 if ((accessor.Attributes & MethodAttributes.NewSlot) != 0)
3304 MethodInfo GetAccessor (Type invocation_type, bool is_set)
3306 MethodInfo mi = FindAccessor (invocation_type, is_set);
3310 MethodAttributes ma = mi.Attributes & MethodAttributes.MemberAccessMask;
3313 // If only accessible to the current class or children
3315 if (ma == MethodAttributes.Private) {
3316 Type declaring_type = mi.DeclaringType;
3318 if (invocation_type != declaring_type){
3319 if (TypeManager.IsSubclassOrNestedChildOf (invocation_type, mi.DeclaringType))
3327 // FamAndAssem requires that we not only derivate, but we are on the
3330 if (ma == MethodAttributes.FamANDAssem){
3331 if (mi.DeclaringType.Assembly != invocation_type.Assembly)
3337 // Assembly and FamORAssem succeed if we're in the same assembly.
3338 if ((ma == MethodAttributes.Assembly) || (ma == MethodAttributes.FamORAssem)){
3339 if (mi.DeclaringType.Assembly == invocation_type.Assembly)
3343 // We already know that we aren't in the same assembly.
3344 if (ma == MethodAttributes.Assembly)
3347 // Family and FamANDAssem require that we derive.
3348 if ((ma == MethodAttributes.Family) || (ma == MethodAttributes.FamANDAssem) || (ma == MethodAttributes.FamORAssem)){
3349 if (!TypeManager.IsSubclassOrNestedChildOf (invocation_type, mi.DeclaringType))
3352 if (!TypeManager.IsNestedChildOf (invocation_type, mi.DeclaringType))
3353 must_do_cs1540_check = true;
3363 // We also perform the permission checking here, as the PropertyInfo does not
3364 // hold the information for the accessibility of its setter/getter
3366 void ResolveAccessors (EmitContext ec)
3368 getter = GetAccessor (ec.ContainerType, false);
3369 if ((getter != null) && getter.IsStatic)
3372 setter = GetAccessor (ec.ContainerType, true);
3373 if ((setter != null) && setter.IsStatic)
3376 if (setter == null && getter == null){
3377 Report.Error_T (122, loc, PropertyInfo.Name);
3381 bool InstanceResolve (EmitContext ec)
3383 if ((instance_expr == null) && ec.IsStatic && !is_static) {
3384 SimpleName.Error_ObjectRefRequired (ec, loc, PropertyInfo.Name);
3388 if (instance_expr != null) {
3389 instance_expr = instance_expr.DoResolve (ec);
3390 if (instance_expr == null)
3394 if (must_do_cs1540_check && (instance_expr != null)) {
3395 if ((instance_expr.Type != ec.ContainerType) &&
3396 ec.ContainerType.IsSubclassOf (instance_expr.Type)) {
3397 Report.Error (1540, loc, "Cannot access protected member `" +
3398 PropertyInfo.DeclaringType + "." + PropertyInfo.Name +
3399 "' via a qualifier of type `" +
3400 TypeManager.CSharpName (instance_expr.Type) +
3401 "'; the qualifier must be of type `" +
3402 TypeManager.CSharpName (ec.ContainerType) +
3403 "' (or derived from it)");
3411 override public Expression DoResolve (EmitContext ec)
3413 if (getter != null){
3414 if (TypeManager.GetArgumentTypes (getter).Length != 0){
3416 117, loc, "`{0}' does not contain a " +
3417 "definition for `{1}'.", getter.DeclaringType,
3423 if (getter == null){
3425 // The following condition happens if the PropertyExpr was
3426 // created, but is invalid (ie, the property is inaccessible),
3427 // and we did not want to embed the knowledge about this in
3428 // the caller routine. This only avoids double error reporting.
3433 Report.Error (154, loc,
3434 "The property `" + PropertyInfo.Name +
3435 "' can not be used in " +
3436 "this context because it lacks a get accessor");
3440 if (!InstanceResolve (ec))
3444 // Only base will allow this invocation to happen.
3446 if (IsBase && getter.IsAbstract){
3447 Report.Error (205, loc, "Cannot call an abstract base property: " +
3448 PropertyInfo.DeclaringType + "." +PropertyInfo.Name);
3455 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
3457 if (setter == null){
3459 // The following condition happens if the PropertyExpr was
3460 // created, but is invalid (ie, the property is inaccessible),
3461 // and we did not want to embed the knowledge about this in
3462 // the caller routine. This only avoids double error reporting.
3467 Report.Error (154, loc,
3468 "The property `" + PropertyInfo.Name +
3469 "' can not be used in " +
3470 "this context because it lacks a set accessor");
3474 if (TypeManager.GetArgumentTypes (setter).Length != 1){
3476 117, loc, "`{0}' does not contain a " +
3477 "definition for `{1}'.", getter.DeclaringType,
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);
3496 public override void CacheTemporaries (EmitContext ec)
3499 temporary = new LocalTemporary (ec, instance_expr.Type);
3502 Expression EmitInstance (EmitContext ec)
3504 if (temporary != null){
3505 if (!have_temporary){
3506 instance_expr.Emit (ec);
3507 temporary.Store (ec);
3508 have_temporary = true;
3512 return instance_expr;
3515 override public void Emit (EmitContext ec)
3517 Expression expr = EmitInstance (ec);
3520 // Special case: length of single dimension array property is turned into ldlen
3522 if ((getter == TypeManager.system_int_array_get_length) ||
3523 (getter == TypeManager.int_array_get_length)){
3524 Type iet = instance_expr.Type;
3527 // System.Array.Length can be called, but the Type does not
3528 // support invoking GetArrayRank, so test for that case first
3530 if (iet != TypeManager.array_type && (iet.GetArrayRank () == 1)){
3532 ec.ig.Emit (OpCodes.Ldlen);
3533 ec.ig.Emit (OpCodes.Conv_I4);
3538 Invocation.EmitCall (ec, IsBase, IsStatic, expr, getter, null, loc);
3543 // Implements the IAssignMethod interface for assignments
3545 public void EmitAssign (EmitContext ec, Expression source)
3547 Expression expr = EmitInstance (ec);
3549 Argument arg = new Argument (source, Argument.AType.Expression);
3550 ArrayList args = new ArrayList ();
3553 Invocation.EmitCall (ec, IsBase, IsStatic, expr, setter, args, loc);
3556 override public void EmitStatement (EmitContext ec)
3559 ec.ig.Emit (OpCodes.Pop);
3564 /// Fully resolved expression that evaluates to an Event
3566 public class EventExpr : Expression, IMemberExpr {
3567 public readonly EventInfo EventInfo;
3568 Expression instance_expr;
3571 MethodInfo add_accessor, remove_accessor;
3573 public EventExpr (EventInfo ei, Location loc)
3577 eclass = ExprClass.EventAccess;
3579 add_accessor = TypeManager.GetAddMethod (ei);
3580 remove_accessor = TypeManager.GetRemoveMethod (ei);
3582 if (add_accessor.IsStatic || remove_accessor.IsStatic)
3585 if (EventInfo is MyEventBuilder){
3586 MyEventBuilder eb = (MyEventBuilder) EventInfo;
3587 type = eb.EventType;
3590 type = EventInfo.EventHandlerType;
3593 public string Name {
3595 return EventInfo.Name;
3599 public bool IsInstance {
3605 public bool IsStatic {
3611 public Type DeclaringType {
3613 return EventInfo.DeclaringType;
3617 public Expression InstanceExpression {
3619 return instance_expr;
3623 instance_expr = value;
3627 public override Expression DoResolve (EmitContext ec)
3629 if (instance_expr != null) {
3630 instance_expr = instance_expr.DoResolve (ec);
3631 if (instance_expr == null)
3639 public override void Emit (EmitContext ec)
3641 Report.Error (70, loc, "The event `" + Name + "' can only appear on the left hand side of += or -= (except on the defining type)");
3644 public void EmitAddOrRemove (EmitContext ec, Expression source)
3646 BinaryDelegate source_del = (BinaryDelegate) source;
3647 Expression handler = source_del.Right;
3649 Argument arg = new Argument (handler, Argument.AType.Expression);
3650 ArrayList args = new ArrayList ();
3654 if (source_del.IsAddition)
3655 Invocation.EmitCall (
3656 ec, false, IsStatic, instance_expr, add_accessor, args, loc);
3658 Invocation.EmitCall (
3659 ec, false, IsStatic, instance_expr, remove_accessor, args, loc);