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, loc);
333 if ((flags & ResolveFlags.VariableOrValue) == 0) {
334 e.Error_UnexpectedKind (flags, loc);
339 case ExprClass.MethodGroup:
340 if (RootContext.Version == LanguageVersion.ISO_1){
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, loc);
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 = System.Enum.GetUnderlyingType (real_type);
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, Location loc)
840 string kind = "Unknown";
842 kind = ExprClassName (eclass);
844 Report.Error (118, loc, "Expression denotes a `" + kind +
845 "' where a `" + expected + "' was expected");
848 public void Error_UnexpectedKind (ResolveFlags flags, Location loc)
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 public static void Error_NegativeArrayIndex (Location loc)
1272 Report.Error (248, loc, "Cannot create an 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)
1435 public override bool IsNegative {
1444 /// This class is used to wrap literals which belong inside Enums
1446 public class EnumConstant : Constant {
1447 public Constant Child;
1449 public EnumConstant (Constant child, Type enum_type)
1451 eclass = child.eclass;
1456 public override Expression DoResolve (EmitContext ec)
1458 // This should never be invoked, we are born in fully
1459 // initialized state.
1464 public override void Emit (EmitContext ec)
1469 public override object GetValue ()
1471 return Child.GetValue ();
1474 public object GetValueAsEnumType ()
1476 return System.Enum.ToObject (type, Child.GetValue ());
1480 // Converts from one of the valid underlying types for an enumeration
1481 // (int32, uint32, int64, uint64, short, ushort, byte, sbyte) to
1482 // one of the internal compiler literals: Int/UInt/Long/ULong Literals.
1484 public Constant WidenToCompilerConstant ()
1486 Type t = TypeManager.EnumToUnderlying (Child.Type);
1487 object v = ((Constant) Child).GetValue ();;
1489 if (t == TypeManager.int32_type)
1490 return new IntConstant ((int) v);
1491 if (t == TypeManager.uint32_type)
1492 return new UIntConstant ((uint) v);
1493 if (t == TypeManager.int64_type)
1494 return new LongConstant ((long) v);
1495 if (t == TypeManager.uint64_type)
1496 return new ULongConstant ((ulong) v);
1497 if (t == TypeManager.short_type)
1498 return new ShortConstant ((short) v);
1499 if (t == TypeManager.ushort_type)
1500 return new UShortConstant ((ushort) v);
1501 if (t == TypeManager.byte_type)
1502 return new ByteConstant ((byte) v);
1503 if (t == TypeManager.sbyte_type)
1504 return new SByteConstant ((sbyte) v);
1506 throw new Exception ("Invalid enumeration underlying type: " + t);
1510 // Extracts the value in the enumeration on its native representation
1512 public object GetPlainValue ()
1514 Type t = TypeManager.EnumToUnderlying (Child.Type);
1515 object v = ((Constant) Child).GetValue ();;
1517 if (t == TypeManager.int32_type)
1519 if (t == TypeManager.uint32_type)
1521 if (t == TypeManager.int64_type)
1523 if (t == TypeManager.uint64_type)
1525 if (t == TypeManager.short_type)
1527 if (t == TypeManager.ushort_type)
1529 if (t == TypeManager.byte_type)
1531 if (t == TypeManager.sbyte_type)
1537 public override string AsString ()
1539 return Child.AsString ();
1542 public override DoubleConstant ConvertToDouble ()
1544 return Child.ConvertToDouble ();
1547 public override FloatConstant ConvertToFloat ()
1549 return Child.ConvertToFloat ();
1552 public override ULongConstant ConvertToULong ()
1554 return Child.ConvertToULong ();
1557 public override LongConstant ConvertToLong ()
1559 return Child.ConvertToLong ();
1562 public override UIntConstant ConvertToUInt ()
1564 return Child.ConvertToUInt ();
1567 public override IntConstant ConvertToInt ()
1569 return Child.ConvertToInt ();
1572 public override bool IsZeroInteger {
1573 get { return Child.IsZeroInteger; }
1576 public override bool IsNegative {
1578 return Child.IsNegative;
1584 /// This kind of cast is used to encapsulate Value Types in objects.
1586 /// The effect of it is to box the value type emitted by the previous
1589 public class BoxedCast : EmptyCast {
1591 public BoxedCast (Expression expr)
1592 : base (expr, TypeManager.object_type)
1594 eclass = ExprClass.Value;
1597 public BoxedCast (Expression expr, Type target_type)
1598 : base (expr, target_type)
1600 eclass = ExprClass.Value;
1603 public override Expression DoResolve (EmitContext ec)
1605 // This should never be invoked, we are born in fully
1606 // initialized state.
1611 public override void Emit (EmitContext ec)
1615 ec.ig.Emit (OpCodes.Box, child.Type);
1619 public class UnboxCast : EmptyCast {
1620 public UnboxCast (Expression expr, Type return_type)
1621 : base (expr, return_type)
1625 public override Expression DoResolve (EmitContext ec)
1627 // This should never be invoked, we are born in fully
1628 // initialized state.
1633 public override void Emit (EmitContext ec)
1636 ILGenerator ig = ec.ig;
1639 if (t.IsGenericParameter)
1640 ig.Emit (OpCodes.Unbox_Any, t);
1642 ig.Emit (OpCodes.Unbox, t);
1644 LoadFromPtr (ig, t);
1650 /// This is used to perform explicit numeric conversions.
1652 /// Explicit numeric conversions might trigger exceptions in a checked
1653 /// context, so they should generate the conv.ovf opcodes instead of
1656 public class ConvCast : EmptyCast {
1657 public enum Mode : byte {
1658 I1_U1, I1_U2, I1_U4, I1_U8, I1_CH,
1660 I2_I1, I2_U1, I2_U2, I2_U4, I2_U8, I2_CH,
1661 U2_I1, U2_U1, U2_I2, U2_CH,
1662 I4_I1, I4_U1, I4_I2, I4_U2, I4_U4, I4_U8, I4_CH,
1663 U4_I1, U4_U1, U4_I2, U4_U2, U4_I4, U4_CH,
1664 I8_I1, I8_U1, I8_I2, I8_U2, I8_I4, I8_U4, I8_U8, I8_CH,
1665 U8_I1, U8_U1, U8_I2, U8_U2, U8_I4, U8_U4, U8_I8, U8_CH,
1666 CH_I1, CH_U1, CH_I2,
1667 R4_I1, R4_U1, R4_I2, R4_U2, R4_I4, R4_U4, R4_I8, R4_U8, R4_CH,
1668 R8_I1, R8_U1, R8_I2, R8_U2, R8_I4, R8_U4, R8_I8, R8_U8, R8_CH, R8_R4
1674 public ConvCast (EmitContext ec, Expression child, Type return_type, Mode m)
1675 : base (child, return_type)
1677 checked_state = ec.CheckState;
1681 public override Expression DoResolve (EmitContext ec)
1683 // This should never be invoked, we are born in fully
1684 // initialized state.
1689 public override string ToString ()
1691 return String.Format ("ConvCast ({0}, {1})", mode, child);
1694 public override void Emit (EmitContext ec)
1696 ILGenerator ig = ec.ig;
1702 case Mode.I1_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1703 case Mode.I1_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1704 case Mode.I1_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1705 case Mode.I1_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1706 case Mode.I1_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1708 case Mode.U1_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1709 case Mode.U1_CH: /* nothing */ break;
1711 case Mode.I2_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1712 case Mode.I2_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1713 case Mode.I2_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1714 case Mode.I2_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1715 case Mode.I2_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1716 case Mode.I2_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1718 case Mode.U2_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1719 case Mode.U2_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
1720 case Mode.U2_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
1721 case Mode.U2_CH: /* nothing */ break;
1723 case Mode.I4_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1724 case Mode.I4_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1725 case Mode.I4_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
1726 case Mode.I4_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1727 case Mode.I4_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1728 case Mode.I4_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1729 case Mode.I4_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1731 case Mode.U4_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1732 case Mode.U4_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
1733 case Mode.U4_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
1734 case Mode.U4_U2: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
1735 case Mode.U4_I4: ig.Emit (OpCodes.Conv_Ovf_I4_Un); break;
1736 case Mode.U4_CH: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
1738 case Mode.I8_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1739 case Mode.I8_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1740 case Mode.I8_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
1741 case Mode.I8_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1742 case Mode.I8_I4: ig.Emit (OpCodes.Conv_Ovf_I4); break;
1743 case Mode.I8_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1744 case Mode.I8_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1745 case Mode.I8_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1747 case Mode.U8_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1748 case Mode.U8_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
1749 case Mode.U8_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
1750 case Mode.U8_U2: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
1751 case Mode.U8_I4: ig.Emit (OpCodes.Conv_Ovf_I4_Un); break;
1752 case Mode.U8_U4: ig.Emit (OpCodes.Conv_Ovf_U4_Un); break;
1753 case Mode.U8_I8: ig.Emit (OpCodes.Conv_Ovf_I8_Un); break;
1754 case Mode.U8_CH: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
1756 case Mode.CH_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1757 case Mode.CH_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
1758 case Mode.CH_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
1760 case Mode.R4_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1761 case Mode.R4_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1762 case Mode.R4_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
1763 case Mode.R4_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1764 case Mode.R4_I4: ig.Emit (OpCodes.Conv_Ovf_I4); break;
1765 case Mode.R4_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1766 case Mode.R4_I8: ig.Emit (OpCodes.Conv_Ovf_I8); break;
1767 case Mode.R4_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1768 case Mode.R4_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1770 case Mode.R8_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1771 case Mode.R8_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1772 case Mode.R8_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
1773 case Mode.R8_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1774 case Mode.R8_I4: ig.Emit (OpCodes.Conv_Ovf_I4); break;
1775 case Mode.R8_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1776 case Mode.R8_I8: ig.Emit (OpCodes.Conv_Ovf_I8); break;
1777 case Mode.R8_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1778 case Mode.R8_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1779 case Mode.R8_R4: ig.Emit (OpCodes.Conv_R4); break;
1783 case Mode.I1_U1: ig.Emit (OpCodes.Conv_U1); break;
1784 case Mode.I1_U2: ig.Emit (OpCodes.Conv_U2); break;
1785 case Mode.I1_U4: ig.Emit (OpCodes.Conv_U4); break;
1786 case Mode.I1_U8: ig.Emit (OpCodes.Conv_I8); break;
1787 case Mode.I1_CH: ig.Emit (OpCodes.Conv_U2); break;
1789 case Mode.U1_I1: ig.Emit (OpCodes.Conv_I1); break;
1790 case Mode.U1_CH: ig.Emit (OpCodes.Conv_U2); break;
1792 case Mode.I2_I1: ig.Emit (OpCodes.Conv_I1); break;
1793 case Mode.I2_U1: ig.Emit (OpCodes.Conv_U1); break;
1794 case Mode.I2_U2: ig.Emit (OpCodes.Conv_U2); break;
1795 case Mode.I2_U4: ig.Emit (OpCodes.Conv_U4); break;
1796 case Mode.I2_U8: ig.Emit (OpCodes.Conv_I8); break;
1797 case Mode.I2_CH: ig.Emit (OpCodes.Conv_U2); break;
1799 case Mode.U2_I1: ig.Emit (OpCodes.Conv_I1); break;
1800 case Mode.U2_U1: ig.Emit (OpCodes.Conv_U1); break;
1801 case Mode.U2_I2: ig.Emit (OpCodes.Conv_I2); break;
1802 case Mode.U2_CH: /* nothing */ break;
1804 case Mode.I4_I1: ig.Emit (OpCodes.Conv_I1); break;
1805 case Mode.I4_U1: ig.Emit (OpCodes.Conv_U1); break;
1806 case Mode.I4_I2: ig.Emit (OpCodes.Conv_I2); break;
1807 case Mode.I4_U4: /* nothing */ break;
1808 case Mode.I4_U2: ig.Emit (OpCodes.Conv_U2); break;
1809 case Mode.I4_U8: ig.Emit (OpCodes.Conv_I8); break;
1810 case Mode.I4_CH: ig.Emit (OpCodes.Conv_U2); break;
1812 case Mode.U4_I1: ig.Emit (OpCodes.Conv_I1); break;
1813 case Mode.U4_U1: ig.Emit (OpCodes.Conv_U1); break;
1814 case Mode.U4_I2: ig.Emit (OpCodes.Conv_I2); break;
1815 case Mode.U4_U2: ig.Emit (OpCodes.Conv_U2); break;
1816 case Mode.U4_I4: /* nothing */ break;
1817 case Mode.U4_CH: ig.Emit (OpCodes.Conv_U2); break;
1819 case Mode.I8_I1: ig.Emit (OpCodes.Conv_I1); break;
1820 case Mode.I8_U1: ig.Emit (OpCodes.Conv_U1); break;
1821 case Mode.I8_I2: ig.Emit (OpCodes.Conv_I2); break;
1822 case Mode.I8_U2: ig.Emit (OpCodes.Conv_U2); break;
1823 case Mode.I8_I4: ig.Emit (OpCodes.Conv_I4); break;
1824 case Mode.I8_U4: ig.Emit (OpCodes.Conv_U4); break;
1825 case Mode.I8_U8: /* nothing */ break;
1826 case Mode.I8_CH: ig.Emit (OpCodes.Conv_U2); break;
1828 case Mode.U8_I1: ig.Emit (OpCodes.Conv_I1); break;
1829 case Mode.U8_U1: ig.Emit (OpCodes.Conv_U1); break;
1830 case Mode.U8_I2: ig.Emit (OpCodes.Conv_I2); break;
1831 case Mode.U8_U2: ig.Emit (OpCodes.Conv_U2); break;
1832 case Mode.U8_I4: ig.Emit (OpCodes.Conv_I4); break;
1833 case Mode.U8_U4: ig.Emit (OpCodes.Conv_U4); break;
1834 case Mode.U8_I8: /* nothing */ break;
1835 case Mode.U8_CH: ig.Emit (OpCodes.Conv_U2); break;
1837 case Mode.CH_I1: ig.Emit (OpCodes.Conv_I1); break;
1838 case Mode.CH_U1: ig.Emit (OpCodes.Conv_U1); break;
1839 case Mode.CH_I2: ig.Emit (OpCodes.Conv_I2); break;
1841 case Mode.R4_I1: ig.Emit (OpCodes.Conv_I1); break;
1842 case Mode.R4_U1: ig.Emit (OpCodes.Conv_U1); break;
1843 case Mode.R4_I2: ig.Emit (OpCodes.Conv_I2); break;
1844 case Mode.R4_U2: ig.Emit (OpCodes.Conv_U2); break;
1845 case Mode.R4_I4: ig.Emit (OpCodes.Conv_I4); break;
1846 case Mode.R4_U4: ig.Emit (OpCodes.Conv_U4); break;
1847 case Mode.R4_I8: ig.Emit (OpCodes.Conv_I8); break;
1848 case Mode.R4_U8: ig.Emit (OpCodes.Conv_U8); break;
1849 case Mode.R4_CH: ig.Emit (OpCodes.Conv_U2); break;
1851 case Mode.R8_I1: ig.Emit (OpCodes.Conv_I1); break;
1852 case Mode.R8_U1: ig.Emit (OpCodes.Conv_U1); break;
1853 case Mode.R8_I2: ig.Emit (OpCodes.Conv_I2); break;
1854 case Mode.R8_U2: ig.Emit (OpCodes.Conv_U2); break;
1855 case Mode.R8_I4: ig.Emit (OpCodes.Conv_I4); break;
1856 case Mode.R8_U4: ig.Emit (OpCodes.Conv_U4); break;
1857 case Mode.R8_I8: ig.Emit (OpCodes.Conv_I8); break;
1858 case Mode.R8_U8: ig.Emit (OpCodes.Conv_U8); break;
1859 case Mode.R8_CH: ig.Emit (OpCodes.Conv_U2); break;
1860 case Mode.R8_R4: ig.Emit (OpCodes.Conv_R4); break;
1866 public class OpcodeCast : EmptyCast {
1870 public OpcodeCast (Expression child, Type return_type, OpCode op)
1871 : base (child, return_type)
1875 second_valid = false;
1878 public OpcodeCast (Expression child, Type return_type, OpCode op, OpCode op2)
1879 : base (child, return_type)
1884 second_valid = true;
1887 public override Expression DoResolve (EmitContext ec)
1889 // This should never be invoked, we are born in fully
1890 // initialized state.
1895 public override void Emit (EmitContext ec)
1906 /// This kind of cast is used to encapsulate a child and cast it
1907 /// to the class requested
1909 public class ClassCast : EmptyCast {
1910 public ClassCast (Expression child, Type return_type)
1911 : base (child, return_type)
1916 public override Expression DoResolve (EmitContext ec)
1918 // This should never be invoked, we are born in fully
1919 // initialized state.
1924 public override void Emit (EmitContext ec)
1928 if (child.Type.IsGenericParameter)
1929 ec.ig.Emit (OpCodes.Box, child.Type);
1931 if (type.IsGenericParameter)
1932 ec.ig.Emit (OpCodes.Unbox_Any, type);
1934 ec.ig.Emit (OpCodes.Castclass, type);
1939 /// SimpleName expressions are initially formed of a single
1940 /// word and it only happens at the beginning of the expression.
1944 /// The expression will try to be bound to a Field, a Method
1945 /// group or a Property. If those fail we pass the name to our
1946 /// caller and the SimpleName is compounded to perform a type
1947 /// lookup. The idea behind this process is that we want to avoid
1948 /// creating a namespace map from the assemblies, as that requires
1949 /// the GetExportedTypes function to be called and a hashtable to
1950 /// be constructed which reduces startup time. If later we find
1951 /// that this is slower, we should create a `NamespaceExpr' expression
1952 /// that fully participates in the resolution process.
1954 /// For example `System.Console.WriteLine' is decomposed into
1955 /// MemberAccess (MemberAccess (SimpleName ("System"), "Console"), "WriteLine")
1957 /// The first SimpleName wont produce a match on its own, so it will
1959 /// MemberAccess (SimpleName ("System.Console"), "WriteLine").
1961 /// System.Console will produce a TypeExpr match.
1963 /// The downside of this is that we might be hitting `LookupType' too many
1964 /// times with this scheme.
1966 public class SimpleName : Expression {
1968 public readonly TypeArguments Arguments;
1971 // If true, then we are a simple name, not composed with a ".
1975 public SimpleName (string a, string b, Location l)
1977 Name = String.Concat (a, ".", b);
1982 public SimpleName (string name, Location l)
1989 public SimpleName (string name, TypeArguments args, Location l)
1997 public static void Error_ObjectRefRequired (EmitContext ec, Location l, string name)
1999 if (ec.IsFieldInitializer)
2002 "A field initializer cannot reference the non-static field, " +
2003 "method or property `"+name+"'");
2007 "An object reference is required " +
2008 "for the non-static field `"+name+"'");
2012 // Checks whether we are trying to access an instance
2013 // property, method or field from a static body.
2015 Expression MemberStaticCheck (EmitContext ec, Expression e)
2017 if (e is IMemberExpr){
2018 IMemberExpr member = (IMemberExpr) e;
2020 if (!member.IsStatic){
2021 Error_ObjectRefRequired (ec, loc, Name);
2029 public override Expression DoResolve (EmitContext ec)
2031 return SimpleNameResolve (ec, null, false, false);
2034 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
2036 return SimpleNameResolve (ec, right_side, false, false);
2040 public Expression DoResolveAllowStatic (EmitContext ec, bool intermediate)
2042 return SimpleNameResolve (ec, null, true, intermediate);
2045 public override Expression ResolveAsTypeStep (EmitContext ec)
2047 DeclSpace ds = ec.DeclSpace;
2048 NamespaceEntry ns = ds.NamespaceEntry;
2053 // Since we are cheating: we only do the Alias lookup for
2054 // namespaces if the name does not include any dots in it
2056 if (ns != null && is_base)
2057 alias_value = ns.LookupAlias (Name);
2061 TypeParameterExpr generic_type = ds.LookupGeneric (Name, loc);
2062 if (generic_type != null)
2063 return generic_type.ResolveAsTypeTerminal (ec);
2065 if (ec.ResolvingTypeTree){
2066 int errors = Report.Errors;
2067 Type dt = ds.FindType (loc, Name);
2069 if (Report.Errors != errors)
2073 return new TypeExpression (dt, loc);
2075 if (alias_value != null){
2076 if (alias_value.IsType)
2077 return alias_value.Type;
2078 if ((t = RootContext.LookupType (ds, alias_value.Name, true, loc)) != null)
2084 // First, the using aliases
2086 if (alias_value != null){
2087 if (alias_value.IsType)
2088 return alias_value.Type;
2089 if ((t = RootContext.LookupType (ds, alias_value.Name, true, loc)) != null)
2092 // we have alias value, but it isn't Type, so try if it's namespace
2093 return new SimpleName (alias_value.Name, loc);
2097 // Stage 2: Lookup up if we are an alias to a type
2101 if ((t = RootContext.LookupType (ds, Name, true, loc)) != null)
2104 // No match, maybe our parent can compose us
2105 // into something meaningful.
2109 Expression SimpleNameResolve (EmitContext ec, Expression right_side,
2110 bool allow_static, bool intermediate)
2112 Expression e = DoSimpleNameResolve (ec, right_side, allow_static, intermediate);
2116 Block current_block = ec.CurrentBlock;
2117 if (current_block != null){
2118 //LocalInfo vi = current_block.GetLocalInfo (Name);
2120 current_block.IsVariableNameUsedInChildBlock(Name)) {
2121 Report.Error (135, Location,
2122 "'{0}' has a different meaning in a " +
2123 "child block", Name);
2128 if (e.Type != null && e.Type.IsPointer && !ec.InUnsafe) {
2137 /// 7.5.2: Simple Names.
2139 /// Local Variables and Parameters are handled at
2140 /// parse time, so they never occur as SimpleNames.
2142 /// The `allow_static' flag is used by MemberAccess only
2143 /// and it is used to inform us that it is ok for us to
2144 /// avoid the static check, because MemberAccess might end
2145 /// up resolving the Name as a Type name and the access as
2146 /// a static type access.
2148 /// ie: Type Type; .... { Type.GetType (""); }
2150 /// Type is both an instance variable and a Type; Type.GetType
2151 /// is the static method not an instance method of type.
2153 Expression DoSimpleNameResolve (EmitContext ec, Expression right_side, bool allow_static, bool intermediate)
2155 Expression e = null;
2158 // Stage 1: Performed by the parser (binding to locals or parameters).
2160 Block current_block = ec.CurrentBlock;
2161 if (current_block != null){
2162 LocalInfo vi = current_block.GetLocalInfo (Name);
2166 var = new LocalVariableReference (ec.CurrentBlock, Name, loc);
2168 if (right_side != null)
2169 return var.ResolveLValue (ec, right_side);
2171 return var.Resolve (ec);
2175 Parameter par = null;
2176 Parameters pars = current_block.Parameters;
2178 par = pars.GetParameterByName (Name, out idx);
2181 ParameterReference param;
2183 param = new ParameterReference (pars, current_block, idx, Name, loc);
2185 if (right_side != null)
2186 return param.ResolveLValue (ec, right_side);
2188 return param.Resolve (ec);
2193 // Stage 2: Lookup members
2196 DeclSpace lookup_ds = ec.DeclSpace;
2198 if (lookup_ds.TypeBuilder == null)
2201 e = MemberLookup (ec, lookup_ds.TypeBuilder, Name, loc);
2205 lookup_ds =lookup_ds.Parent;
2206 } while (lookup_ds != null);
2208 if (e == null && ec.ContainerType != null)
2209 e = MemberLookup (ec, ec.ContainerType, Name, loc);
2213 // Since we are cheating (is_base is our hint
2214 // that we are the beginning of the name): we
2215 // only do the Alias lookup for namespaces if
2216 // the name does not include any dots in it
2218 NamespaceEntry ns = ec.DeclSpace.NamespaceEntry;
2219 if (is_base && ns != null){
2220 IAlias alias_value = ns.LookupAlias (Name);
2221 if (alias_value != null){
2222 if (alias_value.IsType)
2223 return alias_value.Type;
2225 Name = alias_value.Name;
2228 if ((t = TypeManager.LookupType (Name)) != null)
2229 return new TypeExpression (t, loc);
2231 // No match, maybe our parent can compose us
2232 // into something meaningful.
2237 return ResolveAsTypeStep (ec);
2243 if (e is IMemberExpr) {
2244 e = MemberAccess.ResolveMemberAccess (ec, e, null, loc, this);
2248 IMemberExpr me = e as IMemberExpr;
2252 if (Arguments != null) {
2253 MethodGroupExpr mg = me as MethodGroupExpr;
2257 return mg.ResolveGeneric (ec, Arguments);
2260 // This fails if ResolveMemberAccess() was unable to decide whether
2261 // it's a field or a type of the same name.
2263 if (!me.IsStatic && (me.InstanceExpression == null))
2267 TypeManager.IsNestedFamilyAccessible (me.InstanceExpression.Type, me.DeclaringType) &&
2268 me.InstanceExpression.Type != me.DeclaringType &&
2269 !TypeManager.IsFamilyAccessible (me.InstanceExpression.Type, me.DeclaringType) &&
2270 (!intermediate || !MemberAccess.IdenticalNameAndTypeName (ec, this, e, loc))) {
2271 Error (38, "Cannot access nonstatic member `" + me.Name + "' of " +
2272 "outer type `" + me.DeclaringType + "' via nested type `" +
2273 me.InstanceExpression.Type + "'");
2277 return (right_side != null)
2278 ? e.DoResolveLValue (ec, right_side)
2282 if (ec.IsStatic || ec.IsFieldInitializer){
2286 return MemberStaticCheck (ec, e);
2291 public override void Emit (EmitContext ec)
2294 // If this is ever reached, then we failed to
2295 // find the name as a namespace
2298 Error (103, "The name `" + Name +
2299 "' does not exist in the class `" +
2300 ec.DeclSpace.Name + "'");
2303 public override string ToString ()
2310 /// Fully resolved expression that evaluates to a type
2312 public abstract class TypeExpr : Expression, IAlias {
2313 override public Expression ResolveAsTypeStep (EmitContext ec)
2315 TypeExpr t = DoResolveAsTypeStep (ec);
2319 eclass = ExprClass.Type;
2323 override public Expression DoResolve (EmitContext ec)
2325 return ResolveAsTypeTerminal (ec);
2328 override public void Emit (EmitContext ec)
2330 throw new Exception ("Should never be called");
2333 public virtual bool CheckAccessLevel (DeclSpace ds)
2335 return ds.CheckAccessLevel (Type);
2338 public virtual bool AsAccessible (DeclSpace ds, int flags)
2340 return ds.AsAccessible (Type, flags);
2343 public virtual bool IsClass {
2344 get { return Type.IsClass; }
2347 public virtual bool IsValueType {
2348 get { return Type.IsValueType; }
2351 public virtual bool IsInterface {
2352 get { return Type.IsInterface; }
2355 public virtual bool IsSealed {
2356 get { return Type.IsSealed; }
2359 public virtual bool CanInheritFrom ()
2361 if (Type == TypeManager.enum_type ||
2362 (Type == TypeManager.value_type && RootContext.StdLib) ||
2363 Type == TypeManager.multicast_delegate_type ||
2364 Type == TypeManager.delegate_type ||
2365 Type == TypeManager.array_type)
2371 public virtual bool IsAttribute {
2373 return Type == TypeManager.attribute_type ||
2374 Type.IsSubclassOf (TypeManager.attribute_type);
2378 public abstract TypeExpr DoResolveAsTypeStep (EmitContext ec);
2380 public virtual Type ResolveType (EmitContext ec)
2382 TypeExpr t = ResolveAsTypeTerminal (ec);
2389 public abstract string Name {
2393 public override bool Equals (object obj)
2395 TypeExpr tobj = obj as TypeExpr;
2399 return Type == tobj.Type;
2402 public override int GetHashCode ()
2404 return Type.GetHashCode ();
2407 public override string ToString ()
2412 bool IAlias.IsType {
2413 get { return true; }
2416 TypeExpr IAlias.Type {
2423 public class TypeExpression : TypeExpr, IAlias {
2424 public TypeExpression (Type t, Location l)
2427 eclass = ExprClass.Type;
2431 public override TypeExpr DoResolveAsTypeStep (EmitContext ec)
2436 public override string Name {
2438 return Type.ToString ();
2442 string IAlias.Name {
2444 return Type.FullName != null ? Type.FullName : Type.Name;
2450 /// Used to create types from a fully qualified name. These are just used
2451 /// by the parser to setup the core types. A TypeLookupExpression is always
2452 /// classified as a type.
2454 public class TypeLookupExpression : TypeExpr {
2457 public TypeLookupExpression (string name)
2462 public override TypeExpr DoResolveAsTypeStep (EmitContext ec)
2465 TypeExpr texpr = RootContext.LookupType (
2466 ec.DeclSpace, name, false, Location.Null);
2470 type = texpr.ResolveType (ec);
2478 public override string Name {
2486 /// Represents an "unbound generic type", ie. typeof (Foo<>).
2489 public class UnboundTypeExpression : TypeLookupExpression {
2490 public UnboundTypeExpression (string name)
2495 public class TypeAliasExpression : TypeExpr, IAlias {
2500 public TypeAliasExpression (TypeExpr texpr, TypeArguments args, Location l)
2504 loc = texpr.Location;
2506 eclass = ExprClass.Type;
2508 name = texpr.Name + "<" + args.ToString () + ">";
2513 public override string Name {
2514 get { return name; }
2517 public override TypeExpr DoResolveAsTypeStep (EmitContext ec)
2519 Type type = texpr.ResolveType (ec);
2523 int num_args = TypeManager.GetNumberOfTypeArguments (type);
2526 if (num_args == 0) {
2527 Report.Error (308, loc,
2528 "The non-generic type `{0}' cannot " +
2529 "be used with type arguments.",
2530 TypeManager.CSharpName (type));
2534 ConstructedType ctype = new ConstructedType (type, args, loc);
2535 return ctype.ResolveAsTypeTerminal (ec);
2536 } else if (num_args > 0) {
2537 Report.Error (305, loc,
2538 "Using the generic type `{0}' " +
2539 "requires {1} type arguments",
2540 TypeManager.GetFullName (type), num_args);
2544 return new TypeExpression (type, loc);
2547 public override Type ResolveType (EmitContext ec)
2549 TypeExpr t = ResolveAsTypeTerminal (ec);
2553 type = t.ResolveType (ec);
2557 public override bool CheckAccessLevel (DeclSpace ds)
2559 return texpr.CheckAccessLevel (ds);
2562 public override bool AsAccessible (DeclSpace ds, int flags)
2564 return texpr.AsAccessible (ds, flags);
2567 public override bool IsClass {
2568 get { return texpr.IsClass; }
2571 public override bool IsValueType {
2572 get { return texpr.IsValueType; }
2575 public override bool IsInterface {
2576 get { return texpr.IsInterface; }
2579 public override bool IsSealed {
2580 get { return texpr.IsSealed; }
2583 public override bool IsAttribute {
2584 get { return texpr.IsAttribute; }
2589 /// MethodGroup Expression.
2591 /// This is a fully resolved expression that evaluates to a type
2593 public class MethodGroupExpr : Expression, IMemberExpr {
2594 public MethodBase [] Methods;
2595 Expression instance_expression = null;
2596 bool is_explicit_impl = false;
2597 bool has_type_arguments = false;
2598 bool identical_type_name = false;
2601 public MethodGroupExpr (MemberInfo [] mi, Location l)
2603 Methods = new MethodBase [mi.Length];
2604 mi.CopyTo (Methods, 0);
2605 eclass = ExprClass.MethodGroup;
2606 type = TypeManager.object_type;
2610 public MethodGroupExpr (ArrayList list, Location l)
2612 Methods = new MethodBase [list.Count];
2615 list.CopyTo (Methods, 0);
2617 foreach (MemberInfo m in list){
2618 if (!(m is MethodBase)){
2619 Console.WriteLine ("Name " + m.Name);
2620 Console.WriteLine ("Found a: " + m.GetType ().FullName);
2627 eclass = ExprClass.MethodGroup;
2628 type = TypeManager.object_type;
2631 public Type DeclaringType {
2634 // We assume that the top-level type is in the end
2636 return Methods [Methods.Length - 1].DeclaringType;
2637 //return Methods [0].DeclaringType;
2642 // `A method group may have associated an instance expression'
2644 public Expression InstanceExpression {
2646 return instance_expression;
2650 instance_expression = value;
2654 public bool IsExplicitImpl {
2656 return is_explicit_impl;
2660 is_explicit_impl = value;
2664 public bool HasTypeArguments {
2666 return has_type_arguments;
2670 has_type_arguments = value;
2674 public bool IdenticalTypeName {
2676 return identical_type_name;
2680 identical_type_name = value;
2684 public bool IsBase {
2693 public string Name {
2695 //return Methods [0].Name;
2696 return Methods [Methods.Length - 1].Name;
2700 public bool IsInstance {
2702 foreach (MethodBase mb in Methods)
2710 public bool IsStatic {
2712 foreach (MethodBase mb in Methods)
2720 override public Expression DoResolve (EmitContext ec)
2723 instance_expression = null;
2725 if (instance_expression != null) {
2726 instance_expression = instance_expression.DoResolve (ec);
2727 if (instance_expression == null)
2734 public void ReportUsageError ()
2736 Report.Error (654, loc, "Method `" + DeclaringType + "." +
2737 Name + "()' is referenced without parentheses");
2740 override public void Emit (EmitContext ec)
2742 ReportUsageError ();
2745 bool RemoveMethods (bool keep_static)
2747 ArrayList smethods = new ArrayList ();
2749 foreach (MethodBase mb in Methods){
2750 if (mb.IsStatic == keep_static)
2754 if (smethods.Count == 0)
2757 Methods = new MethodBase [smethods.Count];
2758 smethods.CopyTo (Methods, 0);
2764 /// Removes any instance methods from the MethodGroup, returns
2765 /// false if the resulting set is empty.
2767 public bool RemoveInstanceMethods ()
2769 return RemoveMethods (true);
2773 /// Removes any static methods from the MethodGroup, returns
2774 /// false if the resulting set is empty.
2776 public bool RemoveStaticMethods ()
2778 return RemoveMethods (false);
2781 public Expression ResolveGeneric (EmitContext ec, TypeArguments args)
2783 if (args.Resolve (ec) == false)
2786 Type[] atypes = args.Arguments;
2788 int first_count = 0;
2789 MethodInfo first = null;
2791 ArrayList list = new ArrayList ();
2792 foreach (MethodBase mb in Methods) {
2793 MethodInfo mi = mb as MethodInfo;
2794 if ((mi == null) || !mi.HasGenericParameters)
2797 Type[] gen_params = mi.GetGenericArguments ();
2799 if (first == null) {
2801 first_count = gen_params.Length;
2804 if (gen_params.Length != atypes.Length)
2807 list.Add (mi.BindGenericParameters (atypes));
2810 if (list.Count > 0) {
2811 MethodGroupExpr new_mg = new MethodGroupExpr (list, Location);
2812 new_mg.InstanceExpression = InstanceExpression;
2813 new_mg.HasTypeArguments = true;
2819 305, loc, "Using the generic method `{0}' " +
2820 "requires {1} type arguments", Name,
2824 308, loc, "The non-generic method `{0}' " +
2825 "cannot be used with type arguments", Name);
2832 /// Fully resolved expression that evaluates to a Field
2834 public class FieldExpr : Expression, IAssignMethod, IMemoryLocation, IMemberExpr, IVariable {
2835 public readonly FieldInfo FieldInfo;
2836 Expression instance_expr;
2837 VariableInfo variable_info;
2839 LocalTemporary temp;
2841 bool is_field_initializer;
2843 public FieldExpr (FieldInfo fi, Location l)
2846 eclass = ExprClass.Variable;
2847 type = TypeManager.TypeToCoreType (fi.FieldType);
2851 public string Name {
2853 return FieldInfo.Name;
2857 public bool IsInstance {
2859 return !FieldInfo.IsStatic;
2863 public bool IsStatic {
2865 return FieldInfo.IsStatic;
2869 public Type DeclaringType {
2871 return FieldInfo.DeclaringType;
2875 public Expression InstanceExpression {
2877 return instance_expr;
2881 instance_expr = value;
2885 public bool IsFieldInitializer {
2887 return is_field_initializer;
2891 is_field_initializer = value;
2895 public VariableInfo VariableInfo {
2897 return variable_info;
2901 override public Expression DoResolve (EmitContext ec)
2903 if (!FieldInfo.IsStatic){
2904 if (instance_expr == null){
2906 // This can happen when referencing an instance field using
2907 // a fully qualified type expression: TypeName.InstanceField = xxx
2909 SimpleName.Error_ObjectRefRequired (ec, loc, FieldInfo.Name);
2913 // Resolve the field's instance expression while flow analysis is turned
2914 // off: when accessing a field "a.b", we must check whether the field
2915 // "a.b" is initialized, not whether the whole struct "a" is initialized.
2916 instance_expr = instance_expr.Resolve (ec, ResolveFlags.VariableOrValue |
2917 ResolveFlags.DisableFlowAnalysis);
2918 if (instance_expr == null)
2922 ObsoleteAttribute oa;
2923 FieldBase f = TypeManager.GetField (FieldInfo);
2925 oa = f.GetObsoleteAttribute (f.Parent);
2927 AttributeTester.Report_ObsoleteMessage (oa, f.GetSignatureForError (), loc);
2928 // To be sure that type is external because we do not register generated fields
2929 } else if (!(FieldInfo.DeclaringType is TypeBuilder)) {
2930 oa = AttributeTester.GetMemberObsoleteAttribute (FieldInfo);
2932 AttributeTester.Report_ObsoleteMessage (oa, TypeManager.GetFullNameSignature (FieldInfo), loc);
2935 // If the instance expression is a local variable or parameter.
2936 IVariable var = instance_expr as IVariable;
2937 if ((var == null) || (var.VariableInfo == null))
2940 VariableInfo vi = var.VariableInfo;
2941 if (!vi.IsFieldAssigned (ec, FieldInfo.Name, loc))
2944 variable_info = vi.GetSubStruct (FieldInfo.Name);
2948 void Report_AssignToReadonly (bool is_instance)
2953 msg = "Readonly field can not be assigned outside " +
2954 "of constructor or variable initializer";
2956 msg = "A static readonly field can only be assigned in " +
2957 "a static constructor";
2959 Report.Error (is_instance ? 191 : 198, loc, msg);
2962 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
2964 IVariable var = instance_expr as IVariable;
2965 if ((var != null) && (var.VariableInfo != null))
2966 var.VariableInfo.SetFieldAssigned (ec, FieldInfo.Name);
2968 Expression e = DoResolve (ec);
2973 if (!FieldInfo.IsStatic && (instance_expr.Type.IsValueType && !(instance_expr is IMemoryLocation))) {
2974 // FIXME: Provide better error reporting.
2975 Error (1612, "Cannot modify expression because it is not a variable.");
2979 if (!FieldInfo.IsInitOnly)
2982 FieldBase fb = TypeManager.GetField (FieldInfo);
2987 // InitOnly fields can only be assigned in constructors
2990 if (ec.IsConstructor){
2991 if (IsStatic && !ec.IsStatic)
2992 Report_AssignToReadonly (false);
2995 if (!is_field_initializer &&
2996 (ec.TypeContainer.CurrentType != null))
2997 ctype = ec.TypeContainer.CurrentType.ResolveType (ec);
2999 ctype = ec.ContainerType;
3001 if (TypeManager.IsEqual (ctype, FieldInfo.DeclaringType))
3005 Report_AssignToReadonly (!IsStatic);
3010 public bool VerifyFixed (bool is_expression)
3012 IVariable variable = instance_expr as IVariable;
3013 if ((variable == null) || !variable.VerifyFixed (true))
3019 public void Emit (EmitContext ec, bool leave_copy)
3021 ILGenerator ig = ec.ig;
3022 bool is_volatile = false;
3024 if (FieldInfo is FieldBuilder){
3025 FieldBase f = TypeManager.GetField (FieldInfo);
3027 if ((f.ModFlags & Modifiers.VOLATILE) != 0)
3030 f.status |= Field.Status.USED;
3034 if (FieldInfo.IsStatic){
3036 ig.Emit (OpCodes.Volatile);
3038 ig.Emit (OpCodes.Ldsfld, FieldInfo);
3044 ig.Emit (OpCodes.Volatile);
3046 ig.Emit (OpCodes.Ldfld, FieldInfo);
3050 ec.ig.Emit (OpCodes.Dup);
3051 if (!FieldInfo.IsStatic) {
3052 temp = new LocalTemporary (ec, this.Type);
3058 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
3060 FieldAttributes fa = FieldInfo.Attributes;
3061 bool is_static = (fa & FieldAttributes.Static) != 0;
3062 bool is_readonly = (fa & FieldAttributes.InitOnly) != 0;
3063 ILGenerator ig = ec.ig;
3064 prepared = prepare_for_load;
3066 if (is_readonly && !ec.IsConstructor){
3067 Report_AssignToReadonly (!is_static);
3073 if (prepare_for_load)
3074 ig.Emit (OpCodes.Dup);
3079 ec.ig.Emit (OpCodes.Dup);
3080 if (!FieldInfo.IsStatic) {
3081 temp = new LocalTemporary (ec, this.Type);
3086 if (FieldInfo is FieldBuilder){
3087 FieldBase f = TypeManager.GetField (FieldInfo);
3089 if ((f.ModFlags & Modifiers.VOLATILE) != 0)
3090 ig.Emit (OpCodes.Volatile);
3092 f.status |= Field.Status.ASSIGNED;
3097 ig.Emit (OpCodes.Stsfld, FieldInfo);
3099 ig.Emit (OpCodes.Stfld, FieldInfo);
3105 void EmitInstance (EmitContext ec)
3107 if (instance_expr.Type.IsValueType) {
3108 if (instance_expr is IMemoryLocation) {
3109 ((IMemoryLocation) instance_expr).AddressOf (ec, AddressOp.LoadStore);
3111 LocalTemporary t = new LocalTemporary (ec, instance_expr.Type);
3112 instance_expr.Emit (ec);
3114 t.AddressOf (ec, AddressOp.Store);
3117 instance_expr.Emit (ec);
3120 public override void Emit (EmitContext ec)
3125 public void AddressOf (EmitContext ec, AddressOp mode)
3127 ILGenerator ig = ec.ig;
3129 if (FieldInfo is FieldBuilder){
3130 FieldBase f = TypeManager.GetField (FieldInfo);
3132 if ((f.ModFlags & Modifiers.VOLATILE) != 0){
3133 Error (676, "volatile variable: can not take its address, or pass as ref/out parameter");
3137 if ((mode & AddressOp.Store) != 0)
3138 f.status |= Field.Status.ASSIGNED;
3139 if ((mode & AddressOp.Load) != 0)
3140 f.status |= Field.Status.USED;
3145 // Handle initonly fields specially: make a copy and then
3146 // get the address of the copy.
3149 if (FieldInfo.IsInitOnly){
3151 if (ec.IsConstructor){
3152 if (FieldInfo.IsStatic){
3164 local = ig.DeclareLocal (type);
3165 ig.Emit (OpCodes.Stloc, local);
3166 ig.Emit (OpCodes.Ldloca, local);
3171 if (FieldInfo.IsStatic){
3172 ig.Emit (OpCodes.Ldsflda, FieldInfo);
3175 ig.Emit (OpCodes.Ldflda, FieldInfo);
3181 // A FieldExpr whose address can not be taken
3183 public class FieldExprNoAddress : FieldExpr, IMemoryLocation {
3184 public FieldExprNoAddress (FieldInfo fi, Location loc) : base (fi, loc)
3188 public new void AddressOf (EmitContext ec, AddressOp mode)
3190 Report.Error (-215, "Report this: Taking the address of a remapped parameter not supported");
3195 /// Expression that evaluates to a Property. The Assign class
3196 /// might set the `Value' expression if we are in an assignment.
3198 /// This is not an LValue because we need to re-write the expression, we
3199 /// can not take data from the stack and store it.
3201 public class PropertyExpr : ExpressionStatement, IAssignMethod, IMemberExpr {
3202 public readonly PropertyInfo PropertyInfo;
3205 // This is set externally by the `BaseAccess' class
3208 MethodInfo getter, setter;
3210 bool must_do_cs1540_check;
3212 Expression instance_expr;
3213 LocalTemporary temp;
3216 public PropertyExpr (EmitContext ec, PropertyInfo pi, Location l)
3219 eclass = ExprClass.PropertyAccess;
3223 type = TypeManager.TypeToCoreType (pi.PropertyType);
3225 ResolveAccessors (ec);
3228 public string Name {
3230 return PropertyInfo.Name;
3234 public bool IsInstance {
3240 public bool IsStatic {
3246 public Type DeclaringType {
3248 return PropertyInfo.DeclaringType;
3253 // The instance expression associated with this expression
3255 public Expression InstanceExpression {
3257 instance_expr = value;
3261 return instance_expr;
3265 public bool VerifyAssignable ()
3267 if (setter == null) {
3268 Report.Error (200, loc,
3269 "The property `" + PropertyInfo.Name +
3270 "' can not be assigned to, as it has not set accessor");
3277 void FindAccessors (Type invocation_type)
3279 BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic |
3280 BindingFlags.Static | BindingFlags.Instance |
3281 BindingFlags.DeclaredOnly;
3283 Type current = PropertyInfo.DeclaringType;
3284 for (; current != null; current = current.BaseType) {
3285 MemberInfo[] group = TypeManager.MemberLookup (
3286 invocation_type, invocation_type, current,
3287 MemberTypes.Property, flags, PropertyInfo.Name, null);
3292 if (group.Length != 1)
3293 // Oooops, can this ever happen ?
3296 PropertyInfo pi = (PropertyInfo) group [0];
3299 getter = pi.GetGetMethod (true);;
3302 setter = pi.GetSetMethod (true);;
3304 MethodInfo accessor = getter != null ? getter : setter;
3306 if (!accessor.IsVirtual)
3311 bool IsAccessorAccessible (Type invocation_type, MethodInfo mi)
3313 MethodAttributes ma = mi.Attributes & MethodAttributes.MemberAccessMask;
3316 // If only accessible to the current class or children
3318 if (ma == MethodAttributes.Private) {
3319 Type declaring_type = mi.DeclaringType;
3321 if (invocation_type != declaring_type)
3322 return TypeManager.IsNestedFamilyAccessible (invocation_type, declaring_type);
3327 // FamAndAssem requires that we not only derivate, but we are on the
3330 if (ma == MethodAttributes.FamANDAssem){
3331 return (mi.DeclaringType.Assembly != invocation_type.Assembly);
3334 // Assembly and FamORAssem succeed if we're in the same assembly.
3335 if ((ma == MethodAttributes.Assembly) || (ma == MethodAttributes.FamORAssem)){
3336 if (mi.DeclaringType.Assembly == invocation_type.Assembly)
3340 // We already know that we aren't in the same assembly.
3341 if (ma == MethodAttributes.Assembly)
3344 // Family and FamANDAssem require that we derive.
3345 if ((ma == MethodAttributes.Family) || (ma == MethodAttributes.FamANDAssem) || (ma == MethodAttributes.FamORAssem)){
3346 if (!TypeManager.IsNestedFamilyAccessible (invocation_type, mi.DeclaringType))
3349 if (!TypeManager.IsNestedChildOf (invocation_type, mi.DeclaringType))
3350 must_do_cs1540_check = true;
3360 // We also perform the permission checking here, as the PropertyInfo does not
3361 // hold the information for the accessibility of its setter/getter
3363 void ResolveAccessors (EmitContext ec)
3365 FindAccessors (ec.ContainerType);
3367 if (setter != null && !IsAccessorAccessible (ec.ContainerType, setter) ||
3368 getter != null && !IsAccessorAccessible (ec.ContainerType, getter)) {
3369 Report.Error (122, loc, "'{0}' is inaccessible due to its protection level", PropertyInfo.Name);
3372 is_static = getter != null ? getter.IsStatic : setter.IsStatic;
3375 bool InstanceResolve (EmitContext ec)
3377 if ((instance_expr == null) && ec.IsStatic && !is_static) {
3378 SimpleName.Error_ObjectRefRequired (ec, loc, PropertyInfo.Name);
3382 if (instance_expr != null) {
3383 instance_expr = instance_expr.DoResolve (ec);
3384 if (instance_expr == null)
3388 if (must_do_cs1540_check && (instance_expr != null)) {
3389 if ((instance_expr.Type != ec.ContainerType) &&
3390 ec.ContainerType.IsSubclassOf (instance_expr.Type)) {
3391 Report.Error (1540, loc, "Cannot access protected member `" +
3392 PropertyInfo.DeclaringType + "." + PropertyInfo.Name +
3393 "' via a qualifier of type `" +
3394 TypeManager.CSharpName (instance_expr.Type) +
3395 "'; the qualifier must be of type `" +
3396 TypeManager.CSharpName (ec.ContainerType) +
3397 "' (or derived from it)");
3405 override public Expression DoResolve (EmitContext ec)
3407 if (getter != null){
3408 if (TypeManager.GetArgumentTypes (getter).Length != 0){
3410 117, loc, "`{0}' does not contain a " +
3411 "definition for `{1}'.", getter.DeclaringType,
3417 if (getter == null){
3419 // The following condition happens if the PropertyExpr was
3420 // created, but is invalid (ie, the property is inaccessible),
3421 // and we did not want to embed the knowledge about this in
3422 // the caller routine. This only avoids double error reporting.
3427 Report.Error (154, loc,
3428 "The property `" + PropertyInfo.Name +
3429 "' can not be used in " +
3430 "this context because it lacks a get accessor");
3434 if (!InstanceResolve (ec))
3438 // Only base will allow this invocation to happen.
3440 if (IsBase && getter.IsAbstract){
3441 Report.Error (205, loc, "Cannot call an abstract base property: " +
3442 PropertyInfo.DeclaringType + "." +PropertyInfo.Name);
3449 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
3451 if (setter == null){
3453 // The following condition happens if the PropertyExpr was
3454 // created, but is invalid (ie, the property is inaccessible),
3455 // and we did not want to embed the knowledge about this in
3456 // the caller routine. This only avoids double error reporting.
3461 Report.Error (154, loc,
3462 "The property `" + PropertyInfo.Name +
3463 "' can not be used in " +
3464 "this context because it lacks a set accessor");
3468 if (TypeManager.GetArgumentTypes (setter).Length != 1){
3470 117, loc, "`{0}' does not contain a " +
3471 "definition for `{1}'.", getter.DeclaringType,
3476 if (!InstanceResolve (ec))
3480 // Only base will allow this invocation to happen.
3482 if (IsBase && setter.IsAbstract){
3483 Report.Error (205, loc, "Cannot call an abstract base property: " +
3484 PropertyInfo.DeclaringType + "." +PropertyInfo.Name);
3489 // Check that we are not making changes to a temporary memory location
3491 if (instance_expr != null && instance_expr.Type.IsValueType && !(instance_expr is IMemoryLocation)) {
3492 // FIXME: Provide better error reporting.
3493 Error (1612, "Cannot modify expression because it is not a variable.");
3502 public override void Emit (EmitContext ec)
3507 void EmitInstance (EmitContext ec)
3512 if (instance_expr.Type.IsValueType) {
3513 if (instance_expr is IMemoryLocation) {
3514 ((IMemoryLocation) instance_expr).AddressOf (ec, AddressOp.LoadStore);
3516 LocalTemporary t = new LocalTemporary (ec, instance_expr.Type);
3517 instance_expr.Emit (ec);
3519 t.AddressOf (ec, AddressOp.Store);
3522 instance_expr.Emit (ec);
3525 ec.ig.Emit (OpCodes.Dup);
3529 public void Emit (EmitContext ec, bool leave_copy)
3535 // Special case: length of single dimension array property is turned into ldlen
3537 if ((getter == TypeManager.system_int_array_get_length) ||
3538 (getter == TypeManager.int_array_get_length)){
3539 Type iet = instance_expr.Type;
3542 // System.Array.Length can be called, but the Type does not
3543 // support invoking GetArrayRank, so test for that case first
3545 if (iet != TypeManager.array_type && (iet.GetArrayRank () == 1)) {
3546 ec.ig.Emit (OpCodes.Ldlen);
3547 ec.ig.Emit (OpCodes.Conv_I4);
3552 Invocation.EmitCall (ec, IsBase, IsStatic, new EmptyAddressOf (), getter, null, loc);
3557 ec.ig.Emit (OpCodes.Dup);
3559 temp = new LocalTemporary (ec, this.Type);
3565 // Implements the IAssignMethod interface for assignments
3567 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
3569 prepared = prepare_for_load;
3575 ec.ig.Emit (OpCodes.Dup);
3577 temp = new LocalTemporary (ec, this.Type);
3582 ArrayList args = new ArrayList (1);
3583 args.Add (new Argument (new EmptyAddressOf (), Argument.AType.Expression));
3585 Invocation.EmitCall (ec, IsBase, IsStatic, new EmptyAddressOf (), setter, args, loc);
3591 override public void EmitStatement (EmitContext ec)
3594 ec.ig.Emit (OpCodes.Pop);
3599 /// Fully resolved expression that evaluates to an Event
3601 public class EventExpr : Expression, IMemberExpr {
3602 public readonly EventInfo EventInfo;
3603 Expression instance_expr;
3606 MethodInfo add_accessor, remove_accessor;
3608 public EventExpr (EventInfo ei, Location loc)
3612 eclass = ExprClass.EventAccess;
3614 add_accessor = TypeManager.GetAddMethod (ei);
3615 remove_accessor = TypeManager.GetRemoveMethod (ei);
3617 if (add_accessor.IsStatic || remove_accessor.IsStatic)
3620 if (EventInfo is MyEventBuilder){
3621 MyEventBuilder eb = (MyEventBuilder) EventInfo;
3622 type = eb.EventType;
3625 type = EventInfo.EventHandlerType;
3628 public string Name {
3630 return EventInfo.Name;
3634 public bool IsInstance {
3640 public bool IsStatic {
3646 public Type DeclaringType {
3648 return EventInfo.DeclaringType;
3652 public Expression InstanceExpression {
3654 return instance_expr;
3658 instance_expr = value;
3662 public override Expression DoResolve (EmitContext ec)
3664 if (instance_expr != null) {
3665 instance_expr = instance_expr.DoResolve (ec);
3666 if (instance_expr == null)
3674 public override void Emit (EmitContext ec)
3676 Report.Error (70, loc, "The event `" + Name + "' can only appear on the left hand side of += or -= (except on the defining type)");
3679 public void EmitAddOrRemove (EmitContext ec, Expression source)
3681 BinaryDelegate source_del = (BinaryDelegate) source;
3682 Expression handler = source_del.Right;
3684 Argument arg = new Argument (handler, Argument.AType.Expression);
3685 ArrayList args = new ArrayList ();
3689 if (source_del.IsAddition)
3690 Invocation.EmitCall (
3691 ec, false, IsStatic, instance_expr, add_accessor, args, loc);
3693 Invocation.EmitCall (
3694 ec, false, IsStatic, instance_expr, remove_accessor, args, loc);