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 {
118 /// This interface is implemented by variables
120 public interface IVariable {
121 VariableInfo VariableInfo {
125 bool VerifyFixed (bool is_expression);
129 /// This interface denotes an expression which evaluates to a member
130 /// of a struct or a class.
132 public interface IMemberExpr
135 /// The name of this member.
142 /// Whether this is an instance member.
149 /// Whether this is a static member.
156 /// The type which declares this member.
163 /// The instance expression associated with this member, if it's a
164 /// non-static member.
166 Expression InstanceExpression {
172 /// Base class for expressions
174 public abstract class Expression {
175 public ExprClass eclass;
177 protected Location loc;
189 public Location Location {
196 /// Utility wrapper routine for Error, just to beautify the code
198 public void Error (int error, string s)
200 if (!Location.IsNull (loc))
201 Report.Error (error, loc, s);
203 Report.Error (error, s);
207 /// Utility wrapper routine for Warning, just to beautify the code
209 public void Warning (int code, string format, params object[] args)
211 Report.Warning (code, loc, format, args);
215 /// Tests presence of ObsoleteAttribute and report proper error
217 protected void CheckObsoleteAttribute (Type type)
219 ObsoleteAttribute obsolete_attr = AttributeTester.GetObsoleteAttribute (type);
220 if (obsolete_attr == null)
223 AttributeTester.Report_ObsoleteMessage (obsolete_attr, type.FullName, loc);
227 /// Performs semantic analysis on the Expression
231 /// The Resolve method is invoked to perform the semantic analysis
234 /// The return value is an expression (it can be the
235 /// same expression in some cases) or a new
236 /// expression that better represents this node.
238 /// For example, optimizations of Unary (LiteralInt)
239 /// would return a new LiteralInt with a negated
242 /// If there is an error during semantic analysis,
243 /// then an error should be reported (using Report)
244 /// and a null value should be returned.
246 /// There are two side effects expected from calling
247 /// Resolve(): the the field variable "eclass" should
248 /// be set to any value of the enumeration
249 /// `ExprClass' and the type variable should be set
250 /// to a valid type (this is the type of the
253 public abstract Expression DoResolve (EmitContext ec);
255 public virtual Expression DoResolveLValue (EmitContext ec, Expression right_side)
257 return DoResolve (ec);
261 // This is used if the expression should be resolved as a type.
262 // the default implementation fails. Use this method in
263 // those participants in the SimpleName chain system.
265 public virtual Expression ResolveAsTypeStep (EmitContext ec)
271 // This is used to resolve the expression as a type, a null
272 // value will be returned if the expression is not a type
275 public TypeExpr ResolveAsTypeTerminal (EmitContext ec)
277 return ResolveAsTypeStep (ec) as TypeExpr;
281 /// Resolves an expression and performs semantic analysis on it.
285 /// Currently Resolve wraps DoResolve to perform sanity
286 /// checking and assertion checking on what we expect from Resolve.
288 public Expression Resolve (EmitContext ec, ResolveFlags flags)
290 if ((flags & ResolveFlags.MaskExprClass) == ResolveFlags.Type)
291 return ResolveAsTypeStep (ec);
293 bool old_do_flow_analysis = ec.DoFlowAnalysis;
294 if ((flags & ResolveFlags.DisableFlowAnalysis) != 0)
295 ec.DoFlowAnalysis = false;
298 bool intermediate = (flags & ResolveFlags.Intermediate) == ResolveFlags.Intermediate;
299 if (this is SimpleName)
300 e = ((SimpleName) this).DoResolveAllowStatic (ec, intermediate);
305 ec.DoFlowAnalysis = old_do_flow_analysis;
310 if (e is SimpleName){
311 SimpleName s = (SimpleName) e;
313 if ((flags & ResolveFlags.SimpleName) == 0) {
314 MemberLookupFailed (ec, null, ec.ContainerType, s.Name,
315 ec.DeclSpace.Name, loc);
322 if ((e is TypeExpr) || (e is ComposedCast)) {
323 if ((flags & ResolveFlags.Type) == 0) {
324 e.Error_UnexpectedKind (flags);
333 if ((flags & ResolveFlags.VariableOrValue) == 0) {
334 e.Error_UnexpectedKind (flags);
339 case ExprClass.MethodGroup:
340 if (!RootContext.V2){
341 if ((flags & ResolveFlags.MethodGroup) == 0) {
342 ((MethodGroupExpr) e).ReportUsageError ();
348 case ExprClass.Value:
349 case ExprClass.Variable:
350 case ExprClass.PropertyAccess:
351 case ExprClass.EventAccess:
352 case ExprClass.IndexerAccess:
353 if ((flags & ResolveFlags.VariableOrValue) == 0) {
354 Console.WriteLine ("I got: {0} and {1}", e.GetType (), e);
355 Console.WriteLine ("I am {0} and {1}", this.GetType (), this);
356 FieldInfo fi = ((FieldExpr) e).FieldInfo;
358 Console.WriteLine ("{0} and {1}", fi.DeclaringType, fi.Name);
359 e.Error_UnexpectedKind (flags);
365 throw new Exception ("Expression " + e.GetType () +
366 " ExprClass is Invalid after resolve");
370 throw new Exception (
371 "Expression " + e.GetType () +
372 " did not set its type after Resolve\n" +
373 "called from: " + this.GetType ());
379 /// Resolves an expression and performs semantic analysis on it.
381 public Expression Resolve (EmitContext ec)
383 return Resolve (ec, ResolveFlags.VariableOrValue);
387 /// Resolves an expression for LValue assignment
391 /// Currently ResolveLValue wraps DoResolveLValue to perform sanity
392 /// checking and assertion checking on what we expect from Resolve
394 public Expression ResolveLValue (EmitContext ec, Expression right_side)
396 Expression e = DoResolveLValue (ec, right_side);
399 if (e is SimpleName){
400 SimpleName s = (SimpleName) e;
401 MemberLookupFailed (ec, null, ec.ContainerType, s.Name,
402 ec.DeclSpace.Name, loc);
406 if (e.eclass == ExprClass.Invalid)
407 throw new Exception ("Expression " + e +
408 " ExprClass is Invalid after resolve");
410 if (e.eclass == ExprClass.MethodGroup) {
411 ((MethodGroupExpr) e).ReportUsageError ();
415 if ((e.type == null) && !(e is ConstructedType))
416 throw new Exception ("Expression " + e +
417 " did not set its type after Resolve");
424 /// Emits the code for the expression
428 /// The Emit method is invoked to generate the code
429 /// for the expression.
431 public abstract void Emit (EmitContext ec);
433 public virtual void EmitBranchable (EmitContext ec, Label target, bool onTrue)
436 ec.ig.Emit (onTrue ? OpCodes.Brtrue : OpCodes.Brfalse, target);
440 /// Protected constructor. Only derivate types should
441 /// be able to be created
444 protected Expression ()
446 eclass = ExprClass.Invalid;
451 /// Returns a literalized version of a literal FieldInfo
455 /// The possible return values are:
456 /// IntConstant, UIntConstant
457 /// LongLiteral, ULongConstant
458 /// FloatConstant, DoubleConstant
461 /// The value returned is already resolved.
463 public static Constant Constantify (object v, Type t)
465 if (t == TypeManager.int32_type)
466 return new IntConstant ((int) v);
467 else if (t == TypeManager.uint32_type)
468 return new UIntConstant ((uint) v);
469 else if (t == TypeManager.int64_type)
470 return new LongConstant ((long) v);
471 else if (t == TypeManager.uint64_type)
472 return new ULongConstant ((ulong) v);
473 else if (t == TypeManager.float_type)
474 return new FloatConstant ((float) v);
475 else if (t == TypeManager.double_type)
476 return new DoubleConstant ((double) v);
477 else if (t == TypeManager.string_type)
478 return new StringConstant ((string) v);
479 else if (t == TypeManager.short_type)
480 return new ShortConstant ((short)v);
481 else if (t == TypeManager.ushort_type)
482 return new UShortConstant ((ushort)v);
483 else if (t == TypeManager.sbyte_type)
484 return new SByteConstant (((sbyte)v));
485 else if (t == TypeManager.byte_type)
486 return new ByteConstant ((byte)v);
487 else if (t == TypeManager.char_type)
488 return new CharConstant ((char)v);
489 else if (t == TypeManager.bool_type)
490 return new BoolConstant ((bool) v);
491 else if (TypeManager.IsEnumType (t)){
492 Type real_type = TypeManager.TypeToCoreType (v.GetType ());
494 real_type = real_type.UnderlyingSystemType;
496 Constant e = Constantify (v, real_type);
498 return new EnumConstant (e, t);
500 throw new Exception ("Unknown type for constant (" + t +
505 /// Returns a fully formed expression after a MemberLookup
507 public static Expression ExprClassFromMemberInfo (EmitContext ec, MemberInfo mi, Location loc)
510 return new EventExpr ((EventInfo) mi, loc);
511 else if (mi is FieldInfo)
512 return new FieldExpr ((FieldInfo) mi, loc);
513 else if (mi is PropertyInfo)
514 return new PropertyExpr (ec, (PropertyInfo) mi, loc);
515 else if (mi is Type){
516 return new TypeExpression ((System.Type) mi, loc);
523 private static ArrayList almostMatchedMembers = new ArrayList (4);
526 // FIXME: Probably implement a cache for (t,name,current_access_set)?
528 // This code could use some optimizations, but we need to do some
529 // measurements. For example, we could use a delegate to `flag' when
530 // something can not any longer be a method-group (because it is something
534 // If the return value is an Array, then it is an array of
537 // If the return value is an MemberInfo, it is anything, but a Method
541 // FIXME: When calling MemberLookup inside an `Invocation', we should pass
542 // the arguments here and have MemberLookup return only the methods that
543 // match the argument count/type, unlike we are doing now (we delay this
546 // This is so we can catch correctly attempts to invoke instance methods
547 // from a static body (scan for error 120 in ResolveSimpleName).
550 // FIXME: Potential optimization, have a static ArrayList
553 public static Expression MemberLookup (EmitContext ec, Type queried_type, string name,
554 MemberTypes mt, BindingFlags bf, Location loc)
556 return MemberLookup (ec, ec.ContainerType, null, queried_type, name, mt, bf, loc);
560 // Lookup type `queried_type' for code in class `container_type' with a qualifier of
561 // `qualifier_type' or null to lookup members in the current class.
564 public static Expression MemberLookup (EmitContext ec, Type container_type,
565 Type qualifier_type, Type queried_type,
566 string name, MemberTypes mt,
567 BindingFlags bf, Location loc)
569 almostMatchedMembers.Clear ();
571 MemberInfo [] mi = TypeManager.MemberLookup (
572 container_type, qualifier_type,queried_type, mt, bf, name,
573 almostMatchedMembers);
578 int count = mi.Length;
580 if (mi [0] is MethodBase)
581 return new MethodGroupExpr (mi, loc);
586 return ExprClassFromMemberInfo (ec, mi [0], loc);
589 public const MemberTypes AllMemberTypes =
590 MemberTypes.Constructor |
594 MemberTypes.NestedType |
595 MemberTypes.Property;
597 public const BindingFlags AllBindingFlags =
598 BindingFlags.Public |
599 BindingFlags.Static |
600 BindingFlags.Instance;
602 public static Expression MemberLookup (EmitContext ec, Type queried_type,
603 string name, Location loc)
605 return MemberLookup (ec, ec.ContainerType, null, queried_type, name,
606 AllMemberTypes, AllBindingFlags, loc);
609 public static Expression MemberLookup (EmitContext ec, Type qualifier_type,
610 Type queried_type, string name, Location loc)
612 return MemberLookup (ec, ec.ContainerType, qualifier_type, queried_type,
613 name, AllMemberTypes, AllBindingFlags, loc);
616 public static Expression MethodLookup (EmitContext ec, Type queried_type,
617 string name, Location loc)
619 return MemberLookup (ec, ec.ContainerType, null, queried_type, name,
620 MemberTypes.Method, AllBindingFlags, loc);
624 /// This is a wrapper for MemberLookup that is not used to "probe", but
625 /// to find a final definition. If the final definition is not found, we
626 /// look for private members and display a useful debugging message if we
629 public static Expression MemberLookupFinal (EmitContext ec, Type qualifier_type,
630 Type queried_type, string name,
633 return MemberLookupFinal (ec, qualifier_type, queried_type, name,
634 AllMemberTypes, AllBindingFlags, loc);
637 public static Expression MemberLookupFinal (EmitContext ec, Type qualifier_type,
638 Type queried_type, string name,
639 MemberTypes mt, BindingFlags bf,
644 int errors = Report.Errors;
646 e = MemberLookup (ec, ec.ContainerType, qualifier_type, queried_type,
649 if (e == null && errors == Report.Errors)
650 // No errors were reported by MemberLookup, but there was an error.
651 MemberLookupFailed (ec, qualifier_type, queried_type, name,
657 public static void MemberLookupFailed (EmitContext ec, Type qualifier_type,
658 Type queried_type, string name,
659 string class_name, Location loc)
661 if (almostMatchedMembers.Count != 0) {
662 if (qualifier_type == null) {
663 foreach (MemberInfo m in almostMatchedMembers)
664 Report.Error (38, loc,
665 "Cannot access non-static member `{0}' via nested type `{1}'",
666 TypeManager.GetFullNameSignature (m),
667 TypeManager.CSharpName (ec.ContainerType));
672 if (qualifier_type != ec.ContainerType) {
673 // Although a derived class can access protected members of
674 // its base class it cannot do so through an instance of the
675 // base class (CS1540). If the qualifier_type is a parent of the
676 // ec.ContainerType and the lookup succeeds with the latter one,
677 // then we are in this situation.
678 foreach (MemberInfo m in almostMatchedMembers)
679 Report.Error (1540, loc,
680 "Cannot access protected member `{0}' via a qualifier of type `{1}';"
681 + " the qualifier must be of type `{2}' (or derived from it)",
682 TypeManager.GetFullNameSignature (m),
683 TypeManager.CSharpName (qualifier_type),
684 TypeManager.CSharpName (ec.ContainerType));
687 almostMatchedMembers.Clear ();
690 MemberInfo[] mi = TypeManager.MemberLookup (queried_type, null, queried_type,
691 AllMemberTypes, AllBindingFlags |
692 BindingFlags.NonPublic, name, null);
695 if (class_name != null)
696 Report.Error (103, loc, "The name `" + name + "' could not be " +
697 "found in `" + class_name + "'");
700 117, loc, "`" + queried_type + "' does not contain a " +
701 "definition for `" + name + "'");
705 if (TypeManager.MemberLookup (queried_type, null, queried_type,
706 AllMemberTypes, AllBindingFlags |
707 BindingFlags.NonPublic, name, null) == null) {
708 if ((mi.Length == 1) && (mi [0] is Type)) {
709 Type t = (Type) mi [0];
711 Report.Error (305, loc,
712 "Using the generic type `{0}' " +
713 "requires {1} type arguments",
714 TypeManager.GetFullName (t),
715 TypeManager.GetNumberOfTypeArguments (t));
722 if (qualifier_type != null)
723 Report.Error (122, loc, "'{0}' is inaccessible due to its protection level", TypeManager.CSharpName (qualifier_type) + "." + name);
724 else if (name == ".ctor") {
725 Report.Error (143, loc, String.Format ("The type {0} has no constructors defined",
726 TypeManager.CSharpName (queried_type)));
728 Report.Error (122, loc, "'{0}' is inaccessible due to its protection level", name);
732 static public MemberInfo GetFieldFromEvent (EventExpr event_expr)
734 EventInfo ei = event_expr.EventInfo;
736 return TypeManager.GetPrivateFieldOfEvent (ei);
740 /// Returns an expression that can be used to invoke operator true
741 /// on the expression if it exists.
743 static public StaticCallExpr GetOperatorTrue (EmitContext ec, Expression e, Location loc)
745 return GetOperatorTrueOrFalse (ec, e, true, loc);
749 /// Returns an expression that can be used to invoke operator false
750 /// on the expression if it exists.
752 static public StaticCallExpr GetOperatorFalse (EmitContext ec, Expression e, Location loc)
754 return GetOperatorTrueOrFalse (ec, e, false, loc);
757 static StaticCallExpr GetOperatorTrueOrFalse (EmitContext ec, Expression e, bool is_true, Location loc)
760 Expression operator_group;
762 operator_group = MethodLookup (ec, e.Type, is_true ? "op_True" : "op_False", loc);
763 if (operator_group == null)
766 ArrayList arguments = new ArrayList ();
767 arguments.Add (new Argument (e, Argument.AType.Expression));
768 method = Invocation.OverloadResolve (
769 ec, (MethodGroupExpr) operator_group, arguments, false, loc);
774 return new StaticCallExpr ((MethodInfo) method, arguments, loc);
778 /// Resolves the expression `e' into a boolean expression: either through
779 /// an implicit conversion, or through an `operator true' invocation
781 public static Expression ResolveBoolean (EmitContext ec, Expression e, Location loc)
787 Expression converted = e;
788 if (e.Type != TypeManager.bool_type)
789 converted = Convert.ImplicitConversion (ec, e, TypeManager.bool_type, new Location (-1));
792 // If no implicit conversion to bool exists, try using `operator true'
794 if (converted == null){
795 Expression operator_true = Expression.GetOperatorTrue (ec, e, loc);
796 if (operator_true == null){
798 31, loc, "Can not convert the expression to a boolean");
808 static string ExprClassName (ExprClass c)
811 case ExprClass.Invalid:
813 case ExprClass.Value:
815 case ExprClass.Variable:
817 case ExprClass.Namespace:
821 case ExprClass.MethodGroup:
822 return "method group";
823 case ExprClass.PropertyAccess:
824 return "property access";
825 case ExprClass.EventAccess:
826 return "event access";
827 case ExprClass.IndexerAccess:
828 return "indexer access";
829 case ExprClass.Nothing:
832 throw new Exception ("Should not happen");
836 /// Reports that we were expecting `expr' to be of class `expected'
838 public void Error_UnexpectedKind (string expected)
840 string kind = "Unknown";
842 kind = ExprClassName (eclass);
844 Error (118, "Expression denotes a `" + kind +
845 "' where a `" + expected + "' was expected");
848 public void Error_UnexpectedKind (ResolveFlags flags)
850 ArrayList valid = new ArrayList (10);
852 if ((flags & ResolveFlags.VariableOrValue) != 0) {
853 valid.Add ("variable");
857 if ((flags & ResolveFlags.Type) != 0)
860 if ((flags & ResolveFlags.MethodGroup) != 0)
861 valid.Add ("method group");
863 if ((flags & ResolveFlags.SimpleName) != 0)
864 valid.Add ("simple name");
866 if (valid.Count == 0)
867 valid.Add ("unknown");
869 StringBuilder sb = new StringBuilder ();
870 for (int i = 0; i < valid.Count; i++) {
873 else if (i == valid.Count)
875 sb.Append (valid [i]);
878 string kind = ExprClassName (eclass);
880 Error (119, "Expression denotes a `" + kind + "' where " +
881 "a `" + sb.ToString () + "' was expected");
884 static public void Error_ConstantValueCannotBeConverted (Location l, string val, Type t)
886 Report.Error (31, l, "Constant value `" + val + "' cannot be converted to " +
887 TypeManager.CSharpName (t));
890 public static void UnsafeError (Location loc)
892 Report.Error (214, loc, "Pointers may only be used in an unsafe context");
896 /// Converts the IntConstant, UIntConstant, LongConstant or
897 /// ULongConstant into the integral target_type. Notice
898 /// that we do not return an `Expression' we do return
899 /// a boxed integral type.
901 /// FIXME: Since I added the new constants, we need to
902 /// also support conversions from CharConstant, ByteConstant,
903 /// SByteConstant, UShortConstant, ShortConstant
905 /// This is used by the switch statement, so the domain
906 /// of work is restricted to the literals above, and the
907 /// targets are int32, uint32, char, byte, sbyte, ushort,
908 /// short, uint64 and int64
910 public static object ConvertIntLiteral (Constant c, Type target_type, Location loc)
912 if (!Convert.ImplicitStandardConversionExists (c, target_type)){
913 Convert.Error_CannotImplicitConversion (loc, c.Type, target_type);
919 if (c.Type == target_type)
920 return ((Constant) c).GetValue ();
923 // Make into one of the literals we handle, we dont really care
924 // about this value as we will just return a few limited types
926 if (c is EnumConstant)
927 c = ((EnumConstant)c).WidenToCompilerConstant ();
929 if (c is IntConstant){
930 int v = ((IntConstant) c).Value;
932 if (target_type == TypeManager.uint32_type){
935 } else if (target_type == TypeManager.char_type){
936 if (v >= Char.MinValue && v <= Char.MaxValue)
938 } else if (target_type == TypeManager.byte_type){
939 if (v >= Byte.MinValue && v <= Byte.MaxValue)
941 } else if (target_type == TypeManager.sbyte_type){
942 if (v >= SByte.MinValue && v <= SByte.MaxValue)
944 } else if (target_type == TypeManager.short_type){
945 if (v >= Int16.MinValue && v <= UInt16.MaxValue)
947 } else if (target_type == TypeManager.ushort_type){
948 if (v >= UInt16.MinValue && v <= UInt16.MaxValue)
950 } else if (target_type == TypeManager.int64_type)
952 else if (target_type == TypeManager.uint64_type){
958 } else if (c is UIntConstant){
959 uint v = ((UIntConstant) c).Value;
961 if (target_type == TypeManager.int32_type){
962 if (v <= Int32.MaxValue)
964 } else if (target_type == TypeManager.char_type){
965 if (v >= Char.MinValue && v <= Char.MaxValue)
967 } else if (target_type == TypeManager.byte_type){
968 if (v <= Byte.MaxValue)
970 } else if (target_type == TypeManager.sbyte_type){
971 if (v <= SByte.MaxValue)
973 } else if (target_type == TypeManager.short_type){
974 if (v <= UInt16.MaxValue)
976 } else if (target_type == TypeManager.ushort_type){
977 if (v <= UInt16.MaxValue)
979 } else if (target_type == TypeManager.int64_type)
981 else if (target_type == TypeManager.uint64_type)
984 } else if (c is LongConstant){
985 long v = ((LongConstant) c).Value;
987 if (target_type == TypeManager.int32_type){
988 if (v >= UInt32.MinValue && v <= UInt32.MaxValue)
990 } else if (target_type == TypeManager.uint32_type){
991 if (v >= 0 && v <= UInt32.MaxValue)
993 } else if (target_type == TypeManager.char_type){
994 if (v >= Char.MinValue && v <= Char.MaxValue)
996 } else if (target_type == TypeManager.byte_type){
997 if (v >= Byte.MinValue && v <= Byte.MaxValue)
999 } else if (target_type == TypeManager.sbyte_type){
1000 if (v >= SByte.MinValue && v <= SByte.MaxValue)
1002 } else if (target_type == TypeManager.short_type){
1003 if (v >= Int16.MinValue && v <= UInt16.MaxValue)
1005 } else if (target_type == TypeManager.ushort_type){
1006 if (v >= UInt16.MinValue && v <= UInt16.MaxValue)
1008 } else if (target_type == TypeManager.uint64_type){
1013 } else if (c is ULongConstant){
1014 ulong v = ((ULongConstant) c).Value;
1016 if (target_type == TypeManager.int32_type){
1017 if (v <= Int32.MaxValue)
1019 } else if (target_type == TypeManager.uint32_type){
1020 if (v <= UInt32.MaxValue)
1022 } else if (target_type == TypeManager.char_type){
1023 if (v >= Char.MinValue && v <= Char.MaxValue)
1025 } else if (target_type == TypeManager.byte_type){
1026 if (v >= Byte.MinValue && v <= Byte.MaxValue)
1028 } else if (target_type == TypeManager.sbyte_type){
1029 if (v <= (int) SByte.MaxValue)
1031 } else if (target_type == TypeManager.short_type){
1032 if (v <= UInt16.MaxValue)
1034 } else if (target_type == TypeManager.ushort_type){
1035 if (v <= UInt16.MaxValue)
1037 } else if (target_type == TypeManager.int64_type){
1038 if (v <= Int64.MaxValue)
1042 } else if (c is ByteConstant){
1043 byte v = ((ByteConstant) c).Value;
1045 if (target_type == TypeManager.int32_type)
1047 else if (target_type == TypeManager.uint32_type)
1049 else if (target_type == TypeManager.char_type)
1051 else if (target_type == TypeManager.sbyte_type){
1052 if (v <= SByte.MaxValue)
1054 } else if (target_type == TypeManager.short_type)
1056 else if (target_type == TypeManager.ushort_type)
1058 else if (target_type == TypeManager.int64_type)
1060 else if (target_type == TypeManager.uint64_type)
1063 } else if (c is SByteConstant){
1064 sbyte v = ((SByteConstant) c).Value;
1066 if (target_type == TypeManager.int32_type)
1068 else if (target_type == TypeManager.uint32_type){
1071 } else if (target_type == TypeManager.char_type){
1074 } else if (target_type == TypeManager.byte_type){
1077 } else if (target_type == TypeManager.short_type)
1079 else if (target_type == TypeManager.ushort_type){
1082 } else if (target_type == TypeManager.int64_type)
1084 else if (target_type == TypeManager.uint64_type){
1089 } else if (c is ShortConstant){
1090 short v = ((ShortConstant) c).Value;
1092 if (target_type == TypeManager.int32_type){
1094 } else if (target_type == TypeManager.uint32_type){
1097 } else if (target_type == TypeManager.char_type){
1100 } else if (target_type == TypeManager.byte_type){
1101 if (v >= Byte.MinValue && v <= Byte.MaxValue)
1103 } else if (target_type == TypeManager.sbyte_type){
1104 if (v >= SByte.MinValue && v <= SByte.MaxValue)
1106 } else if (target_type == TypeManager.ushort_type){
1109 } else if (target_type == TypeManager.int64_type)
1111 else if (target_type == TypeManager.uint64_type)
1115 } else if (c is UShortConstant){
1116 ushort v = ((UShortConstant) c).Value;
1118 if (target_type == TypeManager.int32_type)
1120 else if (target_type == TypeManager.uint32_type)
1122 else if (target_type == TypeManager.char_type){
1123 if (v >= Char.MinValue && v <= Char.MaxValue)
1125 } else if (target_type == TypeManager.byte_type){
1126 if (v >= Byte.MinValue && v <= Byte.MaxValue)
1128 } else if (target_type == TypeManager.sbyte_type){
1129 if (v <= SByte.MaxValue)
1131 } else if (target_type == TypeManager.short_type){
1132 if (v <= Int16.MaxValue)
1134 } else if (target_type == TypeManager.int64_type)
1136 else if (target_type == TypeManager.uint64_type)
1140 } else if (c is CharConstant){
1141 char v = ((CharConstant) c).Value;
1143 if (target_type == TypeManager.int32_type)
1145 else if (target_type == TypeManager.uint32_type)
1147 else if (target_type == TypeManager.byte_type){
1148 if (v >= Byte.MinValue && v <= Byte.MaxValue)
1150 } else if (target_type == TypeManager.sbyte_type){
1151 if (v <= SByte.MaxValue)
1153 } else if (target_type == TypeManager.short_type){
1154 if (v <= Int16.MaxValue)
1156 } else if (target_type == TypeManager.ushort_type)
1158 else if (target_type == TypeManager.int64_type)
1160 else if (target_type == TypeManager.uint64_type)
1165 Error_ConstantValueCannotBeConverted (loc, s, target_type);
1170 // Load the object from the pointer.
1172 public static void LoadFromPtr (ILGenerator ig, Type t)
1174 if (t == TypeManager.int32_type)
1175 ig.Emit (OpCodes.Ldind_I4);
1176 else if (t == TypeManager.uint32_type)
1177 ig.Emit (OpCodes.Ldind_U4);
1178 else if (t == TypeManager.short_type)
1179 ig.Emit (OpCodes.Ldind_I2);
1180 else if (t == TypeManager.ushort_type)
1181 ig.Emit (OpCodes.Ldind_U2);
1182 else if (t == TypeManager.char_type)
1183 ig.Emit (OpCodes.Ldind_U2);
1184 else if (t == TypeManager.byte_type)
1185 ig.Emit (OpCodes.Ldind_U1);
1186 else if (t == TypeManager.sbyte_type)
1187 ig.Emit (OpCodes.Ldind_I1);
1188 else if (t == TypeManager.uint64_type)
1189 ig.Emit (OpCodes.Ldind_I8);
1190 else if (t == TypeManager.int64_type)
1191 ig.Emit (OpCodes.Ldind_I8);
1192 else if (t == TypeManager.float_type)
1193 ig.Emit (OpCodes.Ldind_R4);
1194 else if (t == TypeManager.double_type)
1195 ig.Emit (OpCodes.Ldind_R8);
1196 else if (t == TypeManager.bool_type)
1197 ig.Emit (OpCodes.Ldind_I1);
1198 else if (t == TypeManager.intptr_type)
1199 ig.Emit (OpCodes.Ldind_I);
1200 else if (TypeManager.IsEnumType (t)) {
1201 if (t == TypeManager.enum_type)
1202 ig.Emit (OpCodes.Ldind_Ref);
1204 LoadFromPtr (ig, TypeManager.EnumToUnderlying (t));
1205 } else if (t.IsValueType)
1206 ig.Emit (OpCodes.Ldobj, t);
1207 else if (t.IsPointer)
1208 ig.Emit (OpCodes.Ldind_I);
1210 ig.Emit (OpCodes.Ldind_Ref);
1214 // The stack contains the pointer and the value of type `type'
1216 public static void StoreFromPtr (ILGenerator ig, Type type)
1218 if (TypeManager.IsEnumType (type))
1219 type = TypeManager.EnumToUnderlying (type);
1220 if (type == TypeManager.int32_type || type == TypeManager.uint32_type)
1221 ig.Emit (OpCodes.Stind_I4);
1222 else if (type == TypeManager.int64_type || type == TypeManager.uint64_type)
1223 ig.Emit (OpCodes.Stind_I8);
1224 else if (type == TypeManager.char_type || type == TypeManager.short_type ||
1225 type == TypeManager.ushort_type)
1226 ig.Emit (OpCodes.Stind_I2);
1227 else if (type == TypeManager.float_type)
1228 ig.Emit (OpCodes.Stind_R4);
1229 else if (type == TypeManager.double_type)
1230 ig.Emit (OpCodes.Stind_R8);
1231 else if (type == TypeManager.byte_type || type == TypeManager.sbyte_type ||
1232 type == TypeManager.bool_type)
1233 ig.Emit (OpCodes.Stind_I1);
1234 else if (type == TypeManager.intptr_type)
1235 ig.Emit (OpCodes.Stind_I);
1236 else if (type.IsValueType)
1237 ig.Emit (OpCodes.Stobj, type);
1239 ig.Emit (OpCodes.Stind_Ref);
1243 // Returns the size of type `t' if known, otherwise, 0
1245 public static int GetTypeSize (Type t)
1247 t = TypeManager.TypeToCoreType (t);
1248 if (t == TypeManager.int32_type ||
1249 t == TypeManager.uint32_type ||
1250 t == TypeManager.float_type)
1252 else if (t == TypeManager.int64_type ||
1253 t == TypeManager.uint64_type ||
1254 t == TypeManager.double_type)
1256 else if (t == TypeManager.byte_type ||
1257 t == TypeManager.sbyte_type ||
1258 t == TypeManager.bool_type)
1260 else if (t == TypeManager.short_type ||
1261 t == TypeManager.char_type ||
1262 t == TypeManager.ushort_type)
1264 else if (t == TypeManager.decimal_type)
1270 static void Error_NegativeArrayIndex (Location loc)
1272 Report.Error (284, loc, "Can not create array with a negative size");
1276 // Converts `source' to an int, uint, long or ulong.
1278 public Expression ExpressionToArrayArgument (EmitContext ec, Expression source, Location loc)
1282 bool old_checked = ec.CheckState;
1283 ec.CheckState = true;
1285 target = Convert.ImplicitConversion (ec, source, TypeManager.int32_type, loc);
1286 if (target == null){
1287 target = Convert.ImplicitConversion (ec, source, TypeManager.uint32_type, loc);
1288 if (target == null){
1289 target = Convert.ImplicitConversion (ec, source, TypeManager.int64_type, loc);
1290 if (target == null){
1291 target = Convert.ImplicitConversion (ec, source, TypeManager.uint64_type, loc);
1293 Convert.Error_CannotImplicitConversion (loc, source.Type, TypeManager.int32_type);
1297 ec.CheckState = old_checked;
1300 // Only positive constants are allowed at compile time
1302 if (target is Constant){
1303 if (target is IntConstant){
1304 if (((IntConstant) target).Value < 0){
1305 Error_NegativeArrayIndex (loc);
1310 if (target is LongConstant){
1311 if (((LongConstant) target).Value < 0){
1312 Error_NegativeArrayIndex (loc);
1325 /// This is just a base class for expressions that can
1326 /// appear on statements (invocations, object creation,
1327 /// assignments, post/pre increment and decrement). The idea
1328 /// being that they would support an extra Emition interface that
1329 /// does not leave a result on the stack.
1331 public abstract class ExpressionStatement : Expression {
1333 public virtual ExpressionStatement ResolveStatement (EmitContext ec)
1335 Expression e = Resolve (ec);
1339 ExpressionStatement es = e as ExpressionStatement;
1341 Error (201, "Only assignment, call, increment, decrement and new object " +
1342 "expressions can be used as a statement");
1348 /// Requests the expression to be emitted in a `statement'
1349 /// context. This means that no new value is left on the
1350 /// stack after invoking this method (constrasted with
1351 /// Emit that will always leave a value on the stack).
1353 public abstract void EmitStatement (EmitContext ec);
1357 /// This kind of cast is used to encapsulate the child
1358 /// whose type is child.Type into an expression that is
1359 /// reported to return "return_type". This is used to encapsulate
1360 /// expressions which have compatible types, but need to be dealt
1361 /// at higher levels with.
1363 /// For example, a "byte" expression could be encapsulated in one
1364 /// of these as an "unsigned int". The type for the expression
1365 /// would be "unsigned int".
1368 public class EmptyCast : Expression {
1369 protected Expression child;
1371 public Expression Child {
1377 public EmptyCast (Expression child, Type return_type)
1379 eclass = child.eclass;
1384 public override Expression DoResolve (EmitContext ec)
1386 // This should never be invoked, we are born in fully
1387 // initialized state.
1392 public override void Emit (EmitContext ec)
1399 // We need to special case this since an empty cast of
1400 // a NullLiteral is still a Constant
1402 public class NullCast : Constant {
1403 protected Expression child;
1405 public NullCast (Expression child, Type return_type)
1407 eclass = child.eclass;
1412 override public string AsString ()
1417 public override object GetValue ()
1422 public override Expression DoResolve (EmitContext ec)
1424 // This should never be invoked, we are born in fully
1425 // initialized state.
1430 public override void Emit (EmitContext ec)
1438 /// This class is used to wrap literals which belong inside Enums
1440 public class EnumConstant : Constant {
1441 public Constant Child;
1443 public EnumConstant (Constant child, Type enum_type)
1445 eclass = child.eclass;
1450 public override Expression DoResolve (EmitContext ec)
1452 // This should never be invoked, we are born in fully
1453 // initialized state.
1458 public override void Emit (EmitContext ec)
1463 public override object GetValue ()
1465 return Child.GetValue ();
1469 // Converts from one of the valid underlying types for an enumeration
1470 // (int32, uint32, int64, uint64, short, ushort, byte, sbyte) to
1471 // one of the internal compiler literals: Int/UInt/Long/ULong Literals.
1473 public Constant WidenToCompilerConstant ()
1475 Type t = TypeManager.EnumToUnderlying (Child.Type);
1476 object v = ((Constant) Child).GetValue ();;
1478 if (t == TypeManager.int32_type)
1479 return new IntConstant ((int) v);
1480 if (t == TypeManager.uint32_type)
1481 return new UIntConstant ((uint) v);
1482 if (t == TypeManager.int64_type)
1483 return new LongConstant ((long) v);
1484 if (t == TypeManager.uint64_type)
1485 return new ULongConstant ((ulong) v);
1486 if (t == TypeManager.short_type)
1487 return new ShortConstant ((short) v);
1488 if (t == TypeManager.ushort_type)
1489 return new UShortConstant ((ushort) v);
1490 if (t == TypeManager.byte_type)
1491 return new ByteConstant ((byte) v);
1492 if (t == TypeManager.sbyte_type)
1493 return new SByteConstant ((sbyte) v);
1495 throw new Exception ("Invalid enumeration underlying type: " + t);
1499 // Extracts the value in the enumeration on its native representation
1501 public object GetPlainValue ()
1503 Type t = TypeManager.EnumToUnderlying (Child.Type);
1504 object v = ((Constant) Child).GetValue ();;
1506 if (t == TypeManager.int32_type)
1508 if (t == TypeManager.uint32_type)
1510 if (t == TypeManager.int64_type)
1512 if (t == TypeManager.uint64_type)
1514 if (t == TypeManager.short_type)
1516 if (t == TypeManager.ushort_type)
1518 if (t == TypeManager.byte_type)
1520 if (t == TypeManager.sbyte_type)
1526 public override string AsString ()
1528 return Child.AsString ();
1531 public override DoubleConstant ConvertToDouble ()
1533 return Child.ConvertToDouble ();
1536 public override FloatConstant ConvertToFloat ()
1538 return Child.ConvertToFloat ();
1541 public override ULongConstant ConvertToULong ()
1543 return Child.ConvertToULong ();
1546 public override LongConstant ConvertToLong ()
1548 return Child.ConvertToLong ();
1551 public override UIntConstant ConvertToUInt ()
1553 return Child.ConvertToUInt ();
1556 public override IntConstant ConvertToInt ()
1558 return Child.ConvertToInt ();
1561 public override bool IsZeroInteger {
1562 get { return Child.IsZeroInteger; }
1567 /// This kind of cast is used to encapsulate Value Types in objects.
1569 /// The effect of it is to box the value type emitted by the previous
1572 public class BoxedCast : EmptyCast {
1574 public BoxedCast (Expression expr)
1575 : base (expr, TypeManager.object_type)
1577 eclass = ExprClass.Value;
1580 public BoxedCast (Expression expr, Type target_type)
1581 : base (expr, target_type)
1583 eclass = ExprClass.Value;
1586 public override Expression DoResolve (EmitContext ec)
1588 // This should never be invoked, we are born in fully
1589 // initialized state.
1594 public override void Emit (EmitContext ec)
1598 ec.ig.Emit (OpCodes.Box, child.Type);
1602 public class UnboxCast : EmptyCast {
1603 public UnboxCast (Expression expr, Type return_type)
1604 : base (expr, return_type)
1608 public override Expression DoResolve (EmitContext ec)
1610 // This should never be invoked, we are born in fully
1611 // initialized state.
1616 public override void Emit (EmitContext ec)
1619 ILGenerator ig = ec.ig;
1622 if (t.IsGenericParameter)
1623 ig.Emit (OpCodes.Unbox_Any, t);
1625 ig.Emit (OpCodes.Unbox, t);
1627 LoadFromPtr (ig, t);
1633 /// This is used to perform explicit numeric conversions.
1635 /// Explicit numeric conversions might trigger exceptions in a checked
1636 /// context, so they should generate the conv.ovf opcodes instead of
1639 public class ConvCast : EmptyCast {
1640 public enum Mode : byte {
1641 I1_U1, I1_U2, I1_U4, I1_U8, I1_CH,
1643 I2_I1, I2_U1, I2_U2, I2_U4, I2_U8, I2_CH,
1644 U2_I1, U2_U1, U2_I2, U2_CH,
1645 I4_I1, I4_U1, I4_I2, I4_U2, I4_U4, I4_U8, I4_CH,
1646 U4_I1, U4_U1, U4_I2, U4_U2, U4_I4, U4_CH,
1647 I8_I1, I8_U1, I8_I2, I8_U2, I8_I4, I8_U4, I8_U8, I8_CH,
1648 U8_I1, U8_U1, U8_I2, U8_U2, U8_I4, U8_U4, U8_I8, U8_CH,
1649 CH_I1, CH_U1, CH_I2,
1650 R4_I1, R4_U1, R4_I2, R4_U2, R4_I4, R4_U4, R4_I8, R4_U8, R4_CH,
1651 R8_I1, R8_U1, R8_I2, R8_U2, R8_I4, R8_U4, R8_I8, R8_U8, R8_CH, R8_R4
1657 public ConvCast (EmitContext ec, Expression child, Type return_type, Mode m)
1658 : base (child, return_type)
1660 checked_state = ec.CheckState;
1664 public override Expression DoResolve (EmitContext ec)
1666 // This should never be invoked, we are born in fully
1667 // initialized state.
1672 public override string ToString ()
1674 return String.Format ("ConvCast ({0}, {1})", mode, child);
1677 public override void Emit (EmitContext ec)
1679 ILGenerator ig = ec.ig;
1685 case Mode.I1_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1686 case Mode.I1_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1687 case Mode.I1_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1688 case Mode.I1_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1689 case Mode.I1_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1691 case Mode.U1_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1692 case Mode.U1_CH: /* nothing */ break;
1694 case Mode.I2_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1695 case Mode.I2_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1696 case Mode.I2_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1697 case Mode.I2_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1698 case Mode.I2_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1699 case Mode.I2_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1701 case Mode.U2_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1702 case Mode.U2_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
1703 case Mode.U2_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
1704 case Mode.U2_CH: /* nothing */ break;
1706 case Mode.I4_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1707 case Mode.I4_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1708 case Mode.I4_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
1709 case Mode.I4_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1710 case Mode.I4_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1711 case Mode.I4_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1712 case Mode.I4_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1714 case Mode.U4_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1715 case Mode.U4_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
1716 case Mode.U4_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
1717 case Mode.U4_U2: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
1718 case Mode.U4_I4: ig.Emit (OpCodes.Conv_Ovf_I4_Un); break;
1719 case Mode.U4_CH: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
1721 case Mode.I8_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1722 case Mode.I8_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1723 case Mode.I8_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
1724 case Mode.I8_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1725 case Mode.I8_I4: ig.Emit (OpCodes.Conv_Ovf_I4); break;
1726 case Mode.I8_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1727 case Mode.I8_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1728 case Mode.I8_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1730 case Mode.U8_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1731 case Mode.U8_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
1732 case Mode.U8_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
1733 case Mode.U8_U2: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
1734 case Mode.U8_I4: ig.Emit (OpCodes.Conv_Ovf_I4_Un); break;
1735 case Mode.U8_U4: ig.Emit (OpCodes.Conv_Ovf_U4_Un); break;
1736 case Mode.U8_I8: ig.Emit (OpCodes.Conv_Ovf_I8_Un); break;
1737 case Mode.U8_CH: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
1739 case Mode.CH_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1740 case Mode.CH_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
1741 case Mode.CH_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
1743 case Mode.R4_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1744 case Mode.R4_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1745 case Mode.R4_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
1746 case Mode.R4_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1747 case Mode.R4_I4: ig.Emit (OpCodes.Conv_Ovf_I4); break;
1748 case Mode.R4_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1749 case Mode.R4_I8: ig.Emit (OpCodes.Conv_Ovf_I8); break;
1750 case Mode.R4_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1751 case Mode.R4_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1753 case Mode.R8_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1754 case Mode.R8_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1755 case Mode.R8_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
1756 case Mode.R8_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1757 case Mode.R8_I4: ig.Emit (OpCodes.Conv_Ovf_I4); break;
1758 case Mode.R8_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1759 case Mode.R8_I8: ig.Emit (OpCodes.Conv_Ovf_I8); break;
1760 case Mode.R8_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1761 case Mode.R8_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1762 case Mode.R8_R4: ig.Emit (OpCodes.Conv_R4); break;
1766 case Mode.I1_U1: ig.Emit (OpCodes.Conv_U1); break;
1767 case Mode.I1_U2: ig.Emit (OpCodes.Conv_U2); break;
1768 case Mode.I1_U4: ig.Emit (OpCodes.Conv_U4); break;
1769 case Mode.I1_U8: ig.Emit (OpCodes.Conv_I8); break;
1770 case Mode.I1_CH: ig.Emit (OpCodes.Conv_U2); break;
1772 case Mode.U1_I1: ig.Emit (OpCodes.Conv_I1); break;
1773 case Mode.U1_CH: ig.Emit (OpCodes.Conv_U2); break;
1775 case Mode.I2_I1: ig.Emit (OpCodes.Conv_I1); break;
1776 case Mode.I2_U1: ig.Emit (OpCodes.Conv_U1); break;
1777 case Mode.I2_U2: ig.Emit (OpCodes.Conv_U2); break;
1778 case Mode.I2_U4: ig.Emit (OpCodes.Conv_U4); break;
1779 case Mode.I2_U8: ig.Emit (OpCodes.Conv_I8); break;
1780 case Mode.I2_CH: ig.Emit (OpCodes.Conv_U2); break;
1782 case Mode.U2_I1: ig.Emit (OpCodes.Conv_I1); break;
1783 case Mode.U2_U1: ig.Emit (OpCodes.Conv_U1); break;
1784 case Mode.U2_I2: ig.Emit (OpCodes.Conv_I2); break;
1785 case Mode.U2_CH: /* nothing */ break;
1787 case Mode.I4_I1: ig.Emit (OpCodes.Conv_I1); break;
1788 case Mode.I4_U1: ig.Emit (OpCodes.Conv_U1); break;
1789 case Mode.I4_I2: ig.Emit (OpCodes.Conv_I2); break;
1790 case Mode.I4_U4: /* nothing */ break;
1791 case Mode.I4_U2: ig.Emit (OpCodes.Conv_U2); break;
1792 case Mode.I4_U8: ig.Emit (OpCodes.Conv_I8); break;
1793 case Mode.I4_CH: ig.Emit (OpCodes.Conv_U2); break;
1795 case Mode.U4_I1: ig.Emit (OpCodes.Conv_I1); break;
1796 case Mode.U4_U1: ig.Emit (OpCodes.Conv_U1); break;
1797 case Mode.U4_I2: ig.Emit (OpCodes.Conv_I2); break;
1798 case Mode.U4_U2: ig.Emit (OpCodes.Conv_U2); break;
1799 case Mode.U4_I4: /* nothing */ break;
1800 case Mode.U4_CH: ig.Emit (OpCodes.Conv_U2); break;
1802 case Mode.I8_I1: ig.Emit (OpCodes.Conv_I1); break;
1803 case Mode.I8_U1: ig.Emit (OpCodes.Conv_U1); break;
1804 case Mode.I8_I2: ig.Emit (OpCodes.Conv_I2); break;
1805 case Mode.I8_U2: ig.Emit (OpCodes.Conv_U2); break;
1806 case Mode.I8_I4: ig.Emit (OpCodes.Conv_I4); break;
1807 case Mode.I8_U4: ig.Emit (OpCodes.Conv_U4); break;
1808 case Mode.I8_U8: /* nothing */ break;
1809 case Mode.I8_CH: ig.Emit (OpCodes.Conv_U2); break;
1811 case Mode.U8_I1: ig.Emit (OpCodes.Conv_I1); break;
1812 case Mode.U8_U1: ig.Emit (OpCodes.Conv_U1); break;
1813 case Mode.U8_I2: ig.Emit (OpCodes.Conv_I2); break;
1814 case Mode.U8_U2: ig.Emit (OpCodes.Conv_U2); break;
1815 case Mode.U8_I4: ig.Emit (OpCodes.Conv_I4); break;
1816 case Mode.U8_U4: ig.Emit (OpCodes.Conv_U4); break;
1817 case Mode.U8_I8: /* nothing */ break;
1818 case Mode.U8_CH: ig.Emit (OpCodes.Conv_U2); break;
1820 case Mode.CH_I1: ig.Emit (OpCodes.Conv_I1); break;
1821 case Mode.CH_U1: ig.Emit (OpCodes.Conv_U1); break;
1822 case Mode.CH_I2: ig.Emit (OpCodes.Conv_I2); break;
1824 case Mode.R4_I1: ig.Emit (OpCodes.Conv_I1); break;
1825 case Mode.R4_U1: ig.Emit (OpCodes.Conv_U1); break;
1826 case Mode.R4_I2: ig.Emit (OpCodes.Conv_I2); break;
1827 case Mode.R4_U2: ig.Emit (OpCodes.Conv_U2); break;
1828 case Mode.R4_I4: ig.Emit (OpCodes.Conv_I4); break;
1829 case Mode.R4_U4: ig.Emit (OpCodes.Conv_U4); break;
1830 case Mode.R4_I8: ig.Emit (OpCodes.Conv_I8); break;
1831 case Mode.R4_U8: ig.Emit (OpCodes.Conv_U8); break;
1832 case Mode.R4_CH: ig.Emit (OpCodes.Conv_U2); break;
1834 case Mode.R8_I1: ig.Emit (OpCodes.Conv_I1); break;
1835 case Mode.R8_U1: ig.Emit (OpCodes.Conv_U1); break;
1836 case Mode.R8_I2: ig.Emit (OpCodes.Conv_I2); break;
1837 case Mode.R8_U2: ig.Emit (OpCodes.Conv_U2); break;
1838 case Mode.R8_I4: ig.Emit (OpCodes.Conv_I4); break;
1839 case Mode.R8_U4: ig.Emit (OpCodes.Conv_U4); break;
1840 case Mode.R8_I8: ig.Emit (OpCodes.Conv_I8); break;
1841 case Mode.R8_U8: ig.Emit (OpCodes.Conv_U8); break;
1842 case Mode.R8_CH: ig.Emit (OpCodes.Conv_U2); break;
1843 case Mode.R8_R4: ig.Emit (OpCodes.Conv_R4); break;
1849 public class OpcodeCast : EmptyCast {
1853 public OpcodeCast (Expression child, Type return_type, OpCode op)
1854 : base (child, return_type)
1858 second_valid = false;
1861 public OpcodeCast (Expression child, Type return_type, OpCode op, OpCode op2)
1862 : base (child, return_type)
1867 second_valid = true;
1870 public override Expression DoResolve (EmitContext ec)
1872 // This should never be invoked, we are born in fully
1873 // initialized state.
1878 public override void Emit (EmitContext ec)
1889 /// This kind of cast is used to encapsulate a child and cast it
1890 /// to the class requested
1892 public class ClassCast : EmptyCast {
1893 public ClassCast (Expression child, Type return_type)
1894 : base (child, return_type)
1899 public override Expression DoResolve (EmitContext ec)
1901 // This should never be invoked, we are born in fully
1902 // initialized state.
1907 public override void Emit (EmitContext ec)
1911 if (child.Type.IsGenericParameter)
1912 ec.ig.Emit (OpCodes.Box, child.Type);
1914 if (type.IsGenericParameter)
1915 ec.ig.Emit (OpCodes.Unbox_Any, type);
1917 ec.ig.Emit (OpCodes.Castclass, type);
1922 /// SimpleName expressions are initially formed of a single
1923 /// word and it only happens at the beginning of the expression.
1927 /// The expression will try to be bound to a Field, a Method
1928 /// group or a Property. If those fail we pass the name to our
1929 /// caller and the SimpleName is compounded to perform a type
1930 /// lookup. The idea behind this process is that we want to avoid
1931 /// creating a namespace map from the assemblies, as that requires
1932 /// the GetExportedTypes function to be called and a hashtable to
1933 /// be constructed which reduces startup time. If later we find
1934 /// that this is slower, we should create a `NamespaceExpr' expression
1935 /// that fully participates in the resolution process.
1937 /// For example `System.Console.WriteLine' is decomposed into
1938 /// MemberAccess (MemberAccess (SimpleName ("System"), "Console"), "WriteLine")
1940 /// The first SimpleName wont produce a match on its own, so it will
1942 /// MemberAccess (SimpleName ("System.Console"), "WriteLine").
1944 /// System.Console will produce a TypeExpr match.
1946 /// The downside of this is that we might be hitting `LookupType' too many
1947 /// times with this scheme.
1949 public class SimpleName : Expression {
1951 public readonly TypeArguments Arguments;
1954 // If true, then we are a simple name, not composed with a ".
1958 public SimpleName (string a, string b, Location l)
1960 Name = String.Concat (a, ".", b);
1965 public SimpleName (string name, Location l)
1972 public SimpleName (string name, TypeArguments args, Location l)
1980 public static void Error_ObjectRefRequired (EmitContext ec, Location l, string name)
1982 if (ec.IsFieldInitializer)
1985 "A field initializer cannot reference the non-static field, " +
1986 "method or property `"+name+"'");
1990 "An object reference is required " +
1991 "for the non-static field `"+name+"'");
1995 // Checks whether we are trying to access an instance
1996 // property, method or field from a static body.
1998 Expression MemberStaticCheck (EmitContext ec, Expression e)
2000 if (e is IMemberExpr){
2001 IMemberExpr member = (IMemberExpr) e;
2003 if (!member.IsStatic){
2004 Error_ObjectRefRequired (ec, loc, Name);
2012 public override Expression DoResolve (EmitContext ec)
2014 return SimpleNameResolve (ec, null, false, false);
2017 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
2019 return SimpleNameResolve (ec, right_side, false, false);
2023 public Expression DoResolveAllowStatic (EmitContext ec, bool intermediate)
2025 return SimpleNameResolve (ec, null, true, intermediate);
2028 public override Expression ResolveAsTypeStep (EmitContext ec)
2030 DeclSpace ds = ec.DeclSpace;
2031 NamespaceEntry ns = ds.NamespaceEntry;
2036 // Since we are cheating: we only do the Alias lookup for
2037 // namespaces if the name does not include any dots in it
2039 if (ns != null && is_base)
2040 alias_value = ns.LookupAlias (Name);
2044 TypeParameterExpr generic_type = ds.LookupGeneric (Name, loc);
2045 if (generic_type != null)
2046 return generic_type.ResolveAsTypeTerminal (ec);
2048 if (ec.ResolvingTypeTree){
2049 int errors = Report.Errors;
2050 Type dt = ds.FindType (loc, Name);
2052 if (Report.Errors != errors)
2056 return new TypeExpression (dt, loc);
2058 if (alias_value != null){
2059 if (alias_value.IsType)
2060 return alias_value.Type;
2061 if ((t = RootContext.LookupType (ds, alias_value.Name, true, loc)) != null)
2067 // First, the using aliases
2069 if (alias_value != null){
2070 if (alias_value.IsType)
2071 return alias_value.Type;
2072 if ((t = RootContext.LookupType (ds, alias_value.Name, true, loc)) != null)
2075 // we have alias value, but it isn't Type, so try if it's namespace
2076 return new SimpleName (alias_value.Name, loc);
2080 // Stage 2: Lookup up if we are an alias to a type
2084 if ((t = RootContext.LookupType (ds, Name, true, loc)) != null)
2087 // No match, maybe our parent can compose us
2088 // into something meaningful.
2092 Expression SimpleNameResolve (EmitContext ec, Expression right_side,
2093 bool allow_static, bool intermediate)
2095 Expression e = DoSimpleNameResolve (ec, right_side, allow_static, intermediate);
2099 Block current_block = ec.CurrentBlock;
2100 if (current_block != null){
2101 LocalInfo vi = current_block.GetLocalInfo (Name);
2103 current_block.IsVariableNameUsedInChildBlock(Name)) {
2104 Report.Error (135, Location,
2105 "'{0}' has a different meaning in a " +
2106 "child block", Name);
2111 if (e.Type != null && e.Type.IsPointer && !ec.InUnsafe) {
2120 /// 7.5.2: Simple Names.
2122 /// Local Variables and Parameters are handled at
2123 /// parse time, so they never occur as SimpleNames.
2125 /// The `allow_static' flag is used by MemberAccess only
2126 /// and it is used to inform us that it is ok for us to
2127 /// avoid the static check, because MemberAccess might end
2128 /// up resolving the Name as a Type name and the access as
2129 /// a static type access.
2131 /// ie: Type Type; .... { Type.GetType (""); }
2133 /// Type is both an instance variable and a Type; Type.GetType
2134 /// is the static method not an instance method of type.
2136 Expression DoSimpleNameResolve (EmitContext ec, Expression right_side, bool allow_static, bool intermediate)
2138 Expression e = null;
2141 // Stage 1: Performed by the parser (binding to locals or parameters).
2143 Block current_block = ec.CurrentBlock;
2144 if (current_block != null){
2145 LocalInfo vi = current_block.GetLocalInfo (Name);
2149 var = new LocalVariableReference (ec.CurrentBlock, Name, loc);
2151 if (right_side != null)
2152 return var.ResolveLValue (ec, right_side);
2154 return var.Resolve (ec);
2158 Parameter par = null;
2159 Parameters pars = current_block.Parameters;
2161 par = pars.GetParameterByName (Name, out idx);
2164 ParameterReference param;
2166 param = new ParameterReference (pars, current_block, idx, Name, loc);
2168 if (right_side != null)
2169 return param.ResolveLValue (ec, right_side);
2171 return param.Resolve (ec);
2176 // Stage 2: Lookup members
2179 DeclSpace lookup_ds = ec.DeclSpace;
2181 if (lookup_ds.TypeBuilder == null)
2184 e = MemberLookup (ec, lookup_ds.TypeBuilder, Name, loc);
2188 lookup_ds =lookup_ds.Parent;
2189 } while (lookup_ds != null);
2191 if (e == null && ec.ContainerType != null)
2192 e = MemberLookup (ec, ec.ContainerType, Name, loc);
2196 // Since we are cheating (is_base is our hint
2197 // that we are the beginning of the name): we
2198 // only do the Alias lookup for namespaces if
2199 // the name does not include any dots in it
2201 NamespaceEntry ns = ec.DeclSpace.NamespaceEntry;
2202 if (is_base && ns != null){
2203 IAlias alias_value = ns.LookupAlias (Name);
2204 if (alias_value != null){
2205 if (alias_value.IsType)
2206 return alias_value.Type;
2208 Name = alias_value.Name;
2211 if ((t = TypeManager.LookupType (Name)) != null)
2212 return new TypeExpression (t, loc);
2214 // No match, maybe our parent can compose us
2215 // into something meaningful.
2220 return ResolveAsTypeStep (ec);
2226 if (e is IMemberExpr) {
2227 e = MemberAccess.ResolveMemberAccess (ec, e, null, loc, this);
2231 IMemberExpr me = e as IMemberExpr;
2235 if (Arguments != null) {
2236 MethodGroupExpr mg = me as MethodGroupExpr;
2240 return mg.ResolveGeneric (ec, Arguments);
2243 // This fails if ResolveMemberAccess() was unable to decide whether
2244 // it's a field or a type of the same name.
2246 if (!me.IsStatic && (me.InstanceExpression == null))
2250 TypeManager.IsSubclassOrNestedChildOf (me.InstanceExpression.Type, me.DeclaringType) &&
2251 me.InstanceExpression.Type != me.DeclaringType &&
2252 !TypeManager.IsSubclassOf (me.InstanceExpression.Type, me.DeclaringType) &&
2253 (!intermediate || !MemberAccess.IdenticalNameAndTypeName (ec, this, e, loc))) {
2254 Error (38, "Cannot access nonstatic member `" + me.Name + "' of " +
2255 "outer type `" + me.DeclaringType + "' via nested type `" +
2256 me.InstanceExpression.Type + "'");
2260 return (right_side != null)
2261 ? e.DoResolveLValue (ec, right_side)
2265 if (ec.IsStatic || ec.IsFieldInitializer){
2269 return MemberStaticCheck (ec, e);
2274 public override void Emit (EmitContext ec)
2277 // If this is ever reached, then we failed to
2278 // find the name as a namespace
2281 Error (103, "The name `" + Name +
2282 "' does not exist in the class `" +
2283 ec.DeclSpace.Name + "'");
2286 public override string ToString ()
2293 /// Fully resolved expression that evaluates to a type
2295 public abstract class TypeExpr : Expression, IAlias {
2296 override public Expression ResolveAsTypeStep (EmitContext ec)
2298 TypeExpr t = DoResolveAsTypeStep (ec);
2302 eclass = ExprClass.Type;
2306 override public Expression DoResolve (EmitContext ec)
2308 return ResolveAsTypeTerminal (ec);
2311 override public void Emit (EmitContext ec)
2313 throw new Exception ("Should never be called");
2316 public virtual bool CheckAccessLevel (DeclSpace ds)
2318 return ds.CheckAccessLevel (Type);
2321 public virtual bool AsAccessible (DeclSpace ds, int flags)
2323 return ds.AsAccessible (Type, flags);
2326 public virtual bool IsClass {
2327 get { return Type.IsClass; }
2330 public virtual bool IsValueType {
2331 get { return Type.IsValueType; }
2334 public virtual bool IsInterface {
2335 get { return Type.IsInterface; }
2338 public virtual bool IsSealed {
2339 get { return Type.IsSealed; }
2342 public virtual bool CanInheritFrom ()
2344 if (Type == TypeManager.enum_type ||
2345 (Type == TypeManager.value_type && RootContext.StdLib) ||
2346 Type == TypeManager.multicast_delegate_type ||
2347 Type == TypeManager.delegate_type ||
2348 Type == TypeManager.array_type)
2354 public virtual bool IsAttribute {
2356 return Type == TypeManager.attribute_type ||
2357 Type.IsSubclassOf (TypeManager.attribute_type);
2361 public abstract TypeExpr DoResolveAsTypeStep (EmitContext ec);
2363 public virtual Type ResolveType (EmitContext ec)
2365 TypeExpr t = ResolveAsTypeTerminal (ec);
2372 public abstract string Name {
2376 public override bool Equals (object obj)
2378 TypeExpr tobj = obj as TypeExpr;
2382 return Type == tobj.Type;
2385 public override int GetHashCode ()
2387 return Type.GetHashCode ();
2390 public override string ToString ()
2395 bool IAlias.IsType {
2396 get { return true; }
2399 TypeExpr IAlias.Type {
2406 public class TypeExpression : TypeExpr, IAlias {
2407 public TypeExpression (Type t, Location l)
2410 eclass = ExprClass.Type;
2414 public override TypeExpr DoResolveAsTypeStep (EmitContext ec)
2419 public override string Name {
2421 return Type.ToString ();
2425 string IAlias.Name {
2427 return Type.FullName != null ? Type.FullName : Type.Name;
2433 /// Used to create types from a fully qualified name. These are just used
2434 /// by the parser to setup the core types. A TypeLookupExpression is always
2435 /// classified as a type.
2437 public class TypeLookupExpression : TypeExpr {
2440 public TypeLookupExpression (string name)
2445 public override TypeExpr DoResolveAsTypeStep (EmitContext ec)
2448 TypeExpr texpr = RootContext.LookupType (
2449 ec.DeclSpace, name, false, Location.Null);
2453 type = texpr.ResolveType (ec);
2461 public override string Name {
2469 /// Represents an "unbound generic type", ie. typeof (Foo<>).
2472 public class UnboundTypeExpression : TypeLookupExpression {
2473 public UnboundTypeExpression (string name)
2478 public class TypeAliasExpression : TypeExpr, IAlias {
2483 public TypeAliasExpression (TypeExpr texpr, TypeArguments args, Location l)
2487 loc = texpr.Location;
2489 eclass = ExprClass.Type;
2491 name = texpr.Name + "<" + args.ToString () + ">";
2496 public override string Name {
2497 get { return name; }
2500 public override TypeExpr DoResolveAsTypeStep (EmitContext ec)
2502 Type type = texpr.ResolveType (ec);
2506 int num_args = TypeManager.GetNumberOfTypeArguments (type);
2509 if (num_args == 0) {
2510 Report.Error (308, loc,
2511 "The non-generic type `{0}' cannot " +
2512 "be used with type arguments.",
2513 TypeManager.CSharpName (type));
2517 ConstructedType ctype = new ConstructedType (type, args, loc);
2518 return ctype.ResolveAsTypeTerminal (ec);
2519 } else if (num_args > 0) {
2520 Report.Error (305, loc,
2521 "Using the generic type `{0}' " +
2522 "requires {1} type arguments",
2523 TypeManager.GetFullName (type), num_args);
2527 return new TypeExpression (type, loc);
2530 public override Type ResolveType (EmitContext ec)
2532 TypeExpr t = ResolveAsTypeTerminal (ec);
2536 type = t.ResolveType (ec);
2540 public override bool CheckAccessLevel (DeclSpace ds)
2542 return texpr.CheckAccessLevel (ds);
2545 public override bool AsAccessible (DeclSpace ds, int flags)
2547 return texpr.AsAccessible (ds, flags);
2550 public override bool IsClass {
2551 get { return texpr.IsClass; }
2554 public override bool IsValueType {
2555 get { return texpr.IsValueType; }
2558 public override bool IsInterface {
2559 get { return texpr.IsInterface; }
2562 public override bool IsSealed {
2563 get { return texpr.IsSealed; }
2566 public override bool IsAttribute {
2567 get { return texpr.IsAttribute; }
2572 /// MethodGroup Expression.
2574 /// This is a fully resolved expression that evaluates to a type
2576 public class MethodGroupExpr : Expression, IMemberExpr {
2577 public MethodBase [] Methods;
2578 Expression instance_expression = null;
2579 bool is_explicit_impl = false;
2580 bool has_type_arguments = false;
2581 bool identical_type_name = false;
2584 public MethodGroupExpr (MemberInfo [] mi, Location l)
2586 Methods = new MethodBase [mi.Length];
2587 mi.CopyTo (Methods, 0);
2588 eclass = ExprClass.MethodGroup;
2589 type = TypeManager.object_type;
2593 public MethodGroupExpr (ArrayList list, Location l)
2595 Methods = new MethodBase [list.Count];
2598 list.CopyTo (Methods, 0);
2600 foreach (MemberInfo m in list){
2601 if (!(m is MethodBase)){
2602 Console.WriteLine ("Name " + m.Name);
2603 Console.WriteLine ("Found a: " + m.GetType ().FullName);
2610 eclass = ExprClass.MethodGroup;
2611 type = TypeManager.object_type;
2614 public Type DeclaringType {
2617 // We assume that the top-level type is in the end
2619 return Methods [Methods.Length - 1].DeclaringType;
2620 //return Methods [0].DeclaringType;
2625 // `A method group may have associated an instance expression'
2627 public Expression InstanceExpression {
2629 return instance_expression;
2633 instance_expression = value;
2637 public bool IsExplicitImpl {
2639 return is_explicit_impl;
2643 is_explicit_impl = value;
2647 public bool HasTypeArguments {
2649 return has_type_arguments;
2653 has_type_arguments = value;
2657 public bool IdenticalTypeName {
2659 return identical_type_name;
2663 identical_type_name = value;
2667 public bool IsBase {
2676 public string Name {
2678 //return Methods [0].Name;
2679 return Methods [Methods.Length - 1].Name;
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 temp;
2824 bool is_field_initializer;
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 bool IsFieldInitializer {
2870 return is_field_initializer;
2874 is_field_initializer = value;
2878 public VariableInfo VariableInfo {
2880 return variable_info;
2884 override public Expression DoResolve (EmitContext ec)
2886 if (!FieldInfo.IsStatic){
2887 if (instance_expr == null){
2889 // This can happen when referencing an instance field using
2890 // a fully qualified type expression: TypeName.InstanceField = xxx
2892 SimpleName.Error_ObjectRefRequired (ec, loc, FieldInfo.Name);
2896 // Resolve the field's instance expression while flow analysis is turned
2897 // off: when accessing a field "a.b", we must check whether the field
2898 // "a.b" is initialized, not whether the whole struct "a" is initialized.
2899 instance_expr = instance_expr.Resolve (ec, ResolveFlags.VariableOrValue |
2900 ResolveFlags.DisableFlowAnalysis);
2901 if (instance_expr == null)
2905 ObsoleteAttribute oa;
2906 FieldBase f = TypeManager.GetField (FieldInfo);
2908 oa = f.GetObsoleteAttribute (ec.DeclSpace);
2910 AttributeTester.Report_ObsoleteMessage (oa, f.GetSignatureForError (), loc);
2911 // To be sure that type is external because we do not register generated fields
2912 } else if (!(FieldInfo.DeclaringType is TypeBuilder)) {
2913 oa = AttributeTester.GetMemberObsoleteAttribute (FieldInfo);
2915 AttributeTester.Report_ObsoleteMessage (oa, TypeManager.GetFullNameSignature (FieldInfo), loc);
2918 // If the instance expression is a local variable or parameter.
2919 IVariable var = instance_expr as IVariable;
2920 if ((var == null) || (var.VariableInfo == null))
2923 VariableInfo vi = var.VariableInfo;
2924 if (!vi.IsFieldAssigned (ec, FieldInfo.Name, loc))
2927 variable_info = vi.GetSubStruct (FieldInfo.Name);
2931 void Report_AssignToReadonly (bool is_instance)
2936 msg = "Readonly field can not be assigned outside " +
2937 "of constructor or variable initializer";
2939 msg = "A static readonly field can only be assigned in " +
2940 "a static constructor";
2942 Report.Error (is_instance ? 191 : 198, loc, msg);
2945 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
2947 IVariable var = instance_expr as IVariable;
2948 if ((var != null) && (var.VariableInfo != null))
2949 var.VariableInfo.SetFieldAssigned (ec, FieldInfo.Name);
2951 Expression e = DoResolve (ec);
2956 if (!FieldInfo.IsStatic && (instance_expr.Type.IsValueType && !(instance_expr is IMemoryLocation))) {
2957 // FIXME: Provide better error reporting.
2958 Error (1612, "Cannot modify expression because it is not a variable.");
2962 if (!FieldInfo.IsInitOnly)
2965 FieldBase fb = TypeManager.GetField (FieldInfo);
2970 // InitOnly fields can only be assigned in constructors
2973 if (ec.IsConstructor){
2974 if (IsStatic && !ec.IsStatic)
2975 Report_AssignToReadonly (false);
2978 if (!is_field_initializer &&
2979 (ec.TypeContainer.CurrentType != null))
2980 ctype = ec.TypeContainer.CurrentType.ResolveType (ec);
2982 ctype = ec.ContainerType;
2984 if (TypeManager.IsEqual (ctype, FieldInfo.DeclaringType))
2988 Report_AssignToReadonly (true);
2993 public bool VerifyFixed (bool is_expression)
2995 IVariable variable = instance_expr as IVariable;
2996 if ((variable == null) || !variable.VerifyFixed (true))
3002 public void Emit (EmitContext ec, bool leave_copy)
3004 ILGenerator ig = ec.ig;
3005 bool is_volatile = false;
3007 if (FieldInfo is FieldBuilder){
3008 FieldBase f = TypeManager.GetField (FieldInfo);
3010 if ((f.ModFlags & Modifiers.VOLATILE) != 0)
3013 f.status |= Field.Status.USED;
3017 if (FieldInfo.IsStatic){
3019 ig.Emit (OpCodes.Volatile);
3021 ig.Emit (OpCodes.Ldsfld, FieldInfo);
3027 ig.Emit (OpCodes.Volatile);
3029 ig.Emit (OpCodes.Ldfld, FieldInfo);
3033 ec.ig.Emit (OpCodes.Dup);
3034 if (!FieldInfo.IsStatic) {
3035 temp = new LocalTemporary (ec, this.Type);
3041 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
3043 FieldAttributes fa = FieldInfo.Attributes;
3044 bool is_static = (fa & FieldAttributes.Static) != 0;
3045 bool is_readonly = (fa & FieldAttributes.InitOnly) != 0;
3046 ILGenerator ig = ec.ig;
3047 prepared = prepare_for_load;
3049 if (is_readonly && !ec.IsConstructor){
3050 Report_AssignToReadonly (!is_static);
3056 if (prepare_for_load)
3057 ig.Emit (OpCodes.Dup);
3062 ec.ig.Emit (OpCodes.Dup);
3063 if (!FieldInfo.IsStatic) {
3064 temp = new LocalTemporary (ec, this.Type);
3069 if (FieldInfo is FieldBuilder){
3070 FieldBase f = TypeManager.GetField (FieldInfo);
3072 if ((f.ModFlags & Modifiers.VOLATILE) != 0)
3073 ig.Emit (OpCodes.Volatile);
3075 f.status |= Field.Status.ASSIGNED;
3080 ig.Emit (OpCodes.Stsfld, FieldInfo);
3082 ig.Emit (OpCodes.Stfld, FieldInfo);
3088 void EmitInstance (EmitContext ec)
3090 if (instance_expr.Type.IsValueType) {
3091 if (instance_expr is IMemoryLocation) {
3092 ((IMemoryLocation) instance_expr).AddressOf (ec, AddressOp.LoadStore);
3094 LocalTemporary t = new LocalTemporary (ec, instance_expr.Type);
3095 instance_expr.Emit (ec);
3097 t.AddressOf (ec, AddressOp.Store);
3100 instance_expr.Emit (ec);
3103 public override void Emit (EmitContext ec)
3108 public void AddressOf (EmitContext ec, AddressOp mode)
3110 ILGenerator ig = ec.ig;
3112 if (FieldInfo is FieldBuilder){
3113 FieldBase f = TypeManager.GetField (FieldInfo);
3115 if ((f.ModFlags & Modifiers.VOLATILE) != 0){
3116 Error (676, "volatile variable: can not take its address, or pass as ref/out parameter");
3120 if ((mode & AddressOp.Store) != 0)
3121 f.status |= Field.Status.ASSIGNED;
3122 if ((mode & AddressOp.Load) != 0)
3123 f.status |= Field.Status.USED;
3128 // Handle initonly fields specially: make a copy and then
3129 // get the address of the copy.
3132 if (FieldInfo.IsInitOnly){
3134 if (ec.IsConstructor){
3135 if (FieldInfo.IsStatic){
3147 local = ig.DeclareLocal (type);
3148 ig.Emit (OpCodes.Stloc, local);
3149 ig.Emit (OpCodes.Ldloca, local);
3154 if (FieldInfo.IsStatic){
3155 ig.Emit (OpCodes.Ldsflda, FieldInfo);
3158 ig.Emit (OpCodes.Ldflda, FieldInfo);
3164 // A FieldExpr whose address can not be taken
3166 public class FieldExprNoAddress : FieldExpr, IMemoryLocation {
3167 public FieldExprNoAddress (FieldInfo fi, Location loc) : base (fi, loc)
3171 public new void AddressOf (EmitContext ec, AddressOp mode)
3173 Report.Error (-215, "Report this: Taking the address of a remapped parameter not supported");
3178 /// Expression that evaluates to a Property. The Assign class
3179 /// might set the `Value' expression if we are in an assignment.
3181 /// This is not an LValue because we need to re-write the expression, we
3182 /// can not take data from the stack and store it.
3184 public class PropertyExpr : ExpressionStatement, IAssignMethod, IMemberExpr {
3185 public readonly PropertyInfo PropertyInfo;
3188 // This is set externally by the `BaseAccess' class
3191 MethodInfo getter, setter;
3193 bool must_do_cs1540_check;
3195 Expression instance_expr;
3196 LocalTemporary temp;
3199 public PropertyExpr (EmitContext ec, PropertyInfo pi, Location l)
3202 eclass = ExprClass.PropertyAccess;
3206 type = TypeManager.TypeToCoreType (pi.PropertyType);
3208 ResolveAccessors (ec);
3211 public string Name {
3213 return PropertyInfo.Name;
3217 public bool IsInstance {
3223 public bool IsStatic {
3229 public Type DeclaringType {
3231 return PropertyInfo.DeclaringType;
3236 // The instance expression associated with this expression
3238 public Expression InstanceExpression {
3240 instance_expr = value;
3244 return instance_expr;
3248 public bool VerifyAssignable ()
3250 if (setter == null) {
3251 Report.Error (200, loc,
3252 "The property `" + PropertyInfo.Name +
3253 "' can not be assigned to, as it has not set accessor");
3260 MethodInfo FindAccessor (Type invocation_type, bool is_set)
3262 BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic |
3263 BindingFlags.Static | BindingFlags.Instance |
3264 BindingFlags.DeclaredOnly;
3266 Type current = PropertyInfo.DeclaringType;
3267 for (; current != null; current = current.BaseType) {
3268 MemberInfo[] group = TypeManager.MemberLookup (
3269 invocation_type, invocation_type, current,
3270 MemberTypes.Property, flags, PropertyInfo.Name, null);
3275 if (group.Length != 1)
3276 // Oooops, can this ever happen ?
3279 PropertyInfo pi = (PropertyInfo) group [0];
3281 MethodInfo get = pi.GetGetMethod (true);
3282 MethodInfo set = pi.GetSetMethod (true);
3292 MethodInfo accessor = get != null ? get : set;
3293 if (accessor == null)
3295 if ((accessor.Attributes & MethodAttributes.NewSlot) != 0)
3302 MethodInfo GetAccessor (Type invocation_type, bool is_set)
3304 MethodInfo mi = FindAccessor (invocation_type, is_set);
3308 MethodAttributes ma = mi.Attributes & MethodAttributes.MemberAccessMask;
3311 // If only accessible to the current class or children
3313 if (ma == MethodAttributes.Private) {
3314 Type declaring_type = mi.DeclaringType;
3316 if (invocation_type != declaring_type){
3317 if (TypeManager.IsSubclassOrNestedChildOf (invocation_type, mi.DeclaringType))
3325 // FamAndAssem requires that we not only derivate, but we are on the
3328 if (ma == MethodAttributes.FamANDAssem){
3329 if (mi.DeclaringType.Assembly != invocation_type.Assembly)
3335 // Assembly and FamORAssem succeed if we're in the same assembly.
3336 if ((ma == MethodAttributes.Assembly) || (ma == MethodAttributes.FamORAssem)){
3337 if (mi.DeclaringType.Assembly == invocation_type.Assembly)
3341 // We already know that we aren't in the same assembly.
3342 if (ma == MethodAttributes.Assembly)
3345 // Family and FamANDAssem require that we derive.
3346 if ((ma == MethodAttributes.Family) || (ma == MethodAttributes.FamANDAssem) || (ma == MethodAttributes.FamORAssem)){
3347 if (!TypeManager.IsSubclassOrNestedChildOf (invocation_type, mi.DeclaringType))
3350 if (!TypeManager.IsNestedChildOf (invocation_type, mi.DeclaringType))
3351 must_do_cs1540_check = true;
3361 // We also perform the permission checking here, as the PropertyInfo does not
3362 // hold the information for the accessibility of its setter/getter
3364 void ResolveAccessors (EmitContext ec)
3366 getter = GetAccessor (ec.ContainerType, false);
3367 if ((getter != null) && getter.IsStatic)
3370 setter = GetAccessor (ec.ContainerType, true);
3371 if ((setter != null) && setter.IsStatic)
3374 if (setter == null && getter == null){
3375 Report.Error (122, loc, "'{0}' is inaccessible due to its protection level", PropertyInfo.Name);
3379 bool InstanceResolve (EmitContext ec)
3381 if ((instance_expr == null) && ec.IsStatic && !is_static) {
3382 SimpleName.Error_ObjectRefRequired (ec, loc, PropertyInfo.Name);
3386 if (instance_expr != null) {
3387 instance_expr = instance_expr.DoResolve (ec);
3388 if (instance_expr == null)
3392 if (must_do_cs1540_check && (instance_expr != null)) {
3393 if ((instance_expr.Type != ec.ContainerType) &&
3394 ec.ContainerType.IsSubclassOf (instance_expr.Type)) {
3395 Report.Error (1540, loc, "Cannot access protected member `" +
3396 PropertyInfo.DeclaringType + "." + PropertyInfo.Name +
3397 "' via a qualifier of type `" +
3398 TypeManager.CSharpName (instance_expr.Type) +
3399 "'; the qualifier must be of type `" +
3400 TypeManager.CSharpName (ec.ContainerType) +
3401 "' (or derived from it)");
3409 override public Expression DoResolve (EmitContext ec)
3411 if (getter != null){
3412 if (TypeManager.GetArgumentTypes (getter).Length != 0){
3414 117, loc, "`{0}' does not contain a " +
3415 "definition for `{1}'.", getter.DeclaringType,
3421 if (getter == null){
3423 // The following condition happens if the PropertyExpr was
3424 // created, but is invalid (ie, the property is inaccessible),
3425 // and we did not want to embed the knowledge about this in
3426 // the caller routine. This only avoids double error reporting.
3431 Report.Error (154, loc,
3432 "The property `" + PropertyInfo.Name +
3433 "' can not be used in " +
3434 "this context because it lacks a get accessor");
3438 if (!InstanceResolve (ec))
3442 // Only base will allow this invocation to happen.
3444 if (IsBase && getter.IsAbstract){
3445 Report.Error (205, loc, "Cannot call an abstract base property: " +
3446 PropertyInfo.DeclaringType + "." +PropertyInfo.Name);
3453 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
3455 if (setter == null){
3457 // The following condition happens if the PropertyExpr was
3458 // created, but is invalid (ie, the property is inaccessible),
3459 // and we did not want to embed the knowledge about this in
3460 // the caller routine. This only avoids double error reporting.
3465 Report.Error (154, loc,
3466 "The property `" + PropertyInfo.Name +
3467 "' can not be used in " +
3468 "this context because it lacks a set accessor");
3472 if (TypeManager.GetArgumentTypes (setter).Length != 1){
3474 117, loc, "`{0}' does not contain a " +
3475 "definition for `{1}'.", getter.DeclaringType,
3480 if (!InstanceResolve (ec))
3484 // Only base will allow this invocation to happen.
3486 if (IsBase && setter.IsAbstract){
3487 Report.Error (205, loc, "Cannot call an abstract base property: " +
3488 PropertyInfo.DeclaringType + "." +PropertyInfo.Name);
3493 // Check that we are not making changes to a temporary memory location
3495 if (instance_expr != null && instance_expr.Type.IsValueType && !(instance_expr is IMemoryLocation)) {
3496 // FIXME: Provide better error reporting.
3497 Error (1612, "Cannot modify expression because it is not a variable.");
3506 public override void Emit (EmitContext ec)
3511 void EmitInstance (EmitContext ec)
3516 if (instance_expr.Type.IsValueType) {
3517 if (instance_expr is IMemoryLocation) {
3518 ((IMemoryLocation) instance_expr).AddressOf (ec, AddressOp.LoadStore);
3520 LocalTemporary t = new LocalTemporary (ec, instance_expr.Type);
3521 instance_expr.Emit (ec);
3523 t.AddressOf (ec, AddressOp.Store);
3526 instance_expr.Emit (ec);
3529 ec.ig.Emit (OpCodes.Dup);
3533 public void Emit (EmitContext ec, bool leave_copy)
3539 // Special case: length of single dimension array property is turned into ldlen
3541 if ((getter == TypeManager.system_int_array_get_length) ||
3542 (getter == TypeManager.int_array_get_length)){
3543 Type iet = instance_expr.Type;
3546 // System.Array.Length can be called, but the Type does not
3547 // support invoking GetArrayRank, so test for that case first
3549 if (iet != TypeManager.array_type && (iet.GetArrayRank () == 1)) {
3550 ec.ig.Emit (OpCodes.Ldlen);
3551 ec.ig.Emit (OpCodes.Conv_I4);
3556 Invocation.EmitCall (ec, IsBase, IsStatic, new EmptyAddressOf (), getter, null, loc);
3561 ec.ig.Emit (OpCodes.Dup);
3563 temp = new LocalTemporary (ec, this.Type);
3569 // Implements the IAssignMethod interface for assignments
3571 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
3573 prepared = prepare_for_load;
3579 ec.ig.Emit (OpCodes.Dup);
3581 temp = new LocalTemporary (ec, this.Type);
3586 ArrayList args = new ArrayList (1);
3587 args.Add (new Argument (new EmptyAddressOf (), Argument.AType.Expression));
3589 Invocation.EmitCall (ec, IsBase, IsStatic, new EmptyAddressOf (), setter, args, loc);
3595 override public void EmitStatement (EmitContext ec)
3598 ec.ig.Emit (OpCodes.Pop);
3603 /// Fully resolved expression that evaluates to an Event
3605 public class EventExpr : Expression, IMemberExpr {
3606 public readonly EventInfo EventInfo;
3607 Expression instance_expr;
3610 MethodInfo add_accessor, remove_accessor;
3612 public EventExpr (EventInfo ei, Location loc)
3616 eclass = ExprClass.EventAccess;
3618 add_accessor = TypeManager.GetAddMethod (ei);
3619 remove_accessor = TypeManager.GetRemoveMethod (ei);
3621 if (add_accessor.IsStatic || remove_accessor.IsStatic)
3624 if (EventInfo is MyEventBuilder){
3625 MyEventBuilder eb = (MyEventBuilder) EventInfo;
3626 type = eb.EventType;
3629 type = EventInfo.EventHandlerType;
3632 public string Name {
3634 return EventInfo.Name;
3638 public bool IsInstance {
3644 public bool IsStatic {
3650 public Type DeclaringType {
3652 return EventInfo.DeclaringType;
3656 public Expression InstanceExpression {
3658 return instance_expr;
3662 instance_expr = value;
3666 public override Expression DoResolve (EmitContext ec)
3668 if (instance_expr != null) {
3669 instance_expr = instance_expr.DoResolve (ec);
3670 if (instance_expr == null)
3678 public override void Emit (EmitContext ec)
3680 Report.Error (70, loc, "The event `" + Name + "' can only appear on the left hand side of += or -= (except on the defining type)");
3683 public void EmitAddOrRemove (EmitContext ec, Expression source)
3685 BinaryDelegate source_del = (BinaryDelegate) source;
3686 Expression handler = source_del.Right;
3688 Argument arg = new Argument (handler, Argument.AType.Expression);
3689 ArrayList args = new ArrayList ();
3693 if (source_del.IsAddition)
3694 Invocation.EmitCall (
3695 ec, false, IsStatic, instance_expr, add_accessor, args, loc);
3697 Invocation.EmitCall (
3698 ec, false, IsStatic, instance_expr, remove_accessor, args, loc);