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 // Mask of all the expression class flags.
57 // Disable control flow analysis while resolving the expression.
58 // This is used when resolving the instance expression of a field expression.
59 DisableFlowAnalysis = 8,
61 // Set if this is resolving the first part of a MemberAccess.
66 // This is just as a hint to AddressOf of what will be done with the
69 public enum AddressOp {
76 /// This interface is implemented by variables
78 public interface IMemoryLocation {
80 /// The AddressOf method should generate code that loads
81 /// the address of the object and leaves it on the stack.
83 /// The `mode' argument is used to notify the expression
84 /// of whether this will be used to read from the address or
85 /// write to the address.
87 /// This is just a hint that can be used to provide good error
88 /// reporting, and should have no other side effects.
90 void AddressOf (EmitContext ec, AddressOp mode);
94 /// We are either a namespace or a type.
95 /// If we're a type, `IsType' is true and we may use `Type' to get
96 /// a TypeExpr representing that type.
98 public interface IAlias {
107 TypeExpr ResolveAsType (EmitContext ec);
111 /// This interface is implemented by variables
113 public interface IVariable {
114 VariableInfo VariableInfo {
118 bool VerifyFixed (bool is_expression);
122 /// Base class for expressions
124 public abstract class Expression {
125 public ExprClass eclass;
127 protected Location loc;
139 public Location Location {
146 /// Utility wrapper routine for Error, just to beautify the code
148 public void Error (int error, string s)
150 if (!Location.IsNull (loc))
151 Report.Error (error, loc, s);
153 Report.Error (error, s);
157 /// Utility wrapper routine for Warning, just to beautify the code
159 public void Warning (int code, string format, params object[] args)
161 Report.Warning (code, loc, format, args);
164 // Not nice but we have broken hierarchy
165 public virtual void CheckMarshallByRefAccess (Type container) {}
168 /// Tests presence of ObsoleteAttribute and report proper error
170 protected void CheckObsoleteAttribute (Type type)
172 ObsoleteAttribute obsolete_attr = AttributeTester.GetObsoleteAttribute (type);
173 if (obsolete_attr == null)
176 AttributeTester.Report_ObsoleteMessage (obsolete_attr, type.FullName, loc);
179 public static bool IsAccessorAccessible (Type invocation_type, MethodInfo mi, out bool must_do_cs1540_check)
181 MethodAttributes ma = mi.Attributes & MethodAttributes.MemberAccessMask;
183 must_do_cs1540_check = false; // by default we do not check for this
186 // If only accessible to the current class or children
188 if (ma == MethodAttributes.Private)
189 return invocation_type == mi.DeclaringType ||
190 TypeManager.IsNestedChildOf (invocation_type, mi.DeclaringType);
192 if (mi.DeclaringType.Assembly == invocation_type.Assembly) {
193 if (ma == MethodAttributes.Assembly || ma == MethodAttributes.FamORAssem)
196 if (ma == MethodAttributes.Assembly || ma == MethodAttributes.FamANDAssem)
200 // Family and FamANDAssem require that we derive.
201 // FamORAssem requires that we derive if in different assemblies.
202 if (ma == MethodAttributes.Family ||
203 ma == MethodAttributes.FamANDAssem ||
204 ma == MethodAttributes.FamORAssem) {
205 if (!TypeManager.IsNestedFamilyAccessible (invocation_type, mi.DeclaringType))
208 if (!TypeManager.IsNestedChildOf (invocation_type, mi.DeclaringType))
209 must_do_cs1540_check = true;
218 /// Performs semantic analysis on the Expression
222 /// The Resolve method is invoked to perform the semantic analysis
225 /// The return value is an expression (it can be the
226 /// same expression in some cases) or a new
227 /// expression that better represents this node.
229 /// For example, optimizations of Unary (LiteralInt)
230 /// would return a new LiteralInt with a negated
233 /// If there is an error during semantic analysis,
234 /// then an error should be reported (using Report)
235 /// and a null value should be returned.
237 /// There are two side effects expected from calling
238 /// Resolve(): the the field variable "eclass" should
239 /// be set to any value of the enumeration
240 /// `ExprClass' and the type variable should be set
241 /// to a valid type (this is the type of the
244 public abstract Expression DoResolve (EmitContext ec);
246 public virtual Expression DoResolveLValue (EmitContext ec, Expression right_side)
252 // This is used if the expression should be resolved as a type or namespace name.
253 // the default implementation fails.
255 public virtual FullNamedExpression ResolveAsTypeStep (EmitContext ec)
261 // This is used to resolve the expression as a type, a null
262 // value will be returned if the expression is not a type
265 public TypeExpr ResolveAsTypeTerminal (EmitContext ec, bool silent)
267 int errors = Report.Errors;
269 FullNamedExpression fne = ResolveAsTypeStep (ec);
272 if (!silent && errors == Report.Errors)
273 Report.Error (246, Location, "Cannot find type '{0}'", ToString ());
277 if (fne.eclass != ExprClass.Type) {
278 if (!silent && errors == Report.Errors)
279 Report.Error (118, Location, "'{0}' denotes a '{1}', where a type was expected",
280 fne.FullName, fne.ExprClassName ());
284 TypeExpr te = fne as TypeExpr;
286 if (!te.CheckAccessLevel (ec.DeclSpace)) {
287 Report.Error (122, Location, "'{0}' is inaccessible due to its protection level", te.Name);
295 /// Resolves an expression and performs semantic analysis on it.
299 /// Currently Resolve wraps DoResolve to perform sanity
300 /// checking and assertion checking on what we expect from Resolve.
302 public Expression Resolve (EmitContext ec, ResolveFlags flags)
304 if ((flags & ResolveFlags.MaskExprClass) == ResolveFlags.Type)
305 return ResolveAsTypeStep (ec);
307 bool old_do_flow_analysis = ec.DoFlowAnalysis;
308 if ((flags & ResolveFlags.DisableFlowAnalysis) != 0)
309 ec.DoFlowAnalysis = false;
312 bool intermediate = (flags & ResolveFlags.Intermediate) == ResolveFlags.Intermediate;
313 if (this is SimpleName)
314 e = ((SimpleName) this).DoResolve (ec, intermediate);
319 ec.DoFlowAnalysis = old_do_flow_analysis;
324 if ((e is TypeExpr) || (e is ComposedCast) || (e is Namespace)) {
325 if ((flags & ResolveFlags.Type) == 0) {
326 e.Error_UnexpectedKind (flags, loc);
335 case ExprClass.Namespace:
336 if ((flags & ResolveFlags.VariableOrValue) == 0) {
337 e.Error_UnexpectedKind (flags, loc);
342 case ExprClass.MethodGroup:
343 if (RootContext.Version == LanguageVersion.ISO_1){
344 if ((flags & ResolveFlags.MethodGroup) == 0) {
345 ((MethodGroupExpr) e).ReportUsageError ();
351 case ExprClass.Value:
352 case ExprClass.Variable:
353 case ExprClass.PropertyAccess:
354 case ExprClass.EventAccess:
355 case ExprClass.IndexerAccess:
356 if ((flags & ResolveFlags.VariableOrValue) == 0) {
357 Console.WriteLine ("I got: {0} and {1}", e.GetType (), e);
358 Console.WriteLine ("I am {0} and {1}", this.GetType (), this);
359 FieldInfo fi = ((FieldExpr) e).FieldInfo;
361 Console.WriteLine ("{0} and {1}", fi.DeclaringType, fi.Name);
362 e.Error_UnexpectedKind (flags, loc);
368 throw new Exception ("Expression " + e.GetType () +
369 " ExprClass is Invalid after resolve");
372 if (e.type == null && !(e is Namespace)) {
373 throw new Exception (
374 "Expression " + e.GetType () +
375 " did not set its type after Resolve\n" +
376 "called from: " + this.GetType ());
383 /// Resolves an expression and performs semantic analysis on it.
385 public Expression Resolve (EmitContext ec)
387 return Resolve (ec, ResolveFlags.VariableOrValue);
391 /// Resolves an expression for LValue assignment
395 /// Currently ResolveLValue wraps DoResolveLValue to perform sanity
396 /// checking and assertion checking on what we expect from Resolve
398 public Expression ResolveLValue (EmitContext ec, Expression right_side)
400 int errors = Report.Errors;
401 Expression e = DoResolveLValue (ec, right_side);
404 if (errors == Report.Errors)
405 Report.Error (131, Location, "The left-hand side of an assignment or mutating operation must be a variable, property or indexer");
410 if (e.eclass == ExprClass.Invalid)
411 throw new Exception ("Expression " + e +
412 " ExprClass is Invalid after resolve");
414 if (e.eclass == ExprClass.MethodGroup) {
415 ((MethodGroupExpr) e).ReportUsageError ();
420 throw new Exception ("Expression " + e +
421 " did not set its type after Resolve");
428 /// Emits the code for the expression
432 /// The Emit method is invoked to generate the code
433 /// for the expression.
435 public abstract void Emit (EmitContext ec);
437 public virtual void EmitBranchable (EmitContext ec, Label target, bool onTrue)
440 ec.ig.Emit (onTrue ? OpCodes.Brtrue : OpCodes.Brfalse, target);
444 /// Protected constructor. Only derivate types should
445 /// be able to be created
448 protected Expression ()
450 eclass = ExprClass.Invalid;
455 /// Returns a literalized version of a literal FieldInfo
459 /// The possible return values are:
460 /// IntConstant, UIntConstant
461 /// LongLiteral, ULongConstant
462 /// FloatConstant, DoubleConstant
465 /// The value returned is already resolved.
467 public static Constant Constantify (object v, Type t)
469 if (t == TypeManager.int32_type)
470 return new IntConstant ((int) v);
471 else if (t == TypeManager.uint32_type)
472 return new UIntConstant ((uint) v);
473 else if (t == TypeManager.int64_type)
474 return new LongConstant ((long) v);
475 else if (t == TypeManager.uint64_type)
476 return new ULongConstant ((ulong) v);
477 else if (t == TypeManager.float_type)
478 return new FloatConstant ((float) v);
479 else if (t == TypeManager.double_type)
480 return new DoubleConstant ((double) v);
481 else if (t == TypeManager.string_type)
482 return new StringConstant ((string) v);
483 else if (t == TypeManager.short_type)
484 return new ShortConstant ((short)v);
485 else if (t == TypeManager.ushort_type)
486 return new UShortConstant ((ushort)v);
487 else if (t == TypeManager.sbyte_type)
488 return new SByteConstant (((sbyte)v));
489 else if (t == TypeManager.byte_type)
490 return new ByteConstant ((byte)v);
491 else if (t == TypeManager.char_type)
492 return new CharConstant ((char)v);
493 else if (t == TypeManager.bool_type)
494 return new BoolConstant ((bool) v);
495 else if (t == TypeManager.decimal_type)
496 return new DecimalConstant ((decimal) v);
497 else if (TypeManager.IsEnumType (t)){
498 Type real_type = TypeManager.TypeToCoreType (v.GetType ());
500 real_type = System.Enum.GetUnderlyingType (real_type);
502 Constant e = Constantify (v, real_type);
504 return new EnumConstant (e, t);
505 } else if (v == null && !TypeManager.IsValueType (t))
506 return NullLiteral.Null;
508 throw new Exception ("Unknown type for constant (" + t +
513 /// Returns a fully formed expression after a MemberLookup
515 public static Expression ExprClassFromMemberInfo (EmitContext ec, MemberInfo mi, Location loc)
518 return new EventExpr ((EventInfo) mi, loc);
519 else if (mi is FieldInfo)
520 return new FieldExpr ((FieldInfo) mi, loc);
521 else if (mi is PropertyInfo)
522 return new PropertyExpr (ec, (PropertyInfo) mi, loc);
523 else if (mi is Type){
524 return new TypeExpression ((System.Type) mi, loc);
530 protected static ArrayList almostMatchedMembers = new ArrayList (4);
533 // FIXME: Probably implement a cache for (t,name,current_access_set)?
535 // This code could use some optimizations, but we need to do some
536 // measurements. For example, we could use a delegate to `flag' when
537 // something can not any longer be a method-group (because it is something
541 // If the return value is an Array, then it is an array of
544 // If the return value is an MemberInfo, it is anything, but a Method
548 // FIXME: When calling MemberLookup inside an `Invocation', we should pass
549 // the arguments here and have MemberLookup return only the methods that
550 // match the argument count/type, unlike we are doing now (we delay this
553 // This is so we can catch correctly attempts to invoke instance methods
554 // from a static body (scan for error 120 in ResolveSimpleName).
557 // FIXME: Potential optimization, have a static ArrayList
560 public static Expression MemberLookup (EmitContext ec, Type queried_type, string name,
561 MemberTypes mt, BindingFlags bf, Location loc)
563 return MemberLookup (ec, ec.ContainerType, null, queried_type, name, mt, bf, loc);
567 // Lookup type `queried_type' for code in class `container_type' with a qualifier of
568 // `qualifier_type' or null to lookup members in the current class.
571 public static Expression MemberLookup (EmitContext ec, Type container_type,
572 Type qualifier_type, Type queried_type,
573 string name, MemberTypes mt,
574 BindingFlags bf, Location loc)
576 almostMatchedMembers.Clear ();
578 MemberInfo [] mi = TypeManager.MemberLookup (container_type, qualifier_type,
579 queried_type, mt, bf, name, almostMatchedMembers);
584 int count = mi.Length;
586 if (mi [0] is MethodBase)
587 return new MethodGroupExpr (mi, loc);
592 return ExprClassFromMemberInfo (ec, mi [0], loc);
595 public const MemberTypes AllMemberTypes =
596 MemberTypes.Constructor |
600 MemberTypes.NestedType |
601 MemberTypes.Property;
603 public const BindingFlags AllBindingFlags =
604 BindingFlags.Public |
605 BindingFlags.Static |
606 BindingFlags.Instance;
608 public static Expression MemberLookup (EmitContext ec, Type queried_type,
609 string name, Location loc)
611 return MemberLookup (ec, ec.ContainerType, null, queried_type, name,
612 AllMemberTypes, AllBindingFlags, loc);
615 public static Expression MemberLookup (EmitContext ec, Type qualifier_type,
616 Type queried_type, string name, Location loc)
618 return MemberLookup (ec, ec.ContainerType, qualifier_type, queried_type,
619 name, AllMemberTypes, AllBindingFlags, loc);
622 public static Expression MethodLookup (EmitContext ec, Type queried_type,
623 string name, Location loc)
625 return MemberLookup (ec, ec.ContainerType, null, queried_type, name,
626 MemberTypes.Method, AllBindingFlags, loc);
630 /// This is a wrapper for MemberLookup that is not used to "probe", but
631 /// to find a final definition. If the final definition is not found, we
632 /// look for private members and display a useful debugging message if we
635 public static Expression MemberLookupFinal (EmitContext ec, Type qualifier_type,
636 Type queried_type, string name, Location loc)
638 return MemberLookupFinal (ec, qualifier_type, queried_type, name,
639 AllMemberTypes, AllBindingFlags, loc);
642 public static Expression MemberLookupFinal (EmitContext ec, Type qualifier_type,
643 Type queried_type, string name,
644 MemberTypes mt, BindingFlags bf,
649 int errors = Report.Errors;
651 e = MemberLookup (ec, ec.ContainerType, qualifier_type, queried_type, name, mt, bf, loc);
653 if (e == null && errors == Report.Errors)
654 // No errors were reported by MemberLookup, but there was an error.
655 MemberLookupFailed (ec, qualifier_type, queried_type, name, null, true, loc);
660 public static void MemberLookupFailed (EmitContext ec, Type qualifier_type,
661 Type queried_type, string name,
662 string class_name, bool complain_if_none_found,
665 if (almostMatchedMembers.Count != 0) {
666 if (qualifier_type == null) {
667 foreach (MemberInfo m in almostMatchedMembers)
668 Report.Error (38, loc,
669 "Cannot access non-static member `{0}' via nested type `{1}'",
670 TypeManager.GetFullNameSignature (m),
671 TypeManager.CSharpName (ec.ContainerType));
675 if (qualifier_type != ec.ContainerType) {
676 // Although a derived class can access protected members of
677 // its base class it cannot do so through an instance of the
678 // base class (CS1540). If the qualifier_type is a base of the
679 // ec.ContainerType and the lookup succeeds with the latter one,
680 // then we are in this situation.
681 for (int i = 0; i < almostMatchedMembers.Count; ++i) {
682 MemberInfo m = (MemberInfo) almostMatchedMembers [i];
683 for (int j = 0; j < i; ++j) {
684 if (m == almostMatchedMembers [j]) {
692 Report.SymbolRelatedToPreviousError (m);
693 Report.Error (1540, loc,
694 "Cannot access protected member `{0}' via a qualifier of type `{1}';"
695 + " the qualifier must be of type `{2}' (or derived from it)",
696 TypeManager.GetFullNameSignature (m),
697 TypeManager.CSharpName (qualifier_type),
698 TypeManager.CSharpName (ec.ContainerType));
702 almostMatchedMembers.Clear ();
705 object lookup = TypeManager.MemberLookup (queried_type, null, queried_type,
706 AllMemberTypes, AllBindingFlags |
707 BindingFlags.NonPublic, name, null);
709 if (lookup == null) {
710 if (!complain_if_none_found)
713 if (class_name != null)
714 Report.Error (103, loc, "The name `" + name + "' could not be " +
715 "found in `" + class_name + "'");
718 117, loc, "`" + queried_type + "' does not contain a " +
719 "definition for `" + name + "'");
723 if (name == ".ctor" && TypeManager.FindMembers (qualifier_type, MemberTypes.Constructor,
724 BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly, null, null).Count == 0)
726 Report.Error (143, loc, String.Format ("The type '{0}' has no constructors defined", TypeManager.CSharpName (queried_type)));
730 if (qualifier_type != null) {
731 Report.Error (122, loc, "'{0}' is inaccessible due to its protection level", TypeManager.CSharpName (qualifier_type) + "." + name);
733 Report.Error (122, loc, "'{0}' is inaccessible due to its protection level", name);
738 /// Returns an expression that can be used to invoke operator true
739 /// on the expression if it exists.
741 static public StaticCallExpr GetOperatorTrue (EmitContext ec, Expression e, Location loc)
743 return GetOperatorTrueOrFalse (ec, e, true, loc);
747 /// Returns an expression that can be used to invoke operator false
748 /// on the expression if it exists.
750 static public StaticCallExpr GetOperatorFalse (EmitContext ec, Expression e, Location loc)
752 return GetOperatorTrueOrFalse (ec, e, false, loc);
755 static StaticCallExpr GetOperatorTrueOrFalse (EmitContext ec, Expression e, bool is_true, Location loc)
758 Expression operator_group;
760 operator_group = MethodLookup (ec, e.Type, is_true ? "op_True" : "op_False", loc);
761 if (operator_group == null)
764 ArrayList arguments = new ArrayList ();
765 arguments.Add (new Argument (e, Argument.AType.Expression));
766 method = Invocation.OverloadResolve (
767 ec, (MethodGroupExpr) operator_group, arguments, false, loc);
772 return new StaticCallExpr ((MethodInfo) method, arguments, loc);
776 /// Resolves the expression `e' into a boolean expression: either through
777 /// an implicit conversion, or through an `operator true' invocation
779 public static Expression ResolveBoolean (EmitContext ec, Expression e, Location loc)
785 if (e.Type == TypeManager.bool_type)
788 Expression converted = Convert.ImplicitConversion (ec, e, TypeManager.bool_type, Location.Null);
790 if (converted != null)
794 // If no implicit conversion to bool exists, try using `operator true'
796 Expression operator_true = Expression.GetOperatorTrue (ec, e, loc);
797 if (operator_true == null){
798 Report.Error (31, loc, "Can not convert the expression to a boolean");
801 return operator_true;
804 public string ExprClassName ()
807 case ExprClass.Invalid:
809 case ExprClass.Value:
811 case ExprClass.Variable:
813 case ExprClass.Namespace:
817 case ExprClass.MethodGroup:
818 return "method group";
819 case ExprClass.PropertyAccess:
820 return "property access";
821 case ExprClass.EventAccess:
822 return "event access";
823 case ExprClass.IndexerAccess:
824 return "indexer access";
825 case ExprClass.Nothing:
828 throw new Exception ("Should not happen");
832 /// Reports that we were expecting `expr' to be of class `expected'
834 public void Error_UnexpectedKind (string expected, Location loc)
836 Report.Error (118, loc, "Expression denotes a `" + ExprClassName () +
837 "' where a `" + expected + "' was expected");
840 public void Error_UnexpectedKind (ResolveFlags flags, Location loc)
842 ArrayList valid = new ArrayList (10);
844 if ((flags & ResolveFlags.VariableOrValue) != 0) {
845 valid.Add ("variable");
849 if ((flags & ResolveFlags.Type) != 0)
852 if ((flags & ResolveFlags.MethodGroup) != 0)
853 valid.Add ("method group");
855 if (valid.Count == 0)
856 valid.Add ("unknown");
858 StringBuilder sb = new StringBuilder ();
859 for (int i = 0; i < valid.Count; i++) {
862 else if (i == valid.Count)
864 sb.Append (valid [i]);
867 Report.Error (119, loc, "Expression denotes a `" + ExprClassName () + "' where " +
868 "a `" + sb.ToString () + "' was expected");
871 static public void Error_ConstantValueCannotBeConverted (Location l, string val, Type t)
873 Report.Error (31, l, "Constant value `" + val + "' cannot be converted to " +
874 TypeManager.CSharpName (t));
877 public static void UnsafeError (Location loc)
879 Report.Error (214, loc, "Pointers may only be used in an unsafe context");
883 /// Converts the IntConstant, UIntConstant, LongConstant or
884 /// ULongConstant into the integral target_type. Notice
885 /// that we do not return an `Expression' we do return
886 /// a boxed integral type.
888 /// FIXME: Since I added the new constants, we need to
889 /// also support conversions from CharConstant, ByteConstant,
890 /// SByteConstant, UShortConstant, ShortConstant
892 /// This is used by the switch statement, so the domain
893 /// of work is restricted to the literals above, and the
894 /// targets are int32, uint32, char, byte, sbyte, ushort,
895 /// short, uint64 and int64
897 public static object ConvertIntLiteral (Constant c, Type target_type, Location loc)
899 if (!Convert.ImplicitStandardConversionExists (Convert.ConstantEC, c, target_type)){
900 Convert.Error_CannotImplicitConversion (loc, c.Type, target_type);
906 if (c.Type == target_type)
907 return ((Constant) c).GetValue ();
910 // Make into one of the literals we handle, we dont really care
911 // about this value as we will just return a few limited types
913 if (c is EnumConstant)
914 c = ((EnumConstant)c).WidenToCompilerConstant ();
916 if (c is IntConstant){
917 int v = ((IntConstant) c).Value;
919 if (target_type == TypeManager.uint32_type){
922 } else if (target_type == TypeManager.char_type){
923 if (v >= Char.MinValue && v <= Char.MaxValue)
925 } else if (target_type == TypeManager.byte_type){
926 if (v >= Byte.MinValue && v <= Byte.MaxValue)
928 } else if (target_type == TypeManager.sbyte_type){
929 if (v >= SByte.MinValue && v <= SByte.MaxValue)
931 } else if (target_type == TypeManager.short_type){
932 if (v >= Int16.MinValue && v <= UInt16.MaxValue)
934 } else if (target_type == TypeManager.ushort_type){
935 if (v >= UInt16.MinValue && v <= UInt16.MaxValue)
937 } else if (target_type == TypeManager.int64_type)
939 else if (target_type == TypeManager.uint64_type){
945 } else if (c is UIntConstant){
946 uint v = ((UIntConstant) c).Value;
948 if (target_type == TypeManager.int32_type){
949 if (v <= Int32.MaxValue)
951 } else if (target_type == TypeManager.char_type){
952 if (v >= Char.MinValue && v <= Char.MaxValue)
954 } else if (target_type == TypeManager.byte_type){
955 if (v <= Byte.MaxValue)
957 } else if (target_type == TypeManager.sbyte_type){
958 if (v <= SByte.MaxValue)
960 } else if (target_type == TypeManager.short_type){
961 if (v <= UInt16.MaxValue)
963 } else if (target_type == TypeManager.ushort_type){
964 if (v <= UInt16.MaxValue)
966 } else if (target_type == TypeManager.int64_type)
968 else if (target_type == TypeManager.uint64_type)
971 } else if (c is LongConstant){
972 long v = ((LongConstant) c).Value;
974 if (target_type == TypeManager.int32_type){
975 if (v >= UInt32.MinValue && v <= UInt32.MaxValue)
977 } else if (target_type == TypeManager.uint32_type){
978 if (v >= 0 && v <= UInt32.MaxValue)
980 } else if (target_type == TypeManager.char_type){
981 if (v >= Char.MinValue && v <= Char.MaxValue)
983 } else if (target_type == TypeManager.byte_type){
984 if (v >= Byte.MinValue && v <= Byte.MaxValue)
986 } else if (target_type == TypeManager.sbyte_type){
987 if (v >= SByte.MinValue && v <= SByte.MaxValue)
989 } else if (target_type == TypeManager.short_type){
990 if (v >= Int16.MinValue && v <= UInt16.MaxValue)
992 } else if (target_type == TypeManager.ushort_type){
993 if (v >= UInt16.MinValue && v <= UInt16.MaxValue)
995 } else if (target_type == TypeManager.uint64_type){
1000 } else if (c is ULongConstant){
1001 ulong v = ((ULongConstant) c).Value;
1003 if (target_type == TypeManager.int32_type){
1004 if (v <= Int32.MaxValue)
1006 } else if (target_type == TypeManager.uint32_type){
1007 if (v <= UInt32.MaxValue)
1009 } else if (target_type == TypeManager.char_type){
1010 if (v >= Char.MinValue && v <= Char.MaxValue)
1012 } else if (target_type == TypeManager.byte_type){
1013 if (v >= Byte.MinValue && v <= Byte.MaxValue)
1015 } else if (target_type == TypeManager.sbyte_type){
1016 if (v <= (int) SByte.MaxValue)
1018 } else if (target_type == TypeManager.short_type){
1019 if (v <= UInt16.MaxValue)
1021 } else if (target_type == TypeManager.ushort_type){
1022 if (v <= UInt16.MaxValue)
1024 } else if (target_type == TypeManager.int64_type){
1025 if (v <= Int64.MaxValue)
1029 } else if (c is ByteConstant){
1030 byte v = ((ByteConstant) c).Value;
1032 if (target_type == TypeManager.int32_type)
1034 else if (target_type == TypeManager.uint32_type)
1036 else if (target_type == TypeManager.char_type)
1038 else if (target_type == TypeManager.sbyte_type){
1039 if (v <= SByte.MaxValue)
1041 } else if (target_type == TypeManager.short_type)
1043 else if (target_type == TypeManager.ushort_type)
1045 else if (target_type == TypeManager.int64_type)
1047 else if (target_type == TypeManager.uint64_type)
1050 } else if (c is SByteConstant){
1051 sbyte v = ((SByteConstant) c).Value;
1053 if (target_type == TypeManager.int32_type)
1055 else if (target_type == TypeManager.uint32_type){
1058 } else if (target_type == TypeManager.char_type){
1061 } else if (target_type == TypeManager.byte_type){
1064 } else if (target_type == TypeManager.short_type)
1066 else if (target_type == TypeManager.ushort_type){
1069 } else if (target_type == TypeManager.int64_type)
1071 else if (target_type == TypeManager.uint64_type){
1076 } else if (c is ShortConstant){
1077 short v = ((ShortConstant) c).Value;
1079 if (target_type == TypeManager.int32_type){
1081 } else if (target_type == TypeManager.uint32_type){
1084 } else if (target_type == TypeManager.char_type){
1087 } else if (target_type == TypeManager.byte_type){
1088 if (v >= Byte.MinValue && v <= Byte.MaxValue)
1090 } else if (target_type == TypeManager.sbyte_type){
1091 if (v >= SByte.MinValue && v <= SByte.MaxValue)
1093 } else if (target_type == TypeManager.ushort_type){
1096 } else if (target_type == TypeManager.int64_type)
1098 else if (target_type == TypeManager.uint64_type)
1102 } else if (c is UShortConstant){
1103 ushort v = ((UShortConstant) c).Value;
1105 if (target_type == TypeManager.int32_type)
1107 else if (target_type == TypeManager.uint32_type)
1109 else if (target_type == TypeManager.char_type){
1110 if (v >= Char.MinValue && v <= Char.MaxValue)
1112 } else if (target_type == TypeManager.byte_type){
1113 if (v >= Byte.MinValue && v <= Byte.MaxValue)
1115 } else if (target_type == TypeManager.sbyte_type){
1116 if (v <= SByte.MaxValue)
1118 } else if (target_type == TypeManager.short_type){
1119 if (v <= Int16.MaxValue)
1121 } else if (target_type == TypeManager.int64_type)
1123 else if (target_type == TypeManager.uint64_type)
1127 } else if (c is CharConstant){
1128 char v = ((CharConstant) c).Value;
1130 if (target_type == TypeManager.int32_type)
1132 else if (target_type == TypeManager.uint32_type)
1134 else if (target_type == TypeManager.byte_type){
1135 if (v >= Byte.MinValue && v <= Byte.MaxValue)
1137 } else if (target_type == TypeManager.sbyte_type){
1138 if (v <= SByte.MaxValue)
1140 } else if (target_type == TypeManager.short_type){
1141 if (v <= Int16.MaxValue)
1143 } else if (target_type == TypeManager.ushort_type)
1145 else if (target_type == TypeManager.int64_type)
1147 else if (target_type == TypeManager.uint64_type)
1152 Error_ConstantValueCannotBeConverted (loc, s, target_type);
1157 // Load the object from the pointer.
1159 public static void LoadFromPtr (ILGenerator ig, Type t)
1161 if (t == TypeManager.int32_type)
1162 ig.Emit (OpCodes.Ldind_I4);
1163 else if (t == TypeManager.uint32_type)
1164 ig.Emit (OpCodes.Ldind_U4);
1165 else if (t == TypeManager.short_type)
1166 ig.Emit (OpCodes.Ldind_I2);
1167 else if (t == TypeManager.ushort_type)
1168 ig.Emit (OpCodes.Ldind_U2);
1169 else if (t == TypeManager.char_type)
1170 ig.Emit (OpCodes.Ldind_U2);
1171 else if (t == TypeManager.byte_type)
1172 ig.Emit (OpCodes.Ldind_U1);
1173 else if (t == TypeManager.sbyte_type)
1174 ig.Emit (OpCodes.Ldind_I1);
1175 else if (t == TypeManager.uint64_type)
1176 ig.Emit (OpCodes.Ldind_I8);
1177 else if (t == TypeManager.int64_type)
1178 ig.Emit (OpCodes.Ldind_I8);
1179 else if (t == TypeManager.float_type)
1180 ig.Emit (OpCodes.Ldind_R4);
1181 else if (t == TypeManager.double_type)
1182 ig.Emit (OpCodes.Ldind_R8);
1183 else if (t == TypeManager.bool_type)
1184 ig.Emit (OpCodes.Ldind_I1);
1185 else if (t == TypeManager.intptr_type)
1186 ig.Emit (OpCodes.Ldind_I);
1187 else if (TypeManager.IsEnumType (t)) {
1188 if (t == TypeManager.enum_type)
1189 ig.Emit (OpCodes.Ldind_Ref);
1191 LoadFromPtr (ig, TypeManager.EnumToUnderlying (t));
1192 } else if (t.IsValueType)
1193 ig.Emit (OpCodes.Ldobj, t);
1194 else if (t.IsPointer)
1195 ig.Emit (OpCodes.Ldind_I);
1197 ig.Emit (OpCodes.Ldind_Ref);
1201 // The stack contains the pointer and the value of type `type'
1203 public static void StoreFromPtr (ILGenerator ig, Type type)
1205 if (TypeManager.IsEnumType (type))
1206 type = TypeManager.EnumToUnderlying (type);
1207 if (type == TypeManager.int32_type || type == TypeManager.uint32_type)
1208 ig.Emit (OpCodes.Stind_I4);
1209 else if (type == TypeManager.int64_type || type == TypeManager.uint64_type)
1210 ig.Emit (OpCodes.Stind_I8);
1211 else if (type == TypeManager.char_type || type == TypeManager.short_type ||
1212 type == TypeManager.ushort_type)
1213 ig.Emit (OpCodes.Stind_I2);
1214 else if (type == TypeManager.float_type)
1215 ig.Emit (OpCodes.Stind_R4);
1216 else if (type == TypeManager.double_type)
1217 ig.Emit (OpCodes.Stind_R8);
1218 else if (type == TypeManager.byte_type || type == TypeManager.sbyte_type ||
1219 type == TypeManager.bool_type)
1220 ig.Emit (OpCodes.Stind_I1);
1221 else if (type == TypeManager.intptr_type)
1222 ig.Emit (OpCodes.Stind_I);
1223 else if (type.IsValueType)
1224 ig.Emit (OpCodes.Stobj, type);
1226 ig.Emit (OpCodes.Stind_Ref);
1230 // Returns the size of type `t' if known, otherwise, 0
1232 public static int GetTypeSize (Type t)
1234 t = TypeManager.TypeToCoreType (t);
1235 if (t == TypeManager.int32_type ||
1236 t == TypeManager.uint32_type ||
1237 t == TypeManager.float_type)
1239 else if (t == TypeManager.int64_type ||
1240 t == TypeManager.uint64_type ||
1241 t == TypeManager.double_type)
1243 else if (t == TypeManager.byte_type ||
1244 t == TypeManager.sbyte_type ||
1245 t == TypeManager.bool_type)
1247 else if (t == TypeManager.short_type ||
1248 t == TypeManager.char_type ||
1249 t == TypeManager.ushort_type)
1251 else if (t == TypeManager.decimal_type)
1257 public static void Error_NegativeArrayIndex (Location loc)
1259 Report.Error (248, loc, "Cannot create an array with a negative size");
1263 // Converts `source' to an int, uint, long or ulong.
1265 public Expression ExpressionToArrayArgument (EmitContext ec, Expression source, Location loc)
1269 bool old_checked = ec.CheckState;
1270 ec.CheckState = true;
1272 target = Convert.ImplicitConversion (ec, source, TypeManager.int32_type, loc);
1273 if (target == null){
1274 target = Convert.ImplicitConversion (ec, source, TypeManager.uint32_type, loc);
1275 if (target == null){
1276 target = Convert.ImplicitConversion (ec, source, TypeManager.int64_type, loc);
1277 if (target == null){
1278 target = Convert.ImplicitConversion (ec, source, TypeManager.uint64_type, loc);
1280 Convert.Error_CannotImplicitConversion (loc, source.Type, TypeManager.int32_type);
1284 ec.CheckState = old_checked;
1287 // Only positive constants are allowed at compile time
1289 if (target is Constant){
1290 if (target is IntConstant){
1291 if (((IntConstant) target).Value < 0){
1292 Error_NegativeArrayIndex (loc);
1297 if (target is LongConstant){
1298 if (((LongConstant) target).Value < 0){
1299 Error_NegativeArrayIndex (loc);
1312 /// This is just a base class for expressions that can
1313 /// appear on statements (invocations, object creation,
1314 /// assignments, post/pre increment and decrement). The idea
1315 /// being that they would support an extra Emition interface that
1316 /// does not leave a result on the stack.
1318 public abstract class ExpressionStatement : Expression {
1320 public virtual ExpressionStatement ResolveStatement (EmitContext ec)
1322 Expression e = Resolve (ec);
1326 ExpressionStatement es = e as ExpressionStatement;
1328 Error (201, "Only assignment, call, increment, decrement and new object " +
1329 "expressions can be used as a statement");
1335 /// Requests the expression to be emitted in a `statement'
1336 /// context. This means that no new value is left on the
1337 /// stack after invoking this method (constrasted with
1338 /// Emit that will always leave a value on the stack).
1340 public abstract void EmitStatement (EmitContext ec);
1344 /// This kind of cast is used to encapsulate the child
1345 /// whose type is child.Type into an expression that is
1346 /// reported to return "return_type". This is used to encapsulate
1347 /// expressions which have compatible types, but need to be dealt
1348 /// at higher levels with.
1350 /// For example, a "byte" expression could be encapsulated in one
1351 /// of these as an "unsigned int". The type for the expression
1352 /// would be "unsigned int".
1355 public class EmptyCast : Expression {
1356 protected Expression child;
1358 public Expression Child {
1364 public EmptyCast (Expression child, Type return_type)
1366 eclass = child.eclass;
1367 loc = child.Location;
1372 public override Expression DoResolve (EmitContext ec)
1374 // This should never be invoked, we are born in fully
1375 // initialized state.
1380 public override void Emit (EmitContext ec)
1387 // We need to special case this since an empty cast of
1388 // a NullLiteral is still a Constant
1390 public class NullCast : Constant {
1391 protected Expression child;
1393 public NullCast (Expression child, Type return_type)
1395 eclass = child.eclass;
1400 override public string AsString ()
1405 public override object GetValue ()
1410 public override Expression DoResolve (EmitContext ec)
1412 // This should never be invoked, we are born in fully
1413 // initialized state.
1418 public override void Emit (EmitContext ec)
1423 public override bool IsDefaultValue {
1425 throw new NotImplementedException ();
1429 public override bool IsNegative {
1438 /// This class is used to wrap literals which belong inside Enums
1440 public class EnumConstant : Constant {
1441 public Constant Child;
1443 public EnumConstant (Constant child, Type enum_type)
1445 eclass = child.eclass;
1450 public override Expression DoResolve (EmitContext ec)
1452 // This should never be invoked, we are born in fully
1453 // initialized state.
1458 public override void Emit (EmitContext ec)
1463 public override object GetValue ()
1465 return Child.GetValue ();
1468 public object GetValueAsEnumType ()
1470 return System.Enum.ToObject (type, Child.GetValue ());
1474 // Converts from one of the valid underlying types for an enumeration
1475 // (int32, uint32, int64, uint64, short, ushort, byte, sbyte) to
1476 // one of the internal compiler literals: Int/UInt/Long/ULong Literals.
1478 public Constant WidenToCompilerConstant ()
1480 Type t = TypeManager.EnumToUnderlying (Child.Type);
1481 object v = ((Constant) Child).GetValue ();;
1483 if (t == TypeManager.int32_type)
1484 return new IntConstant ((int) v);
1485 if (t == TypeManager.uint32_type)
1486 return new UIntConstant ((uint) v);
1487 if (t == TypeManager.int64_type)
1488 return new LongConstant ((long) v);
1489 if (t == TypeManager.uint64_type)
1490 return new ULongConstant ((ulong) v);
1491 if (t == TypeManager.short_type)
1492 return new ShortConstant ((short) v);
1493 if (t == TypeManager.ushort_type)
1494 return new UShortConstant ((ushort) v);
1495 if (t == TypeManager.byte_type)
1496 return new ByteConstant ((byte) v);
1497 if (t == TypeManager.sbyte_type)
1498 return new SByteConstant ((sbyte) v);
1500 throw new Exception ("Invalid enumeration underlying type: " + t);
1504 // Extracts the value in the enumeration on its native representation
1506 public object GetPlainValue ()
1508 Type t = TypeManager.EnumToUnderlying (Child.Type);
1509 object v = ((Constant) Child).GetValue ();;
1511 if (t == TypeManager.int32_type)
1513 if (t == TypeManager.uint32_type)
1515 if (t == TypeManager.int64_type)
1517 if (t == TypeManager.uint64_type)
1519 if (t == TypeManager.short_type)
1521 if (t == TypeManager.ushort_type)
1523 if (t == TypeManager.byte_type)
1525 if (t == TypeManager.sbyte_type)
1531 public override string AsString ()
1533 return Child.AsString ();
1536 public override DoubleConstant ConvertToDouble ()
1538 return Child.ConvertToDouble ();
1541 public override FloatConstant ConvertToFloat ()
1543 return Child.ConvertToFloat ();
1546 public override ULongConstant ConvertToULong ()
1548 return Child.ConvertToULong ();
1551 public override LongConstant ConvertToLong ()
1553 return Child.ConvertToLong ();
1556 public override UIntConstant ConvertToUInt ()
1558 return Child.ConvertToUInt ();
1561 public override IntConstant ConvertToInt ()
1563 return Child.ConvertToInt ();
1566 public override bool IsDefaultValue {
1568 return Child.IsDefaultValue;
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 ig.Emit (OpCodes.Unbox, t);
1641 LoadFromPtr (ig, t);
1646 /// This is used to perform explicit numeric conversions.
1648 /// Explicit numeric conversions might trigger exceptions in a checked
1649 /// context, so they should generate the conv.ovf opcodes instead of
1652 public class ConvCast : EmptyCast {
1653 public enum Mode : byte {
1654 I1_U1, I1_U2, I1_U4, I1_U8, I1_CH,
1656 I2_I1, I2_U1, I2_U2, I2_U4, I2_U8, I2_CH,
1657 U2_I1, U2_U1, U2_I2, U2_CH,
1658 I4_I1, I4_U1, I4_I2, I4_U2, I4_U4, I4_U8, I4_CH,
1659 U4_I1, U4_U1, U4_I2, U4_U2, U4_I4, U4_CH,
1660 I8_I1, I8_U1, I8_I2, I8_U2, I8_I4, I8_U4, I8_U8, I8_CH,
1661 U8_I1, U8_U1, U8_I2, U8_U2, U8_I4, U8_U4, U8_I8, U8_CH,
1662 CH_I1, CH_U1, CH_I2,
1663 R4_I1, R4_U1, R4_I2, R4_U2, R4_I4, R4_U4, R4_I8, R4_U8, R4_CH,
1664 R8_I1, R8_U1, R8_I2, R8_U2, R8_I4, R8_U4, R8_I8, R8_U8, R8_CH, R8_R4
1670 public ConvCast (EmitContext ec, Expression child, Type return_type, Mode m)
1671 : base (child, return_type)
1673 checked_state = ec.CheckState;
1677 public override Expression DoResolve (EmitContext ec)
1679 // This should never be invoked, we are born in fully
1680 // initialized state.
1685 public override string ToString ()
1687 return String.Format ("ConvCast ({0}, {1})", mode, child);
1690 public override void Emit (EmitContext ec)
1692 ILGenerator ig = ec.ig;
1698 case Mode.I1_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1699 case Mode.I1_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1700 case Mode.I1_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1701 case Mode.I1_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1702 case Mode.I1_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1704 case Mode.U1_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1705 case Mode.U1_CH: /* nothing */ break;
1707 case Mode.I2_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1708 case Mode.I2_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1709 case Mode.I2_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1710 case Mode.I2_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1711 case Mode.I2_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1712 case Mode.I2_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1714 case Mode.U2_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1715 case Mode.U2_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
1716 case Mode.U2_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
1717 case Mode.U2_CH: /* nothing */ break;
1719 case Mode.I4_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1720 case Mode.I4_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1721 case Mode.I4_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
1722 case Mode.I4_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1723 case Mode.I4_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1724 case Mode.I4_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1725 case Mode.I4_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1727 case Mode.U4_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1728 case Mode.U4_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
1729 case Mode.U4_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
1730 case Mode.U4_U2: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
1731 case Mode.U4_I4: ig.Emit (OpCodes.Conv_Ovf_I4_Un); break;
1732 case Mode.U4_CH: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
1734 case Mode.I8_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1735 case Mode.I8_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1736 case Mode.I8_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
1737 case Mode.I8_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1738 case Mode.I8_I4: ig.Emit (OpCodes.Conv_Ovf_I4); break;
1739 case Mode.I8_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1740 case Mode.I8_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1741 case Mode.I8_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1743 case Mode.U8_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1744 case Mode.U8_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
1745 case Mode.U8_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
1746 case Mode.U8_U2: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
1747 case Mode.U8_I4: ig.Emit (OpCodes.Conv_Ovf_I4_Un); break;
1748 case Mode.U8_U4: ig.Emit (OpCodes.Conv_Ovf_U4_Un); break;
1749 case Mode.U8_I8: ig.Emit (OpCodes.Conv_Ovf_I8_Un); break;
1750 case Mode.U8_CH: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
1752 case Mode.CH_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1753 case Mode.CH_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
1754 case Mode.CH_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
1756 case Mode.R4_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1757 case Mode.R4_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1758 case Mode.R4_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
1759 case Mode.R4_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1760 case Mode.R4_I4: ig.Emit (OpCodes.Conv_Ovf_I4); break;
1761 case Mode.R4_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1762 case Mode.R4_I8: ig.Emit (OpCodes.Conv_Ovf_I8); break;
1763 case Mode.R4_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1764 case Mode.R4_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1766 case Mode.R8_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1767 case Mode.R8_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1768 case Mode.R8_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
1769 case Mode.R8_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1770 case Mode.R8_I4: ig.Emit (OpCodes.Conv_Ovf_I4); break;
1771 case Mode.R8_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1772 case Mode.R8_I8: ig.Emit (OpCodes.Conv_Ovf_I8); break;
1773 case Mode.R8_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1774 case Mode.R8_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1775 case Mode.R8_R4: ig.Emit (OpCodes.Conv_R4); break;
1779 case Mode.I1_U1: ig.Emit (OpCodes.Conv_U1); break;
1780 case Mode.I1_U2: ig.Emit (OpCodes.Conv_U2); break;
1781 case Mode.I1_U4: ig.Emit (OpCodes.Conv_U4); break;
1782 case Mode.I1_U8: ig.Emit (OpCodes.Conv_I8); break;
1783 case Mode.I1_CH: ig.Emit (OpCodes.Conv_U2); break;
1785 case Mode.U1_I1: ig.Emit (OpCodes.Conv_I1); break;
1786 case Mode.U1_CH: ig.Emit (OpCodes.Conv_U2); break;
1788 case Mode.I2_I1: ig.Emit (OpCodes.Conv_I1); break;
1789 case Mode.I2_U1: ig.Emit (OpCodes.Conv_U1); break;
1790 case Mode.I2_U2: ig.Emit (OpCodes.Conv_U2); break;
1791 case Mode.I2_U4: ig.Emit (OpCodes.Conv_U4); break;
1792 case Mode.I2_U8: ig.Emit (OpCodes.Conv_I8); break;
1793 case Mode.I2_CH: ig.Emit (OpCodes.Conv_U2); break;
1795 case Mode.U2_I1: ig.Emit (OpCodes.Conv_I1); break;
1796 case Mode.U2_U1: ig.Emit (OpCodes.Conv_U1); break;
1797 case Mode.U2_I2: ig.Emit (OpCodes.Conv_I2); break;
1798 case Mode.U2_CH: /* nothing */ break;
1800 case Mode.I4_I1: ig.Emit (OpCodes.Conv_I1); break;
1801 case Mode.I4_U1: ig.Emit (OpCodes.Conv_U1); break;
1802 case Mode.I4_I2: ig.Emit (OpCodes.Conv_I2); break;
1803 case Mode.I4_U4: /* nothing */ break;
1804 case Mode.I4_U2: ig.Emit (OpCodes.Conv_U2); break;
1805 case Mode.I4_U8: ig.Emit (OpCodes.Conv_I8); break;
1806 case Mode.I4_CH: ig.Emit (OpCodes.Conv_U2); break;
1808 case Mode.U4_I1: ig.Emit (OpCodes.Conv_I1); break;
1809 case Mode.U4_U1: ig.Emit (OpCodes.Conv_U1); break;
1810 case Mode.U4_I2: ig.Emit (OpCodes.Conv_I2); break;
1811 case Mode.U4_U2: ig.Emit (OpCodes.Conv_U2); break;
1812 case Mode.U4_I4: /* nothing */ break;
1813 case Mode.U4_CH: ig.Emit (OpCodes.Conv_U2); break;
1815 case Mode.I8_I1: ig.Emit (OpCodes.Conv_I1); break;
1816 case Mode.I8_U1: ig.Emit (OpCodes.Conv_U1); break;
1817 case Mode.I8_I2: ig.Emit (OpCodes.Conv_I2); break;
1818 case Mode.I8_U2: ig.Emit (OpCodes.Conv_U2); break;
1819 case Mode.I8_I4: ig.Emit (OpCodes.Conv_I4); break;
1820 case Mode.I8_U4: ig.Emit (OpCodes.Conv_U4); break;
1821 case Mode.I8_U8: /* nothing */ break;
1822 case Mode.I8_CH: ig.Emit (OpCodes.Conv_U2); break;
1824 case Mode.U8_I1: ig.Emit (OpCodes.Conv_I1); break;
1825 case Mode.U8_U1: ig.Emit (OpCodes.Conv_U1); break;
1826 case Mode.U8_I2: ig.Emit (OpCodes.Conv_I2); break;
1827 case Mode.U8_U2: ig.Emit (OpCodes.Conv_U2); break;
1828 case Mode.U8_I4: ig.Emit (OpCodes.Conv_I4); break;
1829 case Mode.U8_U4: ig.Emit (OpCodes.Conv_U4); break;
1830 case Mode.U8_I8: /* nothing */ break;
1831 case Mode.U8_CH: ig.Emit (OpCodes.Conv_U2); break;
1833 case Mode.CH_I1: ig.Emit (OpCodes.Conv_I1); break;
1834 case Mode.CH_U1: ig.Emit (OpCodes.Conv_U1); break;
1835 case Mode.CH_I2: ig.Emit (OpCodes.Conv_I2); break;
1837 case Mode.R4_I1: ig.Emit (OpCodes.Conv_I1); break;
1838 case Mode.R4_U1: ig.Emit (OpCodes.Conv_U1); break;
1839 case Mode.R4_I2: ig.Emit (OpCodes.Conv_I2); break;
1840 case Mode.R4_U2: ig.Emit (OpCodes.Conv_U2); break;
1841 case Mode.R4_I4: ig.Emit (OpCodes.Conv_I4); break;
1842 case Mode.R4_U4: ig.Emit (OpCodes.Conv_U4); break;
1843 case Mode.R4_I8: ig.Emit (OpCodes.Conv_I8); break;
1844 case Mode.R4_U8: ig.Emit (OpCodes.Conv_U8); break;
1845 case Mode.R4_CH: ig.Emit (OpCodes.Conv_U2); break;
1847 case Mode.R8_I1: ig.Emit (OpCodes.Conv_I1); break;
1848 case Mode.R8_U1: ig.Emit (OpCodes.Conv_U1); break;
1849 case Mode.R8_I2: ig.Emit (OpCodes.Conv_I2); break;
1850 case Mode.R8_U2: ig.Emit (OpCodes.Conv_U2); break;
1851 case Mode.R8_I4: ig.Emit (OpCodes.Conv_I4); break;
1852 case Mode.R8_U4: ig.Emit (OpCodes.Conv_U4); break;
1853 case Mode.R8_I8: ig.Emit (OpCodes.Conv_I8); break;
1854 case Mode.R8_U8: ig.Emit (OpCodes.Conv_U8); break;
1855 case Mode.R8_CH: ig.Emit (OpCodes.Conv_U2); break;
1856 case Mode.R8_R4: ig.Emit (OpCodes.Conv_R4); break;
1862 public class OpcodeCast : EmptyCast {
1866 public OpcodeCast (Expression child, Type return_type, OpCode op)
1867 : base (child, return_type)
1871 second_valid = false;
1874 public OpcodeCast (Expression child, Type return_type, OpCode op, OpCode op2)
1875 : base (child, return_type)
1880 second_valid = true;
1883 public override Expression DoResolve (EmitContext ec)
1885 // This should never be invoked, we are born in fully
1886 // initialized state.
1891 public override void Emit (EmitContext ec)
1902 /// This kind of cast is used to encapsulate a child and cast it
1903 /// to the class requested
1905 public class ClassCast : EmptyCast {
1906 public ClassCast (Expression child, Type return_type)
1907 : base (child, return_type)
1912 public override Expression DoResolve (EmitContext ec)
1914 // This should never be invoked, we are born in fully
1915 // initialized state.
1920 public override void Emit (EmitContext ec)
1924 ec.ig.Emit (OpCodes.Castclass, type);
1930 /// SimpleName expressions are formed of a single word and only happen at the beginning
1931 /// of a dotted-name.
1933 public class SimpleName : Expression {
1936 public SimpleName (string name, Location l)
1942 public static void Error_ObjectRefRequired (EmitContext ec, Location l, string name)
1944 if (ec.IsFieldInitializer)
1947 "A field initializer cannot reference the non-static field, " +
1948 "method or property `"+name+"'");
1952 "An object reference is required " +
1953 "for the non-static field `"+name+"'");
1956 public bool IdenticalNameAndTypeName (EmitContext ec, Expression resolved_to, Location loc)
1958 return resolved_to != null && resolved_to.Type != null &&
1959 resolved_to.Type.Name == Name &&
1960 (ec.DeclSpace.LookupType (Name, loc, /* ignore_cs0104 = */ true) != null);
1963 public override Expression DoResolve (EmitContext ec)
1965 return SimpleNameResolve (ec, null, false);
1968 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
1970 return SimpleNameResolve (ec, right_side, false);
1974 public Expression DoResolve (EmitContext ec, bool intermediate)
1976 return SimpleNameResolve (ec, null, intermediate);
1979 public override FullNamedExpression ResolveAsTypeStep (EmitContext ec)
1981 int errors = Report.Errors;
1982 FullNamedExpression dt = ec.DeclSpace.LookupType (Name, loc, /*ignore_cs0104=*/ false);
1983 if (Report.Errors != errors)
1989 Expression SimpleNameResolve (EmitContext ec, Expression right_side, bool intermediate)
1991 Expression e = DoSimpleNameResolve (ec, right_side, intermediate);
1995 if (ec.CurrentBlock == null || ec.CurrentBlock.CheckInvariantMeaningInBlock (Name, e, Location))
2002 /// 7.5.2: Simple Names.
2004 /// Local Variables and Parameters are handled at
2005 /// parse time, so they never occur as SimpleNames.
2007 /// The `intermediate' flag is used by MemberAccess only
2008 /// and it is used to inform us that it is ok for us to
2009 /// avoid the static check, because MemberAccess might end
2010 /// up resolving the Name as a Type name and the access as
2011 /// a static type access.
2013 /// ie: Type Type; .... { Type.GetType (""); }
2015 /// Type is both an instance variable and a Type; Type.GetType
2016 /// is the static method not an instance method of type.
2018 Expression DoSimpleNameResolve (EmitContext ec, Expression right_side, bool intermediate)
2020 Expression e = null;
2023 // Stage 1: Performed by the parser (binding to locals or parameters).
2025 Block current_block = ec.CurrentBlock;
2026 if (current_block != null){
2027 LocalInfo vi = current_block.GetLocalInfo (Name);
2031 var = new LocalVariableReference (ec.CurrentBlock, Name, loc);
2033 if (right_side != null)
2034 return var.ResolveLValue (ec, right_side);
2036 return var.Resolve (ec);
2039 ParameterReference pref = current_block.GetParameterReference (Name, loc);
2041 if (right_side != null)
2042 return pref.ResolveLValue (ec, right_side);
2044 return pref.Resolve (ec);
2049 // Stage 2: Lookup members
2052 DeclSpace lookup_ds = ec.DeclSpace;
2053 Type almost_matched_type = null;
2054 ArrayList almost_matched = null;
2056 if (lookup_ds.TypeBuilder == null)
2059 e = MemberLookup (ec, lookup_ds.TypeBuilder, Name, loc);
2063 if (almost_matched == null && almostMatchedMembers.Count > 0) {
2064 almost_matched_type = lookup_ds.TypeBuilder;
2065 almost_matched = (ArrayList) almostMatchedMembers.Clone ();
2068 lookup_ds =lookup_ds.Parent;
2069 } while (lookup_ds != null);
2071 if (e == null && ec.ContainerType != null)
2072 e = MemberLookup (ec, ec.ContainerType, Name, loc);
2075 if (almost_matched == null && almostMatchedMembers.Count > 0) {
2076 almost_matched_type = ec.ContainerType;
2077 almost_matched = (ArrayList) almostMatchedMembers.Clone ();
2079 e = ResolveAsTypeStep (ec);
2083 if (almost_matched != null)
2084 almostMatchedMembers = almost_matched;
2085 if (almost_matched_type == null)
2086 almost_matched_type = ec.ContainerType;
2087 MemberLookupFailed (ec, null, almost_matched_type, ((SimpleName) this).Name, ec.DeclSpace.Name, true, loc);
2094 if (e is MemberExpr) {
2095 MemberExpr me = (MemberExpr) e;
2098 if (me.IsInstance) {
2099 if (ec.IsStatic || ec.IsFieldInitializer) {
2101 // Note that an MemberExpr can be both IsInstance and IsStatic.
2102 // An unresolved MethodGroupExpr can contain both kinds of methods
2103 // and each predicate is true if the MethodGroupExpr contains
2104 // at least one of that kind of method.
2108 (!intermediate || !IdenticalNameAndTypeName (ec, me, loc))) {
2109 Error_ObjectRefRequired (ec, loc, Name);
2114 // Pass the buck to MemberAccess and Invocation.
2116 left = EmptyExpression.Null;
2118 left = ec.GetThis (loc);
2121 left = new TypeExpression (ec.ContainerType, loc);
2124 e = me.ResolveMemberAccess (ec, left, loc, null);
2128 me = e as MemberExpr;
2133 TypeManager.IsNestedFamilyAccessible (me.InstanceExpression.Type, me.DeclaringType) &&
2134 me.InstanceExpression.Type != me.DeclaringType &&
2135 !me.InstanceExpression.Type.IsSubclassOf (me.DeclaringType) &&
2136 (!intermediate || !IdenticalNameAndTypeName (ec, e, loc))) {
2137 Error (38, "Cannot access nonstatic member `" + me.Name + "' of " +
2138 "outer type `" + me.DeclaringType + "' via nested type `" +
2139 me.InstanceExpression.Type + "'");
2143 return (right_side != null)
2144 ? me.DoResolveLValue (ec, right_side)
2145 : me.DoResolve (ec);
2151 public override void Emit (EmitContext ec)
2154 // If this is ever reached, then we failed to
2155 // find the name as a namespace
2158 Error (103, "The name `" + Name +
2159 "' does not exist in the class `" +
2160 ec.DeclSpace.Name + "'");
2163 public override string ToString ()
2170 /// Represents a namespace or a type. The name of the class was inspired by
2171 /// section 10.8.1 (Fully Qualified Names).
2173 public abstract class FullNamedExpression : Expression {
2174 public override FullNamedExpression ResolveAsTypeStep (EmitContext ec)
2179 public abstract string FullName {
2185 /// Fully resolved expression that evaluates to a type
2187 public abstract class TypeExpr : FullNamedExpression {
2188 override public FullNamedExpression ResolveAsTypeStep (EmitContext ec)
2190 TypeExpr t = DoResolveAsTypeStep (ec);
2194 eclass = ExprClass.Type;
2198 override public Expression DoResolve (EmitContext ec)
2200 return ResolveAsTypeTerminal (ec, false);
2203 override public void Emit (EmitContext ec)
2205 throw new Exception ("Should never be called");
2208 public virtual bool CheckAccessLevel (DeclSpace ds)
2210 return ds.CheckAccessLevel (Type);
2213 public virtual bool AsAccessible (DeclSpace ds, int flags)
2215 return ds.AsAccessible (Type, flags);
2218 public virtual bool IsClass {
2219 get { return Type.IsClass; }
2222 public virtual bool IsValueType {
2223 get { return Type.IsValueType; }
2226 public virtual bool IsInterface {
2227 get { return Type.IsInterface; }
2230 public virtual bool IsSealed {
2231 get { return Type.IsSealed; }
2234 public virtual bool CanInheritFrom ()
2236 if (Type == TypeManager.enum_type ||
2237 (Type == TypeManager.value_type && RootContext.StdLib) ||
2238 Type == TypeManager.multicast_delegate_type ||
2239 Type == TypeManager.delegate_type ||
2240 Type == TypeManager.array_type)
2246 public abstract TypeExpr DoResolveAsTypeStep (EmitContext ec);
2248 public virtual Type ResolveType (EmitContext ec)
2250 TypeExpr t = ResolveAsTypeTerminal (ec, false);
2257 public abstract string Name {
2261 public override bool Equals (object obj)
2263 TypeExpr tobj = obj as TypeExpr;
2267 return Type == tobj.Type;
2270 public override int GetHashCode ()
2272 return Type.GetHashCode ();
2275 public override string ToString ()
2281 public class TypeExpression : TypeExpr {
2282 public TypeExpression (Type t, Location l)
2285 eclass = ExprClass.Type;
2289 public override TypeExpr DoResolveAsTypeStep (EmitContext ec)
2294 public override string Name {
2296 return Type.ToString ();
2300 public override string FullName {
2302 return Type.FullName;
2308 /// Used to create types from a fully qualified name. These are just used
2309 /// by the parser to setup the core types. A TypeLookupExpression is always
2310 /// classified as a type.
2312 public class TypeLookupExpression : TypeExpr {
2315 public TypeLookupExpression (string name)
2320 public override TypeExpr DoResolveAsTypeStep (EmitContext ec)
2323 FullNamedExpression t = ec.DeclSpace.LookupType (name, Location.Null, /*ignore_cs0104=*/ false);
2325 Report.Error (246, loc, "Cannot find type `" + name + "'");
2328 if (!(t is TypeExpr)) {
2329 Report.Error (118, Location, "'{0}' denotes a '{1}', where a type was expected",
2330 t.FullName, t.ExprClassName ());
2334 type = ((TypeExpr) t).ResolveType (ec);
2340 public override string Name {
2346 public override string FullName {
2353 public class TypeAliasExpression : TypeExpr {
2356 public TypeAliasExpression (TypeExpr texpr, Location l)
2359 loc = texpr.Location;
2361 eclass = ExprClass.Type;
2364 public override string Name {
2365 get { return texpr.Name; }
2368 public override string FullName {
2369 get { return texpr.FullName; }
2372 public override TypeExpr DoResolveAsTypeStep (EmitContext ec)
2374 Type type = texpr.ResolveType (ec);
2378 return new TypeExpression (type, loc);
2381 public override bool CheckAccessLevel (DeclSpace ds)
2383 return texpr.CheckAccessLevel (ds);
2386 public override bool AsAccessible (DeclSpace ds, int flags)
2388 return texpr.AsAccessible (ds, flags);
2391 public override bool IsClass {
2392 get { return texpr.IsClass; }
2395 public override bool IsValueType {
2396 get { return texpr.IsValueType; }
2399 public override bool IsInterface {
2400 get { return texpr.IsInterface; }
2403 public override bool IsSealed {
2404 get { return texpr.IsSealed; }
2409 /// This class denotes an expression which evaluates to a member
2410 /// of a struct or a class.
2412 public abstract class MemberExpr : Expression
2415 /// The name of this member.
2417 public abstract string Name {
2422 /// Whether this is an instance member.
2424 public abstract bool IsInstance {
2429 /// Whether this is a static member.
2431 public abstract bool IsStatic {
2436 /// The type which declares this member.
2438 public abstract Type DeclaringType {
2443 /// The instance expression associated with this member, if it's a
2444 /// non-static member.
2446 public Expression InstanceExpression;
2448 public static void error176 (Location loc, string name)
2450 Report.Error (176, loc, "Static member `" + name + "' cannot be accessed " +
2451 "with an instance reference, qualify with a type name instead");
2455 // TODO: possible optimalization
2456 // Cache resolved constant result in FieldBuilder <-> expression map
2457 public virtual Expression ResolveMemberAccess (EmitContext ec, Expression left, Location loc,
2458 SimpleName original)
2462 // original == null || original.Resolve (...) ==> left
2465 if (left is TypeExpr) {
2467 SimpleName.Error_ObjectRefRequired (ec, loc, Name);
2475 if (original != null && original.IdenticalNameAndTypeName (ec, left, loc))
2478 error176 (loc, Name);
2482 InstanceExpression = left;
2489 /// MethodGroup Expression.
2491 /// This is a fully resolved expression that evaluates to a type
2493 public class MethodGroupExpr : MemberExpr {
2494 public MethodBase [] Methods;
2495 bool identical_type_name = false;
2498 public MethodGroupExpr (MemberInfo [] mi, Location l)
2500 Methods = new MethodBase [mi.Length];
2501 mi.CopyTo (Methods, 0);
2502 eclass = ExprClass.MethodGroup;
2503 type = TypeManager.object_type;
2507 public MethodGroupExpr (ArrayList list, Location l)
2509 Methods = new MethodBase [list.Count];
2512 list.CopyTo (Methods, 0);
2514 foreach (MemberInfo m in list){
2515 if (!(m is MethodBase)){
2516 Console.WriteLine ("Name " + m.Name);
2517 Console.WriteLine ("Found a: " + m.GetType ().FullName);
2524 eclass = ExprClass.MethodGroup;
2525 type = TypeManager.object_type;
2528 public override Type DeclaringType {
2531 // The methods are arranged in this order:
2532 // derived type -> base type
2534 return Methods [0].DeclaringType;
2538 public bool IdenticalTypeName {
2540 return identical_type_name;
2544 identical_type_name = value;
2548 public bool IsBase {
2557 public override string Name {
2559 return Methods [0].Name;
2563 public override bool IsInstance {
2565 foreach (MethodBase mb in Methods)
2573 public override bool IsStatic {
2575 foreach (MethodBase mb in Methods)
2583 public override Expression ResolveMemberAccess (EmitContext ec, Expression left, Location loc,
2584 SimpleName original)
2586 if (!(left is TypeExpr) &&
2587 original != null && original.IdenticalNameAndTypeName (ec, left, loc))
2588 IdenticalTypeName = true;
2590 return base.ResolveMemberAccess (ec, left, loc, original);
2593 override public Expression DoResolve (EmitContext ec)
2596 InstanceExpression = null;
2598 if (InstanceExpression != null) {
2599 InstanceExpression = InstanceExpression.DoResolve (ec);
2600 if (InstanceExpression == null)
2607 public void ReportUsageError ()
2609 Report.Error (654, loc, "Method `" + DeclaringType + "." +
2610 Name + "()' is referenced without parentheses");
2613 override public void Emit (EmitContext ec)
2615 ReportUsageError ();
2618 bool RemoveMethods (bool keep_static)
2620 ArrayList smethods = new ArrayList ();
2622 foreach (MethodBase mb in Methods){
2623 if (mb.IsStatic == keep_static)
2627 if (smethods.Count == 0)
2630 Methods = new MethodBase [smethods.Count];
2631 smethods.CopyTo (Methods, 0);
2637 /// Removes any instance methods from the MethodGroup, returns
2638 /// false if the resulting set is empty.
2640 public bool RemoveInstanceMethods ()
2642 return RemoveMethods (true);
2646 /// Removes any static methods from the MethodGroup, returns
2647 /// false if the resulting set is empty.
2649 public bool RemoveStaticMethods ()
2651 return RemoveMethods (false);
2656 /// Fully resolved expression that evaluates to a Field
2658 public class FieldExpr : MemberExpr, IAssignMethod, IMemoryLocation, IVariable {
2659 public readonly FieldInfo FieldInfo;
2660 VariableInfo variable_info;
2662 LocalTemporary temp;
2665 public FieldExpr (FieldInfo fi, Location l)
2668 eclass = ExprClass.Variable;
2669 type = fi.FieldType;
2673 public override string Name {
2675 return FieldInfo.Name;
2679 public override bool IsInstance {
2681 return !FieldInfo.IsStatic;
2685 public override bool IsStatic {
2687 return FieldInfo.IsStatic;
2691 public override Type DeclaringType {
2693 return FieldInfo.DeclaringType;
2697 public VariableInfo VariableInfo {
2699 return variable_info;
2703 public override Expression ResolveMemberAccess (EmitContext ec, Expression left, Location loc,
2704 SimpleName original)
2706 bool left_is_type = left is TypeExpr;
2708 Type decl_type = FieldInfo.DeclaringType;
2710 bool is_emitted = FieldInfo is FieldBuilder;
2711 Type t = FieldInfo.FieldType;
2714 Const c = TypeManager.LookupConstant ((FieldBuilder) FieldInfo);
2718 if (!c.LookupConstantValue (out o))
2721 c.SetMemberIsUsed ();
2722 object real_value = ((Constant) c.Expr).GetValue ();
2724 Expression exp = Constantify (real_value, t);
2726 if (!left_is_type &&
2727 (original == null || !original.IdenticalNameAndTypeName (ec, left, loc))) {
2728 Report.SymbolRelatedToPreviousError (c);
2729 error176 (loc, c.GetSignatureForError ());
2737 // IsInitOnly is because of MS compatibility, I don't know why but they emit decimal constant as InitOnly
2738 if (FieldInfo.IsInitOnly && !is_emitted && t == TypeManager.decimal_type) {
2739 object[] attrs = FieldInfo.GetCustomAttributes (TypeManager.decimal_constant_attribute_type, false);
2740 if (attrs.Length == 1)
2741 return new DecimalConstant (((System.Runtime.CompilerServices.DecimalConstantAttribute) attrs [0]).Value);
2744 if (FieldInfo.IsLiteral) {
2748 o = TypeManager.GetValue ((FieldBuilder) FieldInfo);
2750 o = FieldInfo.GetValue (FieldInfo);
2752 if (decl_type.IsSubclassOf (TypeManager.enum_type)) {
2753 if (!left_is_type &&
2754 (original == null || !original.IdenticalNameAndTypeName (ec, left, loc))) {
2755 error176 (loc, FieldInfo.Name);
2759 Expression enum_member = MemberLookup (
2760 ec, decl_type, "value__", MemberTypes.Field,
2761 AllBindingFlags | BindingFlags.NonPublic, loc);
2763 Enum en = TypeManager.LookupEnum (decl_type);
2767 c = Constantify (o, en.UnderlyingType);
2769 c = Constantify (o, enum_member.Type);
2771 return new EnumConstant (c, decl_type);
2774 Expression exp = Constantify (o, t);
2776 if (!left_is_type) {
2777 error176 (loc, FieldInfo.Name);
2784 if (t.IsPointer && !ec.InUnsafe) {
2789 return base.ResolveMemberAccess (ec, left, loc, original);
2792 override public Expression DoResolve (EmitContext ec)
2794 if (!FieldInfo.IsStatic){
2795 if (InstanceExpression == null){
2797 // This can happen when referencing an instance field using
2798 // a fully qualified type expression: TypeName.InstanceField = xxx
2800 SimpleName.Error_ObjectRefRequired (ec, loc, FieldInfo.Name);
2804 // Resolve the field's instance expression while flow analysis is turned
2805 // off: when accessing a field "a.b", we must check whether the field
2806 // "a.b" is initialized, not whether the whole struct "a" is initialized.
2807 InstanceExpression = InstanceExpression.Resolve (ec, ResolveFlags.VariableOrValue |
2808 ResolveFlags.DisableFlowAnalysis);
2809 if (InstanceExpression == null)
2813 ObsoleteAttribute oa;
2814 FieldBase f = TypeManager.GetField (FieldInfo);
2816 oa = f.GetObsoleteAttribute (f.Parent);
2818 AttributeTester.Report_ObsoleteMessage (oa, f.GetSignatureForError (), loc);
2820 // To be sure that type is external because we do not register generated fields
2821 } else if (!(FieldInfo.DeclaringType is TypeBuilder)) {
2822 oa = AttributeTester.GetMemberObsoleteAttribute (FieldInfo);
2824 AttributeTester.Report_ObsoleteMessage (oa, TypeManager.GetFullNameSignature (FieldInfo), loc);
2827 if (ec.CurrentAnonymousMethod != null){
2828 if (!FieldInfo.IsStatic){
2829 if (ec.TypeContainer is Struct){
2830 Report.Error (1673, loc, "Can not reference instance variables in anonymous methods hosted in structs");
2833 ec.CaptureField (this);
2837 // If the instance expression is a local variable or parameter.
2838 IVariable var = InstanceExpression as IVariable;
2839 if ((var == null) || (var.VariableInfo == null))
2842 VariableInfo vi = var.VariableInfo;
2843 if (!vi.IsFieldAssigned (ec, FieldInfo.Name, loc))
2846 variable_info = vi.GetSubStruct (FieldInfo.Name);
2850 void Report_AssignToReadonly (bool is_instance)
2855 msg = "Readonly field can not be assigned outside " +
2856 "of constructor or variable initializer";
2858 msg = "A static readonly field can only be assigned in " +
2859 "a static constructor";
2861 Report.Error (is_instance ? 191 : 198, loc, msg);
2864 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
2866 IVariable var = InstanceExpression as IVariable;
2867 if ((var != null) && (var.VariableInfo != null))
2868 var.VariableInfo.SetFieldAssigned (ec, FieldInfo.Name);
2870 Expression e = DoResolve (ec);
2875 if (!FieldInfo.IsStatic && (InstanceExpression.Type.IsValueType && !(InstanceExpression is IMemoryLocation))) {
2876 // FIXME: Provide better error reporting.
2877 Error (1612, "Cannot modify expression because it is not a variable.");
2881 if (!FieldInfo.IsInitOnly)
2884 FieldBase fb = TypeManager.GetField (FieldInfo);
2889 // InitOnly fields can only be assigned in constructors
2892 if (ec.IsConstructor){
2893 if (IsStatic && !ec.IsStatic)
2894 Report_AssignToReadonly (false);
2896 if (ec.ContainerType == FieldInfo.DeclaringType)
2900 Report_AssignToReadonly (!IsStatic);
2905 public override void CheckMarshallByRefAccess (Type container)
2907 if (!IsStatic && Type.IsValueType && !container.IsSubclassOf (TypeManager.mbr_type) && DeclaringType.IsSubclassOf (TypeManager.mbr_type)) {
2908 Report.SymbolRelatedToPreviousError (DeclaringType);
2909 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);
2913 public bool VerifyFixed (bool is_expression)
2915 IVariable variable = InstanceExpression as IVariable;
2916 if ((variable == null) || !variable.VerifyFixed (true))
2922 public override int GetHashCode()
2924 return FieldInfo.GetHashCode ();
2927 public override bool Equals (object obj)
2929 FieldExpr fe = obj as FieldExpr;
2933 if (FieldInfo != fe.FieldInfo)
2936 if (InstanceExpression == null || fe.InstanceExpression == null)
2939 return InstanceExpression.Equals (fe.InstanceExpression);
2942 public void Emit (EmitContext ec, bool leave_copy)
2944 ILGenerator ig = ec.ig;
2945 bool is_volatile = false;
2947 if (FieldInfo is FieldBuilder){
2948 FieldBase f = TypeManager.GetField (FieldInfo);
2950 if ((f.ModFlags & Modifiers.VOLATILE) != 0)
2953 f.SetMemberIsUsed ();
2957 if (FieldInfo.IsStatic){
2959 ig.Emit (OpCodes.Volatile);
2961 ig.Emit (OpCodes.Ldsfld, FieldInfo);
2967 ig.Emit (OpCodes.Volatile);
2969 IFixedBuffer ff = AttributeTester.GetFixedBuffer (FieldInfo);
2972 ig.Emit (OpCodes.Ldflda, FieldInfo);
2973 ig.Emit (OpCodes.Ldflda, ff.Element);
2976 ig.Emit (OpCodes.Ldfld, FieldInfo);
2981 ec.ig.Emit (OpCodes.Dup);
2982 if (!FieldInfo.IsStatic) {
2983 temp = new LocalTemporary (ec, this.Type);
2989 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
2991 FieldAttributes fa = FieldInfo.Attributes;
2992 bool is_static = (fa & FieldAttributes.Static) != 0;
2993 bool is_readonly = (fa & FieldAttributes.InitOnly) != 0;
2994 ILGenerator ig = ec.ig;
2995 prepared = prepare_for_load;
2997 if (is_readonly && !ec.IsConstructor){
2998 Report_AssignToReadonly (!is_static);
3004 if (prepare_for_load)
3005 ig.Emit (OpCodes.Dup);
3010 ec.ig.Emit (OpCodes.Dup);
3011 if (!FieldInfo.IsStatic) {
3012 temp = new LocalTemporary (ec, this.Type);
3017 if (FieldInfo is FieldBuilder){
3018 FieldBase f = TypeManager.GetField (FieldInfo);
3020 if ((f.ModFlags & Modifiers.VOLATILE) != 0)
3021 ig.Emit (OpCodes.Volatile);
3023 f.status |= Field.Status.ASSIGNED;
3028 ig.Emit (OpCodes.Stsfld, FieldInfo);
3030 ig.Emit (OpCodes.Stfld, FieldInfo);
3036 void EmitInstance (EmitContext ec)
3038 if (InstanceExpression.Type.IsValueType) {
3039 if (InstanceExpression is IMemoryLocation) {
3040 ((IMemoryLocation) InstanceExpression).AddressOf (ec, AddressOp.LoadStore);
3042 LocalTemporary t = new LocalTemporary (ec, InstanceExpression.Type);
3043 InstanceExpression.Emit (ec);
3045 t.AddressOf (ec, AddressOp.Store);
3048 InstanceExpression.Emit (ec);
3051 public override void Emit (EmitContext ec)
3056 public void AddressOf (EmitContext ec, AddressOp mode)
3058 ILGenerator ig = ec.ig;
3060 if (FieldInfo is FieldBuilder){
3061 FieldBase f = TypeManager.GetField (FieldInfo);
3063 if ((f.ModFlags & Modifiers.VOLATILE) != 0){
3064 Error (676, "volatile variable: can not take its address, or pass as ref/out parameter");
3068 if ((mode & AddressOp.Store) != 0)
3069 f.status |= Field.Status.ASSIGNED;
3070 if ((mode & AddressOp.Load) != 0)
3071 f.SetMemberIsUsed ();
3076 // Handle initonly fields specially: make a copy and then
3077 // get the address of the copy.
3080 if (FieldInfo.IsInitOnly){
3082 if (ec.IsConstructor){
3083 if (FieldInfo.IsStatic){
3095 local = ig.DeclareLocal (type);
3096 ig.Emit (OpCodes.Stloc, local);
3097 ig.Emit (OpCodes.Ldloca, local);
3102 if (FieldInfo.IsStatic){
3103 ig.Emit (OpCodes.Ldsflda, FieldInfo);
3106 ig.Emit (OpCodes.Ldflda, FieldInfo);
3112 // A FieldExpr whose address can not be taken
3114 public class FieldExprNoAddress : FieldExpr, IMemoryLocation {
3115 public FieldExprNoAddress (FieldInfo fi, Location loc) : base (fi, loc)
3119 public new void AddressOf (EmitContext ec, AddressOp mode)
3121 Report.Error (-215, "Report this: Taking the address of a remapped parameter not supported");
3126 /// Expression that evaluates to a Property. The Assign class
3127 /// might set the `Value' expression if we are in an assignment.
3129 /// This is not an LValue because we need to re-write the expression, we
3130 /// can not take data from the stack and store it.
3132 public class PropertyExpr : MemberExpr, IAssignMethod {
3133 public readonly PropertyInfo PropertyInfo;
3136 // This is set externally by the `BaseAccess' class
3139 MethodInfo getter, setter;
3142 LocalTemporary temp;
3145 internal static PtrHashtable AccessorTable = new PtrHashtable ();
3147 public PropertyExpr (EmitContext ec, PropertyInfo pi, Location l)
3150 eclass = ExprClass.PropertyAccess;
3154 type = TypeManager.TypeToCoreType (pi.PropertyType);
3156 ResolveAccessors (ec);
3159 public override string Name {
3161 return PropertyInfo.Name;
3165 public override bool IsInstance {
3171 public override bool IsStatic {
3177 public override Type DeclaringType {
3179 return PropertyInfo.DeclaringType;
3183 public bool VerifyAssignable ()
3185 if (setter == null) {
3186 Report.Error (200, loc,
3187 "The property `" + PropertyInfo.Name +
3188 "' can not be assigned to, as it has not set accessor");
3195 void FindAccessors (Type invocation_type)
3197 BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic |
3198 BindingFlags.Static | BindingFlags.Instance |
3199 BindingFlags.DeclaredOnly;
3201 Type current = PropertyInfo.DeclaringType;
3202 for (; current != null; current = current.BaseType) {
3203 MemberInfo[] group = TypeManager.MemberLookup (
3204 invocation_type, invocation_type, current,
3205 MemberTypes.Property, flags, PropertyInfo.Name, null);
3210 if (group.Length != 1)
3211 // Oooops, can this ever happen ?
3214 PropertyInfo pi = (PropertyInfo) group [0];
3217 getter = pi.GetGetMethod (true);
3220 setter = pi.GetSetMethod (true);
3222 MethodInfo accessor = getter != null ? getter : setter;
3224 if (!accessor.IsVirtual)
3230 // We also perform the permission checking here, as the PropertyInfo does not
3231 // hold the information for the accessibility of its setter/getter
3233 void ResolveAccessors (EmitContext ec)
3235 FindAccessors (ec.ContainerType);
3237 if (getter != null) {
3238 IMethodData md = TypeManager.GetMethod (getter);
3240 md.SetMemberIsUsed ();
3242 AccessorTable [getter] = PropertyInfo;
3243 is_static = getter.IsStatic;
3246 if (setter != null) {
3247 IMethodData md = TypeManager.GetMethod (setter);
3249 md.SetMemberIsUsed ();
3251 AccessorTable [setter] = PropertyInfo;
3252 is_static = setter.IsStatic;
3256 bool InstanceResolve (EmitContext ec, bool must_do_cs1540_check)
3258 if ((InstanceExpression == null) && ec.IsStatic && !is_static) {
3259 SimpleName.Error_ObjectRefRequired (ec, loc, PropertyInfo.Name);
3263 if (InstanceExpression != null) {
3264 InstanceExpression = InstanceExpression.DoResolve (ec);
3265 if (InstanceExpression == null)
3268 InstanceExpression.CheckMarshallByRefAccess (ec.ContainerType);
3271 if (must_do_cs1540_check && (InstanceExpression != null)) {
3272 if ((InstanceExpression.Type != ec.ContainerType) &&
3273 ec.ContainerType.IsSubclassOf (InstanceExpression.Type)) {
3274 Report.Error (1540, loc, "Cannot access protected member `" +
3275 PropertyInfo.DeclaringType + "." + PropertyInfo.Name +
3276 "' via a qualifier of type `" +
3277 TypeManager.CSharpName (InstanceExpression.Type) +
3278 "'; the qualifier must be of type `" +
3279 TypeManager.CSharpName (ec.ContainerType) +
3280 "' (or derived from it)");
3288 override public Expression DoResolve (EmitContext ec)
3290 if (getter != null){
3291 if (TypeManager.GetArgumentTypes (getter).Length != 0){
3293 117, loc, "`{0}' does not contain a " +
3294 "definition for `{1}'.", getter.DeclaringType,
3300 if (getter == null){
3302 // The following condition happens if the PropertyExpr was
3303 // created, but is invalid (ie, the property is inaccessible),
3304 // and we did not want to embed the knowledge about this in
3305 // the caller routine. This only avoids double error reporting.
3310 Report.Error (154, loc,
3311 "The property `" + PropertyInfo.Name +
3312 "' can not be used in " +
3313 "this context because it lacks a get accessor");
3317 bool must_do_cs1540_check;
3318 if (!IsAccessorAccessible (ec.ContainerType, getter, out must_do_cs1540_check)) {
3319 PropertyBase.PropertyMethod pm = TypeManager.GetMethod (getter) as PropertyBase.PropertyMethod;
3320 if (pm != null && pm.HasCustomAccessModifier) {
3321 Report.SymbolRelatedToPreviousError (pm);
3322 Report.Error (271, loc, "The property or indexer '{0}' cannot be used in this context because the get accessor is inaccessible",
3323 TypeManager.CSharpSignature (getter));
3326 Report.Error (122, loc, "'{0}' is inaccessible due to its protection level",
3327 TypeManager.CSharpSignature (getter));
3331 if (!InstanceResolve (ec, must_do_cs1540_check))
3335 // Only base will allow this invocation to happen.
3337 if (IsBase && getter.IsAbstract){
3338 Report.Error (205, loc, "Cannot call an abstract base property: " +
3339 PropertyInfo.DeclaringType + "." +PropertyInfo.Name);
3343 if (PropertyInfo.PropertyType.IsPointer && !ec.InUnsafe){
3351 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
3353 if (setter == null){
3355 // The following condition happens if the PropertyExpr was
3356 // created, but is invalid (ie, the property is inaccessible),
3357 // and we did not want to embed the knowledge about this in
3358 // the caller routine. This only avoids double error reporting.
3363 // TODO: Print better property name
3364 Report.Error (200, loc, "Property or indexer '{0}' cannot be assigned to -- it is read only",
3369 if (TypeManager.GetArgumentTypes (setter).Length != 1){
3371 117, loc, "`{0}' does not contain a " +
3372 "definition for `{1}'.", getter.DeclaringType,
3377 bool must_do_cs1540_check;
3378 if (!IsAccessorAccessible (ec.ContainerType, setter, out must_do_cs1540_check)) {
3379 PropertyBase.PropertyMethod pm = TypeManager.GetMethod (setter) as PropertyBase.PropertyMethod;
3380 if (pm != null && pm.HasCustomAccessModifier) {
3381 Report.SymbolRelatedToPreviousError (pm);
3382 Report.Error (272, loc, "The property or indexer '{0}' cannot be used in this context because the set accessor is inaccessible",
3383 TypeManager.CSharpSignature (setter));
3386 Report.Error (122, loc, "'{0}' is inaccessible due to its protection level",
3387 TypeManager.CSharpSignature (setter));
3391 if (!InstanceResolve (ec, must_do_cs1540_check))
3395 // Only base will allow this invocation to happen.
3397 if (IsBase && setter.IsAbstract){
3398 Report.Error (205, loc, "Cannot call an abstract base property: " +
3399 PropertyInfo.DeclaringType + "." +PropertyInfo.Name);
3404 // Check that we are not making changes to a temporary memory location
3406 if (InstanceExpression != null && InstanceExpression.Type.IsValueType && !(InstanceExpression is IMemoryLocation)) {
3407 // FIXME: Provide better error reporting.
3408 Error (1612, "Cannot modify expression because it is not a variable.");
3417 public override void Emit (EmitContext ec)
3422 void EmitInstance (EmitContext ec)
3427 if (InstanceExpression.Type.IsValueType) {
3428 if (InstanceExpression is IMemoryLocation) {
3429 ((IMemoryLocation) InstanceExpression).AddressOf (ec, AddressOp.LoadStore);
3431 LocalTemporary t = new LocalTemporary (ec, InstanceExpression.Type);
3432 InstanceExpression.Emit (ec);
3434 t.AddressOf (ec, AddressOp.Store);
3437 InstanceExpression.Emit (ec);
3440 ec.ig.Emit (OpCodes.Dup);
3444 public void Emit (EmitContext ec, bool leave_copy)
3450 // Special case: length of single dimension array property is turned into ldlen
3452 if ((getter == TypeManager.system_int_array_get_length) ||
3453 (getter == TypeManager.int_array_get_length)){
3454 Type iet = InstanceExpression.Type;
3457 // System.Array.Length can be called, but the Type does not
3458 // support invoking GetArrayRank, so test for that case first
3460 if (iet != TypeManager.array_type && (iet.GetArrayRank () == 1)) {
3461 ec.ig.Emit (OpCodes.Ldlen);
3462 ec.ig.Emit (OpCodes.Conv_I4);
3467 Invocation.EmitCall (ec, IsBase, IsStatic, new EmptyAddressOf (), getter, null, loc);
3472 ec.ig.Emit (OpCodes.Dup);
3474 temp = new LocalTemporary (ec, this.Type);
3480 // Implements the IAssignMethod interface for assignments
3482 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
3484 prepared = prepare_for_load;
3490 ec.ig.Emit (OpCodes.Dup);
3492 temp = new LocalTemporary (ec, this.Type);
3497 ArrayList args = new ArrayList (1);
3498 args.Add (new Argument (new EmptyAddressOf (), Argument.AType.Expression));
3500 Invocation.EmitCall (ec, IsBase, IsStatic, new EmptyAddressOf (), setter, args, loc);
3508 /// Fully resolved expression that evaluates to an Event
3510 public class EventExpr : MemberExpr {
3511 public readonly EventInfo EventInfo;
3514 MethodInfo add_accessor, remove_accessor;
3516 public EventExpr (EventInfo ei, Location loc)
3520 eclass = ExprClass.EventAccess;
3522 add_accessor = TypeManager.GetAddMethod (ei);
3523 remove_accessor = TypeManager.GetRemoveMethod (ei);
3525 if (add_accessor.IsStatic || remove_accessor.IsStatic)
3528 if (EventInfo is MyEventBuilder){
3529 MyEventBuilder eb = (MyEventBuilder) EventInfo;
3530 type = eb.EventType;
3533 type = EventInfo.EventHandlerType;
3536 public override string Name {
3538 return EventInfo.Name;
3542 public override bool IsInstance {
3548 public override bool IsStatic {
3554 public override Type DeclaringType {
3556 return EventInfo.DeclaringType;
3560 public override Expression ResolveMemberAccess (EmitContext ec, Expression left, Location loc,
3561 SimpleName original)
3564 // If the event is local to this class, we transform ourselves into a FieldExpr
3567 if (EventInfo.DeclaringType == ec.ContainerType ||
3568 TypeManager.IsNestedChildOf(ec.ContainerType, EventInfo.DeclaringType)) {
3569 MemberInfo mi = TypeManager.GetPrivateFieldOfEvent (EventInfo);
3572 MemberExpr ml = (MemberExpr) ExprClassFromMemberInfo (ec, mi, loc);
3575 Report.Error (-200, loc, "Internal error!!");
3579 InstanceExpression = null;
3581 return ml.ResolveMemberAccess (ec, left, loc, original);
3585 return base.ResolveMemberAccess (ec, left, loc, original);
3589 bool InstanceResolve (EmitContext ec, bool must_do_cs1540_check)
3591 if ((InstanceExpression == null) && ec.IsStatic && !is_static) {
3592 SimpleName.Error_ObjectRefRequired (ec, loc, EventInfo.Name);
3596 if (InstanceExpression != null) {
3597 InstanceExpression = InstanceExpression.DoResolve (ec);
3598 if (InstanceExpression == null)
3603 // This is using the same mechanism as the CS1540 check in PropertyExpr.
3604 // However, in the Event case, we reported a CS0122 instead.
3606 if (must_do_cs1540_check && (InstanceExpression != null)) {
3607 if ((InstanceExpression.Type != ec.ContainerType) &&
3608 ec.ContainerType.IsSubclassOf (InstanceExpression.Type)) {
3609 Report.Error (122, loc, "'{0}' is inaccessible due to its protection level",
3610 DeclaringType.Name + "." + EventInfo.Name);
3619 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
3621 return DoResolve (ec);
3624 public override Expression DoResolve (EmitContext ec)
3626 if (InstanceExpression != null) {
3627 InstanceExpression = InstanceExpression.DoResolve (ec);
3628 if (InstanceExpression == null)
3632 bool must_do_cs1540_check;
3633 if (!(IsAccessorAccessible (ec.ContainerType, add_accessor, out must_do_cs1540_check) &&
3634 IsAccessorAccessible (ec.ContainerType, remove_accessor, out must_do_cs1540_check))) {
3636 Report.Error (122, loc, "'{0}' is inaccessible due to its protection level",
3637 DeclaringType.Name + "." + EventInfo.Name);
3641 if (!InstanceResolve (ec, must_do_cs1540_check))
3647 public override void Emit (EmitContext ec)
3649 if (InstanceExpression is This)
3650 Report.Error (79, loc, "The event `{0}' can only appear on the left hand side of += or -=, try calling the actual delegate", Name);
3652 Report.Error (70, loc, "The event `{0}' can only appear on the left hand side of += or -= "+
3653 "(except on the defining type)", Name);
3656 public void EmitAddOrRemove (EmitContext ec, Expression source)
3658 BinaryDelegate source_del = (BinaryDelegate) source;
3659 Expression handler = source_del.Right;
3661 Argument arg = new Argument (handler, Argument.AType.Expression);
3662 ArrayList args = new ArrayList ();
3666 if (source_del.IsAddition)
3667 Invocation.EmitCall (
3668 ec, false, IsStatic, InstanceExpression, add_accessor, args, loc);
3670 Invocation.EmitCall (
3671 ec, false, IsStatic, InstanceExpression, remove_accessor, args, loc);