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);
213 /// Tests presence of ObsoleteAttribute and report proper error
215 protected void CheckObsoleteAttribute (Type type)
217 ObsoleteAttribute obsolete_attr = AttributeTester.GetObsoleteAttribute (type);
218 if (obsolete_attr == null)
221 AttributeTester.Report_ObsoleteMessage (obsolete_attr, type.FullName, loc);
225 /// Performs semantic analysis on the Expression
229 /// The Resolve method is invoked to perform the semantic analysis
232 /// The return value is an expression (it can be the
233 /// same expression in some cases) or a new
234 /// expression that better represents this node.
236 /// For example, optimizations of Unary (LiteralInt)
237 /// would return a new LiteralInt with a negated
240 /// If there is an error during semantic analysis,
241 /// then an error should be reported (using Report)
242 /// and a null value should be returned.
244 /// There are two side effects expected from calling
245 /// Resolve(): the the field variable "eclass" should
246 /// be set to any value of the enumeration
247 /// `ExprClass' and the type variable should be set
248 /// to a valid type (this is the type of the
251 public abstract Expression DoResolve (EmitContext ec);
253 public virtual Expression DoResolveLValue (EmitContext ec, Expression right_side)
255 return DoResolve (ec);
259 // This is used if the expression should be resolved as a type.
260 // the default implementation fails. Use this method in
261 // those participants in the SimpleName chain system.
263 public virtual Expression ResolveAsTypeStep (EmitContext ec)
269 // This is used to resolve the expression as a type, a null
270 // value will be returned if the expression is not a type
273 public virtual TypeExpr ResolveAsTypeTerminal (EmitContext ec)
275 int errors = Report.Errors;
277 TypeExpr te = ResolveAsTypeStep (ec) as TypeExpr;
279 if ((te == null) || (te.eclass != ExprClass.Type) || (te.Type == null)) {
280 if (errors == Report.Errors)
281 Report.Error (246, Location, "Cannot find type '{0}'", ToString ());
285 if (!te.CheckAccessLevel (ec.DeclSpace)) {
286 Report.Error (122, Location, "'{0}' is inaccessible due to its protection level", te.Name);
294 /// Resolves an expression and performs semantic analysis on it.
298 /// Currently Resolve wraps DoResolve to perform sanity
299 /// checking and assertion checking on what we expect from Resolve.
301 public Expression Resolve (EmitContext ec, ResolveFlags flags)
303 if ((flags & ResolveFlags.MaskExprClass) == ResolveFlags.Type)
304 return ResolveAsTypeStep (ec);
306 bool old_do_flow_analysis = ec.DoFlowAnalysis;
307 if ((flags & ResolveFlags.DisableFlowAnalysis) != 0)
308 ec.DoFlowAnalysis = false;
311 bool intermediate = (flags & ResolveFlags.Intermediate) == ResolveFlags.Intermediate;
312 if (this is SimpleName)
313 e = ((SimpleName) this).DoResolveAllowStatic (ec, intermediate);
318 ec.DoFlowAnalysis = old_do_flow_analysis;
323 if (e is SimpleName){
324 SimpleName s = (SimpleName) e;
326 if ((flags & ResolveFlags.SimpleName) == 0) {
327 MemberLookupFailed (ec, null, ec.ContainerType, s.Name,
328 ec.DeclSpace.Name, loc);
335 if ((e is TypeExpr) || (e is ComposedCast)) {
336 if ((flags & ResolveFlags.Type) == 0) {
337 e.Error_UnexpectedKind (flags, loc);
346 if ((flags & ResolveFlags.VariableOrValue) == 0) {
347 e.Error_UnexpectedKind (flags, loc);
352 case ExprClass.MethodGroup:
353 if (RootContext.Version == LanguageVersion.ISO_1){
354 if ((flags & ResolveFlags.MethodGroup) == 0) {
355 ((MethodGroupExpr) e).ReportUsageError ();
361 case ExprClass.Value:
362 case ExprClass.Variable:
363 case ExprClass.PropertyAccess:
364 case ExprClass.EventAccess:
365 case ExprClass.IndexerAccess:
366 if ((flags & ResolveFlags.VariableOrValue) == 0) {
367 Console.WriteLine ("I got: {0} and {1}", e.GetType (), e);
368 Console.WriteLine ("I am {0} and {1}", this.GetType (), this);
369 FieldInfo fi = ((FieldExpr) e).FieldInfo;
371 Console.WriteLine ("{0} and {1}", fi.DeclaringType, fi.Name);
372 e.Error_UnexpectedKind (flags, loc);
378 throw new Exception ("Expression " + e.GetType () +
379 " ExprClass is Invalid after resolve");
383 throw new Exception (
384 "Expression " + e.GetType () +
385 " did not set its type after Resolve\n" +
386 "called from: " + this.GetType ());
392 /// Resolves an expression and performs semantic analysis on it.
394 public Expression Resolve (EmitContext ec)
396 return Resolve (ec, ResolveFlags.VariableOrValue);
400 /// Resolves an expression for LValue assignment
404 /// Currently ResolveLValue wraps DoResolveLValue to perform sanity
405 /// checking and assertion checking on what we expect from Resolve
407 public Expression ResolveLValue (EmitContext ec, Expression right_side)
409 Expression e = DoResolveLValue (ec, right_side);
412 if (e is SimpleName){
413 SimpleName s = (SimpleName) e;
414 MemberLookupFailed (ec, null, ec.ContainerType, s.Name,
415 ec.DeclSpace.Name, loc);
419 if (e.eclass == ExprClass.Invalid)
420 throw new Exception ("Expression " + e +
421 " ExprClass is Invalid after resolve");
423 if (e.eclass == ExprClass.MethodGroup) {
424 ((MethodGroupExpr) e).ReportUsageError ();
428 if ((e.type == null) && !(e is ConstructedType))
429 throw new Exception ("Expression " + e +
430 " did not set its type after Resolve");
437 /// Emits the code for the expression
441 /// The Emit method is invoked to generate the code
442 /// for the expression.
444 public abstract void Emit (EmitContext ec);
446 public virtual void EmitBranchable (EmitContext ec, Label target, bool onTrue)
449 ec.ig.Emit (onTrue ? OpCodes.Brtrue : OpCodes.Brfalse, target);
453 /// Protected constructor. Only derivate types should
454 /// be able to be created
457 protected Expression ()
459 eclass = ExprClass.Invalid;
464 /// Returns a literalized version of a literal FieldInfo
468 /// The possible return values are:
469 /// IntConstant, UIntConstant
470 /// LongLiteral, ULongConstant
471 /// FloatConstant, DoubleConstant
474 /// The value returned is already resolved.
476 public static Constant Constantify (object v, Type t)
478 if (t == TypeManager.int32_type)
479 return new IntConstant ((int) v);
480 else if (t == TypeManager.uint32_type)
481 return new UIntConstant ((uint) v);
482 else if (t == TypeManager.int64_type)
483 return new LongConstant ((long) v);
484 else if (t == TypeManager.uint64_type)
485 return new ULongConstant ((ulong) v);
486 else if (t == TypeManager.float_type)
487 return new FloatConstant ((float) v);
488 else if (t == TypeManager.double_type)
489 return new DoubleConstant ((double) v);
490 else if (t == TypeManager.string_type)
491 return new StringConstant ((string) v);
492 else if (t == TypeManager.short_type)
493 return new ShortConstant ((short)v);
494 else if (t == TypeManager.ushort_type)
495 return new UShortConstant ((ushort)v);
496 else if (t == TypeManager.sbyte_type)
497 return new SByteConstant (((sbyte)v));
498 else if (t == TypeManager.byte_type)
499 return new ByteConstant ((byte)v);
500 else if (t == TypeManager.char_type)
501 return new CharConstant ((char)v);
502 else if (t == TypeManager.bool_type)
503 return new BoolConstant ((bool) v);
504 else if (TypeManager.IsEnumType (t)){
505 Type real_type = TypeManager.TypeToCoreType (v.GetType ());
507 real_type = System.Enum.GetUnderlyingType (real_type);
509 Constant e = Constantify (v, real_type);
511 return new EnumConstant (e, t);
512 } else if (v == null && !TypeManager.IsValueType (t))
513 return NullLiteral.Null;
515 throw new Exception ("Unknown type for constant (" + t +
520 /// Returns a fully formed expression after a MemberLookup
522 public static Expression ExprClassFromMemberInfo (EmitContext ec, MemberInfo mi, Location loc)
525 return new EventExpr ((EventInfo) mi, loc);
526 else if (mi is FieldInfo)
527 return new FieldExpr ((FieldInfo) mi, loc);
528 else if (mi is PropertyInfo)
529 return new PropertyExpr (ec, (PropertyInfo) mi, loc);
530 else if (mi is Type){
531 return new TypeExpression ((System.Type) mi, loc);
538 private static ArrayList almostMatchedMembers = new ArrayList (4);
541 // FIXME: Probably implement a cache for (t,name,current_access_set)?
543 // This code could use some optimizations, but we need to do some
544 // measurements. For example, we could use a delegate to `flag' when
545 // something can not any longer be a method-group (because it is something
549 // If the return value is an Array, then it is an array of
552 // If the return value is an MemberInfo, it is anything, but a Method
556 // FIXME: When calling MemberLookup inside an `Invocation', we should pass
557 // the arguments here and have MemberLookup return only the methods that
558 // match the argument count/type, unlike we are doing now (we delay this
561 // This is so we can catch correctly attempts to invoke instance methods
562 // from a static body (scan for error 120 in ResolveSimpleName).
565 // FIXME: Potential optimization, have a static ArrayList
568 public static Expression MemberLookup (EmitContext ec, Type queried_type, string name,
569 MemberTypes mt, BindingFlags bf, Location loc)
571 return MemberLookup (ec, ec.ContainerType, null, queried_type, name, mt, bf, loc);
575 // Lookup type `queried_type' for code in class `container_type' with a qualifier of
576 // `qualifier_type' or null to lookup members in the current class.
579 public static Expression MemberLookup (EmitContext ec, Type container_type,
580 Type qualifier_type, Type queried_type,
581 string name, MemberTypes mt,
582 BindingFlags bf, Location loc)
584 almostMatchedMembers.Clear ();
586 MemberInfo [] mi = TypeManager.MemberLookup (
587 container_type, qualifier_type,queried_type, mt, bf, name,
588 almostMatchedMembers);
593 int count = mi.Length;
595 if (mi [0] is MethodBase)
596 return new MethodGroupExpr (mi, loc);
601 return ExprClassFromMemberInfo (ec, mi [0], loc);
604 public const MemberTypes AllMemberTypes =
605 MemberTypes.Constructor |
609 MemberTypes.NestedType |
610 MemberTypes.Property;
612 public const BindingFlags AllBindingFlags =
613 BindingFlags.Public |
614 BindingFlags.Static |
615 BindingFlags.Instance;
617 public static Expression MemberLookup (EmitContext ec, Type queried_type,
618 string name, Location loc)
620 return MemberLookup (ec, ec.ContainerType, null, queried_type, name,
621 AllMemberTypes, AllBindingFlags, loc);
624 public static Expression MemberLookup (EmitContext ec, Type qualifier_type,
625 Type queried_type, string name, Location loc)
627 return MemberLookup (ec, ec.ContainerType, qualifier_type, queried_type,
628 name, AllMemberTypes, AllBindingFlags, loc);
631 public static Expression MethodLookup (EmitContext ec, Type queried_type,
632 string name, Location loc)
634 return MemberLookup (ec, ec.ContainerType, null, queried_type, name,
635 MemberTypes.Method, AllBindingFlags, loc);
639 /// This is a wrapper for MemberLookup that is not used to "probe", but
640 /// to find a final definition. If the final definition is not found, we
641 /// look for private members and display a useful debugging message if we
644 public static Expression MemberLookupFinal (EmitContext ec, Type qualifier_type,
645 Type queried_type, string name,
648 return MemberLookupFinal (ec, qualifier_type, queried_type, name,
649 AllMemberTypes, AllBindingFlags, loc);
652 public static Expression MemberLookupFinal (EmitContext ec, Type qualifier_type,
653 Type queried_type, string name,
654 MemberTypes mt, BindingFlags bf,
659 int errors = Report.Errors;
661 e = MemberLookup (ec, ec.ContainerType, qualifier_type, queried_type,
664 if (e == null && errors == Report.Errors)
665 // No errors were reported by MemberLookup, but there was an error.
666 MemberLookupFailed (ec, qualifier_type, queried_type, name,
672 public static void MemberLookupFailed (EmitContext ec, Type qualifier_type,
673 Type queried_type, string name,
674 string class_name, Location loc)
676 if (almostMatchedMembers.Count != 0) {
677 if (qualifier_type == null) {
678 foreach (MemberInfo m in almostMatchedMembers)
679 Report.Error (38, loc,
680 "Cannot access non-static member `{0}' via nested type `{1}'",
681 TypeManager.GetFullNameSignature (m),
682 TypeManager.CSharpName (ec.ContainerType));
687 if (qualifier_type != ec.ContainerType) {
688 // Although a derived class can access protected members of
689 // its base class it cannot do so through an instance of the
690 // base class (CS1540). If the qualifier_type is a parent of the
691 // ec.ContainerType and the lookup succeeds with the latter one,
692 // then we are in this situation.
693 foreach (MemberInfo m in almostMatchedMembers)
694 Report.Error (1540, loc,
695 "Cannot access protected member `{0}' via a qualifier of type `{1}';"
696 + " the qualifier must be of type `{2}' (or derived from it)",
697 TypeManager.GetFullNameSignature (m),
698 TypeManager.CSharpName (qualifier_type),
699 TypeManager.CSharpName (ec.ContainerType));
702 almostMatchedMembers.Clear ();
705 MemberInfo[] mi = TypeManager.MemberLookup (queried_type, null, queried_type,
706 AllMemberTypes, AllBindingFlags |
707 BindingFlags.NonPublic, name, null);
710 if (class_name != null)
711 Report.Error (103, loc, "The name `" + name + "' could not be " +
712 "found in `" + class_name + "'");
715 117, loc, "`" + queried_type + "' does not contain a " +
716 "definition for `" + name + "'");
720 if (TypeManager.MemberLookup (queried_type, null, queried_type,
721 AllMemberTypes, AllBindingFlags |
722 BindingFlags.NonPublic, name, null) == null) {
723 if ((mi.Length == 1) && (mi [0] is Type)) {
724 Type t = (Type) mi [0];
726 Report.Error (305, loc,
727 "Using the generic type `{0}' " +
728 "requires {1} type arguments",
729 TypeManager.GetFullName (t),
730 TypeManager.GetNumberOfTypeArguments (t));
737 if (qualifier_type != null)
738 Report.Error (122, loc, "'{0}' is inaccessible due to its protection level", TypeManager.CSharpName (qualifier_type) + "." + name);
739 else if (name == ".ctor") {
740 Report.Error (143, loc, String.Format ("The type {0} has no constructors defined",
741 TypeManager.CSharpName (queried_type)));
743 Report.Error (122, loc, "'{0}' is inaccessible due to its protection level", name);
747 static public MemberInfo GetFieldFromEvent (EventExpr event_expr)
749 EventInfo ei = event_expr.EventInfo;
751 return TypeManager.GetPrivateFieldOfEvent (ei);
755 /// Returns an expression that can be used to invoke operator true
756 /// on the expression if it exists.
758 static public StaticCallExpr GetOperatorTrue (EmitContext ec, Expression e, Location loc)
760 return GetOperatorTrueOrFalse (ec, e, true, loc);
764 /// Returns an expression that can be used to invoke operator false
765 /// on the expression if it exists.
767 static public StaticCallExpr GetOperatorFalse (EmitContext ec, Expression e, Location loc)
769 return GetOperatorTrueOrFalse (ec, e, false, loc);
772 static StaticCallExpr GetOperatorTrueOrFalse (EmitContext ec, Expression e, bool is_true, Location loc)
775 Expression operator_group;
777 operator_group = MethodLookup (ec, e.Type, is_true ? "op_True" : "op_False", loc);
778 if (operator_group == null)
781 ArrayList arguments = new ArrayList ();
782 arguments.Add (new Argument (e, Argument.AType.Expression));
783 method = Invocation.OverloadResolve (
784 ec, (MethodGroupExpr) operator_group, arguments, false, loc);
789 return new StaticCallExpr ((MethodInfo) method, arguments, loc);
793 /// Resolves the expression `e' into a boolean expression: either through
794 /// an implicit conversion, or through an `operator true' invocation
796 public static Expression ResolveBoolean (EmitContext ec, Expression e, Location loc)
802 Expression converted = e;
803 if (e.Type != TypeManager.bool_type)
804 converted = Convert.ImplicitConversion (ec, e, TypeManager.bool_type, new Location (-1));
807 // If no implicit conversion to bool exists, try using `operator true'
809 if (converted == null){
810 Expression operator_true = Expression.GetOperatorTrue (ec, e, loc);
811 if (operator_true == null){
813 31, loc, "Can not convert the expression to a boolean");
823 static string ExprClassName (ExprClass c)
826 case ExprClass.Invalid:
828 case ExprClass.Value:
830 case ExprClass.Variable:
832 case ExprClass.Namespace:
836 case ExprClass.MethodGroup:
837 return "method group";
838 case ExprClass.PropertyAccess:
839 return "property access";
840 case ExprClass.EventAccess:
841 return "event access";
842 case ExprClass.IndexerAccess:
843 return "indexer access";
844 case ExprClass.Nothing:
847 throw new Exception ("Should not happen");
851 /// Reports that we were expecting `expr' to be of class `expected'
853 public void Error_UnexpectedKind (string expected, Location loc)
855 string kind = "Unknown";
857 kind = ExprClassName (eclass);
859 Report.Error (118, loc, "Expression denotes a `" + kind +
860 "' where a `" + expected + "' was expected");
863 public void Error_UnexpectedKind (ResolveFlags flags, Location loc)
865 ArrayList valid = new ArrayList (10);
867 if ((flags & ResolveFlags.VariableOrValue) != 0) {
868 valid.Add ("variable");
872 if ((flags & ResolveFlags.Type) != 0)
875 if ((flags & ResolveFlags.MethodGroup) != 0)
876 valid.Add ("method group");
878 if ((flags & ResolveFlags.SimpleName) != 0)
879 valid.Add ("simple name");
881 if (valid.Count == 0)
882 valid.Add ("unknown");
884 StringBuilder sb = new StringBuilder ();
885 for (int i = 0; i < valid.Count; i++) {
888 else if (i == valid.Count)
890 sb.Append (valid [i]);
893 string kind = ExprClassName (eclass);
895 Error (119, "Expression denotes a `" + kind + "' where " +
896 "a `" + sb.ToString () + "' was expected");
899 static public void Error_ConstantValueCannotBeConverted (Location l, string val, Type t)
901 Report.Error (31, l, "Constant value `" + val + "' cannot be converted to " +
902 TypeManager.CSharpName (t));
905 public static void UnsafeError (Location loc)
907 Report.Error (214, loc, "Pointers may only be used in an unsafe context");
911 /// Converts the IntConstant, UIntConstant, LongConstant or
912 /// ULongConstant into the integral target_type. Notice
913 /// that we do not return an `Expression' we do return
914 /// a boxed integral type.
916 /// FIXME: Since I added the new constants, we need to
917 /// also support conversions from CharConstant, ByteConstant,
918 /// SByteConstant, UShortConstant, ShortConstant
920 /// This is used by the switch statement, so the domain
921 /// of work is restricted to the literals above, and the
922 /// targets are int32, uint32, char, byte, sbyte, ushort,
923 /// short, uint64 and int64
925 public static object ConvertIntLiteral (Constant c, Type target_type, Location loc)
927 if (!Convert.ImplicitStandardConversionExists (Convert.ConstantEC, c, target_type)){
928 Convert.Error_CannotImplicitConversion (loc, c.Type, target_type);
934 if (c.Type == target_type)
935 return ((Constant) c).GetValue ();
938 // Make into one of the literals we handle, we dont really care
939 // about this value as we will just return a few limited types
941 if (c is EnumConstant)
942 c = ((EnumConstant)c).WidenToCompilerConstant ();
944 if (c is IntConstant){
945 int v = ((IntConstant) c).Value;
947 if (target_type == TypeManager.uint32_type){
950 } else if (target_type == TypeManager.char_type){
951 if (v >= Char.MinValue && v <= Char.MaxValue)
953 } else if (target_type == TypeManager.byte_type){
954 if (v >= Byte.MinValue && v <= Byte.MaxValue)
956 } else if (target_type == TypeManager.sbyte_type){
957 if (v >= SByte.MinValue && v <= SByte.MaxValue)
959 } else if (target_type == TypeManager.short_type){
960 if (v >= Int16.MinValue && v <= UInt16.MaxValue)
962 } else if (target_type == TypeManager.ushort_type){
963 if (v >= UInt16.MinValue && v <= UInt16.MaxValue)
965 } else if (target_type == TypeManager.int64_type)
967 else if (target_type == TypeManager.uint64_type){
973 } else if (c is UIntConstant){
974 uint v = ((UIntConstant) c).Value;
976 if (target_type == TypeManager.int32_type){
977 if (v <= Int32.MaxValue)
979 } else if (target_type == TypeManager.char_type){
980 if (v >= Char.MinValue && v <= Char.MaxValue)
982 } else if (target_type == TypeManager.byte_type){
983 if (v <= Byte.MaxValue)
985 } else if (target_type == TypeManager.sbyte_type){
986 if (v <= SByte.MaxValue)
988 } else if (target_type == TypeManager.short_type){
989 if (v <= UInt16.MaxValue)
991 } else if (target_type == TypeManager.ushort_type){
992 if (v <= UInt16.MaxValue)
994 } else if (target_type == TypeManager.int64_type)
996 else if (target_type == TypeManager.uint64_type)
999 } else if (c is LongConstant){
1000 long v = ((LongConstant) c).Value;
1002 if (target_type == TypeManager.int32_type){
1003 if (v >= UInt32.MinValue && v <= UInt32.MaxValue)
1005 } else if (target_type == TypeManager.uint32_type){
1006 if (v >= 0 && v <= UInt32.MaxValue)
1008 } else if (target_type == TypeManager.char_type){
1009 if (v >= Char.MinValue && v <= Char.MaxValue)
1011 } else if (target_type == TypeManager.byte_type){
1012 if (v >= Byte.MinValue && v <= Byte.MaxValue)
1014 } else if (target_type == TypeManager.sbyte_type){
1015 if (v >= SByte.MinValue && v <= SByte.MaxValue)
1017 } else if (target_type == TypeManager.short_type){
1018 if (v >= Int16.MinValue && v <= UInt16.MaxValue)
1020 } else if (target_type == TypeManager.ushort_type){
1021 if (v >= UInt16.MinValue && v <= UInt16.MaxValue)
1023 } else if (target_type == TypeManager.uint64_type){
1028 } else if (c is ULongConstant){
1029 ulong v = ((ULongConstant) c).Value;
1031 if (target_type == TypeManager.int32_type){
1032 if (v <= Int32.MaxValue)
1034 } else if (target_type == TypeManager.uint32_type){
1035 if (v <= UInt32.MaxValue)
1037 } else if (target_type == TypeManager.char_type){
1038 if (v >= Char.MinValue && v <= Char.MaxValue)
1040 } else if (target_type == TypeManager.byte_type){
1041 if (v >= Byte.MinValue && v <= Byte.MaxValue)
1043 } else if (target_type == TypeManager.sbyte_type){
1044 if (v <= (int) SByte.MaxValue)
1046 } else if (target_type == TypeManager.short_type){
1047 if (v <= UInt16.MaxValue)
1049 } else if (target_type == TypeManager.ushort_type){
1050 if (v <= UInt16.MaxValue)
1052 } else if (target_type == TypeManager.int64_type){
1053 if (v <= Int64.MaxValue)
1057 } else if (c is ByteConstant){
1058 byte v = ((ByteConstant) c).Value;
1060 if (target_type == TypeManager.int32_type)
1062 else if (target_type == TypeManager.uint32_type)
1064 else if (target_type == TypeManager.char_type)
1066 else if (target_type == TypeManager.sbyte_type){
1067 if (v <= SByte.MaxValue)
1069 } else if (target_type == TypeManager.short_type)
1071 else if (target_type == TypeManager.ushort_type)
1073 else if (target_type == TypeManager.int64_type)
1075 else if (target_type == TypeManager.uint64_type)
1078 } else if (c is SByteConstant){
1079 sbyte v = ((SByteConstant) c).Value;
1081 if (target_type == TypeManager.int32_type)
1083 else if (target_type == TypeManager.uint32_type){
1086 } else if (target_type == TypeManager.char_type){
1089 } else if (target_type == TypeManager.byte_type){
1092 } else if (target_type == TypeManager.short_type)
1094 else if (target_type == TypeManager.ushort_type){
1097 } else if (target_type == TypeManager.int64_type)
1099 else if (target_type == TypeManager.uint64_type){
1104 } else if (c is ShortConstant){
1105 short v = ((ShortConstant) c).Value;
1107 if (target_type == TypeManager.int32_type){
1109 } else if (target_type == TypeManager.uint32_type){
1112 } else if (target_type == TypeManager.char_type){
1115 } else if (target_type == TypeManager.byte_type){
1116 if (v >= Byte.MinValue && v <= Byte.MaxValue)
1118 } else if (target_type == TypeManager.sbyte_type){
1119 if (v >= SByte.MinValue && v <= SByte.MaxValue)
1121 } else if (target_type == TypeManager.ushort_type){
1124 } else if (target_type == TypeManager.int64_type)
1126 else if (target_type == TypeManager.uint64_type)
1130 } else if (c is UShortConstant){
1131 ushort v = ((UShortConstant) c).Value;
1133 if (target_type == TypeManager.int32_type)
1135 else if (target_type == TypeManager.uint32_type)
1137 else if (target_type == TypeManager.char_type){
1138 if (v >= Char.MinValue && v <= Char.MaxValue)
1140 } else if (target_type == TypeManager.byte_type){
1141 if (v >= Byte.MinValue && v <= Byte.MaxValue)
1143 } else if (target_type == TypeManager.sbyte_type){
1144 if (v <= SByte.MaxValue)
1146 } else if (target_type == TypeManager.short_type){
1147 if (v <= Int16.MaxValue)
1149 } else if (target_type == TypeManager.int64_type)
1151 else if (target_type == TypeManager.uint64_type)
1155 } else if (c is CharConstant){
1156 char v = ((CharConstant) c).Value;
1158 if (target_type == TypeManager.int32_type)
1160 else if (target_type == TypeManager.uint32_type)
1162 else if (target_type == TypeManager.byte_type){
1163 if (v >= Byte.MinValue && v <= Byte.MaxValue)
1165 } else if (target_type == TypeManager.sbyte_type){
1166 if (v <= SByte.MaxValue)
1168 } else if (target_type == TypeManager.short_type){
1169 if (v <= Int16.MaxValue)
1171 } else if (target_type == TypeManager.ushort_type)
1173 else if (target_type == TypeManager.int64_type)
1175 else if (target_type == TypeManager.uint64_type)
1180 Error_ConstantValueCannotBeConverted (loc, s, target_type);
1185 // Load the object from the pointer.
1187 public static void LoadFromPtr (ILGenerator ig, Type t)
1189 if (t == TypeManager.int32_type)
1190 ig.Emit (OpCodes.Ldind_I4);
1191 else if (t == TypeManager.uint32_type)
1192 ig.Emit (OpCodes.Ldind_U4);
1193 else if (t == TypeManager.short_type)
1194 ig.Emit (OpCodes.Ldind_I2);
1195 else if (t == TypeManager.ushort_type)
1196 ig.Emit (OpCodes.Ldind_U2);
1197 else if (t == TypeManager.char_type)
1198 ig.Emit (OpCodes.Ldind_U2);
1199 else if (t == TypeManager.byte_type)
1200 ig.Emit (OpCodes.Ldind_U1);
1201 else if (t == TypeManager.sbyte_type)
1202 ig.Emit (OpCodes.Ldind_I1);
1203 else if (t == TypeManager.uint64_type)
1204 ig.Emit (OpCodes.Ldind_I8);
1205 else if (t == TypeManager.int64_type)
1206 ig.Emit (OpCodes.Ldind_I8);
1207 else if (t == TypeManager.float_type)
1208 ig.Emit (OpCodes.Ldind_R4);
1209 else if (t == TypeManager.double_type)
1210 ig.Emit (OpCodes.Ldind_R8);
1211 else if (t == TypeManager.bool_type)
1212 ig.Emit (OpCodes.Ldind_I1);
1213 else if (t == TypeManager.intptr_type)
1214 ig.Emit (OpCodes.Ldind_I);
1215 else if (TypeManager.IsEnumType (t)) {
1216 if (t == TypeManager.enum_type)
1217 ig.Emit (OpCodes.Ldind_Ref);
1219 LoadFromPtr (ig, TypeManager.EnumToUnderlying (t));
1220 } else if (t.IsValueType)
1221 ig.Emit (OpCodes.Ldobj, t);
1222 else if (t.IsPointer)
1223 ig.Emit (OpCodes.Ldind_I);
1225 ig.Emit (OpCodes.Ldind_Ref);
1229 // The stack contains the pointer and the value of type `type'
1231 public static void StoreFromPtr (ILGenerator ig, Type type)
1233 if (TypeManager.IsEnumType (type))
1234 type = TypeManager.EnumToUnderlying (type);
1235 if (type == TypeManager.int32_type || type == TypeManager.uint32_type)
1236 ig.Emit (OpCodes.Stind_I4);
1237 else if (type == TypeManager.int64_type || type == TypeManager.uint64_type)
1238 ig.Emit (OpCodes.Stind_I8);
1239 else if (type == TypeManager.char_type || type == TypeManager.short_type ||
1240 type == TypeManager.ushort_type)
1241 ig.Emit (OpCodes.Stind_I2);
1242 else if (type == TypeManager.float_type)
1243 ig.Emit (OpCodes.Stind_R4);
1244 else if (type == TypeManager.double_type)
1245 ig.Emit (OpCodes.Stind_R8);
1246 else if (type == TypeManager.byte_type || type == TypeManager.sbyte_type ||
1247 type == TypeManager.bool_type)
1248 ig.Emit (OpCodes.Stind_I1);
1249 else if (type == TypeManager.intptr_type)
1250 ig.Emit (OpCodes.Stind_I);
1251 else if (type.IsValueType)
1252 ig.Emit (OpCodes.Stobj, type);
1254 ig.Emit (OpCodes.Stind_Ref);
1258 // Returns the size of type `t' if known, otherwise, 0
1260 public static int GetTypeSize (Type t)
1262 t = TypeManager.TypeToCoreType (t);
1263 if (t == TypeManager.int32_type ||
1264 t == TypeManager.uint32_type ||
1265 t == TypeManager.float_type)
1267 else if (t == TypeManager.int64_type ||
1268 t == TypeManager.uint64_type ||
1269 t == TypeManager.double_type)
1271 else if (t == TypeManager.byte_type ||
1272 t == TypeManager.sbyte_type ||
1273 t == TypeManager.bool_type)
1275 else if (t == TypeManager.short_type ||
1276 t == TypeManager.char_type ||
1277 t == TypeManager.ushort_type)
1279 else if (t == TypeManager.decimal_type)
1285 public static void Error_NegativeArrayIndex (Location loc)
1287 Report.Error (248, loc, "Cannot create an 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)
1450 public override bool IsNegative {
1459 /// This class is used to wrap literals which belong inside Enums
1461 public class EnumConstant : Constant {
1462 public Constant Child;
1464 public EnumConstant (Constant child, Type enum_type)
1466 eclass = child.eclass;
1471 public override Expression DoResolve (EmitContext ec)
1473 // This should never be invoked, we are born in fully
1474 // initialized state.
1479 public override void Emit (EmitContext ec)
1484 public override object GetValue ()
1486 return Child.GetValue ();
1489 public object GetValueAsEnumType ()
1491 return System.Enum.ToObject (type, Child.GetValue ());
1495 // Converts from one of the valid underlying types for an enumeration
1496 // (int32, uint32, int64, uint64, short, ushort, byte, sbyte) to
1497 // one of the internal compiler literals: Int/UInt/Long/ULong Literals.
1499 public Constant WidenToCompilerConstant ()
1501 Type t = TypeManager.EnumToUnderlying (Child.Type);
1502 object v = ((Constant) Child).GetValue ();;
1504 if (t == TypeManager.int32_type)
1505 return new IntConstant ((int) v);
1506 if (t == TypeManager.uint32_type)
1507 return new UIntConstant ((uint) v);
1508 if (t == TypeManager.int64_type)
1509 return new LongConstant ((long) v);
1510 if (t == TypeManager.uint64_type)
1511 return new ULongConstant ((ulong) v);
1512 if (t == TypeManager.short_type)
1513 return new ShortConstant ((short) v);
1514 if (t == TypeManager.ushort_type)
1515 return new UShortConstant ((ushort) v);
1516 if (t == TypeManager.byte_type)
1517 return new ByteConstant ((byte) v);
1518 if (t == TypeManager.sbyte_type)
1519 return new SByteConstant ((sbyte) v);
1521 throw new Exception ("Invalid enumeration underlying type: " + t);
1525 // Extracts the value in the enumeration on its native representation
1527 public object GetPlainValue ()
1529 Type t = TypeManager.EnumToUnderlying (Child.Type);
1530 object v = ((Constant) Child).GetValue ();;
1532 if (t == TypeManager.int32_type)
1534 if (t == TypeManager.uint32_type)
1536 if (t == TypeManager.int64_type)
1538 if (t == TypeManager.uint64_type)
1540 if (t == TypeManager.short_type)
1542 if (t == TypeManager.ushort_type)
1544 if (t == TypeManager.byte_type)
1546 if (t == TypeManager.sbyte_type)
1552 public override string AsString ()
1554 return Child.AsString ();
1557 public override DoubleConstant ConvertToDouble ()
1559 return Child.ConvertToDouble ();
1562 public override FloatConstant ConvertToFloat ()
1564 return Child.ConvertToFloat ();
1567 public override ULongConstant ConvertToULong ()
1569 return Child.ConvertToULong ();
1572 public override LongConstant ConvertToLong ()
1574 return Child.ConvertToLong ();
1577 public override UIntConstant ConvertToUInt ()
1579 return Child.ConvertToUInt ();
1582 public override IntConstant ConvertToInt ()
1584 return Child.ConvertToInt ();
1587 public override bool IsZeroInteger {
1588 get { return Child.IsZeroInteger; }
1591 public override bool IsNegative {
1593 return Child.IsNegative;
1599 /// This kind of cast is used to encapsulate Value Types in objects.
1601 /// The effect of it is to box the value type emitted by the previous
1604 public class BoxedCast : EmptyCast {
1606 public BoxedCast (Expression expr)
1607 : base (expr, TypeManager.object_type)
1609 eclass = ExprClass.Value;
1612 public BoxedCast (Expression expr, Type target_type)
1613 : base (expr, target_type)
1615 eclass = ExprClass.Value;
1618 public override Expression DoResolve (EmitContext ec)
1620 // This should never be invoked, we are born in fully
1621 // initialized state.
1626 public override void Emit (EmitContext ec)
1630 ec.ig.Emit (OpCodes.Box, child.Type);
1634 public class UnboxCast : EmptyCast {
1635 public UnboxCast (Expression expr, Type return_type)
1636 : base (expr, return_type)
1640 public override Expression DoResolve (EmitContext ec)
1642 // This should never be invoked, we are born in fully
1643 // initialized state.
1648 public override void Emit (EmitContext ec)
1651 ILGenerator ig = ec.ig;
1654 if (t.IsGenericParameter)
1655 ig.Emit (OpCodes.Unbox_Any, t);
1657 ig.Emit (OpCodes.Unbox, t);
1659 LoadFromPtr (ig, t);
1665 /// This is used to perform explicit numeric conversions.
1667 /// Explicit numeric conversions might trigger exceptions in a checked
1668 /// context, so they should generate the conv.ovf opcodes instead of
1671 public class ConvCast : EmptyCast {
1672 public enum Mode : byte {
1673 I1_U1, I1_U2, I1_U4, I1_U8, I1_CH,
1675 I2_I1, I2_U1, I2_U2, I2_U4, I2_U8, I2_CH,
1676 U2_I1, U2_U1, U2_I2, U2_CH,
1677 I4_I1, I4_U1, I4_I2, I4_U2, I4_U4, I4_U8, I4_CH,
1678 U4_I1, U4_U1, U4_I2, U4_U2, U4_I4, U4_CH,
1679 I8_I1, I8_U1, I8_I2, I8_U2, I8_I4, I8_U4, I8_U8, I8_CH,
1680 U8_I1, U8_U1, U8_I2, U8_U2, U8_I4, U8_U4, U8_I8, U8_CH,
1681 CH_I1, CH_U1, CH_I2,
1682 R4_I1, R4_U1, R4_I2, R4_U2, R4_I4, R4_U4, R4_I8, R4_U8, R4_CH,
1683 R8_I1, R8_U1, R8_I2, R8_U2, R8_I4, R8_U4, R8_I8, R8_U8, R8_CH, R8_R4
1689 public ConvCast (EmitContext ec, Expression child, Type return_type, Mode m)
1690 : base (child, return_type)
1692 checked_state = ec.CheckState;
1696 public override Expression DoResolve (EmitContext ec)
1698 // This should never be invoked, we are born in fully
1699 // initialized state.
1704 public override string ToString ()
1706 return String.Format ("ConvCast ({0}, {1})", mode, child);
1709 public override void Emit (EmitContext ec)
1711 ILGenerator ig = ec.ig;
1717 case Mode.I1_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1718 case Mode.I1_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1719 case Mode.I1_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1720 case Mode.I1_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1721 case Mode.I1_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1723 case Mode.U1_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1724 case Mode.U1_CH: /* nothing */ break;
1726 case Mode.I2_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1727 case Mode.I2_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1728 case Mode.I2_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1729 case Mode.I2_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1730 case Mode.I2_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1731 case Mode.I2_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1733 case Mode.U2_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1734 case Mode.U2_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
1735 case Mode.U2_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
1736 case Mode.U2_CH: /* nothing */ break;
1738 case Mode.I4_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1739 case Mode.I4_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1740 case Mode.I4_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
1741 case Mode.I4_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1742 case Mode.I4_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1743 case Mode.I4_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1744 case Mode.I4_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1746 case Mode.U4_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1747 case Mode.U4_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
1748 case Mode.U4_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
1749 case Mode.U4_U2: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
1750 case Mode.U4_I4: ig.Emit (OpCodes.Conv_Ovf_I4_Un); break;
1751 case Mode.U4_CH: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
1753 case Mode.I8_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1754 case Mode.I8_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1755 case Mode.I8_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
1756 case Mode.I8_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1757 case Mode.I8_I4: ig.Emit (OpCodes.Conv_Ovf_I4); break;
1758 case Mode.I8_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1759 case Mode.I8_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1760 case Mode.I8_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1762 case Mode.U8_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1763 case Mode.U8_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
1764 case Mode.U8_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
1765 case Mode.U8_U2: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
1766 case Mode.U8_I4: ig.Emit (OpCodes.Conv_Ovf_I4_Un); break;
1767 case Mode.U8_U4: ig.Emit (OpCodes.Conv_Ovf_U4_Un); break;
1768 case Mode.U8_I8: ig.Emit (OpCodes.Conv_Ovf_I8_Un); break;
1769 case Mode.U8_CH: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
1771 case Mode.CH_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1772 case Mode.CH_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
1773 case Mode.CH_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
1775 case Mode.R4_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1776 case Mode.R4_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1777 case Mode.R4_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
1778 case Mode.R4_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1779 case Mode.R4_I4: ig.Emit (OpCodes.Conv_Ovf_I4); break;
1780 case Mode.R4_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1781 case Mode.R4_I8: ig.Emit (OpCodes.Conv_Ovf_I8); break;
1782 case Mode.R4_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1783 case Mode.R4_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1785 case Mode.R8_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1786 case Mode.R8_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1787 case Mode.R8_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
1788 case Mode.R8_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1789 case Mode.R8_I4: ig.Emit (OpCodes.Conv_Ovf_I4); break;
1790 case Mode.R8_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1791 case Mode.R8_I8: ig.Emit (OpCodes.Conv_Ovf_I8); break;
1792 case Mode.R8_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1793 case Mode.R8_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1794 case Mode.R8_R4: ig.Emit (OpCodes.Conv_R4); break;
1798 case Mode.I1_U1: ig.Emit (OpCodes.Conv_U1); break;
1799 case Mode.I1_U2: ig.Emit (OpCodes.Conv_U2); break;
1800 case Mode.I1_U4: ig.Emit (OpCodes.Conv_U4); break;
1801 case Mode.I1_U8: ig.Emit (OpCodes.Conv_I8); break;
1802 case Mode.I1_CH: ig.Emit (OpCodes.Conv_U2); break;
1804 case Mode.U1_I1: ig.Emit (OpCodes.Conv_I1); break;
1805 case Mode.U1_CH: ig.Emit (OpCodes.Conv_U2); break;
1807 case Mode.I2_I1: ig.Emit (OpCodes.Conv_I1); break;
1808 case Mode.I2_U1: ig.Emit (OpCodes.Conv_U1); break;
1809 case Mode.I2_U2: ig.Emit (OpCodes.Conv_U2); break;
1810 case Mode.I2_U4: ig.Emit (OpCodes.Conv_U4); break;
1811 case Mode.I2_U8: ig.Emit (OpCodes.Conv_I8); break;
1812 case Mode.I2_CH: ig.Emit (OpCodes.Conv_U2); break;
1814 case Mode.U2_I1: ig.Emit (OpCodes.Conv_I1); break;
1815 case Mode.U2_U1: ig.Emit (OpCodes.Conv_U1); break;
1816 case Mode.U2_I2: ig.Emit (OpCodes.Conv_I2); break;
1817 case Mode.U2_CH: /* nothing */ break;
1819 case Mode.I4_I1: ig.Emit (OpCodes.Conv_I1); break;
1820 case Mode.I4_U1: ig.Emit (OpCodes.Conv_U1); break;
1821 case Mode.I4_I2: ig.Emit (OpCodes.Conv_I2); break;
1822 case Mode.I4_U4: /* nothing */ break;
1823 case Mode.I4_U2: ig.Emit (OpCodes.Conv_U2); break;
1824 case Mode.I4_U8: ig.Emit (OpCodes.Conv_I8); break;
1825 case Mode.I4_CH: ig.Emit (OpCodes.Conv_U2); break;
1827 case Mode.U4_I1: ig.Emit (OpCodes.Conv_I1); break;
1828 case Mode.U4_U1: ig.Emit (OpCodes.Conv_U1); break;
1829 case Mode.U4_I2: ig.Emit (OpCodes.Conv_I2); break;
1830 case Mode.U4_U2: ig.Emit (OpCodes.Conv_U2); break;
1831 case Mode.U4_I4: /* nothing */ break;
1832 case Mode.U4_CH: ig.Emit (OpCodes.Conv_U2); break;
1834 case Mode.I8_I1: ig.Emit (OpCodes.Conv_I1); break;
1835 case Mode.I8_U1: ig.Emit (OpCodes.Conv_U1); break;
1836 case Mode.I8_I2: ig.Emit (OpCodes.Conv_I2); break;
1837 case Mode.I8_U2: ig.Emit (OpCodes.Conv_U2); break;
1838 case Mode.I8_I4: ig.Emit (OpCodes.Conv_I4); break;
1839 case Mode.I8_U4: ig.Emit (OpCodes.Conv_U4); break;
1840 case Mode.I8_U8: /* nothing */ break;
1841 case Mode.I8_CH: ig.Emit (OpCodes.Conv_U2); break;
1843 case Mode.U8_I1: ig.Emit (OpCodes.Conv_I1); break;
1844 case Mode.U8_U1: ig.Emit (OpCodes.Conv_U1); break;
1845 case Mode.U8_I2: ig.Emit (OpCodes.Conv_I2); break;
1846 case Mode.U8_U2: ig.Emit (OpCodes.Conv_U2); break;
1847 case Mode.U8_I4: ig.Emit (OpCodes.Conv_I4); break;
1848 case Mode.U8_U4: ig.Emit (OpCodes.Conv_U4); break;
1849 case Mode.U8_I8: /* nothing */ break;
1850 case Mode.U8_CH: ig.Emit (OpCodes.Conv_U2); break;
1852 case Mode.CH_I1: ig.Emit (OpCodes.Conv_I1); break;
1853 case Mode.CH_U1: ig.Emit (OpCodes.Conv_U1); break;
1854 case Mode.CH_I2: ig.Emit (OpCodes.Conv_I2); break;
1856 case Mode.R4_I1: ig.Emit (OpCodes.Conv_I1); break;
1857 case Mode.R4_U1: ig.Emit (OpCodes.Conv_U1); break;
1858 case Mode.R4_I2: ig.Emit (OpCodes.Conv_I2); break;
1859 case Mode.R4_U2: ig.Emit (OpCodes.Conv_U2); break;
1860 case Mode.R4_I4: ig.Emit (OpCodes.Conv_I4); break;
1861 case Mode.R4_U4: ig.Emit (OpCodes.Conv_U4); break;
1862 case Mode.R4_I8: ig.Emit (OpCodes.Conv_I8); break;
1863 case Mode.R4_U8: ig.Emit (OpCodes.Conv_U8); break;
1864 case Mode.R4_CH: ig.Emit (OpCodes.Conv_U2); break;
1866 case Mode.R8_I1: ig.Emit (OpCodes.Conv_I1); break;
1867 case Mode.R8_U1: ig.Emit (OpCodes.Conv_U1); break;
1868 case Mode.R8_I2: ig.Emit (OpCodes.Conv_I2); break;
1869 case Mode.R8_U2: ig.Emit (OpCodes.Conv_U2); break;
1870 case Mode.R8_I4: ig.Emit (OpCodes.Conv_I4); break;
1871 case Mode.R8_U4: ig.Emit (OpCodes.Conv_U4); break;
1872 case Mode.R8_I8: ig.Emit (OpCodes.Conv_I8); break;
1873 case Mode.R8_U8: ig.Emit (OpCodes.Conv_U8); break;
1874 case Mode.R8_CH: ig.Emit (OpCodes.Conv_U2); break;
1875 case Mode.R8_R4: ig.Emit (OpCodes.Conv_R4); break;
1881 public class OpcodeCast : EmptyCast {
1885 public OpcodeCast (Expression child, Type return_type, OpCode op)
1886 : base (child, return_type)
1890 second_valid = false;
1893 public OpcodeCast (Expression child, Type return_type, OpCode op, OpCode op2)
1894 : base (child, return_type)
1899 second_valid = true;
1902 public override Expression DoResolve (EmitContext ec)
1904 // This should never be invoked, we are born in fully
1905 // initialized state.
1910 public override void Emit (EmitContext ec)
1921 /// This kind of cast is used to encapsulate a child and cast it
1922 /// to the class requested
1924 public class ClassCast : EmptyCast {
1925 public ClassCast (Expression child, Type return_type)
1926 : base (child, return_type)
1931 public override Expression DoResolve (EmitContext ec)
1933 // This should never be invoked, we are born in fully
1934 // initialized state.
1939 public override void Emit (EmitContext ec)
1943 if (child.Type.IsGenericParameter)
1944 ec.ig.Emit (OpCodes.Box, child.Type);
1946 if (type.IsGenericParameter)
1947 ec.ig.Emit (OpCodes.Unbox_Any, type);
1949 ec.ig.Emit (OpCodes.Castclass, type);
1954 /// SimpleName expressions are initially formed of a single
1955 /// word and it only happens at the beginning of the expression.
1959 /// The expression will try to be bound to a Field, a Method
1960 /// group or a Property. If those fail we pass the name to our
1961 /// caller and the SimpleName is compounded to perform a type
1962 /// lookup. The idea behind this process is that we want to avoid
1963 /// creating a namespace map from the assemblies, as that requires
1964 /// the GetExportedTypes function to be called and a hashtable to
1965 /// be constructed which reduces startup time. If later we find
1966 /// that this is slower, we should create a `NamespaceExpr' expression
1967 /// that fully participates in the resolution process.
1969 /// For example `System.Console.WriteLine' is decomposed into
1970 /// MemberAccess (MemberAccess (SimpleName ("System"), "Console"), "WriteLine")
1972 /// The first SimpleName wont produce a match on its own, so it will
1974 /// MemberAccess (SimpleName ("System.Console"), "WriteLine").
1976 /// System.Console will produce a TypeExpr match.
1978 /// The downside of this is that we might be hitting `LookupType' too many
1979 /// times with this scheme.
1981 public class SimpleName : Expression {
1983 public readonly TypeArguments Arguments;
1986 // If true, then we are a simple name, not composed with a ".
1990 public SimpleName (string a, string b, Location l)
1992 Name = String.Concat (a, ".", b);
1997 public SimpleName (string name, Location l)
2004 public SimpleName (string name, TypeArguments args, Location l)
2012 public static void Error_ObjectRefRequired (EmitContext ec, Location l, string name)
2014 if (ec.IsFieldInitializer)
2017 "A field initializer cannot reference the non-static field, " +
2018 "method or property `"+name+"'");
2022 "An object reference is required " +
2023 "for the non-static field `"+name+"'");
2027 // Checks whether we are trying to access an instance
2028 // property, method or field from a static body.
2030 Expression MemberStaticCheck (EmitContext ec, Expression e)
2032 if (e is IMemberExpr){
2033 IMemberExpr member = (IMemberExpr) e;
2035 if (!member.IsStatic){
2036 Error_ObjectRefRequired (ec, loc, Name);
2044 public override Expression DoResolve (EmitContext ec)
2046 return SimpleNameResolve (ec, null, false, false);
2049 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
2051 return SimpleNameResolve (ec, right_side, false, false);
2055 public Expression DoResolveAllowStatic (EmitContext ec, bool intermediate)
2057 return SimpleNameResolve (ec, null, true, intermediate);
2060 public override Expression ResolveAsTypeStep (EmitContext ec)
2062 DeclSpace ds = ec.DeclSpace;
2063 NamespaceEntry ns = ds.NamespaceEntry;
2068 // Since we are cheating: we only do the Alias lookup for
2069 // namespaces if the name does not include any dots in it
2071 if (ns != null && is_base)
2072 alias_value = ns.LookupAlias (Name);
2076 TypeParameterExpr generic_type = ds.LookupGeneric (Name, loc);
2077 if (generic_type != null)
2078 return generic_type.ResolveAsTypeTerminal (ec);
2080 if (ec.ResolvingTypeTree){
2081 int errors = Report.Errors;
2082 Type dt = ds.FindType (loc, Name);
2084 if (Report.Errors != errors)
2088 return new TypeExpression (dt, loc);
2090 if (alias_value != null){
2091 if (alias_value.IsType)
2092 return alias_value.ResolveAsType (ec);
2093 if ((t = RootContext.LookupType (ds, alias_value.Name, true, loc)) != null)
2094 return new TypeExpression (t, loc);
2098 if ((t = RootContext.LookupType (ds, Name, true, loc)) != null)
2099 return new TypeExpression (t, loc);
2101 if (alias_value != null) {
2102 if (alias_value.IsType)
2103 return alias_value.ResolveAsType (ec);
2104 if ((t = RootContext.LookupType (ds, alias_value.Name, true, loc)) != null)
2105 return new TypeExpression (t, loc);
2107 // we have alias value, but it isn't Type, so try if it's namespace
2108 return new SimpleName (alias_value.Name, loc);
2111 // No match, maybe our parent can compose us
2112 // into something meaningful.
2116 Expression SimpleNameResolve (EmitContext ec, Expression right_side,
2117 bool allow_static, bool intermediate)
2119 Expression e = DoSimpleNameResolve (ec, right_side, allow_static, intermediate);
2123 Block current_block = ec.CurrentBlock;
2124 if (current_block != null){
2125 //LocalInfo vi = current_block.GetLocalInfo (Name);
2127 current_block.IsVariableNameUsedInChildBlock(Name)) {
2128 Report.Error (135, Location,
2129 "'{0}' has a different meaning in a " +
2130 "child block", Name);
2135 if (e.Type != null && e.Type.IsPointer && !ec.InUnsafe) {
2144 /// 7.5.2: Simple Names.
2146 /// Local Variables and Parameters are handled at
2147 /// parse time, so they never occur as SimpleNames.
2149 /// The `allow_static' flag is used by MemberAccess only
2150 /// and it is used to inform us that it is ok for us to
2151 /// avoid the static check, because MemberAccess might end
2152 /// up resolving the Name as a Type name and the access as
2153 /// a static type access.
2155 /// ie: Type Type; .... { Type.GetType (""); }
2157 /// Type is both an instance variable and a Type; Type.GetType
2158 /// is the static method not an instance method of type.
2160 Expression DoSimpleNameResolve (EmitContext ec, Expression right_side, bool allow_static, bool intermediate)
2162 Expression e = null;
2165 // Stage 1: Performed by the parser (binding to locals or parameters).
2167 Block current_block = ec.CurrentBlock;
2168 if (current_block != null){
2169 LocalInfo vi = current_block.GetLocalInfo (Name);
2173 var = new LocalVariableReference (ec.CurrentBlock, Name, loc);
2175 if (right_side != null)
2176 return var.ResolveLValue (ec, right_side);
2178 return var.Resolve (ec);
2181 ParameterReference pref = current_block.GetParameterReference (Name, loc);
2183 if (right_side != null)
2184 return pref.ResolveLValue (ec, right_side);
2186 return pref.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.ResolveAsType (ec);
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.
2261 if (!me.IsStatic && (me.InstanceExpression == null))
2265 TypeManager.IsNestedFamilyAccessible (me.InstanceExpression.Type, me.DeclaringType) &&
2266 me.InstanceExpression.Type != me.DeclaringType &&
2267 !TypeManager.IsFamilyAccessible (me.InstanceExpression.Type, me.DeclaringType) &&
2268 (!intermediate || !MemberAccess.IdenticalNameAndTypeName (ec, this, e, loc))) {
2269 Error (38, "Cannot access nonstatic member `" + me.Name + "' of " +
2270 "outer type `" + me.DeclaringType + "' via nested type `" +
2271 me.InstanceExpression.Type + "'");
2275 return (right_side != null)
2276 ? e.DoResolveLValue (ec, right_side)
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 protected abstract TypeExpr DoResolveAsTypeStep (EmitContext ec);
2378 public abstract string Name {
2382 public override bool Equals (object obj)
2384 TypeExpr tobj = obj as TypeExpr;
2388 return Type == tobj.Type;
2391 public override int GetHashCode ()
2393 return Type.GetHashCode ();
2396 public override string ToString ()
2401 bool IAlias.IsType {
2402 get { return true; }
2405 TypeExpr IAlias.ResolveAsType (EmitContext ec)
2407 return ResolveAsTypeTerminal (ec);
2411 public class TypeExpression : TypeExpr, IAlias {
2412 public TypeExpression (Type t, Location l)
2415 eclass = ExprClass.Type;
2419 protected override TypeExpr DoResolveAsTypeStep (EmitContext ec)
2424 public override string Name {
2426 return Type.ToString ();
2430 string IAlias.Name {
2432 return Type.FullName != null ? Type.FullName : Type.Name;
2438 /// Used to create types from a fully qualified name. These are just used
2439 /// by the parser to setup the core types. A TypeLookupExpression is always
2440 /// classified as a type.
2442 public class TypeLookupExpression : TypeExpr {
2445 public TypeLookupExpression (string name)
2450 protected override TypeExpr DoResolveAsTypeStep (EmitContext ec)
2453 type = RootContext.LookupType (
2454 ec.DeclSpace, name, false, Location.Null);
2462 public override string Name {
2470 /// Represents an "unbound generic type", ie. typeof (Foo<>).
2473 public class UnboundTypeExpression : TypeLookupExpression {
2474 public UnboundTypeExpression (string name)
2479 public class TypeAliasExpression : TypeExpr, IAlias {
2485 public TypeAliasExpression (IAlias alias, TypeArguments args, Location l)
2491 eclass = ExprClass.Type;
2493 name = alias.Name + "<" + args.ToString () + ">";
2498 public override string Name {
2499 get { return name; }
2502 protected override TypeExpr DoResolveAsTypeStep (EmitContext ec)
2504 texpr = alias.ResolveAsType (ec);
2508 Type type = texpr.Type;
2509 int num_args = TypeManager.GetNumberOfTypeArguments (type);
2512 if (num_args == 0) {
2513 Report.Error (308, loc,
2514 "The non-generic type `{0}' cannot " +
2515 "be used with type arguments.",
2516 TypeManager.CSharpName (type));
2520 ConstructedType ctype = new ConstructedType (type, args, loc);
2521 return ctype.ResolveAsTypeTerminal (ec);
2522 } else if (num_args > 0) {
2523 Report.Error (305, loc,
2524 "Using the generic type `{0}' " +
2525 "requires {1} type arguments",
2526 TypeManager.GetFullName (type), num_args);
2530 return new TypeExpression (type, loc);
2533 public override bool CheckAccessLevel (DeclSpace ds)
2535 return texpr.CheckAccessLevel (ds);
2538 public override bool AsAccessible (DeclSpace ds, int flags)
2540 return texpr.AsAccessible (ds, flags);
2543 public override bool IsClass {
2544 get { return texpr.IsClass; }
2547 public override bool IsValueType {
2548 get { return texpr.IsValueType; }
2551 public override bool IsInterface {
2552 get { return texpr.IsInterface; }
2555 public override bool IsSealed {
2556 get { return texpr.IsSealed; }
2559 public override bool IsAttribute {
2560 get { return texpr.IsAttribute; }
2565 /// MethodGroup Expression.
2567 /// This is a fully resolved expression that evaluates to a type
2569 public class MethodGroupExpr : Expression, IMemberExpr {
2570 public MethodBase [] Methods;
2571 Expression instance_expression = null;
2572 bool is_explicit_impl = false;
2573 bool has_type_arguments = false;
2574 bool identical_type_name = false;
2577 public MethodGroupExpr (MemberInfo [] mi, Location l)
2579 Methods = new MethodBase [mi.Length];
2580 mi.CopyTo (Methods, 0);
2581 eclass = ExprClass.MethodGroup;
2582 type = TypeManager.object_type;
2586 public MethodGroupExpr (ArrayList list, Location l)
2588 Methods = new MethodBase [list.Count];
2591 list.CopyTo (Methods, 0);
2593 foreach (MemberInfo m in list){
2594 if (!(m is MethodBase)){
2595 Console.WriteLine ("Name " + m.Name);
2596 Console.WriteLine ("Found a: " + m.GetType ().FullName);
2603 eclass = ExprClass.MethodGroup;
2604 type = TypeManager.object_type;
2607 public Type DeclaringType {
2610 // We assume that the top-level type is in the end
2612 return Methods [Methods.Length - 1].DeclaringType;
2613 //return Methods [0].DeclaringType;
2618 // `A method group may have associated an instance expression'
2620 public Expression InstanceExpression {
2622 return instance_expression;
2626 instance_expression = value;
2630 public bool IsExplicitImpl {
2632 return is_explicit_impl;
2636 is_explicit_impl = value;
2640 public bool HasTypeArguments {
2642 return has_type_arguments;
2646 has_type_arguments = value;
2650 public bool IdenticalTypeName {
2652 return identical_type_name;
2656 identical_type_name = value;
2660 public bool IsBase {
2669 public string Name {
2671 //return Methods [0].Name;
2672 return Methods [Methods.Length - 1].Name;
2676 public bool IsInstance {
2678 foreach (MethodBase mb in Methods)
2686 public bool IsStatic {
2688 foreach (MethodBase mb in Methods)
2696 override public Expression DoResolve (EmitContext ec)
2699 instance_expression = null;
2701 if (instance_expression != null) {
2702 instance_expression = instance_expression.DoResolve (ec);
2703 if (instance_expression == null)
2710 public void ReportUsageError ()
2712 Report.Error (654, loc, "Method `" + DeclaringType + "." +
2713 Name + "()' is referenced without parentheses");
2716 override public void Emit (EmitContext ec)
2718 ReportUsageError ();
2721 bool RemoveMethods (bool keep_static)
2723 ArrayList smethods = new ArrayList ();
2725 foreach (MethodBase mb in Methods){
2726 if (mb.IsStatic == keep_static)
2730 if (smethods.Count == 0)
2733 Methods = new MethodBase [smethods.Count];
2734 smethods.CopyTo (Methods, 0);
2740 /// Removes any instance methods from the MethodGroup, returns
2741 /// false if the resulting set is empty.
2743 public bool RemoveInstanceMethods ()
2745 return RemoveMethods (true);
2749 /// Removes any static methods from the MethodGroup, returns
2750 /// false if the resulting set is empty.
2752 public bool RemoveStaticMethods ()
2754 return RemoveMethods (false);
2757 public Expression ResolveGeneric (EmitContext ec, TypeArguments args)
2759 if (args.Resolve (ec) == false)
2762 Type[] atypes = args.Arguments;
2764 int first_count = 0;
2765 MethodInfo first = null;
2767 ArrayList list = new ArrayList ();
2768 foreach (MethodBase mb in Methods) {
2769 MethodInfo mi = mb as MethodInfo;
2770 if ((mi == null) || !mi.HasGenericParameters)
2773 Type[] gen_params = mi.GetGenericArguments ();
2775 if (first == null) {
2777 first_count = gen_params.Length;
2780 if (gen_params.Length != atypes.Length)
2783 list.Add (mi.BindGenericParameters (atypes));
2786 if (list.Count > 0) {
2787 MethodGroupExpr new_mg = new MethodGroupExpr (list, Location);
2788 new_mg.InstanceExpression = InstanceExpression;
2789 new_mg.HasTypeArguments = true;
2795 305, loc, "Using the generic method `{0}' " +
2796 "requires {1} type arguments", Name,
2800 308, loc, "The non-generic method `{0}' " +
2801 "cannot be used with type arguments", Name);
2808 /// Fully resolved expression that evaluates to a Field
2810 public class FieldExpr : Expression, IAssignMethod, IMemoryLocation, IMemberExpr, IVariable {
2811 public readonly FieldInfo FieldInfo;
2812 Expression instance_expr;
2813 VariableInfo variable_info;
2815 LocalTemporary temp;
2817 bool is_field_initializer;
2819 public FieldExpr (FieldInfo fi, Location l)
2822 eclass = ExprClass.Variable;
2823 type = TypeManager.TypeToCoreType (fi.FieldType);
2827 public string Name {
2829 return FieldInfo.Name;
2833 public bool IsInstance {
2835 return !FieldInfo.IsStatic;
2839 public bool IsStatic {
2841 return FieldInfo.IsStatic;
2845 public Type DeclaringType {
2847 return FieldInfo.DeclaringType;
2851 public Expression InstanceExpression {
2853 return instance_expr;
2857 instance_expr = value;
2861 public bool IsFieldInitializer {
2863 return is_field_initializer;
2867 is_field_initializer = value;
2871 public VariableInfo VariableInfo {
2873 return variable_info;
2877 override public Expression DoResolve (EmitContext ec)
2879 if (!FieldInfo.IsStatic){
2880 if (instance_expr == null){
2882 // This can happen when referencing an instance field using
2883 // a fully qualified type expression: TypeName.InstanceField = xxx
2885 SimpleName.Error_ObjectRefRequired (ec, loc, FieldInfo.Name);
2889 // Resolve the field's instance expression while flow analysis is turned
2890 // off: when accessing a field "a.b", we must check whether the field
2891 // "a.b" is initialized, not whether the whole struct "a" is initialized.
2892 instance_expr = instance_expr.Resolve (ec, ResolveFlags.VariableOrValue |
2893 ResolveFlags.DisableFlowAnalysis);
2894 if (instance_expr == null)
2898 ObsoleteAttribute oa;
2899 FieldBase f = TypeManager.GetField (FieldInfo);
2901 oa = f.GetObsoleteAttribute (f.Parent);
2903 AttributeTester.Report_ObsoleteMessage (oa, f.GetSignatureForError (), loc);
2904 // To be sure that type is external because we do not register generated fields
2905 } else if (!(FieldInfo.DeclaringType is TypeBuilder)) {
2906 oa = AttributeTester.GetMemberObsoleteAttribute (FieldInfo);
2908 AttributeTester.Report_ObsoleteMessage (oa, TypeManager.GetFullNameSignature (FieldInfo), loc);
2911 if (ec.CurrentAnonymousMethod != null){
2912 if (!FieldInfo.IsStatic){
2913 if (ec.TypeContainer is Struct){
2914 Report.Error (1673, loc, "Can not reference instance variables in anonymous methods hosted in structs");
2917 ec.CaptureField (this);
2921 // If the instance expression is a local variable or parameter.
2922 IVariable var = instance_expr as IVariable;
2923 if ((var == null) || (var.VariableInfo == null))
2926 VariableInfo vi = var.VariableInfo;
2927 if (!vi.IsFieldAssigned (ec, FieldInfo.Name, loc))
2930 variable_info = vi.GetSubStruct (FieldInfo.Name);
2934 void Report_AssignToReadonly (bool is_instance)
2939 msg = "Readonly field can not be assigned outside " +
2940 "of constructor or variable initializer";
2942 msg = "A static readonly field can only be assigned in " +
2943 "a static constructor";
2945 Report.Error (is_instance ? 191 : 198, loc, msg);
2948 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
2950 IVariable var = instance_expr as IVariable;
2951 if ((var != null) && (var.VariableInfo != null))
2952 var.VariableInfo.SetFieldAssigned (ec, FieldInfo.Name);
2954 Expression e = DoResolve (ec);
2959 if (!FieldInfo.IsStatic && (instance_expr.Type.IsValueType && !(instance_expr is IMemoryLocation))) {
2960 // FIXME: Provide better error reporting.
2961 Error (1612, "Cannot modify expression because it is not a variable.");
2965 if (!FieldInfo.IsInitOnly)
2968 FieldBase fb = TypeManager.GetField (FieldInfo);
2973 // InitOnly fields can only be assigned in constructors
2976 if (ec.IsConstructor){
2977 if (IsStatic && !ec.IsStatic)
2978 Report_AssignToReadonly (false);
2981 if (!is_field_initializer &&
2982 (ec.TypeContainer.CurrentType != null))
2983 ctype = ec.TypeContainer.CurrentType;
2985 ctype = ec.ContainerType;
2987 if (TypeManager.IsEqual (ctype, FieldInfo.DeclaringType))
2991 Report_AssignToReadonly (!IsStatic);
2996 public bool VerifyFixed (bool is_expression)
2998 IVariable variable = instance_expr as IVariable;
2999 if ((variable == null) || !variable.VerifyFixed (true))
3005 public void Emit (EmitContext ec, bool leave_copy)
3007 ILGenerator ig = ec.ig;
3008 bool is_volatile = false;
3010 if (FieldInfo is FieldBuilder){
3011 FieldBase f = TypeManager.GetField (FieldInfo);
3013 if ((f.ModFlags & Modifiers.VOLATILE) != 0)
3016 f.status |= Field.Status.USED;
3020 if (FieldInfo.IsStatic){
3022 ig.Emit (OpCodes.Volatile);
3024 ig.Emit (OpCodes.Ldsfld, FieldInfo);
3030 ig.Emit (OpCodes.Volatile);
3032 ig.Emit (OpCodes.Ldfld, FieldInfo);
3036 ec.ig.Emit (OpCodes.Dup);
3037 if (!FieldInfo.IsStatic) {
3038 temp = new LocalTemporary (ec, this.Type);
3044 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
3046 FieldAttributes fa = FieldInfo.Attributes;
3047 bool is_static = (fa & FieldAttributes.Static) != 0;
3048 bool is_readonly = (fa & FieldAttributes.InitOnly) != 0;
3049 ILGenerator ig = ec.ig;
3050 prepared = prepare_for_load;
3052 if (is_readonly && !ec.IsConstructor){
3053 Report_AssignToReadonly (!is_static);
3059 if (prepare_for_load)
3060 ig.Emit (OpCodes.Dup);
3065 ec.ig.Emit (OpCodes.Dup);
3066 if (!FieldInfo.IsStatic) {
3067 temp = new LocalTemporary (ec, this.Type);
3072 if (FieldInfo is FieldBuilder){
3073 FieldBase f = TypeManager.GetField (FieldInfo);
3075 if ((f.ModFlags & Modifiers.VOLATILE) != 0)
3076 ig.Emit (OpCodes.Volatile);
3078 f.status |= Field.Status.ASSIGNED;
3083 ig.Emit (OpCodes.Stsfld, FieldInfo);
3085 ig.Emit (OpCodes.Stfld, FieldInfo);
3091 void EmitInstance (EmitContext ec)
3093 if (instance_expr.Type.IsValueType) {
3094 if (instance_expr is IMemoryLocation) {
3095 ((IMemoryLocation) instance_expr).AddressOf (ec, AddressOp.LoadStore);
3097 LocalTemporary t = new LocalTemporary (ec, instance_expr.Type);
3098 instance_expr.Emit (ec);
3100 t.AddressOf (ec, AddressOp.Store);
3103 instance_expr.Emit (ec);
3106 public override void Emit (EmitContext ec)
3111 public void AddressOf (EmitContext ec, AddressOp mode)
3113 ILGenerator ig = ec.ig;
3115 if (FieldInfo is FieldBuilder){
3116 FieldBase f = TypeManager.GetField (FieldInfo);
3118 if ((f.ModFlags & Modifiers.VOLATILE) != 0){
3119 Error (676, "volatile variable: can not take its address, or pass as ref/out parameter");
3123 if ((mode & AddressOp.Store) != 0)
3124 f.status |= Field.Status.ASSIGNED;
3125 if ((mode & AddressOp.Load) != 0)
3126 f.status |= Field.Status.USED;
3131 // Handle initonly fields specially: make a copy and then
3132 // get the address of the copy.
3135 if (FieldInfo.IsInitOnly){
3137 if (ec.IsConstructor){
3138 if (FieldInfo.IsStatic){
3150 local = ig.DeclareLocal (type);
3151 ig.Emit (OpCodes.Stloc, local);
3152 ig.Emit (OpCodes.Ldloca, local);
3157 if (FieldInfo.IsStatic){
3158 ig.Emit (OpCodes.Ldsflda, FieldInfo);
3161 ig.Emit (OpCodes.Ldflda, FieldInfo);
3167 // A FieldExpr whose address can not be taken
3169 public class FieldExprNoAddress : FieldExpr, IMemoryLocation {
3170 public FieldExprNoAddress (FieldInfo fi, Location loc) : base (fi, loc)
3174 public new void AddressOf (EmitContext ec, AddressOp mode)
3176 Report.Error (-215, "Report this: Taking the address of a remapped parameter not supported");
3181 /// Expression that evaluates to a Property. The Assign class
3182 /// might set the `Value' expression if we are in an assignment.
3184 /// This is not an LValue because we need to re-write the expression, we
3185 /// can not take data from the stack and store it.
3187 public class PropertyExpr : ExpressionStatement, IAssignMethod, IMemberExpr {
3188 public readonly PropertyInfo PropertyInfo;
3191 // This is set externally by the `BaseAccess' class
3194 MethodInfo getter, setter;
3196 bool must_do_cs1540_check;
3198 Expression instance_expr;
3199 LocalTemporary temp;
3202 public PropertyExpr (EmitContext ec, PropertyInfo pi, Location l)
3205 eclass = ExprClass.PropertyAccess;
3209 type = TypeManager.TypeToCoreType (pi.PropertyType);
3211 ResolveAccessors (ec);
3214 public string Name {
3216 return PropertyInfo.Name;
3220 public bool IsInstance {
3226 public bool IsStatic {
3232 public Type DeclaringType {
3234 return PropertyInfo.DeclaringType;
3239 // The instance expression associated with this expression
3241 public Expression InstanceExpression {
3243 instance_expr = value;
3247 return instance_expr;
3251 public bool VerifyAssignable ()
3253 if (setter == null) {
3254 Report.Error (200, loc,
3255 "The property `" + PropertyInfo.Name +
3256 "' can not be assigned to, as it has not set accessor");
3263 void FindAccessors (Type invocation_type)
3265 BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic |
3266 BindingFlags.Static | BindingFlags.Instance |
3267 BindingFlags.DeclaredOnly;
3269 Type current = PropertyInfo.DeclaringType;
3270 for (; current != null; current = current.BaseType) {
3271 MemberInfo[] group = TypeManager.MemberLookup (
3272 invocation_type, invocation_type, current,
3273 MemberTypes.Property, flags, PropertyInfo.Name, null);
3278 if (group.Length != 1)
3279 // Oooops, can this ever happen ?
3282 PropertyInfo pi = (PropertyInfo) group [0];
3285 getter = pi.GetGetMethod (true);;
3288 setter = pi.GetSetMethod (true);;
3290 MethodInfo accessor = getter != null ? getter : setter;
3292 if (!accessor.IsVirtual)
3297 bool IsAccessorAccessible (Type invocation_type, MethodInfo mi)
3299 MethodAttributes ma = mi.Attributes & MethodAttributes.MemberAccessMask;
3302 // If only accessible to the current class or children
3304 if (ma == MethodAttributes.Private) {
3305 Type declaring_type = mi.DeclaringType;
3307 if (invocation_type != declaring_type)
3308 return TypeManager.IsNestedFamilyAccessible (invocation_type, declaring_type);
3313 // FamAndAssem requires that we not only derivate, but we are on the
3316 if (ma == MethodAttributes.FamANDAssem){
3317 return (mi.DeclaringType.Assembly != invocation_type.Assembly);
3320 // Assembly and FamORAssem succeed if we're in the same assembly.
3321 if ((ma == MethodAttributes.Assembly) || (ma == MethodAttributes.FamORAssem)){
3322 if (mi.DeclaringType.Assembly == invocation_type.Assembly)
3326 // We already know that we aren't in the same assembly.
3327 if (ma == MethodAttributes.Assembly)
3330 // Family and FamANDAssem require that we derive.
3331 if ((ma == MethodAttributes.Family) || (ma == MethodAttributes.FamANDAssem) || (ma == MethodAttributes.FamORAssem)){
3332 if (!TypeManager.IsNestedFamilyAccessible (invocation_type, mi.DeclaringType))
3335 if (!TypeManager.IsNestedChildOf (invocation_type, mi.DeclaringType))
3336 must_do_cs1540_check = true;
3346 // We also perform the permission checking here, as the PropertyInfo does not
3347 // hold the information for the accessibility of its setter/getter
3349 void ResolveAccessors (EmitContext ec)
3351 FindAccessors (ec.ContainerType);
3353 is_static = getter != null ? getter.IsStatic : setter.IsStatic;
3356 bool InstanceResolve (EmitContext ec)
3358 if ((instance_expr == null) && ec.IsStatic && !is_static) {
3359 SimpleName.Error_ObjectRefRequired (ec, loc, PropertyInfo.Name);
3363 if (instance_expr != null) {
3364 instance_expr = instance_expr.DoResolve (ec);
3365 if (instance_expr == null)
3369 if (must_do_cs1540_check && (instance_expr != null)) {
3370 if ((instance_expr.Type != ec.ContainerType) &&
3371 ec.ContainerType.IsSubclassOf (instance_expr.Type)) {
3372 Report.Error (1540, loc, "Cannot access protected member `" +
3373 PropertyInfo.DeclaringType + "." + PropertyInfo.Name +
3374 "' via a qualifier of type `" +
3375 TypeManager.CSharpName (instance_expr.Type) +
3376 "'; the qualifier must be of type `" +
3377 TypeManager.CSharpName (ec.ContainerType) +
3378 "' (or derived from it)");
3386 override public Expression DoResolve (EmitContext ec)
3388 if (getter != null){
3389 if (TypeManager.GetArgumentTypes (getter).Length != 0){
3391 117, loc, "`{0}' does not contain a " +
3392 "definition for `{1}'.", getter.DeclaringType,
3398 if (getter == null){
3400 // The following condition happens if the PropertyExpr was
3401 // created, but is invalid (ie, the property is inaccessible),
3402 // and we did not want to embed the knowledge about this in
3403 // the caller routine. This only avoids double error reporting.
3408 Report.Error (154, loc,
3409 "The property `" + PropertyInfo.Name +
3410 "' can not be used in " +
3411 "this context because it lacks a get accessor");
3415 if (!IsAccessorAccessible (ec.ContainerType, getter)) {
3416 Report.Error (122, loc, "'{0}.get' is inaccessible due to its protection level", PropertyInfo.Name);
3420 if (!InstanceResolve (ec))
3424 // Only base will allow this invocation to happen.
3426 if (IsBase && getter.IsAbstract){
3427 Report.Error (205, loc, "Cannot call an abstract base property: " +
3428 PropertyInfo.DeclaringType + "." +PropertyInfo.Name);
3435 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
3437 if (setter == null){
3439 // The following condition happens if the PropertyExpr was
3440 // created, but is invalid (ie, the property is inaccessible),
3441 // and we did not want to embed the knowledge about this in
3442 // the caller routine. This only avoids double error reporting.
3447 Report.Error (154, loc,
3448 "The property `" + PropertyInfo.Name +
3449 "' can not be used in " +
3450 "this context because it lacks a set accessor");
3454 if (TypeManager.GetArgumentTypes (setter).Length != 1){
3456 117, loc, "`{0}' does not contain a " +
3457 "definition for `{1}'.", getter.DeclaringType,
3462 if (!IsAccessorAccessible (ec.ContainerType, setter)) {
3463 Report.Error (122, loc, "'{0}.set' is inaccessible due to its protection level", PropertyInfo.Name);
3467 if (!InstanceResolve (ec))
3471 // Only base will allow this invocation to happen.
3473 if (IsBase && setter.IsAbstract){
3474 Report.Error (205, loc, "Cannot call an abstract base property: " +
3475 PropertyInfo.DeclaringType + "." +PropertyInfo.Name);
3480 // Check that we are not making changes to a temporary memory location
3482 if (instance_expr != null && instance_expr.Type.IsValueType && !(instance_expr is IMemoryLocation)) {
3483 // FIXME: Provide better error reporting.
3484 Error (1612, "Cannot modify expression because it is not a variable.");
3493 public override void Emit (EmitContext ec)
3498 void EmitInstance (EmitContext ec)
3503 if (instance_expr.Type.IsValueType) {
3504 if (instance_expr is IMemoryLocation) {
3505 ((IMemoryLocation) instance_expr).AddressOf (ec, AddressOp.LoadStore);
3507 LocalTemporary t = new LocalTemporary (ec, instance_expr.Type);
3508 instance_expr.Emit (ec);
3510 t.AddressOf (ec, AddressOp.Store);
3513 instance_expr.Emit (ec);
3516 ec.ig.Emit (OpCodes.Dup);
3520 public void Emit (EmitContext ec, bool leave_copy)
3526 // Special case: length of single dimension array property is turned into ldlen
3528 if ((getter == TypeManager.system_int_array_get_length) ||
3529 (getter == TypeManager.int_array_get_length)){
3530 Type iet = instance_expr.Type;
3533 // System.Array.Length can be called, but the Type does not
3534 // support invoking GetArrayRank, so test for that case first
3536 if (iet != TypeManager.array_type && (iet.GetArrayRank () == 1)) {
3537 ec.ig.Emit (OpCodes.Ldlen);
3538 ec.ig.Emit (OpCodes.Conv_I4);
3543 Invocation.EmitCall (ec, IsBase, IsStatic, new EmptyAddressOf (), getter, null, loc);
3548 ec.ig.Emit (OpCodes.Dup);
3550 temp = new LocalTemporary (ec, this.Type);
3556 // Implements the IAssignMethod interface for assignments
3558 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
3560 prepared = prepare_for_load;
3566 ec.ig.Emit (OpCodes.Dup);
3568 temp = new LocalTemporary (ec, this.Type);
3573 ArrayList args = new ArrayList (1);
3574 args.Add (new Argument (new EmptyAddressOf (), Argument.AType.Expression));
3576 Invocation.EmitCall (ec, IsBase, IsStatic, new EmptyAddressOf (), setter, args, loc);
3582 override public void EmitStatement (EmitContext ec)
3585 ec.ig.Emit (OpCodes.Pop);
3590 /// Fully resolved expression that evaluates to an Event
3592 public class EventExpr : Expression, IMemberExpr {
3593 public readonly EventInfo EventInfo;
3594 Expression instance_expr;
3597 MethodInfo add_accessor, remove_accessor;
3599 public EventExpr (EventInfo ei, Location loc)
3603 eclass = ExprClass.EventAccess;
3605 add_accessor = TypeManager.GetAddMethod (ei);
3606 remove_accessor = TypeManager.GetRemoveMethod (ei);
3608 if (add_accessor.IsStatic || remove_accessor.IsStatic)
3611 if (EventInfo is MyEventBuilder){
3612 MyEventBuilder eb = (MyEventBuilder) EventInfo;
3613 type = eb.EventType;
3616 type = EventInfo.EventHandlerType;
3619 public string Name {
3621 return EventInfo.Name;
3625 public bool IsInstance {
3631 public bool IsStatic {
3637 public Type DeclaringType {
3639 return EventInfo.DeclaringType;
3643 public Expression InstanceExpression {
3645 return instance_expr;
3649 instance_expr = value;
3653 public override Expression DoResolve (EmitContext ec)
3655 if (instance_expr != null) {
3656 instance_expr = instance_expr.DoResolve (ec);
3657 if (instance_expr == null)
3665 public override void Emit (EmitContext ec)
3667 Report.Error (70, loc, "The event `" + Name + "' can only appear on the left hand side of += or -= (except on the defining type)");
3670 public void EmitAddOrRemove (EmitContext ec, Expression source)
3672 BinaryDelegate source_del = (BinaryDelegate) source;
3673 Expression handler = source_del.Right;
3675 Argument arg = new Argument (handler, Argument.AType.Expression);
3676 ArrayList args = new ArrayList ();
3680 if (source_del.IsAddition)
3681 Invocation.EmitCall (
3682 ec, false, IsStatic, instance_expr, add_accessor, args, loc);
3684 Invocation.EmitCall (
3685 ec, false, IsStatic, instance_expr, remove_accessor, args, loc);