2 // ecore.cs: Core of the Expression representation for the intermediate tree.
5 // Miguel de Icaza (miguel@ximian.com)
7 // (C) 2001, 2002, 2003 Ximian, Inc.
11 namespace Mono.CSharp {
13 using System.Collections;
14 using System.Diagnostics;
15 using System.Reflection;
16 using System.Reflection.Emit;
20 /// The ExprClass class contains the is used to pass the
21 /// classification of an expression (value, variable, namespace,
22 /// type, method group, property access, event access, indexer access,
25 public enum ExprClass : byte {
40 /// This is used to tell Resolve in which types of expressions we're
44 public enum ResolveFlags {
45 // Returns Value, Variable, PropertyAccess, EventAccess or IndexerAccess.
48 // Returns a type expression.
51 // Returns a method group.
54 // Allows SimpleNames to be returned.
55 // This is used by MemberAccess to construct long names that can not be
56 // partially resolved (namespace-qualified names for example).
59 // Mask of all the expression class flags.
62 // Disable control flow analysis while resolving the expression.
63 // This is used when resolving the instance expression of a field expression.
64 DisableFlowAnalysis = 16,
66 // Set if this is resolving the first part of a MemberAccess.
71 // This is just as a hint to AddressOf of what will be done with the
74 public enum AddressOp {
81 /// This interface is implemented by variables
83 public interface IMemoryLocation {
85 /// The AddressOf method should generate code that loads
86 /// the address of the object and leaves it on the stack.
88 /// The `mode' argument is used to notify the expression
89 /// of whether this will be used to read from the address or
90 /// write to the address.
92 /// This is just a hint that can be used to provide good error
93 /// reporting, and should have no other side effects.
95 void AddressOf (EmitContext ec, AddressOp mode);
99 /// We are either a namespace or a type.
100 /// If we're a type, `IsType' is true and we may use `Type' to get
101 /// a TypeExpr representing that type.
103 public interface IAlias {
112 TypeExpr ResolveAsType (EmitContext ec);
116 /// This interface is implemented by variables
118 public interface IVariable {
119 VariableInfo VariableInfo {
123 bool VerifyFixed (bool is_expression);
127 /// This interface denotes an expression which evaluates to a member
128 /// of a struct or a class.
130 public interface IMemberExpr
133 /// The name of this member.
140 /// Whether this is an instance member.
147 /// Whether this is a static member.
154 /// The type which declares this member.
161 /// The instance expression associated with this member, if it's a
162 /// non-static member.
164 Expression InstanceExpression {
170 /// Base class for expressions
172 public abstract class Expression {
173 public ExprClass eclass;
175 protected Location loc;
187 public Location Location {
194 /// Utility wrapper routine for Error, just to beautify the code
196 public void Error (int error, string s)
198 if (!Location.IsNull (loc))
199 Report.Error (error, loc, s);
201 Report.Error (error, s);
205 /// Utility wrapper routine for Warning, just to beautify the code
207 public void Warning (int code, string format, params object[] args)
209 Report.Warning (code, loc, format, args);
212 // Not nice but we have broken hierarchy
213 public virtual void CheckMarshallByRefAccess (Type container) {}
216 /// Tests presence of ObsoleteAttribute and report proper error
218 protected void CheckObsoleteAttribute (Type type)
220 ObsoleteAttribute obsolete_attr = AttributeTester.GetObsoleteAttribute (type);
221 if (obsolete_attr == null)
224 AttributeTester.Report_ObsoleteMessage (obsolete_attr, type.FullName, loc);
227 public static bool IsAccessorAccessible (Type invocation_type, MethodInfo mi, out bool must_do_cs1540_check)
229 MethodAttributes ma = mi.Attributes & MethodAttributes.MemberAccessMask;
231 must_do_cs1540_check = false; // by default we do not check for this
234 // If only accessible to the current class or children
236 if (ma == MethodAttributes.Private) {
237 Type declaring_type = mi.DeclaringType;
239 if (invocation_type != declaring_type)
240 return TypeManager.IsNestedFamilyAccessible (invocation_type, declaring_type);
245 // FamAndAssem requires that we not only derivate, but we are on the
248 if (ma == MethodAttributes.FamANDAssem){
249 return (mi.DeclaringType.Assembly != invocation_type.Assembly);
252 // Assembly and FamORAssem succeed if we're in the same assembly.
253 if ((ma == MethodAttributes.Assembly) || (ma == MethodAttributes.FamORAssem)){
254 if (mi.DeclaringType.Assembly == invocation_type.Assembly)
258 // We already know that we aren't in the same assembly.
259 if (ma == MethodAttributes.Assembly)
262 // Family and FamANDAssem require that we derive.
263 if ((ma == MethodAttributes.Family) || (ma == MethodAttributes.FamANDAssem) || (ma == MethodAttributes.FamORAssem)){
264 if (!TypeManager.IsNestedFamilyAccessible (invocation_type, mi.DeclaringType))
267 if (!TypeManager.IsNestedChildOf (invocation_type, mi.DeclaringType))
268 must_do_cs1540_check = true;
277 /// Performs semantic analysis on the Expression
281 /// The Resolve method is invoked to perform the semantic analysis
284 /// The return value is an expression (it can be the
285 /// same expression in some cases) or a new
286 /// expression that better represents this node.
288 /// For example, optimizations of Unary (LiteralInt)
289 /// would return a new LiteralInt with a negated
292 /// If there is an error during semantic analysis,
293 /// then an error should be reported (using Report)
294 /// and a null value should be returned.
296 /// There are two side effects expected from calling
297 /// Resolve(): the the field variable "eclass" should
298 /// be set to any value of the enumeration
299 /// `ExprClass' and the type variable should be set
300 /// to a valid type (this is the type of the
303 public abstract Expression DoResolve (EmitContext ec);
305 public virtual Expression DoResolveLValue (EmitContext ec, Expression right_side)
307 return DoResolve (ec);
311 // This is used if the expression should be resolved as a type.
312 // the default implementation fails. Use this method in
313 // those participants in the SimpleName chain system.
315 public virtual Expression ResolveAsTypeStep (EmitContext ec)
321 // This is used to resolve the expression as a type, a null
322 // value will be returned if the expression is not a type
325 public virtual TypeExpr ResolveAsTypeTerminal (EmitContext ec)
327 int errors = Report.Errors;
329 TypeExpr te = ResolveAsTypeStep (ec) as TypeExpr;
331 if ((te == null) || (te.eclass != ExprClass.Type) || (te.Type == null)) {
332 if (errors == Report.Errors)
333 Report.Error (246, Location, "Cannot find type '{0}'", ToString ());
337 if (!te.CheckAccessLevel (ec.DeclSpace)) {
338 Report.Error (122, Location, "'{0}' is inaccessible due to its protection level", te.Name);
346 /// Resolves an expression and performs semantic analysis on it.
350 /// Currently Resolve wraps DoResolve to perform sanity
351 /// checking and assertion checking on what we expect from Resolve.
353 public Expression Resolve (EmitContext ec, ResolveFlags flags)
355 if ((flags & ResolveFlags.MaskExprClass) == ResolveFlags.Type)
356 return ResolveAsTypeStep (ec);
358 bool old_do_flow_analysis = ec.DoFlowAnalysis;
359 if ((flags & ResolveFlags.DisableFlowAnalysis) != 0)
360 ec.DoFlowAnalysis = false;
363 bool intermediate = (flags & ResolveFlags.Intermediate) == ResolveFlags.Intermediate;
364 if (this is SimpleName)
365 e = ((SimpleName) this).DoResolveAllowStatic (ec, intermediate);
370 ec.DoFlowAnalysis = old_do_flow_analysis;
375 if (e is SimpleName){
376 SimpleName s = (SimpleName) e;
378 if ((flags & ResolveFlags.SimpleName) == 0) {
379 MemberLookupFailed (ec, null, ec.ContainerType, s.Name,
380 ec.DeclSpace.Name, loc);
387 if ((e is TypeExpr) || (e is ComposedCast)) {
388 if ((flags & ResolveFlags.Type) == 0) {
389 e.Error_UnexpectedKind (flags, loc);
398 if ((flags & ResolveFlags.VariableOrValue) == 0) {
399 e.Error_UnexpectedKind (flags, loc);
404 case ExprClass.MethodGroup:
405 if (RootContext.Version == LanguageVersion.ISO_1){
406 if ((flags & ResolveFlags.MethodGroup) == 0) {
407 ((MethodGroupExpr) e).ReportUsageError ();
413 case ExprClass.Value:
414 case ExprClass.Variable:
415 case ExprClass.PropertyAccess:
416 case ExprClass.EventAccess:
417 case ExprClass.IndexerAccess:
418 if ((flags & ResolveFlags.VariableOrValue) == 0) {
419 Console.WriteLine ("I got: {0} and {1}", e.GetType (), e);
420 Console.WriteLine ("I am {0} and {1}", this.GetType (), this);
421 FieldInfo fi = ((FieldExpr) e).FieldInfo;
423 Console.WriteLine ("{0} and {1}", fi.DeclaringType, fi.Name);
424 e.Error_UnexpectedKind (flags, loc);
430 throw new Exception ("Expression " + e.GetType () +
431 " ExprClass is Invalid after resolve");
435 throw new Exception (
436 "Expression " + e.GetType () +
437 " did not set its type after Resolve\n" +
438 "called from: " + this.GetType ());
444 /// Resolves an expression and performs semantic analysis on it.
446 public Expression Resolve (EmitContext ec)
448 return Resolve (ec, ResolveFlags.VariableOrValue);
452 /// Resolves an expression for LValue assignment
456 /// Currently ResolveLValue wraps DoResolveLValue to perform sanity
457 /// checking and assertion checking on what we expect from Resolve
459 public Expression ResolveLValue (EmitContext ec, Expression right_side)
461 Expression e = DoResolveLValue (ec, right_side);
464 if (e is SimpleName){
465 SimpleName s = (SimpleName) e;
466 MemberLookupFailed (ec, null, ec.ContainerType, s.Name,
467 ec.DeclSpace.Name, loc);
471 if (e.eclass == ExprClass.Invalid)
472 throw new Exception ("Expression " + e +
473 " ExprClass is Invalid after resolve");
475 if (e.eclass == ExprClass.MethodGroup) {
476 ((MethodGroupExpr) e).ReportUsageError ();
480 if ((e.type == null) && !(e is ConstructedType))
481 throw new Exception ("Expression " + e +
482 " did not set its type after Resolve");
489 /// Emits the code for the expression
493 /// The Emit method is invoked to generate the code
494 /// for the expression.
496 public abstract void Emit (EmitContext ec);
498 public virtual void EmitBranchable (EmitContext ec, Label target, bool onTrue)
501 ec.ig.Emit (onTrue ? OpCodes.Brtrue : OpCodes.Brfalse, target);
505 /// Protected constructor. Only derivate types should
506 /// be able to be created
509 protected Expression ()
511 eclass = ExprClass.Invalid;
516 /// Returns a literalized version of a literal FieldInfo
520 /// The possible return values are:
521 /// IntConstant, UIntConstant
522 /// LongLiteral, ULongConstant
523 /// FloatConstant, DoubleConstant
526 /// The value returned is already resolved.
528 public static Constant Constantify (object v, Type t)
530 if (t == TypeManager.int32_type)
531 return new IntConstant ((int) v);
532 else if (t == TypeManager.uint32_type)
533 return new UIntConstant ((uint) v);
534 else if (t == TypeManager.int64_type)
535 return new LongConstant ((long) v);
536 else if (t == TypeManager.uint64_type)
537 return new ULongConstant ((ulong) v);
538 else if (t == TypeManager.float_type)
539 return new FloatConstant ((float) v);
540 else if (t == TypeManager.double_type)
541 return new DoubleConstant ((double) v);
542 else if (t == TypeManager.string_type)
543 return new StringConstant ((string) v);
544 else if (t == TypeManager.short_type)
545 return new ShortConstant ((short)v);
546 else if (t == TypeManager.ushort_type)
547 return new UShortConstant ((ushort)v);
548 else if (t == TypeManager.sbyte_type)
549 return new SByteConstant (((sbyte)v));
550 else if (t == TypeManager.byte_type)
551 return new ByteConstant ((byte)v);
552 else if (t == TypeManager.char_type)
553 return new CharConstant ((char)v);
554 else if (t == TypeManager.bool_type)
555 return new BoolConstant ((bool) v);
556 else if (t == TypeManager.decimal_type)
557 return new DecimalConstant ((decimal) v);
558 else if (TypeManager.IsEnumType (t)){
559 Type real_type = TypeManager.TypeToCoreType (v.GetType ());
561 real_type = System.Enum.GetUnderlyingType (real_type);
563 Constant e = Constantify (v, real_type);
565 return new EnumConstant (e, t);
566 } else if (v == null && !TypeManager.IsValueType (t))
567 return NullLiteral.Null;
569 throw new Exception ("Unknown type for constant (" + t +
574 /// Returns a fully formed expression after a MemberLookup
576 public static Expression ExprClassFromMemberInfo (EmitContext ec, MemberInfo mi, Location loc)
579 return new EventExpr ((EventInfo) mi, loc);
580 else if (mi is FieldInfo)
581 return new FieldExpr ((FieldInfo) mi, loc);
582 else if (mi is PropertyInfo)
583 return new PropertyExpr (ec, (PropertyInfo) mi, loc);
584 else if (mi is Type){
585 return new TypeExpression ((System.Type) mi, loc);
592 private static ArrayList almostMatchedMembers = new ArrayList (4);
595 // FIXME: Probably implement a cache for (t,name,current_access_set)?
597 // This code could use some optimizations, but we need to do some
598 // measurements. For example, we could use a delegate to `flag' when
599 // something can not any longer be a method-group (because it is something
603 // If the return value is an Array, then it is an array of
606 // If the return value is an MemberInfo, it is anything, but a Method
610 // FIXME: When calling MemberLookup inside an `Invocation', we should pass
611 // the arguments here and have MemberLookup return only the methods that
612 // match the argument count/type, unlike we are doing now (we delay this
615 // This is so we can catch correctly attempts to invoke instance methods
616 // from a static body (scan for error 120 in ResolveSimpleName).
619 // FIXME: Potential optimization, have a static ArrayList
622 public static Expression MemberLookup (EmitContext ec, Type queried_type, string name,
623 MemberTypes mt, BindingFlags bf, Location loc)
625 return MemberLookup (ec, ec.ContainerType, null, queried_type, name, mt, bf, loc);
629 // Lookup type `queried_type' for code in class `container_type' with a qualifier of
630 // `qualifier_type' or null to lookup members in the current class.
633 public static Expression MemberLookup (EmitContext ec, Type container_type,
634 Type qualifier_type, Type queried_type,
635 string name, MemberTypes mt,
636 BindingFlags bf, Location loc)
638 almostMatchedMembers.Clear ();
640 MemberInfo [] mi = TypeManager.MemberLookup (
641 container_type, qualifier_type,queried_type, mt, bf, name,
642 almostMatchedMembers);
647 int count = mi.Length;
649 if (mi [0] is MethodBase)
650 return new MethodGroupExpr (mi, loc);
655 return ExprClassFromMemberInfo (ec, mi [0], loc);
658 public const MemberTypes AllMemberTypes =
659 MemberTypes.Constructor |
663 MemberTypes.NestedType |
664 MemberTypes.Property;
666 public const BindingFlags AllBindingFlags =
667 BindingFlags.Public |
668 BindingFlags.Static |
669 BindingFlags.Instance;
671 public static Expression MemberLookup (EmitContext ec, Type queried_type,
672 string name, Location loc)
674 return MemberLookup (ec, ec.ContainerType, null, queried_type, name,
675 AllMemberTypes, AllBindingFlags, loc);
678 public static Expression MemberLookup (EmitContext ec, Type qualifier_type,
679 Type queried_type, string name, Location loc)
681 return MemberLookup (ec, ec.ContainerType, qualifier_type, queried_type,
682 name, AllMemberTypes, AllBindingFlags, loc);
685 public static Expression MethodLookup (EmitContext ec, Type queried_type,
686 string name, Location loc)
688 return MemberLookup (ec, ec.ContainerType, null, queried_type, name,
689 MemberTypes.Method, AllBindingFlags, loc);
693 /// This is a wrapper for MemberLookup that is not used to "probe", but
694 /// to find a final definition. If the final definition is not found, we
695 /// look for private members and display a useful debugging message if we
698 public static Expression MemberLookupFinal (EmitContext ec, Type qualifier_type,
699 Type queried_type, string name,
702 return MemberLookupFinal (ec, qualifier_type, queried_type, name,
703 AllMemberTypes, AllBindingFlags, loc);
706 public static Expression MemberLookupFinal (EmitContext ec, Type qualifier_type,
707 Type queried_type, string name,
708 MemberTypes mt, BindingFlags bf,
713 int errors = Report.Errors;
715 e = MemberLookup (ec, ec.ContainerType, qualifier_type, queried_type,
718 if (e == null && errors == Report.Errors)
719 // No errors were reported by MemberLookup, but there was an error.
720 MemberLookupFailed (ec, qualifier_type, queried_type, name,
726 public static void MemberLookupFailed (EmitContext ec, Type qualifier_type,
727 Type queried_type, string name,
728 string class_name, Location loc)
730 if (almostMatchedMembers.Count != 0) {
731 if (qualifier_type == null) {
732 foreach (MemberInfo m in almostMatchedMembers)
733 Report.Error (38, loc,
734 "Cannot access non-static member `{0}' via nested type `{1}'",
735 TypeManager.GetFullNameSignature (m),
736 TypeManager.CSharpName (ec.ContainerType));
741 if (qualifier_type != ec.ContainerType) {
742 // Although a derived class can access protected members of
743 // its base class it cannot do so through an instance of the
744 // base class (CS1540). If the qualifier_type is a parent of the
745 // ec.ContainerType and the lookup succeeds with the latter one,
746 // then we are in this situation.
747 foreach (MemberInfo m in almostMatchedMembers)
748 Report.Error (1540, loc,
749 "Cannot access protected member `{0}' via a qualifier of type `{1}';"
750 + " the qualifier must be of type `{2}' (or derived from it)",
751 TypeManager.GetFullNameSignature (m),
752 TypeManager.CSharpName (qualifier_type),
753 TypeManager.CSharpName (ec.ContainerType));
756 almostMatchedMembers.Clear ();
759 MemberInfo[] mi = TypeManager.MemberLookup (queried_type, null, queried_type,
760 AllMemberTypes, AllBindingFlags |
761 BindingFlags.NonPublic, name, null);
764 if (class_name != null)
765 Report.Error (103, loc, "The name `" + name + "' could not be " +
766 "found in `" + class_name + "'");
769 117, loc, "`" + queried_type + "' does not contain a " +
770 "definition for `" + name + "'");
774 if (TypeManager.MemberLookup (queried_type, null, queried_type,
775 AllMemberTypes, AllBindingFlags |
776 BindingFlags.NonPublic, name, null) == null) {
777 if ((mi.Length == 1) && (mi [0] is Type)) {
778 Type t = (Type) mi [0];
780 Report.Error (305, loc,
781 "Using the generic type `{0}' " +
782 "requires {1} type arguments",
783 TypeManager.GetFullName (t),
784 TypeManager.GetNumberOfTypeArguments (t));
791 if (qualifier_type != null)
792 Report.Error (122, loc, "'{0}' is inaccessible due to its protection level", TypeManager.CSharpName (qualifier_type) + "." + name);
793 else if (name == ".ctor") {
794 Report.Error (143, loc, String.Format ("The type {0} has no constructors defined",
795 TypeManager.CSharpName (queried_type)));
797 Report.Error (122, loc, "'{0}' is inaccessible due to its protection level", name);
801 static public MemberInfo GetFieldFromEvent (EventExpr event_expr)
803 EventInfo ei = event_expr.EventInfo;
805 return TypeManager.GetPrivateFieldOfEvent (ei);
809 /// Returns an expression that can be used to invoke operator true
810 /// on the expression if it exists.
812 static public StaticCallExpr GetOperatorTrue (EmitContext ec, Expression e, Location loc)
814 return GetOperatorTrueOrFalse (ec, e, true, loc);
818 /// Returns an expression that can be used to invoke operator false
819 /// on the expression if it exists.
821 static public StaticCallExpr GetOperatorFalse (EmitContext ec, Expression e, Location loc)
823 return GetOperatorTrueOrFalse (ec, e, false, loc);
826 static StaticCallExpr GetOperatorTrueOrFalse (EmitContext ec, Expression e, bool is_true, Location loc)
829 Expression operator_group;
831 operator_group = MethodLookup (ec, e.Type, is_true ? "op_True" : "op_False", loc);
832 if (operator_group == null)
835 ArrayList arguments = new ArrayList ();
836 arguments.Add (new Argument (e, Argument.AType.Expression));
837 method = Invocation.OverloadResolve (
838 ec, (MethodGroupExpr) operator_group, arguments, false, loc);
843 return new StaticCallExpr ((MethodInfo) method, arguments, loc);
847 /// Resolves the expression `e' into a boolean expression: either through
848 /// an implicit conversion, or through an `operator true' invocation
850 public static Expression ResolveBoolean (EmitContext ec, Expression e, Location loc)
856 if (e.Type == TypeManager.bool_type)
859 Expression converted = Convert.ImplicitConversion (ec, e, TypeManager.bool_type, new Location (-1));
861 if (converted != null)
865 // If no implicit conversion to bool exists, try using `operator true'
867 Expression operator_true = Expression.GetOperatorTrue (ec, e, loc);
868 if (operator_true == null){
869 Report.Error (31, loc, "Can not convert the expression to a boolean");
872 return operator_true;
875 static string ExprClassName (ExprClass c)
878 case ExprClass.Invalid:
880 case ExprClass.Value:
882 case ExprClass.Variable:
884 case ExprClass.Namespace:
888 case ExprClass.MethodGroup:
889 return "method group";
890 case ExprClass.PropertyAccess:
891 return "property access";
892 case ExprClass.EventAccess:
893 return "event access";
894 case ExprClass.IndexerAccess:
895 return "indexer access";
896 case ExprClass.Nothing:
899 throw new Exception ("Should not happen");
903 /// Reports that we were expecting `expr' to be of class `expected'
905 public void Error_UnexpectedKind (string expected, Location loc)
907 string kind = "Unknown";
909 kind = ExprClassName (eclass);
911 Report.Error (118, loc, "Expression denotes a `" + kind +
912 "' where a `" + expected + "' was expected");
915 public void Error_UnexpectedKind (ResolveFlags flags, Location loc)
917 ArrayList valid = new ArrayList (10);
919 if ((flags & ResolveFlags.VariableOrValue) != 0) {
920 valid.Add ("variable");
924 if ((flags & ResolveFlags.Type) != 0)
927 if ((flags & ResolveFlags.MethodGroup) != 0)
928 valid.Add ("method group");
930 if ((flags & ResolveFlags.SimpleName) != 0)
931 valid.Add ("simple name");
933 if (valid.Count == 0)
934 valid.Add ("unknown");
936 StringBuilder sb = new StringBuilder ();
937 for (int i = 0; i < valid.Count; i++) {
940 else if (i == valid.Count)
942 sb.Append (valid [i]);
945 string kind = ExprClassName (eclass);
947 Error (119, "Expression denotes a `" + kind + "' where " +
948 "a `" + sb.ToString () + "' was expected");
951 static public void Error_ConstantValueCannotBeConverted (Location l, string val, Type t)
953 Report.Error (31, l, "Constant value `" + val + "' cannot be converted to " +
954 TypeManager.CSharpName (t));
957 public static void UnsafeError (Location loc)
959 Report.Error (214, loc, "Pointers may only be used in an unsafe context");
963 /// Converts the IntConstant, UIntConstant, LongConstant or
964 /// ULongConstant into the integral target_type. Notice
965 /// that we do not return an `Expression' we do return
966 /// a boxed integral type.
968 /// FIXME: Since I added the new constants, we need to
969 /// also support conversions from CharConstant, ByteConstant,
970 /// SByteConstant, UShortConstant, ShortConstant
972 /// This is used by the switch statement, so the domain
973 /// of work is restricted to the literals above, and the
974 /// targets are int32, uint32, char, byte, sbyte, ushort,
975 /// short, uint64 and int64
977 public static object ConvertIntLiteral (Constant c, Type target_type, Location loc)
979 if (!Convert.ImplicitStandardConversionExists (Convert.ConstantEC, c, target_type)){
980 Convert.Error_CannotImplicitConversion (loc, c.Type, target_type);
986 if (c.Type == target_type)
987 return ((Constant) c).GetValue ();
990 // Make into one of the literals we handle, we dont really care
991 // about this value as we will just return a few limited types
993 if (c is EnumConstant)
994 c = ((EnumConstant)c).WidenToCompilerConstant ();
996 if (c is IntConstant){
997 int v = ((IntConstant) c).Value;
999 if (target_type == TypeManager.uint32_type){
1002 } else if (target_type == TypeManager.char_type){
1003 if (v >= Char.MinValue && v <= Char.MaxValue)
1005 } else if (target_type == TypeManager.byte_type){
1006 if (v >= Byte.MinValue && v <= Byte.MaxValue)
1008 } else if (target_type == TypeManager.sbyte_type){
1009 if (v >= SByte.MinValue && v <= SByte.MaxValue)
1011 } else if (target_type == TypeManager.short_type){
1012 if (v >= Int16.MinValue && v <= UInt16.MaxValue)
1014 } else if (target_type == TypeManager.ushort_type){
1015 if (v >= UInt16.MinValue && v <= UInt16.MaxValue)
1017 } else if (target_type == TypeManager.int64_type)
1019 else if (target_type == TypeManager.uint64_type){
1025 } else if (c is UIntConstant){
1026 uint v = ((UIntConstant) c).Value;
1028 if (target_type == TypeManager.int32_type){
1029 if (v <= Int32.MaxValue)
1031 } else if (target_type == TypeManager.char_type){
1032 if (v >= Char.MinValue && v <= Char.MaxValue)
1034 } else if (target_type == TypeManager.byte_type){
1035 if (v <= Byte.MaxValue)
1037 } else if (target_type == TypeManager.sbyte_type){
1038 if (v <= SByte.MaxValue)
1040 } else if (target_type == TypeManager.short_type){
1041 if (v <= UInt16.MaxValue)
1043 } else if (target_type == TypeManager.ushort_type){
1044 if (v <= UInt16.MaxValue)
1046 } else if (target_type == TypeManager.int64_type)
1048 else if (target_type == TypeManager.uint64_type)
1051 } else if (c is LongConstant){
1052 long v = ((LongConstant) c).Value;
1054 if (target_type == TypeManager.int32_type){
1055 if (v >= UInt32.MinValue && v <= UInt32.MaxValue)
1057 } else if (target_type == TypeManager.uint32_type){
1058 if (v >= 0 && v <= UInt32.MaxValue)
1060 } else if (target_type == TypeManager.char_type){
1061 if (v >= Char.MinValue && v <= Char.MaxValue)
1063 } else if (target_type == TypeManager.byte_type){
1064 if (v >= Byte.MinValue && v <= Byte.MaxValue)
1066 } else if (target_type == TypeManager.sbyte_type){
1067 if (v >= SByte.MinValue && v <= SByte.MaxValue)
1069 } else if (target_type == TypeManager.short_type){
1070 if (v >= Int16.MinValue && v <= UInt16.MaxValue)
1072 } else if (target_type == TypeManager.ushort_type){
1073 if (v >= UInt16.MinValue && v <= UInt16.MaxValue)
1075 } else if (target_type == TypeManager.uint64_type){
1080 } else if (c is ULongConstant){
1081 ulong v = ((ULongConstant) c).Value;
1083 if (target_type == TypeManager.int32_type){
1084 if (v <= Int32.MaxValue)
1086 } else if (target_type == TypeManager.uint32_type){
1087 if (v <= UInt32.MaxValue)
1089 } else if (target_type == TypeManager.char_type){
1090 if (v >= Char.MinValue && v <= Char.MaxValue)
1092 } else if (target_type == TypeManager.byte_type){
1093 if (v >= Byte.MinValue && v <= Byte.MaxValue)
1095 } else if (target_type == TypeManager.sbyte_type){
1096 if (v <= (int) SByte.MaxValue)
1098 } else if (target_type == TypeManager.short_type){
1099 if (v <= UInt16.MaxValue)
1101 } else if (target_type == TypeManager.ushort_type){
1102 if (v <= UInt16.MaxValue)
1104 } else if (target_type == TypeManager.int64_type){
1105 if (v <= Int64.MaxValue)
1109 } else if (c is ByteConstant){
1110 byte v = ((ByteConstant) c).Value;
1112 if (target_type == TypeManager.int32_type)
1114 else if (target_type == TypeManager.uint32_type)
1116 else if (target_type == TypeManager.char_type)
1118 else if (target_type == TypeManager.sbyte_type){
1119 if (v <= SByte.MaxValue)
1121 } else if (target_type == TypeManager.short_type)
1123 else if (target_type == TypeManager.ushort_type)
1125 else if (target_type == TypeManager.int64_type)
1127 else if (target_type == TypeManager.uint64_type)
1130 } else if (c is SByteConstant){
1131 sbyte v = ((SByteConstant) c).Value;
1133 if (target_type == TypeManager.int32_type)
1135 else if (target_type == TypeManager.uint32_type){
1138 } else if (target_type == TypeManager.char_type){
1141 } else if (target_type == TypeManager.byte_type){
1144 } else if (target_type == TypeManager.short_type)
1146 else if (target_type == TypeManager.ushort_type){
1149 } else if (target_type == TypeManager.int64_type)
1151 else if (target_type == TypeManager.uint64_type){
1156 } else if (c is ShortConstant){
1157 short v = ((ShortConstant) c).Value;
1159 if (target_type == TypeManager.int32_type){
1161 } else if (target_type == TypeManager.uint32_type){
1164 } else if (target_type == TypeManager.char_type){
1167 } else if (target_type == TypeManager.byte_type){
1168 if (v >= Byte.MinValue && v <= Byte.MaxValue)
1170 } else if (target_type == TypeManager.sbyte_type){
1171 if (v >= SByte.MinValue && v <= SByte.MaxValue)
1173 } else if (target_type == TypeManager.ushort_type){
1176 } else if (target_type == TypeManager.int64_type)
1178 else if (target_type == TypeManager.uint64_type)
1182 } else if (c is UShortConstant){
1183 ushort v = ((UShortConstant) c).Value;
1185 if (target_type == TypeManager.int32_type)
1187 else if (target_type == TypeManager.uint32_type)
1189 else if (target_type == TypeManager.char_type){
1190 if (v >= Char.MinValue && v <= Char.MaxValue)
1192 } else if (target_type == TypeManager.byte_type){
1193 if (v >= Byte.MinValue && v <= Byte.MaxValue)
1195 } else if (target_type == TypeManager.sbyte_type){
1196 if (v <= SByte.MaxValue)
1198 } else if (target_type == TypeManager.short_type){
1199 if (v <= Int16.MaxValue)
1201 } else if (target_type == TypeManager.int64_type)
1203 else if (target_type == TypeManager.uint64_type)
1207 } else if (c is CharConstant){
1208 char v = ((CharConstant) c).Value;
1210 if (target_type == TypeManager.int32_type)
1212 else if (target_type == TypeManager.uint32_type)
1214 else if (target_type == TypeManager.byte_type){
1215 if (v >= Byte.MinValue && v <= Byte.MaxValue)
1217 } else if (target_type == TypeManager.sbyte_type){
1218 if (v <= SByte.MaxValue)
1220 } else if (target_type == TypeManager.short_type){
1221 if (v <= Int16.MaxValue)
1223 } else if (target_type == TypeManager.ushort_type)
1225 else if (target_type == TypeManager.int64_type)
1227 else if (target_type == TypeManager.uint64_type)
1232 Error_ConstantValueCannotBeConverted (loc, s, target_type);
1237 // Load the object from the pointer.
1239 public static void LoadFromPtr (ILGenerator ig, Type t)
1241 if (t == TypeManager.int32_type)
1242 ig.Emit (OpCodes.Ldind_I4);
1243 else if (t == TypeManager.uint32_type)
1244 ig.Emit (OpCodes.Ldind_U4);
1245 else if (t == TypeManager.short_type)
1246 ig.Emit (OpCodes.Ldind_I2);
1247 else if (t == TypeManager.ushort_type)
1248 ig.Emit (OpCodes.Ldind_U2);
1249 else if (t == TypeManager.char_type)
1250 ig.Emit (OpCodes.Ldind_U2);
1251 else if (t == TypeManager.byte_type)
1252 ig.Emit (OpCodes.Ldind_U1);
1253 else if (t == TypeManager.sbyte_type)
1254 ig.Emit (OpCodes.Ldind_I1);
1255 else if (t == TypeManager.uint64_type)
1256 ig.Emit (OpCodes.Ldind_I8);
1257 else if (t == TypeManager.int64_type)
1258 ig.Emit (OpCodes.Ldind_I8);
1259 else if (t == TypeManager.float_type)
1260 ig.Emit (OpCodes.Ldind_R4);
1261 else if (t == TypeManager.double_type)
1262 ig.Emit (OpCodes.Ldind_R8);
1263 else if (t == TypeManager.bool_type)
1264 ig.Emit (OpCodes.Ldind_I1);
1265 else if (t == TypeManager.intptr_type)
1266 ig.Emit (OpCodes.Ldind_I);
1267 else if (TypeManager.IsEnumType (t)) {
1268 if (t == TypeManager.enum_type)
1269 ig.Emit (OpCodes.Ldind_Ref);
1271 LoadFromPtr (ig, TypeManager.EnumToUnderlying (t));
1272 } else if (t.IsValueType || t.IsGenericParameter)
1273 ig.Emit (OpCodes.Ldobj, t);
1274 else if (t.IsPointer)
1275 ig.Emit (OpCodes.Ldind_I);
1277 ig.Emit (OpCodes.Ldind_Ref);
1281 // The stack contains the pointer and the value of type `type'
1283 public static void StoreFromPtr (ILGenerator ig, Type type)
1285 if (TypeManager.IsEnumType (type))
1286 type = TypeManager.EnumToUnderlying (type);
1287 if (type == TypeManager.int32_type || type == TypeManager.uint32_type)
1288 ig.Emit (OpCodes.Stind_I4);
1289 else if (type == TypeManager.int64_type || type == TypeManager.uint64_type)
1290 ig.Emit (OpCodes.Stind_I8);
1291 else if (type == TypeManager.char_type || type == TypeManager.short_type ||
1292 type == TypeManager.ushort_type)
1293 ig.Emit (OpCodes.Stind_I2);
1294 else if (type == TypeManager.float_type)
1295 ig.Emit (OpCodes.Stind_R4);
1296 else if (type == TypeManager.double_type)
1297 ig.Emit (OpCodes.Stind_R8);
1298 else if (type == TypeManager.byte_type || type == TypeManager.sbyte_type ||
1299 type == TypeManager.bool_type)
1300 ig.Emit (OpCodes.Stind_I1);
1301 else if (type == TypeManager.intptr_type)
1302 ig.Emit (OpCodes.Stind_I);
1303 else if (type.IsValueType || type.IsGenericParameter)
1304 ig.Emit (OpCodes.Stobj, type);
1306 ig.Emit (OpCodes.Stind_Ref);
1310 // Returns the size of type `t' if known, otherwise, 0
1312 public static int GetTypeSize (Type t)
1314 t = TypeManager.TypeToCoreType (t);
1315 if (t == TypeManager.int32_type ||
1316 t == TypeManager.uint32_type ||
1317 t == TypeManager.float_type)
1319 else if (t == TypeManager.int64_type ||
1320 t == TypeManager.uint64_type ||
1321 t == TypeManager.double_type)
1323 else if (t == TypeManager.byte_type ||
1324 t == TypeManager.sbyte_type ||
1325 t == TypeManager.bool_type)
1327 else if (t == TypeManager.short_type ||
1328 t == TypeManager.char_type ||
1329 t == TypeManager.ushort_type)
1331 else if (t == TypeManager.decimal_type)
1337 public static void Error_NegativeArrayIndex (Location loc)
1339 Report.Error (248, loc, "Cannot create an array with a negative size");
1343 // Converts `source' to an int, uint, long or ulong.
1345 public Expression ExpressionToArrayArgument (EmitContext ec, Expression source, Location loc)
1349 bool old_checked = ec.CheckState;
1350 ec.CheckState = true;
1352 target = Convert.ImplicitConversion (ec, source, TypeManager.int32_type, loc);
1353 if (target == null){
1354 target = Convert.ImplicitConversion (ec, source, TypeManager.uint32_type, loc);
1355 if (target == null){
1356 target = Convert.ImplicitConversion (ec, source, TypeManager.int64_type, loc);
1357 if (target == null){
1358 target = Convert.ImplicitConversion (ec, source, TypeManager.uint64_type, loc);
1360 Convert.Error_CannotImplicitConversion (loc, source.Type, TypeManager.int32_type);
1364 ec.CheckState = old_checked;
1367 // Only positive constants are allowed at compile time
1369 if (target is Constant){
1370 if (target is IntConstant){
1371 if (((IntConstant) target).Value < 0){
1372 Error_NegativeArrayIndex (loc);
1377 if (target is LongConstant){
1378 if (((LongConstant) target).Value < 0){
1379 Error_NegativeArrayIndex (loc);
1392 /// This is just a base class for expressions that can
1393 /// appear on statements (invocations, object creation,
1394 /// assignments, post/pre increment and decrement). The idea
1395 /// being that they would support an extra Emition interface that
1396 /// does not leave a result on the stack.
1398 public abstract class ExpressionStatement : Expression {
1400 public virtual ExpressionStatement ResolveStatement (EmitContext ec)
1402 Expression e = Resolve (ec);
1406 ExpressionStatement es = e as ExpressionStatement;
1408 Error (201, "Only assignment, call, increment, decrement and new object " +
1409 "expressions can be used as a statement");
1415 /// Requests the expression to be emitted in a `statement'
1416 /// context. This means that no new value is left on the
1417 /// stack after invoking this method (constrasted with
1418 /// Emit that will always leave a value on the stack).
1420 public abstract void EmitStatement (EmitContext ec);
1424 /// This kind of cast is used to encapsulate the child
1425 /// whose type is child.Type into an expression that is
1426 /// reported to return "return_type". This is used to encapsulate
1427 /// expressions which have compatible types, but need to be dealt
1428 /// at higher levels with.
1430 /// For example, a "byte" expression could be encapsulated in one
1431 /// of these as an "unsigned int". The type for the expression
1432 /// would be "unsigned int".
1435 public class EmptyCast : Expression {
1436 protected Expression child;
1438 public Expression Child {
1444 public EmptyCast (Expression child, Type return_type)
1446 eclass = child.eclass;
1451 public override Expression DoResolve (EmitContext ec)
1453 // This should never be invoked, we are born in fully
1454 // initialized state.
1459 public override void Emit (EmitContext ec)
1466 // We need to special case this since an empty cast of
1467 // a NullLiteral is still a Constant
1469 public class NullCast : Constant {
1470 protected Expression child;
1472 public NullCast (Expression child, Type return_type)
1474 eclass = child.eclass;
1479 override public string AsString ()
1484 public override object GetValue ()
1489 public override Expression DoResolve (EmitContext ec)
1491 // This should never be invoked, we are born in fully
1492 // initialized state.
1497 public override void Emit (EmitContext ec)
1502 public override bool IsNegative {
1511 /// This class is used to wrap literals which belong inside Enums
1513 public class EnumConstant : Constant {
1514 public Constant Child;
1516 public EnumConstant (Constant child, Type enum_type)
1518 eclass = child.eclass;
1523 public override Expression DoResolve (EmitContext ec)
1525 // This should never be invoked, we are born in fully
1526 // initialized state.
1531 public override void Emit (EmitContext ec)
1536 public override object GetValue ()
1538 return Child.GetValue ();
1541 public object GetValueAsEnumType ()
1543 return System.Enum.ToObject (type, Child.GetValue ());
1547 // Converts from one of the valid underlying types for an enumeration
1548 // (int32, uint32, int64, uint64, short, ushort, byte, sbyte) to
1549 // one of the internal compiler literals: Int/UInt/Long/ULong Literals.
1551 public Constant WidenToCompilerConstant ()
1553 Type t = TypeManager.EnumToUnderlying (Child.Type);
1554 object v = ((Constant) Child).GetValue ();;
1556 if (t == TypeManager.int32_type)
1557 return new IntConstant ((int) v);
1558 if (t == TypeManager.uint32_type)
1559 return new UIntConstant ((uint) v);
1560 if (t == TypeManager.int64_type)
1561 return new LongConstant ((long) v);
1562 if (t == TypeManager.uint64_type)
1563 return new ULongConstant ((ulong) v);
1564 if (t == TypeManager.short_type)
1565 return new ShortConstant ((short) v);
1566 if (t == TypeManager.ushort_type)
1567 return new UShortConstant ((ushort) v);
1568 if (t == TypeManager.byte_type)
1569 return new ByteConstant ((byte) v);
1570 if (t == TypeManager.sbyte_type)
1571 return new SByteConstant ((sbyte) v);
1573 throw new Exception ("Invalid enumeration underlying type: " + t);
1577 // Extracts the value in the enumeration on its native representation
1579 public object GetPlainValue ()
1581 Type t = TypeManager.EnumToUnderlying (Child.Type);
1582 object v = ((Constant) Child).GetValue ();;
1584 if (t == TypeManager.int32_type)
1586 if (t == TypeManager.uint32_type)
1588 if (t == TypeManager.int64_type)
1590 if (t == TypeManager.uint64_type)
1592 if (t == TypeManager.short_type)
1594 if (t == TypeManager.ushort_type)
1596 if (t == TypeManager.byte_type)
1598 if (t == TypeManager.sbyte_type)
1604 public override string AsString ()
1606 return Child.AsString ();
1609 public override DoubleConstant ConvertToDouble ()
1611 return Child.ConvertToDouble ();
1614 public override FloatConstant ConvertToFloat ()
1616 return Child.ConvertToFloat ();
1619 public override ULongConstant ConvertToULong ()
1621 return Child.ConvertToULong ();
1624 public override LongConstant ConvertToLong ()
1626 return Child.ConvertToLong ();
1629 public override UIntConstant ConvertToUInt ()
1631 return Child.ConvertToUInt ();
1634 public override IntConstant ConvertToInt ()
1636 return Child.ConvertToInt ();
1639 public override bool IsZeroInteger {
1640 get { return Child.IsZeroInteger; }
1643 public override bool IsNegative {
1645 return Child.IsNegative;
1651 /// This kind of cast is used to encapsulate Value Types in objects.
1653 /// The effect of it is to box the value type emitted by the previous
1656 public class BoxedCast : EmptyCast {
1658 public BoxedCast (Expression expr)
1659 : base (expr, TypeManager.object_type)
1661 eclass = ExprClass.Value;
1664 public BoxedCast (Expression expr, Type target_type)
1665 : base (expr, target_type)
1667 eclass = ExprClass.Value;
1670 public override Expression DoResolve (EmitContext ec)
1672 // This should never be invoked, we are born in fully
1673 // initialized state.
1678 public override void Emit (EmitContext ec)
1682 ec.ig.Emit (OpCodes.Box, child.Type);
1686 public class UnboxCast : EmptyCast {
1687 public UnboxCast (Expression expr, Type return_type)
1688 : base (expr, return_type)
1692 public override Expression DoResolve (EmitContext ec)
1694 // This should never be invoked, we are born in fully
1695 // initialized state.
1700 public override void Emit (EmitContext ec)
1703 ILGenerator ig = ec.ig;
1706 if (t.IsGenericParameter)
1707 ig.Emit (OpCodes.Unbox_Any, t);
1709 ig.Emit (OpCodes.Unbox, t);
1711 LoadFromPtr (ig, t);
1717 /// This is used to perform explicit numeric conversions.
1719 /// Explicit numeric conversions might trigger exceptions in a checked
1720 /// context, so they should generate the conv.ovf opcodes instead of
1723 public class ConvCast : EmptyCast {
1724 public enum Mode : byte {
1725 I1_U1, I1_U2, I1_U4, I1_U8, I1_CH,
1727 I2_I1, I2_U1, I2_U2, I2_U4, I2_U8, I2_CH,
1728 U2_I1, U2_U1, U2_I2, U2_CH,
1729 I4_I1, I4_U1, I4_I2, I4_U2, I4_U4, I4_U8, I4_CH,
1730 U4_I1, U4_U1, U4_I2, U4_U2, U4_I4, U4_CH,
1731 I8_I1, I8_U1, I8_I2, I8_U2, I8_I4, I8_U4, I8_U8, I8_CH,
1732 U8_I1, U8_U1, U8_I2, U8_U2, U8_I4, U8_U4, U8_I8, U8_CH,
1733 CH_I1, CH_U1, CH_I2,
1734 R4_I1, R4_U1, R4_I2, R4_U2, R4_I4, R4_U4, R4_I8, R4_U8, R4_CH,
1735 R8_I1, R8_U1, R8_I2, R8_U2, R8_I4, R8_U4, R8_I8, R8_U8, R8_CH, R8_R4
1741 public ConvCast (EmitContext ec, Expression child, Type return_type, Mode m)
1742 : base (child, return_type)
1744 checked_state = ec.CheckState;
1748 public override Expression DoResolve (EmitContext ec)
1750 // This should never be invoked, we are born in fully
1751 // initialized state.
1756 public override string ToString ()
1758 return String.Format ("ConvCast ({0}, {1})", mode, child);
1761 public override void Emit (EmitContext ec)
1763 ILGenerator ig = ec.ig;
1769 case Mode.I1_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1770 case Mode.I1_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1771 case Mode.I1_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1772 case Mode.I1_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1773 case Mode.I1_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1775 case Mode.U1_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1776 case Mode.U1_CH: /* nothing */ break;
1778 case Mode.I2_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1779 case Mode.I2_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1780 case Mode.I2_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1781 case Mode.I2_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1782 case Mode.I2_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1783 case Mode.I2_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1785 case Mode.U2_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1786 case Mode.U2_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
1787 case Mode.U2_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
1788 case Mode.U2_CH: /* nothing */ break;
1790 case Mode.I4_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1791 case Mode.I4_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1792 case Mode.I4_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
1793 case Mode.I4_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1794 case Mode.I4_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1795 case Mode.I4_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1796 case Mode.I4_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1798 case Mode.U4_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1799 case Mode.U4_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
1800 case Mode.U4_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
1801 case Mode.U4_U2: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
1802 case Mode.U4_I4: ig.Emit (OpCodes.Conv_Ovf_I4_Un); break;
1803 case Mode.U4_CH: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
1805 case Mode.I8_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1806 case Mode.I8_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1807 case Mode.I8_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
1808 case Mode.I8_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1809 case Mode.I8_I4: ig.Emit (OpCodes.Conv_Ovf_I4); break;
1810 case Mode.I8_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1811 case Mode.I8_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1812 case Mode.I8_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1814 case Mode.U8_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1815 case Mode.U8_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
1816 case Mode.U8_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
1817 case Mode.U8_U2: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
1818 case Mode.U8_I4: ig.Emit (OpCodes.Conv_Ovf_I4_Un); break;
1819 case Mode.U8_U4: ig.Emit (OpCodes.Conv_Ovf_U4_Un); break;
1820 case Mode.U8_I8: ig.Emit (OpCodes.Conv_Ovf_I8_Un); break;
1821 case Mode.U8_CH: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
1823 case Mode.CH_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1824 case Mode.CH_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
1825 case Mode.CH_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
1827 case Mode.R4_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1828 case Mode.R4_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1829 case Mode.R4_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
1830 case Mode.R4_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1831 case Mode.R4_I4: ig.Emit (OpCodes.Conv_Ovf_I4); break;
1832 case Mode.R4_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1833 case Mode.R4_I8: ig.Emit (OpCodes.Conv_Ovf_I8); break;
1834 case Mode.R4_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1835 case Mode.R4_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1837 case Mode.R8_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1838 case Mode.R8_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1839 case Mode.R8_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
1840 case Mode.R8_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1841 case Mode.R8_I4: ig.Emit (OpCodes.Conv_Ovf_I4); break;
1842 case Mode.R8_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1843 case Mode.R8_I8: ig.Emit (OpCodes.Conv_Ovf_I8); break;
1844 case Mode.R8_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1845 case Mode.R8_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1846 case Mode.R8_R4: ig.Emit (OpCodes.Conv_R4); break;
1850 case Mode.I1_U1: ig.Emit (OpCodes.Conv_U1); break;
1851 case Mode.I1_U2: ig.Emit (OpCodes.Conv_U2); break;
1852 case Mode.I1_U4: ig.Emit (OpCodes.Conv_U4); break;
1853 case Mode.I1_U8: ig.Emit (OpCodes.Conv_I8); break;
1854 case Mode.I1_CH: ig.Emit (OpCodes.Conv_U2); break;
1856 case Mode.U1_I1: ig.Emit (OpCodes.Conv_I1); break;
1857 case Mode.U1_CH: ig.Emit (OpCodes.Conv_U2); break;
1859 case Mode.I2_I1: ig.Emit (OpCodes.Conv_I1); break;
1860 case Mode.I2_U1: ig.Emit (OpCodes.Conv_U1); break;
1861 case Mode.I2_U2: ig.Emit (OpCodes.Conv_U2); break;
1862 case Mode.I2_U4: ig.Emit (OpCodes.Conv_U4); break;
1863 case Mode.I2_U8: ig.Emit (OpCodes.Conv_I8); break;
1864 case Mode.I2_CH: ig.Emit (OpCodes.Conv_U2); break;
1866 case Mode.U2_I1: ig.Emit (OpCodes.Conv_I1); break;
1867 case Mode.U2_U1: ig.Emit (OpCodes.Conv_U1); break;
1868 case Mode.U2_I2: ig.Emit (OpCodes.Conv_I2); break;
1869 case Mode.U2_CH: /* nothing */ break;
1871 case Mode.I4_I1: ig.Emit (OpCodes.Conv_I1); break;
1872 case Mode.I4_U1: ig.Emit (OpCodes.Conv_U1); break;
1873 case Mode.I4_I2: ig.Emit (OpCodes.Conv_I2); break;
1874 case Mode.I4_U4: /* nothing */ break;
1875 case Mode.I4_U2: ig.Emit (OpCodes.Conv_U2); break;
1876 case Mode.I4_U8: ig.Emit (OpCodes.Conv_I8); break;
1877 case Mode.I4_CH: ig.Emit (OpCodes.Conv_U2); break;
1879 case Mode.U4_I1: ig.Emit (OpCodes.Conv_I1); break;
1880 case Mode.U4_U1: ig.Emit (OpCodes.Conv_U1); break;
1881 case Mode.U4_I2: ig.Emit (OpCodes.Conv_I2); break;
1882 case Mode.U4_U2: ig.Emit (OpCodes.Conv_U2); break;
1883 case Mode.U4_I4: /* nothing */ break;
1884 case Mode.U4_CH: ig.Emit (OpCodes.Conv_U2); break;
1886 case Mode.I8_I1: ig.Emit (OpCodes.Conv_I1); break;
1887 case Mode.I8_U1: ig.Emit (OpCodes.Conv_U1); break;
1888 case Mode.I8_I2: ig.Emit (OpCodes.Conv_I2); break;
1889 case Mode.I8_U2: ig.Emit (OpCodes.Conv_U2); break;
1890 case Mode.I8_I4: ig.Emit (OpCodes.Conv_I4); break;
1891 case Mode.I8_U4: ig.Emit (OpCodes.Conv_U4); break;
1892 case Mode.I8_U8: /* nothing */ break;
1893 case Mode.I8_CH: ig.Emit (OpCodes.Conv_U2); break;
1895 case Mode.U8_I1: ig.Emit (OpCodes.Conv_I1); break;
1896 case Mode.U8_U1: ig.Emit (OpCodes.Conv_U1); break;
1897 case Mode.U8_I2: ig.Emit (OpCodes.Conv_I2); break;
1898 case Mode.U8_U2: ig.Emit (OpCodes.Conv_U2); break;
1899 case Mode.U8_I4: ig.Emit (OpCodes.Conv_I4); break;
1900 case Mode.U8_U4: ig.Emit (OpCodes.Conv_U4); break;
1901 case Mode.U8_I8: /* nothing */ break;
1902 case Mode.U8_CH: ig.Emit (OpCodes.Conv_U2); break;
1904 case Mode.CH_I1: ig.Emit (OpCodes.Conv_I1); break;
1905 case Mode.CH_U1: ig.Emit (OpCodes.Conv_U1); break;
1906 case Mode.CH_I2: ig.Emit (OpCodes.Conv_I2); break;
1908 case Mode.R4_I1: ig.Emit (OpCodes.Conv_I1); break;
1909 case Mode.R4_U1: ig.Emit (OpCodes.Conv_U1); break;
1910 case Mode.R4_I2: ig.Emit (OpCodes.Conv_I2); break;
1911 case Mode.R4_U2: ig.Emit (OpCodes.Conv_U2); break;
1912 case Mode.R4_I4: ig.Emit (OpCodes.Conv_I4); break;
1913 case Mode.R4_U4: ig.Emit (OpCodes.Conv_U4); break;
1914 case Mode.R4_I8: ig.Emit (OpCodes.Conv_I8); break;
1915 case Mode.R4_U8: ig.Emit (OpCodes.Conv_U8); break;
1916 case Mode.R4_CH: ig.Emit (OpCodes.Conv_U2); break;
1918 case Mode.R8_I1: ig.Emit (OpCodes.Conv_I1); break;
1919 case Mode.R8_U1: ig.Emit (OpCodes.Conv_U1); break;
1920 case Mode.R8_I2: ig.Emit (OpCodes.Conv_I2); break;
1921 case Mode.R8_U2: ig.Emit (OpCodes.Conv_U2); break;
1922 case Mode.R8_I4: ig.Emit (OpCodes.Conv_I4); break;
1923 case Mode.R8_U4: ig.Emit (OpCodes.Conv_U4); break;
1924 case Mode.R8_I8: ig.Emit (OpCodes.Conv_I8); break;
1925 case Mode.R8_U8: ig.Emit (OpCodes.Conv_U8); break;
1926 case Mode.R8_CH: ig.Emit (OpCodes.Conv_U2); break;
1927 case Mode.R8_R4: ig.Emit (OpCodes.Conv_R4); break;
1933 public class OpcodeCast : EmptyCast {
1937 public OpcodeCast (Expression child, Type return_type, OpCode op)
1938 : base (child, return_type)
1942 second_valid = false;
1945 public OpcodeCast (Expression child, Type return_type, OpCode op, OpCode op2)
1946 : base (child, return_type)
1951 second_valid = true;
1954 public override Expression DoResolve (EmitContext ec)
1956 // This should never be invoked, we are born in fully
1957 // initialized state.
1962 public override void Emit (EmitContext ec)
1973 /// This kind of cast is used to encapsulate a child and cast it
1974 /// to the class requested
1976 public class ClassCast : EmptyCast {
1977 public ClassCast (Expression child, Type return_type)
1978 : base (child, return_type)
1983 public override Expression DoResolve (EmitContext ec)
1985 // This should never be invoked, we are born in fully
1986 // initialized state.
1991 public override void Emit (EmitContext ec)
1995 if (child.Type.IsGenericParameter)
1996 ec.ig.Emit (OpCodes.Box, child.Type);
1998 if (type.IsGenericParameter)
1999 ec.ig.Emit (OpCodes.Unbox_Any, type);
2001 ec.ig.Emit (OpCodes.Castclass, type);
2006 /// SimpleName expressions are initially formed of a single
2007 /// word and it only happens at the beginning of the expression.
2011 /// The expression will try to be bound to a Field, a Method
2012 /// group or a Property. If those fail we pass the name to our
2013 /// caller and the SimpleName is compounded to perform a type
2014 /// lookup. The idea behind this process is that we want to avoid
2015 /// creating a namespace map from the assemblies, as that requires
2016 /// the GetExportedTypes function to be called and a hashtable to
2017 /// be constructed which reduces startup time. If later we find
2018 /// that this is slower, we should create a `NamespaceExpr' expression
2019 /// that fully participates in the resolution process.
2021 /// For example `System.Console.WriteLine' is decomposed into
2022 /// MemberAccess (MemberAccess (SimpleName ("System"), "Console"), "WriteLine")
2024 /// The first SimpleName wont produce a match on its own, so it will
2026 /// MemberAccess (SimpleName ("System.Console"), "WriteLine").
2028 /// System.Console will produce a TypeExpr match.
2030 /// The downside of this is that we might be hitting `LookupType' too many
2031 /// times with this scheme.
2033 public class SimpleName : Expression {
2035 public readonly TypeArguments Arguments;
2038 // If true, then we are a simple name, not composed with a ".
2042 public SimpleName (string a, string b, Location l)
2044 Name = String.Concat (a, ".", b);
2049 public SimpleName (string name, Location l)
2056 public SimpleName (string name, TypeArguments args, Location l)
2064 public static void Error_ObjectRefRequired (EmitContext ec, Location l, string name)
2066 if (ec.IsFieldInitializer)
2069 "A field initializer cannot reference the non-static field, " +
2070 "method or property `"+name+"'");
2074 "An object reference is required " +
2075 "for the non-static field `"+name+"'");
2079 // Checks whether we are trying to access an instance
2080 // property, method or field from a static body.
2082 Expression MemberStaticCheck (EmitContext ec, Expression e)
2084 if (e is IMemberExpr){
2085 IMemberExpr member = (IMemberExpr) e;
2087 if (!member.IsStatic){
2088 Error_ObjectRefRequired (ec, loc, Name);
2096 public override Expression DoResolve (EmitContext ec)
2098 return SimpleNameResolve (ec, null, false, false);
2101 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
2103 return SimpleNameResolve (ec, right_side, false, false);
2107 public Expression DoResolveAllowStatic (EmitContext ec, bool intermediate)
2109 return SimpleNameResolve (ec, null, true, intermediate);
2112 public override Expression ResolveAsTypeStep (EmitContext ec)
2114 DeclSpace ds = ec.DeclSpace;
2115 NamespaceEntry ns = ds.NamespaceEntry;
2120 // Since we are cheating: we only do the Alias lookup for
2121 // namespaces if the name does not include any dots in it
2123 if (ns != null && is_base)
2124 alias_value = ns.LookupAlias (Name);
2128 TypeParameterExpr generic_type = ds.LookupGeneric (Name, loc);
2129 if (generic_type != null)
2130 return generic_type.ResolveAsTypeTerminal (ec);
2132 if (ec.ResolvingTypeTree){
2133 int errors = Report.Errors;
2134 Type dt = ds.FindType (loc, Name);
2136 if (Report.Errors != errors)
2140 return new TypeExpression (dt, loc);
2142 if (alias_value != null){
2143 if (alias_value.IsType)
2144 return alias_value.ResolveAsType (ec);
2145 if ((t = RootContext.LookupType (ds, alias_value.Name, true, loc)) != null)
2146 return new TypeExpression (t, loc);
2150 if ((t = RootContext.LookupType (ds, Name, true, loc)) != null)
2151 return new TypeExpression (t, loc);
2153 if (alias_value != null) {
2154 if (alias_value.IsType)
2155 return alias_value.ResolveAsType (ec);
2156 if ((t = RootContext.LookupType (ds, alias_value.Name, true, loc)) != null)
2157 return new TypeExpression (t, loc);
2159 // we have alias value, but it isn't Type, so try if it's namespace
2160 return new SimpleName (alias_value.Name, loc);
2163 // No match, maybe our parent can compose us
2164 // into something meaningful.
2168 Expression SimpleNameResolve (EmitContext ec, Expression right_side,
2169 bool allow_static, bool intermediate)
2171 Expression e = DoSimpleNameResolve (ec, right_side, allow_static, intermediate);
2175 Block current_block = ec.CurrentBlock;
2176 if (current_block != null){
2177 //LocalInfo vi = current_block.GetLocalInfo (Name);
2179 current_block.IsVariableNameUsedInChildBlock(Name)) {
2180 Report.Error (135, Location,
2181 "'{0}' has a different meaning in a " +
2182 "child block", Name);
2187 if (e.Type != null && e.Type.IsPointer && !ec.InUnsafe) {
2196 /// 7.5.2: Simple Names.
2198 /// Local Variables and Parameters are handled at
2199 /// parse time, so they never occur as SimpleNames.
2201 /// The `allow_static' flag is used by MemberAccess only
2202 /// and it is used to inform us that it is ok for us to
2203 /// avoid the static check, because MemberAccess might end
2204 /// up resolving the Name as a Type name and the access as
2205 /// a static type access.
2207 /// ie: Type Type; .... { Type.GetType (""); }
2209 /// Type is both an instance variable and a Type; Type.GetType
2210 /// is the static method not an instance method of type.
2212 Expression DoSimpleNameResolve (EmitContext ec, Expression right_side, bool allow_static, bool intermediate)
2214 Expression e = null;
2217 // Stage 1: Performed by the parser (binding to locals or parameters).
2219 Block current_block = ec.CurrentBlock;
2220 if (current_block != null){
2221 LocalInfo vi = current_block.GetLocalInfo (Name);
2225 var = new LocalVariableReference (ec.CurrentBlock, Name, loc);
2227 if (right_side != null)
2228 return var.ResolveLValue (ec, right_side);
2230 return var.Resolve (ec);
2233 ParameterReference pref = current_block.GetParameterReference (Name, loc);
2235 if (right_side != null)
2236 return pref.ResolveLValue (ec, right_side);
2238 return pref.Resolve (ec);
2243 // Stage 2: Lookup members
2246 DeclSpace lookup_ds = ec.DeclSpace;
2248 if (lookup_ds.TypeBuilder == null)
2251 e = MemberLookup (ec, lookup_ds.TypeBuilder, Name, loc);
2255 lookup_ds =lookup_ds.Parent;
2256 } while (lookup_ds != null);
2258 if (e == null && ec.ContainerType != null)
2259 e = MemberLookup (ec, ec.ContainerType, Name, loc);
2263 // Since we are cheating (is_base is our hint
2264 // that we are the beginning of the name): we
2265 // only do the Alias lookup for namespaces if
2266 // the name does not include any dots in it
2268 NamespaceEntry ns = ec.DeclSpace.NamespaceEntry;
2269 if (is_base && ns != null){
2270 IAlias alias_value = ns.LookupAlias (Name);
2271 if (alias_value != null){
2272 if (alias_value.IsType)
2273 return alias_value.ResolveAsType (ec);
2275 Name = alias_value.Name;
2278 if ((t = TypeManager.LookupType (Name)) != null)
2279 return new TypeExpression (t, loc);
2281 // No match, maybe our parent can compose us
2282 // into something meaningful.
2287 return ResolveAsTypeStep (ec);
2293 if (e is IMemberExpr) {
2294 e = MemberAccess.ResolveMemberAccess (ec, e, null, loc, this);
2298 IMemberExpr me = e as IMemberExpr;
2302 if (Arguments != null) {
2303 MethodGroupExpr mg = me as MethodGroupExpr;
2307 return mg.ResolveGeneric (ec, Arguments);
2310 // This fails if ResolveMemberAccess() was unable to decide whether
2311 // it's a field or a type of the same name.
2313 if (!me.IsStatic && (me.InstanceExpression == null))
2317 TypeManager.IsNestedFamilyAccessible (me.InstanceExpression.Type, me.DeclaringType) &&
2318 me.InstanceExpression.Type != me.DeclaringType &&
2319 !TypeManager.IsFamilyAccessible (me.InstanceExpression.Type, me.DeclaringType) &&
2320 (!intermediate || !MemberAccess.IdenticalNameAndTypeName (ec, this, e, loc))) {
2321 Error (38, "Cannot access nonstatic member `" + me.Name + "' of " +
2322 "outer type `" + me.DeclaringType + "' via nested type `" +
2323 me.InstanceExpression.Type + "'");
2327 return (right_side != null)
2328 ? e.DoResolveLValue (ec, right_side)
2332 if (ec.IsStatic || ec.IsFieldInitializer){
2336 return MemberStaticCheck (ec, e);
2341 public override void Emit (EmitContext ec)
2344 // If this is ever reached, then we failed to
2345 // find the name as a namespace
2348 Error (103, "The name `" + Name +
2349 "' does not exist in the class `" +
2350 ec.DeclSpace.Name + "'");
2353 public override string ToString ()
2360 /// Fully resolved expression that evaluates to a type
2362 public abstract class TypeExpr : Expression, IAlias {
2363 override public Expression ResolveAsTypeStep (EmitContext ec)
2365 TypeExpr t = DoResolveAsTypeStep (ec);
2369 eclass = ExprClass.Type;
2373 override public Expression DoResolve (EmitContext ec)
2375 return ResolveAsTypeTerminal (ec);
2378 override public void Emit (EmitContext ec)
2380 throw new Exception ("Should never be called");
2383 public virtual bool CheckAccessLevel (DeclSpace ds)
2385 return ds.CheckAccessLevel (Type);
2388 public virtual bool AsAccessible (DeclSpace ds, int flags)
2390 return ds.AsAccessible (Type, flags);
2393 public virtual bool IsClass {
2394 get { return Type.IsClass; }
2397 public virtual bool IsValueType {
2398 get { return Type.IsValueType; }
2401 public virtual bool IsInterface {
2402 get { return Type.IsInterface; }
2405 public virtual bool IsSealed {
2406 get { return Type.IsSealed; }
2409 public virtual bool CanInheritFrom ()
2411 if (Type == TypeManager.enum_type ||
2412 (Type == TypeManager.value_type && RootContext.StdLib) ||
2413 Type == TypeManager.multicast_delegate_type ||
2414 Type == TypeManager.delegate_type ||
2415 Type == TypeManager.array_type)
2421 public virtual bool IsAttribute {
2423 return Type == TypeManager.attribute_type ||
2424 Type.IsSubclassOf (TypeManager.attribute_type);
2428 protected abstract TypeExpr DoResolveAsTypeStep (EmitContext ec);
2430 public abstract string Name {
2434 public override bool Equals (object obj)
2436 TypeExpr tobj = obj as TypeExpr;
2440 return Type == tobj.Type;
2443 public override int GetHashCode ()
2445 return Type.GetHashCode ();
2448 public override string ToString ()
2453 bool IAlias.IsType {
2454 get { return true; }
2457 TypeExpr IAlias.ResolveAsType (EmitContext ec)
2459 return ResolveAsTypeTerminal (ec);
2463 public class TypeExpression : TypeExpr, IAlias {
2464 public TypeExpression (Type t, Location l)
2467 eclass = ExprClass.Type;
2471 protected override TypeExpr DoResolveAsTypeStep (EmitContext ec)
2476 public override string Name {
2478 return Type.ToString ();
2482 string IAlias.Name {
2484 return Type.FullName != null ? Type.FullName : Type.Name;
2490 /// Used to create types from a fully qualified name. These are just used
2491 /// by the parser to setup the core types. A TypeLookupExpression is always
2492 /// classified as a type.
2494 public class TypeLookupExpression : TypeExpr {
2497 public TypeLookupExpression (string name)
2502 protected override TypeExpr DoResolveAsTypeStep (EmitContext ec)
2505 type = RootContext.LookupType (
2506 ec.DeclSpace, name, false, Location.Null);
2514 public override string Name {
2522 /// Represents an "unbound generic type", ie. typeof (Foo<>).
2525 public class UnboundTypeExpression : TypeLookupExpression {
2526 public UnboundTypeExpression (string name)
2531 public class TypeAliasExpression : TypeExpr, IAlias {
2537 public TypeAliasExpression (IAlias alias, TypeArguments args, Location l)
2543 eclass = ExprClass.Type;
2545 name = alias.Name + "<" + args.ToString () + ">";
2550 public override string Name {
2551 get { return name; }
2554 protected override TypeExpr DoResolveAsTypeStep (EmitContext ec)
2556 texpr = alias.ResolveAsType (ec);
2560 Type type = texpr.Type;
2561 int num_args = TypeManager.GetNumberOfTypeArguments (type);
2564 if (num_args == 0) {
2565 Report.Error (308, loc,
2566 "The non-generic type `{0}' cannot " +
2567 "be used with type arguments.",
2568 TypeManager.CSharpName (type));
2572 ConstructedType ctype = new ConstructedType (type, args, loc);
2573 return ctype.ResolveAsTypeTerminal (ec);
2574 } else if (num_args > 0) {
2575 Report.Error (305, loc,
2576 "Using the generic type `{0}' " +
2577 "requires {1} type arguments",
2578 TypeManager.GetFullName (type), num_args);
2582 return new TypeExpression (type, loc);
2585 public override bool CheckAccessLevel (DeclSpace ds)
2587 return texpr.CheckAccessLevel (ds);
2590 public override bool AsAccessible (DeclSpace ds, int flags)
2592 return texpr.AsAccessible (ds, flags);
2595 public override bool IsClass {
2596 get { return texpr.IsClass; }
2599 public override bool IsValueType {
2600 get { return texpr.IsValueType; }
2603 public override bool IsInterface {
2604 get { return texpr.IsInterface; }
2607 public override bool IsSealed {
2608 get { return texpr.IsSealed; }
2611 public override bool IsAttribute {
2612 get { return texpr.IsAttribute; }
2617 /// MethodGroup Expression.
2619 /// This is a fully resolved expression that evaluates to a type
2621 public class MethodGroupExpr : Expression, IMemberExpr {
2622 public MethodBase [] Methods;
2623 Expression instance_expression = null;
2624 bool is_explicit_impl = false;
2625 bool has_type_arguments = false;
2626 bool identical_type_name = false;
2629 public MethodGroupExpr (MemberInfo [] mi, Location l)
2631 Methods = new MethodBase [mi.Length];
2632 mi.CopyTo (Methods, 0);
2633 eclass = ExprClass.MethodGroup;
2634 type = TypeManager.object_type;
2638 public MethodGroupExpr (ArrayList list, Location l)
2640 Methods = new MethodBase [list.Count];
2643 list.CopyTo (Methods, 0);
2645 foreach (MemberInfo m in list){
2646 if (!(m is MethodBase)){
2647 Console.WriteLine ("Name " + m.Name);
2648 Console.WriteLine ("Found a: " + m.GetType ().FullName);
2655 eclass = ExprClass.MethodGroup;
2656 type = TypeManager.object_type;
2659 public Type DeclaringType {
2662 // We assume that the top-level type is in the end
2664 return Methods [Methods.Length - 1].DeclaringType;
2665 //return Methods [0].DeclaringType;
2670 // `A method group may have associated an instance expression'
2672 public Expression InstanceExpression {
2674 return instance_expression;
2678 instance_expression = value;
2682 public bool IsExplicitImpl {
2684 return is_explicit_impl;
2688 is_explicit_impl = value;
2692 public bool HasTypeArguments {
2694 return has_type_arguments;
2698 has_type_arguments = value;
2702 public bool IdenticalTypeName {
2704 return identical_type_name;
2708 identical_type_name = value;
2712 public bool IsBase {
2721 public string Name {
2723 //return Methods [0].Name;
2724 return Methods [Methods.Length - 1].Name;
2728 public bool IsInstance {
2730 foreach (MethodBase mb in Methods)
2738 public bool IsStatic {
2740 foreach (MethodBase mb in Methods)
2748 override public Expression DoResolve (EmitContext ec)
2751 instance_expression = null;
2753 if (instance_expression != null) {
2754 instance_expression = instance_expression.DoResolve (ec);
2755 if (instance_expression == null)
2762 public void ReportUsageError ()
2764 Report.Error (654, loc, "Method `" + DeclaringType + "." +
2765 Name + "()' is referenced without parentheses");
2768 override public void Emit (EmitContext ec)
2770 ReportUsageError ();
2773 bool RemoveMethods (bool keep_static)
2775 ArrayList smethods = new ArrayList ();
2777 foreach (MethodBase mb in Methods){
2778 if (mb.IsStatic == keep_static)
2782 if (smethods.Count == 0)
2785 Methods = new MethodBase [smethods.Count];
2786 smethods.CopyTo (Methods, 0);
2792 /// Removes any instance methods from the MethodGroup, returns
2793 /// false if the resulting set is empty.
2795 public bool RemoveInstanceMethods ()
2797 return RemoveMethods (true);
2801 /// Removes any static methods from the MethodGroup, returns
2802 /// false if the resulting set is empty.
2804 public bool RemoveStaticMethods ()
2806 return RemoveMethods (false);
2809 public Expression ResolveGeneric (EmitContext ec, TypeArguments args)
2811 if (args.Resolve (ec) == false)
2814 Type[] atypes = args.Arguments;
2816 int first_count = 0;
2817 MethodInfo first = null;
2819 ArrayList list = new ArrayList ();
2820 foreach (MethodBase mb in Methods) {
2821 MethodInfo mi = mb as MethodInfo;
2822 if ((mi == null) || !mi.HasGenericParameters)
2825 Type[] gen_params = mi.GetGenericArguments ();
2827 if (first == null) {
2829 first_count = gen_params.Length;
2832 if (gen_params.Length != atypes.Length)
2835 list.Add (mi.BindGenericParameters (atypes));
2838 if (list.Count > 0) {
2839 MethodGroupExpr new_mg = new MethodGroupExpr (list, Location);
2840 new_mg.InstanceExpression = InstanceExpression;
2841 new_mg.HasTypeArguments = true;
2847 305, loc, "Using the generic method `{0}' " +
2848 "requires {1} type arguments", Name,
2852 308, loc, "The non-generic method `{0}' " +
2853 "cannot be used with type arguments", Name);
2860 /// Fully resolved expression that evaluates to a Field
2862 public class FieldExpr : Expression, IAssignMethod, IMemoryLocation, IMemberExpr, IVariable {
2863 public readonly FieldInfo FieldInfo;
2864 Expression instance_expr;
2865 VariableInfo variable_info;
2867 LocalTemporary temp;
2869 bool is_field_initializer;
2871 public FieldExpr (FieldInfo fi, Location l)
2874 eclass = ExprClass.Variable;
2875 type = TypeManager.TypeToCoreType (fi.FieldType);
2879 public string Name {
2881 return FieldInfo.Name;
2885 public bool IsInstance {
2887 return !FieldInfo.IsStatic;
2891 public bool IsStatic {
2893 return FieldInfo.IsStatic;
2897 public Type DeclaringType {
2899 return FieldInfo.DeclaringType;
2903 public Expression InstanceExpression {
2905 return instance_expr;
2909 instance_expr = value;
2913 public bool IsFieldInitializer {
2915 return is_field_initializer;
2919 is_field_initializer = value;
2923 public VariableInfo VariableInfo {
2925 return variable_info;
2929 override public Expression DoResolve (EmitContext ec)
2931 if (!FieldInfo.IsStatic){
2932 if (instance_expr == null){
2934 // This can happen when referencing an instance field using
2935 // a fully qualified type expression: TypeName.InstanceField = xxx
2937 SimpleName.Error_ObjectRefRequired (ec, loc, FieldInfo.Name);
2941 // Resolve the field's instance expression while flow analysis is turned
2942 // off: when accessing a field "a.b", we must check whether the field
2943 // "a.b" is initialized, not whether the whole struct "a" is initialized.
2944 instance_expr = instance_expr.Resolve (ec, ResolveFlags.VariableOrValue |
2945 ResolveFlags.DisableFlowAnalysis);
2946 if (instance_expr == null)
2950 ObsoleteAttribute oa;
2951 FieldBase f = TypeManager.GetField (FieldInfo);
2953 oa = f.GetObsoleteAttribute (f.Parent);
2955 AttributeTester.Report_ObsoleteMessage (oa, f.GetSignatureForError (), loc);
2956 // To be sure that type is external because we do not register generated fields
2957 } else if (!(FieldInfo.DeclaringType is TypeBuilder)) {
2958 oa = AttributeTester.GetMemberObsoleteAttribute (FieldInfo);
2960 AttributeTester.Report_ObsoleteMessage (oa, TypeManager.GetFullNameSignature (FieldInfo), loc);
2963 if (ec.CurrentAnonymousMethod != null){
2964 if (!FieldInfo.IsStatic){
2965 if (ec.TypeContainer is Struct){
2966 Report.Error (1673, loc, "Can not reference instance variables in anonymous methods hosted in structs");
2969 ec.CaptureField (this);
2973 // If the instance expression is a local variable or parameter.
2974 IVariable var = instance_expr as IVariable;
2975 if ((var == null) || (var.VariableInfo == null))
2978 VariableInfo vi = var.VariableInfo;
2979 if (!vi.IsFieldAssigned (ec, FieldInfo.Name, loc))
2982 variable_info = vi.GetSubStruct (FieldInfo.Name);
2986 void Report_AssignToReadonly (bool is_instance)
2991 msg = "Readonly field can not be assigned outside " +
2992 "of constructor or variable initializer";
2994 msg = "A static readonly field can only be assigned in " +
2995 "a static constructor";
2997 Report.Error (is_instance ? 191 : 198, loc, msg);
3000 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
3002 IVariable var = instance_expr as IVariable;
3003 if ((var != null) && (var.VariableInfo != null))
3004 var.VariableInfo.SetFieldAssigned (ec, FieldInfo.Name);
3006 Expression e = DoResolve (ec);
3011 if (!FieldInfo.IsStatic && (instance_expr.Type.IsValueType && !(instance_expr is IMemoryLocation))) {
3012 // FIXME: Provide better error reporting.
3013 Error (1612, "Cannot modify expression because it is not a variable.");
3017 if (!FieldInfo.IsInitOnly)
3020 FieldBase fb = TypeManager.GetField (FieldInfo);
3025 // InitOnly fields can only be assigned in constructors
3028 if (ec.IsConstructor){
3029 if (IsStatic && !ec.IsStatic)
3030 Report_AssignToReadonly (false);
3033 if (!is_field_initializer &&
3034 (ec.TypeContainer.CurrentType != null))
3035 ctype = ec.TypeContainer.CurrentType;
3037 ctype = ec.ContainerType;
3039 if (TypeManager.IsEqual (ctype, FieldInfo.DeclaringType))
3043 Report_AssignToReadonly (!IsStatic);
3048 public override void CheckMarshallByRefAccess (Type container)
3050 if (!IsStatic && Type.IsValueType && !container.IsSubclassOf (TypeManager.mbr_type) && DeclaringType.IsSubclassOf (TypeManager.mbr_type)) {
3051 Report.SymbolRelatedToPreviousError (DeclaringType);
3052 Report.Error (1690, loc, "Cannot call '{0}' method, property, or indexer because it is a value type member of a marshal-by-reference class", Name);
3056 public bool VerifyFixed (bool is_expression)
3058 IVariable variable = instance_expr as IVariable;
3059 if ((variable == null) || !variable.VerifyFixed (true))
3065 public void Emit (EmitContext ec, bool leave_copy)
3067 ILGenerator ig = ec.ig;
3068 bool is_volatile = false;
3070 if (FieldInfo is FieldBuilder){
3071 FieldBase f = TypeManager.GetField (FieldInfo);
3073 if ((f.ModFlags & Modifiers.VOLATILE) != 0)
3076 f.status |= Field.Status.USED;
3080 if (FieldInfo.IsStatic){
3082 ig.Emit (OpCodes.Volatile);
3084 ig.Emit (OpCodes.Ldsfld, FieldInfo);
3090 ig.Emit (OpCodes.Volatile);
3092 ig.Emit (OpCodes.Ldfld, FieldInfo);
3096 ec.ig.Emit (OpCodes.Dup);
3097 if (!FieldInfo.IsStatic) {
3098 temp = new LocalTemporary (ec, this.Type);
3104 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
3106 FieldAttributes fa = FieldInfo.Attributes;
3107 bool is_static = (fa & FieldAttributes.Static) != 0;
3108 bool is_readonly = (fa & FieldAttributes.InitOnly) != 0;
3109 ILGenerator ig = ec.ig;
3110 prepared = prepare_for_load;
3112 if (is_readonly && !ec.IsConstructor){
3113 Report_AssignToReadonly (!is_static);
3119 if (prepare_for_load)
3120 ig.Emit (OpCodes.Dup);
3125 ec.ig.Emit (OpCodes.Dup);
3126 if (!FieldInfo.IsStatic) {
3127 temp = new LocalTemporary (ec, this.Type);
3132 if (FieldInfo is FieldBuilder){
3133 FieldBase f = TypeManager.GetField (FieldInfo);
3135 if ((f.ModFlags & Modifiers.VOLATILE) != 0)
3136 ig.Emit (OpCodes.Volatile);
3138 f.status |= Field.Status.ASSIGNED;
3143 ig.Emit (OpCodes.Stsfld, FieldInfo);
3145 ig.Emit (OpCodes.Stfld, FieldInfo);
3151 void EmitInstance (EmitContext ec)
3153 if (instance_expr.Type.IsValueType) {
3154 if (instance_expr is IMemoryLocation) {
3155 ((IMemoryLocation) instance_expr).AddressOf (ec, AddressOp.LoadStore);
3157 LocalTemporary t = new LocalTemporary (ec, instance_expr.Type);
3158 instance_expr.Emit (ec);
3160 t.AddressOf (ec, AddressOp.Store);
3163 instance_expr.Emit (ec);
3166 public override void Emit (EmitContext ec)
3171 public void AddressOf (EmitContext ec, AddressOp mode)
3173 ILGenerator ig = ec.ig;
3175 if (FieldInfo is FieldBuilder){
3176 FieldBase f = TypeManager.GetField (FieldInfo);
3178 if ((f.ModFlags & Modifiers.VOLATILE) != 0){
3179 Error (676, "volatile variable: can not take its address, or pass as ref/out parameter");
3183 if ((mode & AddressOp.Store) != 0)
3184 f.status |= Field.Status.ASSIGNED;
3185 if ((mode & AddressOp.Load) != 0)
3186 f.status |= Field.Status.USED;
3191 // Handle initonly fields specially: make a copy and then
3192 // get the address of the copy.
3195 if (FieldInfo.IsInitOnly){
3197 if (ec.IsConstructor){
3198 if (FieldInfo.IsStatic){
3210 local = ig.DeclareLocal (type);
3211 ig.Emit (OpCodes.Stloc, local);
3212 ig.Emit (OpCodes.Ldloca, local);
3217 if (FieldInfo.IsStatic){
3218 ig.Emit (OpCodes.Ldsflda, FieldInfo);
3221 ig.Emit (OpCodes.Ldflda, FieldInfo);
3227 // A FieldExpr whose address can not be taken
3229 public class FieldExprNoAddress : FieldExpr, IMemoryLocation {
3230 public FieldExprNoAddress (FieldInfo fi, Location loc) : base (fi, loc)
3234 public new void AddressOf (EmitContext ec, AddressOp mode)
3236 Report.Error (-215, "Report this: Taking the address of a remapped parameter not supported");
3241 /// Expression that evaluates to a Property. The Assign class
3242 /// might set the `Value' expression if we are in an assignment.
3244 /// This is not an LValue because we need to re-write the expression, we
3245 /// can not take data from the stack and store it.
3247 public class PropertyExpr : ExpressionStatement, IAssignMethod, IMemberExpr {
3248 public readonly PropertyInfo PropertyInfo;
3251 // This is set externally by the `BaseAccess' class
3254 MethodInfo getter, setter;
3257 Expression instance_expr;
3258 LocalTemporary temp;
3261 public PropertyExpr (EmitContext ec, PropertyInfo pi, Location l)
3264 eclass = ExprClass.PropertyAccess;
3268 type = TypeManager.TypeToCoreType (pi.PropertyType);
3270 ResolveAccessors (ec);
3273 public string Name {
3275 return PropertyInfo.Name;
3279 public bool IsInstance {
3285 public bool IsStatic {
3291 public Type DeclaringType {
3293 return PropertyInfo.DeclaringType;
3298 // The instance expression associated with this expression
3300 public Expression InstanceExpression {
3302 instance_expr = value;
3306 return instance_expr;
3310 public bool VerifyAssignable ()
3312 if (setter == null) {
3313 Report.Error (200, loc,
3314 "The property `" + PropertyInfo.Name +
3315 "' can not be assigned to, as it has not set accessor");
3322 void FindAccessors (Type invocation_type)
3324 BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic |
3325 BindingFlags.Static | BindingFlags.Instance |
3326 BindingFlags.DeclaredOnly;
3328 Type current = PropertyInfo.DeclaringType;
3329 for (; current != null; current = current.BaseType) {
3330 MemberInfo[] group = TypeManager.MemberLookup (
3331 invocation_type, invocation_type, current,
3332 MemberTypes.Property, flags, PropertyInfo.Name, null);
3337 if (group.Length != 1)
3338 // Oooops, can this ever happen ?
3341 PropertyInfo pi = (PropertyInfo) group [0];
3344 getter = pi.GetGetMethod (true);;
3347 setter = pi.GetSetMethod (true);;
3349 MethodInfo accessor = getter != null ? getter : setter;
3351 if (!accessor.IsVirtual)
3357 // We also perform the permission checking here, as the PropertyInfo does not
3358 // hold the information for the accessibility of its setter/getter
3360 void ResolveAccessors (EmitContext ec)
3362 FindAccessors (ec.ContainerType);
3364 is_static = getter != null ? getter.IsStatic : setter.IsStatic;
3367 bool InstanceResolve (EmitContext ec, bool must_do_cs1540_check)
3369 if ((instance_expr == null) && ec.IsStatic && !is_static) {
3370 SimpleName.Error_ObjectRefRequired (ec, loc, PropertyInfo.Name);
3374 if (instance_expr != null) {
3375 instance_expr = instance_expr.DoResolve (ec);
3376 if (instance_expr == null)
3379 instance_expr.CheckMarshallByRefAccess (ec.ContainerType);
3382 if (must_do_cs1540_check && (instance_expr != null)) {
3383 if ((instance_expr.Type != ec.ContainerType) &&
3384 ec.ContainerType.IsSubclassOf (instance_expr.Type)) {
3385 Report.Error (1540, loc, "Cannot access protected member `" +
3386 PropertyInfo.DeclaringType + "." + PropertyInfo.Name +
3387 "' via a qualifier of type `" +
3388 TypeManager.CSharpName (instance_expr.Type) +
3389 "'; the qualifier must be of type `" +
3390 TypeManager.CSharpName (ec.ContainerType) +
3391 "' (or derived from it)");
3399 override public Expression DoResolve (EmitContext ec)
3401 if (getter != null){
3402 if (TypeManager.GetArgumentTypes (getter).Length != 0){
3404 117, loc, "`{0}' does not contain a " +
3405 "definition for `{1}'.", getter.DeclaringType,
3411 if (getter == null){
3413 // The following condition happens if the PropertyExpr was
3414 // created, but is invalid (ie, the property is inaccessible),
3415 // and we did not want to embed the knowledge about this in
3416 // the caller routine. This only avoids double error reporting.
3421 Report.Error (154, loc,
3422 "The property `" + PropertyInfo.Name +
3423 "' can not be used in " +
3424 "this context because it lacks a get accessor");
3428 bool must_do_cs1540_check;
3429 if (!IsAccessorAccessible (ec.ContainerType, getter, out must_do_cs1540_check)) {
3430 Report.Error (122, loc, "'{0}.get' is inaccessible due to its protection level", PropertyInfo.Name);
3434 if (!InstanceResolve (ec, must_do_cs1540_check))
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 bool must_do_cs1540_check;
3477 if (!IsAccessorAccessible (ec.ContainerType, setter, out must_do_cs1540_check)) {
3478 Report.Error (122, loc, "'{0}.set' is inaccessible due to its protection level", PropertyInfo.Name);
3482 if (!InstanceResolve (ec, must_do_cs1540_check))
3486 // Only base will allow this invocation to happen.
3488 if (IsBase && setter.IsAbstract){
3489 Report.Error (205, loc, "Cannot call an abstract base property: " +
3490 PropertyInfo.DeclaringType + "." +PropertyInfo.Name);
3495 // Check that we are not making changes to a temporary memory location
3497 if (instance_expr != null && instance_expr.Type.IsValueType && !(instance_expr is IMemoryLocation)) {
3498 // FIXME: Provide better error reporting.
3499 Error (1612, "Cannot modify expression because it is not a variable.");
3508 public override void Emit (EmitContext ec)
3513 void EmitInstance (EmitContext ec)
3518 if (instance_expr.Type.IsValueType) {
3519 if (instance_expr is IMemoryLocation) {
3520 ((IMemoryLocation) instance_expr).AddressOf (ec, AddressOp.LoadStore);
3522 LocalTemporary t = new LocalTemporary (ec, instance_expr.Type);
3523 instance_expr.Emit (ec);
3525 t.AddressOf (ec, AddressOp.Store);
3528 instance_expr.Emit (ec);
3531 ec.ig.Emit (OpCodes.Dup);
3535 public void Emit (EmitContext ec, bool leave_copy)
3541 // Special case: length of single dimension array property is turned into ldlen
3543 if ((getter == TypeManager.system_int_array_get_length) ||
3544 (getter == TypeManager.int_array_get_length)){
3545 Type iet = instance_expr.Type;
3548 // System.Array.Length can be called, but the Type does not
3549 // support invoking GetArrayRank, so test for that case first
3551 if (iet != TypeManager.array_type && (iet.GetArrayRank () == 1)) {
3552 ec.ig.Emit (OpCodes.Ldlen);
3553 ec.ig.Emit (OpCodes.Conv_I4);
3558 Invocation.EmitCall (ec, IsBase, IsStatic, new EmptyAddressOf (), getter, null, loc);
3563 ec.ig.Emit (OpCodes.Dup);
3565 temp = new LocalTemporary (ec, this.Type);
3571 // Implements the IAssignMethod interface for assignments
3573 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
3575 prepared = prepare_for_load;
3581 ec.ig.Emit (OpCodes.Dup);
3583 temp = new LocalTemporary (ec, this.Type);
3588 ArrayList args = new ArrayList (1);
3589 args.Add (new Argument (new EmptyAddressOf (), Argument.AType.Expression));
3591 Invocation.EmitCall (ec, IsBase, IsStatic, new EmptyAddressOf (), setter, args, loc);
3597 override public void EmitStatement (EmitContext ec)
3600 ec.ig.Emit (OpCodes.Pop);
3605 /// Fully resolved expression that evaluates to an Event
3607 public class EventExpr : Expression, IMemberExpr {
3608 public readonly EventInfo EventInfo;
3609 Expression instance_expr;
3612 MethodInfo add_accessor, remove_accessor;
3614 public EventExpr (EventInfo ei, Location loc)
3618 eclass = ExprClass.EventAccess;
3620 add_accessor = TypeManager.GetAddMethod (ei);
3621 remove_accessor = TypeManager.GetRemoveMethod (ei);
3623 if (add_accessor.IsStatic || remove_accessor.IsStatic)
3626 if (EventInfo is MyEventBuilder){
3627 MyEventBuilder eb = (MyEventBuilder) EventInfo;
3628 type = eb.EventType;
3631 type = EventInfo.EventHandlerType;
3634 public string Name {
3636 return EventInfo.Name;
3640 public bool IsInstance {
3646 public bool IsStatic {
3652 public Type DeclaringType {
3654 return EventInfo.DeclaringType;
3658 public Expression InstanceExpression {
3660 return instance_expr;
3664 instance_expr = value;
3668 bool InstanceResolve (EmitContext ec, bool must_do_cs1540_check)
3670 if ((instance_expr == null) && ec.IsStatic && !is_static) {
3671 SimpleName.Error_ObjectRefRequired (ec, loc, EventInfo.Name);
3675 if (instance_expr != null) {
3676 instance_expr = instance_expr.DoResolve (ec);
3677 if (instance_expr == null)
3682 // This is using the same mechanism as the CS1540 check in PropertyExpr.
3683 // However, in the Event case, we reported a CS0122 instead.
3685 if (must_do_cs1540_check && (instance_expr != null)) {
3686 if ((instance_expr.Type != ec.ContainerType) &&
3687 ec.ContainerType.IsSubclassOf (instance_expr.Type)) {
3688 Report.Error (122, loc, "'{0}' is inaccessible due to its protection level",
3689 DeclaringType.Name + "." + EventInfo.Name);
3698 public override Expression DoResolve (EmitContext ec)
3700 if (instance_expr != null) {
3701 instance_expr = instance_expr.DoResolve (ec);
3702 if (instance_expr == null)
3706 bool must_do_cs1540_check;
3707 if (!(IsAccessorAccessible (ec.ContainerType, add_accessor, out must_do_cs1540_check)
3708 && IsAccessorAccessible (ec.ContainerType, remove_accessor, out must_do_cs1540_check))) {
3710 Report.Error (122, loc, "'{0}' is inaccessible due to its protection level",
3711 DeclaringType.Name + "." + EventInfo.Name);
3715 if (!InstanceResolve (ec, must_do_cs1540_check))
3721 public override void Emit (EmitContext ec)
3723 if (instance_expr is This)
3724 Report.Error (79, loc, "The event `{0}' can only appear on the left hand side of += or -=, try calling the actual delegate");
3726 Report.Error (70, loc, "The event `{0}' can only appear on the left hand side of += or -= "+
3727 "(except on the defining type)", Name);
3730 public void EmitAddOrRemove (EmitContext ec, Expression source)
3732 BinaryDelegate source_del = (BinaryDelegate) source;
3733 Expression handler = source_del.Right;
3735 Argument arg = new Argument (handler, Argument.AType.Expression);
3736 ArrayList args = new ArrayList ();
3740 if (source_del.IsAddition)
3741 Invocation.EmitCall (
3742 ec, false, IsStatic, instance_expr, add_accessor, args, loc);
3744 Invocation.EmitCall (
3745 ec, false, IsStatic, instance_expr, remove_accessor, args, loc);