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
68 // This is just as a hint to AddressOf of what will be done with the
71 public enum AddressOp {
78 /// This interface is implemented by variables
80 public interface IMemoryLocation {
82 /// The AddressOf method should generate code that loads
83 /// the address of the object and leaves it on the stack.
85 /// The `mode' argument is used to notify the expression
86 /// of whether this will be used to read from the address or
87 /// write to the address.
89 /// This is just a hint that can be used to provide good error
90 /// reporting, and should have no other side effects.
92 void AddressOf (EmitContext ec, AddressOp mode);
96 /// We are either a namespace or a type.
97 /// If we're a type, `IsType' is true and we may use `Type' to get
98 /// a TypeExpr representing that type.
100 public interface IAlias {
115 /// This interface is implemented by variables
117 public interface IVariable {
118 VariableInfo VariableInfo {
122 bool VerifyFixed (bool is_expression);
126 /// This interface denotes an expression which evaluates to a member
127 /// of a struct or a class.
129 public interface IMemberExpr
132 /// The name of this member.
139 /// Whether this is an instance member.
146 /// Whether this is a static member.
153 /// The type which declares this member.
160 /// The instance expression associated with this member, if it's a
161 /// non-static member.
163 Expression InstanceExpression {
169 /// Base class for expressions
171 public abstract class Expression {
172 public ExprClass eclass;
174 protected Location loc;
186 public Location Location {
193 /// Utility wrapper routine for Error, just to beautify the code
195 public void Error (int error, string s)
197 if (!Location.IsNull (loc))
198 Report.Error (error, loc, s);
200 Report.Error (error, s);
204 /// Utility wrapper routine for Warning, just to beautify the code
206 public void Warning (int warning, string s)
208 if (!Location.IsNull (loc))
209 Report.Warning (warning, loc, s);
211 Report.Warning (warning, s);
215 /// Utility wrapper routine for Warning, only prints the warning if
216 /// warnings of level `level' are enabled.
218 public void Warning (int warning, int level, string s)
220 if (level <= RootContext.WarningLevel)
221 Warning (warning, s);
225 /// Performs semantic analysis on the Expression
229 /// The Resolve method is invoked to perform the semantic analysis
232 /// The return value is an expression (it can be the
233 /// same expression in some cases) or a new
234 /// expression that better represents this node.
236 /// For example, optimizations of Unary (LiteralInt)
237 /// would return a new LiteralInt with a negated
240 /// If there is an error during semantic analysis,
241 /// then an error should be reported (using Report)
242 /// and a null value should be returned.
244 /// There are two side effects expected from calling
245 /// Resolve(): the the field variable "eclass" should
246 /// be set to any value of the enumeration
247 /// `ExprClass' and the type variable should be set
248 /// to a valid type (this is the type of the
251 public abstract Expression DoResolve (EmitContext ec);
253 public virtual Expression DoResolveLValue (EmitContext ec, Expression right_side)
255 return DoResolve (ec);
259 // This is used if the expression should be resolved as a type.
260 // the default implementation fails. Use this method in
261 // those participants in the SimpleName chain system.
263 public virtual Expression ResolveAsTypeStep (EmitContext ec)
269 // This is used to resolve the expression as a type, a null
270 // value will be returned if the expression is not a type
273 public TypeExpr ResolveAsTypeTerminal (EmitContext ec)
275 return ResolveAsTypeStep (ec) as TypeExpr;
279 /// Resolves an expression and performs semantic analysis on it.
283 /// Currently Resolve wraps DoResolve to perform sanity
284 /// checking and assertion checking on what we expect from Resolve.
286 public Expression Resolve (EmitContext ec, ResolveFlags flags)
288 if ((flags & ResolveFlags.MaskExprClass) == ResolveFlags.Type)
289 return ResolveAsTypeStep (ec);
291 bool old_do_flow_analysis = ec.DoFlowAnalysis;
292 if ((flags & ResolveFlags.DisableFlowAnalysis) != 0)
293 ec.DoFlowAnalysis = false;
296 if (this is SimpleName)
297 e = ((SimpleName) this).DoResolveAllowStatic (ec);
301 ec.DoFlowAnalysis = old_do_flow_analysis;
306 if (e is SimpleName){
307 SimpleName s = (SimpleName) e;
309 if ((flags & ResolveFlags.SimpleName) == 0) {
310 MemberLookupFailed (ec, null, ec.ContainerType, s.Name,
311 ec.DeclSpace.Name, loc);
318 if ((e is TypeExpr) || (e is ComposedCast)) {
319 if ((flags & ResolveFlags.Type) == 0) {
320 e.Error_UnexpectedKind (flags);
329 if ((flags & ResolveFlags.VariableOrValue) == 0) {
330 e.Error_UnexpectedKind (flags);
335 case ExprClass.MethodGroup:
336 if (!RootContext.V2){
337 if ((flags & ResolveFlags.MethodGroup) == 0) {
338 ((MethodGroupExpr) e).ReportUsageError ();
344 case ExprClass.Value:
345 case ExprClass.Variable:
346 case ExprClass.PropertyAccess:
347 case ExprClass.EventAccess:
348 case ExprClass.IndexerAccess:
349 if ((flags & ResolveFlags.VariableOrValue) == 0) {
350 Console.WriteLine ("I got: {0} and {1}", e.GetType (), e);
351 Console.WriteLine ("I am {0} and {1}", this.GetType (), this);
352 FieldInfo fi = ((FieldExpr) e).FieldInfo;
354 Console.WriteLine ("{0} and {1}", fi.DeclaringType, fi.Name);
355 e.Error_UnexpectedKind (flags);
361 throw new Exception ("Expression " + e.GetType () +
362 " ExprClass is Invalid after resolve");
366 throw new Exception (
367 "Expression " + e.GetType () +
368 " did not set its type after Resolve\n" +
369 "called from: " + this.GetType ());
375 /// Resolves an expression and performs semantic analysis on it.
377 public Expression Resolve (EmitContext ec)
379 return Resolve (ec, ResolveFlags.VariableOrValue);
383 /// Resolves an expression for LValue assignment
387 /// Currently ResolveLValue wraps DoResolveLValue to perform sanity
388 /// checking and assertion checking on what we expect from Resolve
390 public Expression ResolveLValue (EmitContext ec, Expression right_side)
392 Expression e = DoResolveLValue (ec, right_side);
395 if (e is SimpleName){
396 SimpleName s = (SimpleName) e;
397 MemberLookupFailed (ec, null, ec.ContainerType, s.Name,
398 ec.DeclSpace.Name, loc);
402 if (e.eclass == ExprClass.Invalid)
403 throw new Exception ("Expression " + e +
404 " ExprClass is Invalid after resolve");
406 if (e.eclass == ExprClass.MethodGroup) {
407 ((MethodGroupExpr) e).ReportUsageError ();
411 if ((e.type == null) && !(e is ConstructedType))
412 throw new Exception ("Expression " + e +
413 " did not set its type after Resolve");
420 /// Emits the code for the expression
424 /// The Emit method is invoked to generate the code
425 /// for the expression.
427 public abstract void Emit (EmitContext ec);
429 public virtual void EmitBranchable (EmitContext ec, Label target, bool onTrue)
432 ec.ig.Emit (onTrue ? OpCodes.Brtrue : OpCodes.Brfalse, target);
436 /// Protected constructor. Only derivate types should
437 /// be able to be created
440 protected Expression ()
442 eclass = ExprClass.Invalid;
447 /// Returns a literalized version of a literal FieldInfo
451 /// The possible return values are:
452 /// IntConstant, UIntConstant
453 /// LongLiteral, ULongConstant
454 /// FloatConstant, DoubleConstant
457 /// The value returned is already resolved.
459 public static Constant Constantify (object v, Type t)
461 if (t == TypeManager.int32_type)
462 return new IntConstant ((int) v);
463 else if (t == TypeManager.uint32_type)
464 return new UIntConstant ((uint) v);
465 else if (t == TypeManager.int64_type)
466 return new LongConstant ((long) v);
467 else if (t == TypeManager.uint64_type)
468 return new ULongConstant ((ulong) v);
469 else if (t == TypeManager.float_type)
470 return new FloatConstant ((float) v);
471 else if (t == TypeManager.double_type)
472 return new DoubleConstant ((double) v);
473 else if (t == TypeManager.string_type)
474 return new StringConstant ((string) v);
475 else if (t == TypeManager.short_type)
476 return new ShortConstant ((short)v);
477 else if (t == TypeManager.ushort_type)
478 return new UShortConstant ((ushort)v);
479 else if (t == TypeManager.sbyte_type)
480 return new SByteConstant (((sbyte)v));
481 else if (t == TypeManager.byte_type)
482 return new ByteConstant ((byte)v);
483 else if (t == TypeManager.char_type)
484 return new CharConstant ((char)v);
485 else if (t == TypeManager.bool_type)
486 return new BoolConstant ((bool) v);
487 else if (TypeManager.IsEnumType (t)){
488 Constant e = Constantify (v, TypeManager.TypeToCoreType (v.GetType ()));
490 return new EnumConstant (e, t);
492 throw new Exception ("Unknown type for constant (" + t +
497 /// Returns a fully formed expression after a MemberLookup
499 public static Expression ExprClassFromMemberInfo (EmitContext ec, MemberInfo mi, Location loc)
502 return new EventExpr ((EventInfo) mi, loc);
503 else if (mi is FieldInfo)
504 return new FieldExpr ((FieldInfo) mi, loc);
505 else if (mi is PropertyInfo)
506 return new PropertyExpr (ec, (PropertyInfo) mi, loc);
507 else if (mi is Type){
508 return new TypeExpression ((System.Type) mi, loc);
515 // FIXME: Probably implement a cache for (t,name,current_access_set)?
517 // This code could use some optimizations, but we need to do some
518 // measurements. For example, we could use a delegate to `flag' when
519 // something can not any longer be a method-group (because it is something
523 // If the return value is an Array, then it is an array of
526 // If the return value is an MemberInfo, it is anything, but a Method
530 // FIXME: When calling MemberLookup inside an `Invocation', we should pass
531 // the arguments here and have MemberLookup return only the methods that
532 // match the argument count/type, unlike we are doing now (we delay this
535 // This is so we can catch correctly attempts to invoke instance methods
536 // from a static body (scan for error 120 in ResolveSimpleName).
539 // FIXME: Potential optimization, have a static ArrayList
542 public static Expression MemberLookup (EmitContext ec, Type queried_type, string name,
543 MemberTypes mt, BindingFlags bf, Location loc)
545 return MemberLookup (ec, ec.ContainerType, null, queried_type, name, mt, bf, loc);
549 // Lookup type `queried_type' for code in class `container_type' with a qualifier of
550 // `qualifier_type' or null to lookup members in the current class.
553 public static Expression MemberLookup (EmitContext ec, Type container_type,
554 Type qualifier_type, Type queried_type,
555 string name, MemberTypes mt,
556 BindingFlags bf, Location loc)
558 MemberInfo [] mi = TypeManager.MemberLookup (
559 container_type, qualifier_type,queried_type, mt, bf, name);
564 int count = mi.Length;
566 if (mi [0] is MethodBase)
567 return new MethodGroupExpr (mi, loc);
572 return ExprClassFromMemberInfo (ec, mi [0], loc);
575 public const MemberTypes AllMemberTypes =
576 MemberTypes.Constructor |
580 MemberTypes.NestedType |
581 MemberTypes.Property;
583 public const BindingFlags AllBindingFlags =
584 BindingFlags.Public |
585 BindingFlags.Static |
586 BindingFlags.Instance;
588 public static Expression MemberLookup (EmitContext ec, Type queried_type,
589 string name, Location loc)
591 return MemberLookup (ec, ec.ContainerType, null, queried_type, name,
592 AllMemberTypes, AllBindingFlags, loc);
595 public static Expression MemberLookup (EmitContext ec, Type qualifier_type,
596 Type queried_type, string name, Location loc)
598 return MemberLookup (ec, ec.ContainerType, qualifier_type, queried_type,
599 name, AllMemberTypes, AllBindingFlags, loc);
602 public static Expression MethodLookup (EmitContext ec, Type queried_type,
603 string name, Location loc)
605 return MemberLookup (ec, ec.ContainerType, null, queried_type, name,
606 MemberTypes.Method, AllBindingFlags, loc);
610 /// This is a wrapper for MemberLookup that is not used to "probe", but
611 /// to find a final definition. If the final definition is not found, we
612 /// look for private members and display a useful debugging message if we
615 public static Expression MemberLookupFinal (EmitContext ec, Type qualifier_type,
616 Type queried_type, string name,
619 return MemberLookupFinal (ec, qualifier_type, queried_type, name,
620 AllMemberTypes, AllBindingFlags, loc);
623 public static Expression MemberLookupFinal (EmitContext ec, Type qualifier_type,
624 Type queried_type, string name,
625 MemberTypes mt, BindingFlags bf,
630 int errors = Report.Errors;
632 e = MemberLookup (ec, ec.ContainerType, qualifier_type, queried_type,
638 // Error has already been reported.
639 if (errors < Report.Errors)
642 MemberLookupFailed (ec, qualifier_type, queried_type, name,
647 public static void MemberLookupFailed (EmitContext ec, Type qualifier_type,
648 Type queried_type, string name,
649 string class_name, Location loc)
651 MemberInfo[] mi = TypeManager.MemberLookup (queried_type, null, queried_type,
652 AllMemberTypes, AllBindingFlags |
653 BindingFlags.NonPublic, name);
656 if (class_name != null)
657 Report.Error (103, loc, "The name `" + name + "' could not be " +
658 "found in `" + class_name + "'");
661 117, loc, "`" + queried_type + "' does not contain a " +
662 "definition for `" + name + "'");
666 if (TypeManager.MemberLookup (queried_type, null, queried_type,
667 AllMemberTypes, AllBindingFlags |
668 BindingFlags.NonPublic, name) == null) {
669 if ((mi.Length == 1) && (mi [0] is Type)) {
670 Type t = (Type) mi [0];
672 Report.Error (305, loc,
673 "Using the generic type `{0}' " +
674 "requires {1} type arguments",
675 TypeManager.GetFullName (t),
676 TypeManager.GetNumberOfTypeArguments (t));
681 if ((qualifier_type != null) && (qualifier_type != ec.ContainerType) &&
682 ec.ContainerType.IsSubclassOf (qualifier_type)) {
683 // Although a derived class can access protected members of
684 // its base class it cannot do so through an instance of the
685 // base class (CS1540). If the qualifier_type is a parent of the
686 // ec.ContainerType and the lookup succeeds with the latter one,
687 // then we are in this situation.
689 mi = TypeManager.MemberLookup (
690 ec.ContainerType, ec.ContainerType, ec.ContainerType,
691 AllMemberTypes, AllBindingFlags, name);
695 1540, loc, "Cannot access protected member `" +
696 TypeManager.CSharpName (qualifier_type) + "." +
697 name + "' " + "via a qualifier of type `" +
698 TypeManager.CSharpName (qualifier_type) + "'; the " +
699 "qualifier must be of type `" +
700 TypeManager.CSharpName (ec.ContainerType) + "' " +
701 "(or derived from it)");
706 if (qualifier_type != null)
708 122, loc, "`" + TypeManager.CSharpName (qualifier_type) + "." +
709 name + "' is inaccessible due to its protection level");
710 else if (name == ".ctor") {
711 Report.Error (143, loc, String.Format ("The type {0} has no constructors defined",
712 TypeManager.CSharpName (queried_type)));
715 122, loc, "`" + name + "' is inaccessible due to its " +
720 static public MemberInfo GetFieldFromEvent (EventExpr event_expr)
722 EventInfo ei = event_expr.EventInfo;
724 return TypeManager.GetPrivateFieldOfEvent (ei);
728 /// Returns an expression that can be used to invoke operator true
729 /// on the expression if it exists.
731 static public StaticCallExpr GetOperatorTrue (EmitContext ec, Expression e, Location loc)
733 return GetOperatorTrueOrFalse (ec, e, true, loc);
737 /// Returns an expression that can be used to invoke operator false
738 /// on the expression if it exists.
740 static public StaticCallExpr GetOperatorFalse (EmitContext ec, Expression e, Location loc)
742 return GetOperatorTrueOrFalse (ec, e, false, loc);
745 static StaticCallExpr GetOperatorTrueOrFalse (EmitContext ec, Expression e, bool is_true, Location loc)
748 Expression operator_group;
750 operator_group = MethodLookup (ec, e.Type, is_true ? "op_True" : "op_False", loc);
751 if (operator_group == null)
754 ArrayList arguments = new ArrayList ();
755 arguments.Add (new Argument (e, Argument.AType.Expression));
756 method = Invocation.OverloadResolve (
757 ec, (MethodGroupExpr) operator_group, arguments, false, loc);
762 return new StaticCallExpr ((MethodInfo) method, arguments, loc);
766 /// Resolves the expression `e' into a boolean expression: either through
767 /// an implicit conversion, or through an `operator true' invocation
769 public static Expression ResolveBoolean (EmitContext ec, Expression e, Location loc)
775 Expression converted = e;
776 if (e.Type != TypeManager.bool_type)
777 converted = Convert.ImplicitConversion (ec, e, TypeManager.bool_type, new Location (-1));
780 // If no implicit conversion to bool exists, try using `operator true'
782 if (converted == null){
783 Expression operator_true = Expression.GetOperatorTrue (ec, e, loc);
784 if (operator_true == null){
786 31, loc, "Can not convert the expression to a boolean");
796 static string ExprClassName (ExprClass c)
799 case ExprClass.Invalid:
801 case ExprClass.Value:
803 case ExprClass.Variable:
805 case ExprClass.Namespace:
809 case ExprClass.MethodGroup:
810 return "method group";
811 case ExprClass.PropertyAccess:
812 return "property access";
813 case ExprClass.EventAccess:
814 return "event access";
815 case ExprClass.IndexerAccess:
816 return "indexer access";
817 case ExprClass.Nothing:
820 throw new Exception ("Should not happen");
824 /// Reports that we were expecting `expr' to be of class `expected'
826 public void Error_UnexpectedKind (string expected)
828 string kind = "Unknown";
830 kind = ExprClassName (eclass);
832 Error (118, "Expression denotes a `" + kind +
833 "' where a `" + expected + "' was expected");
836 public void Error_UnexpectedKind (ResolveFlags flags)
838 ArrayList valid = new ArrayList (10);
840 if ((flags & ResolveFlags.VariableOrValue) != 0) {
841 valid.Add ("variable");
845 if ((flags & ResolveFlags.Type) != 0)
848 if ((flags & ResolveFlags.MethodGroup) != 0)
849 valid.Add ("method group");
851 if ((flags & ResolveFlags.SimpleName) != 0)
852 valid.Add ("simple name");
854 if (valid.Count == 0)
855 valid.Add ("unknown");
857 StringBuilder sb = new StringBuilder ();
858 for (int i = 0; i < valid.Count; i++) {
861 else if (i == valid.Count)
863 sb.Append (valid [i]);
866 string kind = ExprClassName (eclass);
868 Error (119, "Expression denotes a `" + kind + "' where " +
869 "a `" + sb.ToString () + "' was expected");
872 static public void Error_ConstantValueCannotBeConverted (Location l, string val, Type t)
874 Report.Error (31, l, "Constant value `" + val + "' cannot be converted to " +
875 TypeManager.CSharpName (t));
878 public static void UnsafeError (Location loc)
880 Report.Error (214, loc, "Pointers may only be used in an unsafe context");
884 /// Converts the IntConstant, UIntConstant, LongConstant or
885 /// ULongConstant into the integral target_type. Notice
886 /// that we do not return an `Expression' we do return
887 /// a boxed integral type.
889 /// FIXME: Since I added the new constants, we need to
890 /// also support conversions from CharConstant, ByteConstant,
891 /// SByteConstant, UShortConstant, ShortConstant
893 /// This is used by the switch statement, so the domain
894 /// of work is restricted to the literals above, and the
895 /// targets are int32, uint32, char, byte, sbyte, ushort,
896 /// short, uint64 and int64
898 public static object ConvertIntLiteral (Constant c, Type target_type, Location loc)
900 if (!Convert.ImplicitStandardConversionExists (c, target_type)){
901 Convert.Error_CannotImplicitConversion (loc, c.Type, target_type);
907 if (c.Type == target_type)
908 return ((Constant) c).GetValue ();
911 // Make into one of the literals we handle, we dont really care
912 // about this value as we will just return a few limited types
914 if (c is EnumConstant)
915 c = ((EnumConstant)c).WidenToCompilerConstant ();
917 if (c is IntConstant){
918 int v = ((IntConstant) c).Value;
920 if (target_type == TypeManager.uint32_type){
923 } else if (target_type == TypeManager.char_type){
924 if (v >= Char.MinValue && v <= Char.MaxValue)
926 } else if (target_type == TypeManager.byte_type){
927 if (v >= Byte.MinValue && v <= Byte.MaxValue)
929 } else if (target_type == TypeManager.sbyte_type){
930 if (v >= SByte.MinValue && v <= SByte.MaxValue)
932 } else if (target_type == TypeManager.short_type){
933 if (v >= Int16.MinValue && v <= UInt16.MaxValue)
935 } else if (target_type == TypeManager.ushort_type){
936 if (v >= UInt16.MinValue && v <= UInt16.MaxValue)
938 } else if (target_type == TypeManager.int64_type)
940 else if (target_type == TypeManager.uint64_type){
946 } else if (c is UIntConstant){
947 uint v = ((UIntConstant) c).Value;
949 if (target_type == TypeManager.int32_type){
950 if (v <= Int32.MaxValue)
952 } else if (target_type == TypeManager.char_type){
953 if (v >= Char.MinValue && v <= Char.MaxValue)
955 } else if (target_type == TypeManager.byte_type){
956 if (v <= Byte.MaxValue)
958 } else if (target_type == TypeManager.sbyte_type){
959 if (v <= SByte.MaxValue)
961 } else if (target_type == TypeManager.short_type){
962 if (v <= UInt16.MaxValue)
964 } else if (target_type == TypeManager.ushort_type){
965 if (v <= UInt16.MaxValue)
967 } else if (target_type == TypeManager.int64_type)
969 else if (target_type == TypeManager.uint64_type)
972 } else if (c is LongConstant){
973 long v = ((LongConstant) c).Value;
975 if (target_type == TypeManager.int32_type){
976 if (v >= UInt32.MinValue && v <= UInt32.MaxValue)
978 } else if (target_type == TypeManager.uint32_type){
979 if (v >= 0 && v <= UInt32.MaxValue)
981 } else if (target_type == TypeManager.char_type){
982 if (v >= Char.MinValue && v <= Char.MaxValue)
984 } else if (target_type == TypeManager.byte_type){
985 if (v >= Byte.MinValue && v <= Byte.MaxValue)
987 } else if (target_type == TypeManager.sbyte_type){
988 if (v >= SByte.MinValue && v <= SByte.MaxValue)
990 } else if (target_type == TypeManager.short_type){
991 if (v >= Int16.MinValue && v <= UInt16.MaxValue)
993 } else if (target_type == TypeManager.ushort_type){
994 if (v >= UInt16.MinValue && v <= UInt16.MaxValue)
996 } else if (target_type == TypeManager.uint64_type){
1001 } else if (c is ULongConstant){
1002 ulong v = ((ULongConstant) c).Value;
1004 if (target_type == TypeManager.int32_type){
1005 if (v <= Int32.MaxValue)
1007 } else if (target_type == TypeManager.uint32_type){
1008 if (v <= UInt32.MaxValue)
1010 } else if (target_type == TypeManager.char_type){
1011 if (v >= Char.MinValue && v <= Char.MaxValue)
1013 } else if (target_type == TypeManager.byte_type){
1014 if (v >= Byte.MinValue && v <= Byte.MaxValue)
1016 } else if (target_type == TypeManager.sbyte_type){
1017 if (v <= (int) SByte.MaxValue)
1019 } else if (target_type == TypeManager.short_type){
1020 if (v <= UInt16.MaxValue)
1022 } else if (target_type == TypeManager.ushort_type){
1023 if (v <= UInt16.MaxValue)
1025 } else if (target_type == TypeManager.int64_type){
1026 if (v <= Int64.MaxValue)
1030 } else if (c is ByteConstant){
1031 byte v = ((ByteConstant) c).Value;
1033 if (target_type == TypeManager.int32_type)
1035 else if (target_type == TypeManager.uint32_type)
1037 else if (target_type == TypeManager.char_type)
1039 else if (target_type == TypeManager.sbyte_type){
1040 if (v <= SByte.MaxValue)
1042 } else if (target_type == TypeManager.short_type)
1044 else if (target_type == TypeManager.ushort_type)
1046 else if (target_type == TypeManager.int64_type)
1048 else if (target_type == TypeManager.uint64_type)
1051 } else if (c is SByteConstant){
1052 sbyte v = ((SByteConstant) c).Value;
1054 if (target_type == TypeManager.int32_type)
1056 else if (target_type == TypeManager.uint32_type){
1059 } else if (target_type == TypeManager.char_type){
1062 } else if (target_type == TypeManager.byte_type){
1065 } else if (target_type == TypeManager.short_type)
1067 else if (target_type == TypeManager.ushort_type){
1070 } else if (target_type == TypeManager.int64_type)
1072 else if (target_type == TypeManager.uint64_type){
1077 } else if (c is ShortConstant){
1078 short v = ((ShortConstant) c).Value;
1080 if (target_type == TypeManager.int32_type){
1082 } else if (target_type == TypeManager.uint32_type){
1085 } else if (target_type == TypeManager.char_type){
1088 } else if (target_type == TypeManager.byte_type){
1089 if (v >= Byte.MinValue && v <= Byte.MaxValue)
1091 } else if (target_type == TypeManager.sbyte_type){
1092 if (v >= SByte.MinValue && v <= SByte.MaxValue)
1094 } else if (target_type == TypeManager.ushort_type){
1097 } else if (target_type == TypeManager.int64_type)
1099 else if (target_type == TypeManager.uint64_type)
1103 } else if (c is UShortConstant){
1104 ushort v = ((UShortConstant) c).Value;
1106 if (target_type == TypeManager.int32_type)
1108 else if (target_type == TypeManager.uint32_type)
1110 else if (target_type == TypeManager.char_type){
1111 if (v >= Char.MinValue && v <= Char.MaxValue)
1113 } else if (target_type == TypeManager.byte_type){
1114 if (v >= Byte.MinValue && v <= Byte.MaxValue)
1116 } else if (target_type == TypeManager.sbyte_type){
1117 if (v <= SByte.MaxValue)
1119 } else if (target_type == TypeManager.short_type){
1120 if (v <= Int16.MaxValue)
1122 } else if (target_type == TypeManager.int64_type)
1124 else if (target_type == TypeManager.uint64_type)
1128 } else if (c is CharConstant){
1129 char v = ((CharConstant) c).Value;
1131 if (target_type == TypeManager.int32_type)
1133 else if (target_type == TypeManager.uint32_type)
1135 else if (target_type == TypeManager.byte_type){
1136 if (v >= Byte.MinValue && v <= Byte.MaxValue)
1138 } else if (target_type == TypeManager.sbyte_type){
1139 if (v <= SByte.MaxValue)
1141 } else if (target_type == TypeManager.short_type){
1142 if (v <= Int16.MaxValue)
1144 } else if (target_type == TypeManager.ushort_type)
1146 else if (target_type == TypeManager.int64_type)
1148 else if (target_type == TypeManager.uint64_type)
1153 Error_ConstantValueCannotBeConverted (loc, s, target_type);
1158 // Load the object from the pointer.
1160 public static void LoadFromPtr (ILGenerator ig, Type t)
1162 if (t == TypeManager.int32_type)
1163 ig.Emit (OpCodes.Ldind_I4);
1164 else if (t == TypeManager.uint32_type)
1165 ig.Emit (OpCodes.Ldind_U4);
1166 else if (t == TypeManager.short_type)
1167 ig.Emit (OpCodes.Ldind_I2);
1168 else if (t == TypeManager.ushort_type)
1169 ig.Emit (OpCodes.Ldind_U2);
1170 else if (t == TypeManager.char_type)
1171 ig.Emit (OpCodes.Ldind_U2);
1172 else if (t == TypeManager.byte_type)
1173 ig.Emit (OpCodes.Ldind_U1);
1174 else if (t == TypeManager.sbyte_type)
1175 ig.Emit (OpCodes.Ldind_I1);
1176 else if (t == TypeManager.uint64_type)
1177 ig.Emit (OpCodes.Ldind_I8);
1178 else if (t == TypeManager.int64_type)
1179 ig.Emit (OpCodes.Ldind_I8);
1180 else if (t == TypeManager.float_type)
1181 ig.Emit (OpCodes.Ldind_R4);
1182 else if (t == TypeManager.double_type)
1183 ig.Emit (OpCodes.Ldind_R8);
1184 else if (t == TypeManager.bool_type)
1185 ig.Emit (OpCodes.Ldind_I1);
1186 else if (t == TypeManager.intptr_type)
1187 ig.Emit (OpCodes.Ldind_I);
1188 else if (TypeManager.IsEnumType (t)) {
1189 if (t == TypeManager.enum_type)
1190 ig.Emit (OpCodes.Ldind_Ref);
1192 LoadFromPtr (ig, TypeManager.EnumToUnderlying (t));
1193 } else if (t.IsValueType)
1194 ig.Emit (OpCodes.Ldobj, t);
1195 else if (t.IsPointer)
1196 ig.Emit (OpCodes.Ldind_I);
1198 ig.Emit (OpCodes.Ldind_Ref);
1202 // The stack contains the pointer and the value of type `type'
1204 public static void StoreFromPtr (ILGenerator ig, Type type)
1206 if (TypeManager.IsEnumType (type))
1207 type = TypeManager.EnumToUnderlying (type);
1208 if (type == TypeManager.int32_type || type == TypeManager.uint32_type)
1209 ig.Emit (OpCodes.Stind_I4);
1210 else if (type == TypeManager.int64_type || type == TypeManager.uint64_type)
1211 ig.Emit (OpCodes.Stind_I8);
1212 else if (type == TypeManager.char_type || type == TypeManager.short_type ||
1213 type == TypeManager.ushort_type)
1214 ig.Emit (OpCodes.Stind_I2);
1215 else if (type == TypeManager.float_type)
1216 ig.Emit (OpCodes.Stind_R4);
1217 else if (type == TypeManager.double_type)
1218 ig.Emit (OpCodes.Stind_R8);
1219 else if (type == TypeManager.byte_type || type == TypeManager.sbyte_type ||
1220 type == TypeManager.bool_type)
1221 ig.Emit (OpCodes.Stind_I1);
1222 else if (type == TypeManager.intptr_type)
1223 ig.Emit (OpCodes.Stind_I);
1224 else if (type.IsValueType)
1225 ig.Emit (OpCodes.Stobj, type);
1227 ig.Emit (OpCodes.Stind_Ref);
1231 // Returns the size of type `t' if known, otherwise, 0
1233 public static int GetTypeSize (Type t)
1235 t = TypeManager.TypeToCoreType (t);
1236 if (t == TypeManager.int32_type ||
1237 t == TypeManager.uint32_type ||
1238 t == TypeManager.float_type)
1240 else if (t == TypeManager.int64_type ||
1241 t == TypeManager.uint64_type ||
1242 t == TypeManager.double_type)
1244 else if (t == TypeManager.byte_type ||
1245 t == TypeManager.sbyte_type ||
1246 t == TypeManager.bool_type)
1248 else if (t == TypeManager.short_type ||
1249 t == TypeManager.char_type ||
1250 t == TypeManager.ushort_type)
1252 else if (t == TypeManager.decimal_type)
1259 // Default implementation of IAssignMethod.CacheTemporaries
1261 public void CacheTemporaries (EmitContext ec)
1265 static void Error_NegativeArrayIndex (Location loc)
1267 Report.Error (284, loc, "Can not create array with a negative size");
1271 // Converts `source' to an int, uint, long or ulong.
1273 public Expression ExpressionToArrayArgument (EmitContext ec, Expression source, Location loc)
1277 bool old_checked = ec.CheckState;
1278 ec.CheckState = true;
1280 target = Convert.ImplicitConversion (ec, source, TypeManager.int32_type, loc);
1281 if (target == null){
1282 target = Convert.ImplicitConversion (ec, source, TypeManager.uint32_type, loc);
1283 if (target == null){
1284 target = Convert.ImplicitConversion (ec, source, TypeManager.int64_type, loc);
1285 if (target == null){
1286 target = Convert.ImplicitConversion (ec, source, TypeManager.uint64_type, loc);
1288 Convert.Error_CannotImplicitConversion (loc, source.Type, TypeManager.int32_type);
1292 ec.CheckState = old_checked;
1295 // Only positive constants are allowed at compile time
1297 if (target is Constant){
1298 if (target is IntConstant){
1299 if (((IntConstant) target).Value < 0){
1300 Error_NegativeArrayIndex (loc);
1305 if (target is LongConstant){
1306 if (((LongConstant) target).Value < 0){
1307 Error_NegativeArrayIndex (loc);
1320 /// This is just a base class for expressions that can
1321 /// appear on statements (invocations, object creation,
1322 /// assignments, post/pre increment and decrement). The idea
1323 /// being that they would support an extra Emition interface that
1324 /// does not leave a result on the stack.
1326 public abstract class ExpressionStatement : Expression {
1328 public virtual ExpressionStatement ResolveStatement (EmitContext ec)
1330 Expression e = Resolve (ec);
1334 ExpressionStatement es = e as ExpressionStatement;
1336 Error (201, "Only assignment, call, increment, decrement and new object " +
1337 "expressions can be used as a statement");
1343 /// Requests the expression to be emitted in a `statement'
1344 /// context. This means that no new value is left on the
1345 /// stack after invoking this method (constrasted with
1346 /// Emit that will always leave a value on the stack).
1348 public abstract void EmitStatement (EmitContext ec);
1352 /// This kind of cast is used to encapsulate the child
1353 /// whose type is child.Type into an expression that is
1354 /// reported to return "return_type". This is used to encapsulate
1355 /// expressions which have compatible types, but need to be dealt
1356 /// at higher levels with.
1358 /// For example, a "byte" expression could be encapsulated in one
1359 /// of these as an "unsigned int". The type for the expression
1360 /// would be "unsigned int".
1363 public class EmptyCast : Expression {
1364 protected Expression child;
1366 public Expression Child {
1372 public EmptyCast (Expression child, Type return_type)
1374 eclass = child.eclass;
1379 public override Expression DoResolve (EmitContext ec)
1381 // This should never be invoked, we are born in fully
1382 // initialized state.
1387 public override void Emit (EmitContext ec)
1394 // We need to special case this since an empty cast of
1395 // a NullLiteral is still a Constant
1397 public class NullCast : Constant {
1398 protected Expression child;
1400 public NullCast (Expression child, Type return_type)
1402 eclass = child.eclass;
1407 override public string AsString ()
1412 public override object GetValue ()
1417 public override Expression DoResolve (EmitContext ec)
1419 // This should never be invoked, we are born in fully
1420 // initialized state.
1425 public override void Emit (EmitContext ec)
1433 /// This class is used to wrap literals which belong inside Enums
1435 public class EnumConstant : Constant {
1436 public Constant Child;
1438 public EnumConstant (Constant child, Type enum_type)
1440 eclass = child.eclass;
1445 public override Expression DoResolve (EmitContext ec)
1447 // This should never be invoked, we are born in fully
1448 // initialized state.
1453 public override void Emit (EmitContext ec)
1458 public override object GetValue ()
1460 return Child.GetValue ();
1464 // Converts from one of the valid underlying types for an enumeration
1465 // (int32, uint32, int64, uint64, short, ushort, byte, sbyte) to
1466 // one of the internal compiler literals: Int/UInt/Long/ULong Literals.
1468 public Constant WidenToCompilerConstant ()
1470 Type t = TypeManager.EnumToUnderlying (Child.Type);
1471 object v = ((Constant) Child).GetValue ();;
1473 if (t == TypeManager.int32_type)
1474 return new IntConstant ((int) v);
1475 if (t == TypeManager.uint32_type)
1476 return new UIntConstant ((uint) v);
1477 if (t == TypeManager.int64_type)
1478 return new LongConstant ((long) v);
1479 if (t == TypeManager.uint64_type)
1480 return new ULongConstant ((ulong) v);
1481 if (t == TypeManager.short_type)
1482 return new ShortConstant ((short) v);
1483 if (t == TypeManager.ushort_type)
1484 return new UShortConstant ((ushort) v);
1485 if (t == TypeManager.byte_type)
1486 return new ByteConstant ((byte) v);
1487 if (t == TypeManager.sbyte_type)
1488 return new SByteConstant ((sbyte) v);
1490 throw new Exception ("Invalid enumeration underlying type: " + t);
1494 // Extracts the value in the enumeration on its native representation
1496 public object GetPlainValue ()
1498 Type t = TypeManager.EnumToUnderlying (Child.Type);
1499 object v = ((Constant) Child).GetValue ();;
1501 if (t == TypeManager.int32_type)
1503 if (t == TypeManager.uint32_type)
1505 if (t == TypeManager.int64_type)
1507 if (t == TypeManager.uint64_type)
1509 if (t == TypeManager.short_type)
1511 if (t == TypeManager.ushort_type)
1513 if (t == TypeManager.byte_type)
1515 if (t == TypeManager.sbyte_type)
1521 public override string AsString ()
1523 return Child.AsString ();
1526 public override DoubleConstant ConvertToDouble ()
1528 return Child.ConvertToDouble ();
1531 public override FloatConstant ConvertToFloat ()
1533 return Child.ConvertToFloat ();
1536 public override ULongConstant ConvertToULong ()
1538 return Child.ConvertToULong ();
1541 public override LongConstant ConvertToLong ()
1543 return Child.ConvertToLong ();
1546 public override UIntConstant ConvertToUInt ()
1548 return Child.ConvertToUInt ();
1551 public override IntConstant ConvertToInt ()
1553 return Child.ConvertToInt ();
1556 public override bool IsZeroInteger {
1557 get { return Child.IsZeroInteger; }
1562 /// This kind of cast is used to encapsulate Value Types in objects.
1564 /// The effect of it is to box the value type emitted by the previous
1567 public class BoxedCast : EmptyCast {
1569 public BoxedCast (Expression expr)
1570 : base (expr, TypeManager.object_type)
1572 eclass = ExprClass.Value;
1575 public BoxedCast (Expression expr, Type target_type)
1576 : base (expr, target_type)
1578 eclass = ExprClass.Value;
1581 public override Expression DoResolve (EmitContext ec)
1583 // This should never be invoked, we are born in fully
1584 // initialized state.
1589 public override void Emit (EmitContext ec)
1593 ec.ig.Emit (OpCodes.Box, child.Type);
1597 public class UnboxCast : EmptyCast {
1598 public UnboxCast (Expression expr, Type return_type)
1599 : base (expr, return_type)
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)
1614 ILGenerator ig = ec.ig;
1617 if (t.IsGenericParameter)
1618 ig.Emit (OpCodes.Unbox_Any, t);
1620 ig.Emit (OpCodes.Unbox, t);
1622 LoadFromPtr (ig, t);
1628 /// This is used to perform explicit numeric conversions.
1630 /// Explicit numeric conversions might trigger exceptions in a checked
1631 /// context, so they should generate the conv.ovf opcodes instead of
1634 public class ConvCast : EmptyCast {
1635 public enum Mode : byte {
1636 I1_U1, I1_U2, I1_U4, I1_U8, I1_CH,
1638 I2_I1, I2_U1, I2_U2, I2_U4, I2_U8, I2_CH,
1639 U2_I1, U2_U1, U2_I2, U2_CH,
1640 I4_I1, I4_U1, I4_I2, I4_U2, I4_U4, I4_U8, I4_CH,
1641 U4_I1, U4_U1, U4_I2, U4_U2, U4_I4, U4_CH,
1642 I8_I1, I8_U1, I8_I2, I8_U2, I8_I4, I8_U4, I8_U8, I8_CH,
1643 U8_I1, U8_U1, U8_I2, U8_U2, U8_I4, U8_U4, U8_I8, U8_CH,
1644 CH_I1, CH_U1, CH_I2,
1645 R4_I1, R4_U1, R4_I2, R4_U2, R4_I4, R4_U4, R4_I8, R4_U8, R4_CH,
1646 R8_I1, R8_U1, R8_I2, R8_U2, R8_I4, R8_U4, R8_I8, R8_U8, R8_CH, R8_R4
1652 public ConvCast (EmitContext ec, Expression child, Type return_type, Mode m)
1653 : base (child, return_type)
1655 checked_state = ec.CheckState;
1659 public override Expression DoResolve (EmitContext ec)
1661 // This should never be invoked, we are born in fully
1662 // initialized state.
1667 public override string ToString ()
1669 return String.Format ("ConvCast ({0}, {1})", mode, child);
1672 public override void Emit (EmitContext ec)
1674 ILGenerator ig = ec.ig;
1680 case Mode.I1_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1681 case Mode.I1_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1682 case Mode.I1_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1683 case Mode.I1_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1684 case Mode.I1_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1686 case Mode.U1_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1687 case Mode.U1_CH: /* nothing */ break;
1689 case Mode.I2_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1690 case Mode.I2_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1691 case Mode.I2_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1692 case Mode.I2_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1693 case Mode.I2_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1694 case Mode.I2_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1696 case Mode.U2_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1697 case Mode.U2_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
1698 case Mode.U2_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
1699 case Mode.U2_CH: /* nothing */ break;
1701 case Mode.I4_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1702 case Mode.I4_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1703 case Mode.I4_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
1704 case Mode.I4_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1705 case Mode.I4_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1706 case Mode.I4_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1707 case Mode.I4_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1709 case Mode.U4_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1710 case Mode.U4_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
1711 case Mode.U4_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
1712 case Mode.U4_U2: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
1713 case Mode.U4_I4: ig.Emit (OpCodes.Conv_Ovf_I4_Un); break;
1714 case Mode.U4_CH: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
1716 case Mode.I8_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1717 case Mode.I8_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1718 case Mode.I8_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
1719 case Mode.I8_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1720 case Mode.I8_I4: ig.Emit (OpCodes.Conv_Ovf_I4); break;
1721 case Mode.I8_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1722 case Mode.I8_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1723 case Mode.I8_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1725 case Mode.U8_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1726 case Mode.U8_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
1727 case Mode.U8_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
1728 case Mode.U8_U2: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
1729 case Mode.U8_I4: ig.Emit (OpCodes.Conv_Ovf_I4_Un); break;
1730 case Mode.U8_U4: ig.Emit (OpCodes.Conv_Ovf_U4_Un); break;
1731 case Mode.U8_I8: ig.Emit (OpCodes.Conv_Ovf_I8_Un); break;
1732 case Mode.U8_CH: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
1734 case Mode.CH_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1735 case Mode.CH_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
1736 case Mode.CH_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
1738 case Mode.R4_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1739 case Mode.R4_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1740 case Mode.R4_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
1741 case Mode.R4_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1742 case Mode.R4_I4: ig.Emit (OpCodes.Conv_Ovf_I4); break;
1743 case Mode.R4_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1744 case Mode.R4_I8: ig.Emit (OpCodes.Conv_Ovf_I8); break;
1745 case Mode.R4_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1746 case Mode.R4_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1748 case Mode.R8_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1749 case Mode.R8_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1750 case Mode.R8_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
1751 case Mode.R8_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1752 case Mode.R8_I4: ig.Emit (OpCodes.Conv_Ovf_I4); break;
1753 case Mode.R8_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1754 case Mode.R8_I8: ig.Emit (OpCodes.Conv_Ovf_I8); break;
1755 case Mode.R8_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1756 case Mode.R8_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1757 case Mode.R8_R4: ig.Emit (OpCodes.Conv_R4); break;
1761 case Mode.I1_U1: ig.Emit (OpCodes.Conv_U1); break;
1762 case Mode.I1_U2: ig.Emit (OpCodes.Conv_U2); break;
1763 case Mode.I1_U4: ig.Emit (OpCodes.Conv_U4); break;
1764 case Mode.I1_U8: ig.Emit (OpCodes.Conv_I8); break;
1765 case Mode.I1_CH: ig.Emit (OpCodes.Conv_U2); break;
1767 case Mode.U1_I1: ig.Emit (OpCodes.Conv_I1); break;
1768 case Mode.U1_CH: ig.Emit (OpCodes.Conv_U2); break;
1770 case Mode.I2_I1: ig.Emit (OpCodes.Conv_I1); break;
1771 case Mode.I2_U1: ig.Emit (OpCodes.Conv_U1); break;
1772 case Mode.I2_U2: ig.Emit (OpCodes.Conv_U2); break;
1773 case Mode.I2_U4: ig.Emit (OpCodes.Conv_U4); break;
1774 case Mode.I2_U8: ig.Emit (OpCodes.Conv_I8); break;
1775 case Mode.I2_CH: ig.Emit (OpCodes.Conv_U2); break;
1777 case Mode.U2_I1: ig.Emit (OpCodes.Conv_I1); break;
1778 case Mode.U2_U1: ig.Emit (OpCodes.Conv_U1); break;
1779 case Mode.U2_I2: ig.Emit (OpCodes.Conv_I2); break;
1780 case Mode.U2_CH: /* nothing */ break;
1782 case Mode.I4_I1: ig.Emit (OpCodes.Conv_I1); break;
1783 case Mode.I4_U1: ig.Emit (OpCodes.Conv_U1); break;
1784 case Mode.I4_I2: ig.Emit (OpCodes.Conv_I2); break;
1785 case Mode.I4_U4: /* nothing */ break;
1786 case Mode.I4_U2: ig.Emit (OpCodes.Conv_U2); break;
1787 case Mode.I4_U8: ig.Emit (OpCodes.Conv_I8); break;
1788 case Mode.I4_CH: ig.Emit (OpCodes.Conv_U2); break;
1790 case Mode.U4_I1: ig.Emit (OpCodes.Conv_I1); break;
1791 case Mode.U4_U1: ig.Emit (OpCodes.Conv_U1); break;
1792 case Mode.U4_I2: ig.Emit (OpCodes.Conv_I2); break;
1793 case Mode.U4_U2: ig.Emit (OpCodes.Conv_U2); break;
1794 case Mode.U4_I4: /* nothing */ break;
1795 case Mode.U4_CH: ig.Emit (OpCodes.Conv_U2); break;
1797 case Mode.I8_I1: ig.Emit (OpCodes.Conv_I1); break;
1798 case Mode.I8_U1: ig.Emit (OpCodes.Conv_U1); break;
1799 case Mode.I8_I2: ig.Emit (OpCodes.Conv_I2); break;
1800 case Mode.I8_U2: ig.Emit (OpCodes.Conv_U2); break;
1801 case Mode.I8_I4: ig.Emit (OpCodes.Conv_I4); break;
1802 case Mode.I8_U4: ig.Emit (OpCodes.Conv_U4); break;
1803 case Mode.I8_U8: /* nothing */ break;
1804 case Mode.I8_CH: ig.Emit (OpCodes.Conv_U2); break;
1806 case Mode.U8_I1: ig.Emit (OpCodes.Conv_I1); break;
1807 case Mode.U8_U1: ig.Emit (OpCodes.Conv_U1); break;
1808 case Mode.U8_I2: ig.Emit (OpCodes.Conv_I2); break;
1809 case Mode.U8_U2: ig.Emit (OpCodes.Conv_U2); break;
1810 case Mode.U8_I4: ig.Emit (OpCodes.Conv_I4); break;
1811 case Mode.U8_U4: ig.Emit (OpCodes.Conv_U4); break;
1812 case Mode.U8_I8: /* nothing */ break;
1813 case Mode.U8_CH: ig.Emit (OpCodes.Conv_U2); break;
1815 case Mode.CH_I1: ig.Emit (OpCodes.Conv_I1); break;
1816 case Mode.CH_U1: ig.Emit (OpCodes.Conv_U1); break;
1817 case Mode.CH_I2: ig.Emit (OpCodes.Conv_I2); break;
1819 case Mode.R4_I1: ig.Emit (OpCodes.Conv_I1); break;
1820 case Mode.R4_U1: ig.Emit (OpCodes.Conv_U1); break;
1821 case Mode.R4_I2: ig.Emit (OpCodes.Conv_I2); break;
1822 case Mode.R4_U2: ig.Emit (OpCodes.Conv_U2); break;
1823 case Mode.R4_I4: ig.Emit (OpCodes.Conv_I4); break;
1824 case Mode.R4_U4: ig.Emit (OpCodes.Conv_U4); break;
1825 case Mode.R4_I8: ig.Emit (OpCodes.Conv_I8); break;
1826 case Mode.R4_U8: ig.Emit (OpCodes.Conv_U8); break;
1827 case Mode.R4_CH: ig.Emit (OpCodes.Conv_U2); break;
1829 case Mode.R8_I1: ig.Emit (OpCodes.Conv_I1); break;
1830 case Mode.R8_U1: ig.Emit (OpCodes.Conv_U1); break;
1831 case Mode.R8_I2: ig.Emit (OpCodes.Conv_I2); break;
1832 case Mode.R8_U2: ig.Emit (OpCodes.Conv_U2); break;
1833 case Mode.R8_I4: ig.Emit (OpCodes.Conv_I4); break;
1834 case Mode.R8_U4: ig.Emit (OpCodes.Conv_U4); break;
1835 case Mode.R8_I8: ig.Emit (OpCodes.Conv_I8); break;
1836 case Mode.R8_U8: ig.Emit (OpCodes.Conv_U8); break;
1837 case Mode.R8_CH: ig.Emit (OpCodes.Conv_U2); break;
1838 case Mode.R8_R4: ig.Emit (OpCodes.Conv_R4); break;
1844 public class OpcodeCast : EmptyCast {
1848 public OpcodeCast (Expression child, Type return_type, OpCode op)
1849 : base (child, return_type)
1853 second_valid = false;
1856 public OpcodeCast (Expression child, Type return_type, OpCode op, OpCode op2)
1857 : base (child, return_type)
1862 second_valid = true;
1865 public override Expression DoResolve (EmitContext ec)
1867 // This should never be invoked, we are born in fully
1868 // initialized state.
1873 public override void Emit (EmitContext ec)
1884 /// This kind of cast is used to encapsulate a child and cast it
1885 /// to the class requested
1887 public class ClassCast : EmptyCast {
1888 public ClassCast (Expression child, Type return_type)
1889 : base (child, return_type)
1894 public override Expression DoResolve (EmitContext ec)
1896 // This should never be invoked, we are born in fully
1897 // initialized state.
1902 public override void Emit (EmitContext ec)
1906 if (child.Type.IsGenericParameter)
1907 ec.ig.Emit (OpCodes.Box, child.Type);
1909 if (type.IsGenericParameter)
1910 ec.ig.Emit (OpCodes.Unbox_Any, type);
1912 ec.ig.Emit (OpCodes.Castclass, type);
1917 /// SimpleName expressions are initially formed of a single
1918 /// word and it only happens at the beginning of the expression.
1922 /// The expression will try to be bound to a Field, a Method
1923 /// group or a Property. If those fail we pass the name to our
1924 /// caller and the SimpleName is compounded to perform a type
1925 /// lookup. The idea behind this process is that we want to avoid
1926 /// creating a namespace map from the assemblies, as that requires
1927 /// the GetExportedTypes function to be called and a hashtable to
1928 /// be constructed which reduces startup time. If later we find
1929 /// that this is slower, we should create a `NamespaceExpr' expression
1930 /// that fully participates in the resolution process.
1932 /// For example `System.Console.WriteLine' is decomposed into
1933 /// MemberAccess (MemberAccess (SimpleName ("System"), "Console"), "WriteLine")
1935 /// The first SimpleName wont produce a match on its own, so it will
1937 /// MemberAccess (SimpleName ("System.Console"), "WriteLine").
1939 /// System.Console will produce a TypeExpr match.
1941 /// The downside of this is that we might be hitting `LookupType' too many
1942 /// times with this scheme.
1944 public class SimpleName : Expression {
1948 // If true, then we are a simple name, not composed with a ".
1952 public SimpleName (string a, string b, Location l)
1954 Name = String.Concat (a, ".", b);
1959 public SimpleName (string name, Location l)
1966 public static void Error_ObjectRefRequired (EmitContext ec, Location l, string name)
1968 if (ec.IsFieldInitializer)
1971 "A field initializer cannot reference the non-static field, " +
1972 "method or property `"+name+"'");
1976 "An object reference is required " +
1977 "for the non-static field `"+name+"'");
1981 // Checks whether we are trying to access an instance
1982 // property, method or field from a static body.
1984 Expression MemberStaticCheck (EmitContext ec, Expression e)
1986 if (e is IMemberExpr){
1987 IMemberExpr member = (IMemberExpr) e;
1989 if (!member.IsStatic){
1990 Error_ObjectRefRequired (ec, loc, Name);
1998 public override Expression DoResolve (EmitContext ec)
2000 return SimpleNameResolve (ec, null, false);
2003 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
2005 return SimpleNameResolve (ec, right_side, false);
2009 public Expression DoResolveAllowStatic (EmitContext ec)
2011 return SimpleNameResolve (ec, null, true);
2014 public override Expression ResolveAsTypeStep (EmitContext ec)
2016 DeclSpace ds = ec.DeclSpace;
2017 NamespaceEntry ns = ds.NamespaceEntry;
2022 // Since we are cheating: we only do the Alias lookup for
2023 // namespaces if the name does not include any dots in it
2025 if (ns != null && is_base)
2026 alias_value = ns.LookupAlias (Name);
2030 TypeParameterExpr generic_type = ds.LookupGeneric (Name, loc);
2031 if (generic_type != null)
2032 return generic_type.ResolveAsTypeTerminal (ec);
2034 if (ec.ResolvingTypeTree){
2035 int errors = Report.Errors;
2036 Type dt = ds.FindType (loc, Name);
2038 if (Report.Errors != errors)
2042 return new TypeExpression (dt, loc);
2044 if (alias_value != null){
2045 if (alias_value.IsType)
2046 return alias_value.Type;
2047 if ((t = RootContext.LookupType (ds, alias_value.Name, true, loc)) != null)
2053 // First, the using aliases
2055 if (alias_value != null){
2056 if (alias_value.IsType)
2057 return alias_value.Type;
2058 if ((t = RootContext.LookupType (ds, alias_value.Name, true, loc)) != null)
2061 // we have alias value, but it isn't Type, so try if it's namespace
2062 return new SimpleName (alias_value.Name, loc);
2066 // Stage 2: Lookup up if we are an alias to a type
2070 if ((t = RootContext.LookupType (ds, Name, true, loc)) != null)
2073 // No match, maybe our parent can compose us
2074 // into something meaningful.
2079 /// 7.5.2: Simple Names.
2081 /// Local Variables and Parameters are handled at
2082 /// parse time, so they never occur as SimpleNames.
2084 /// The `allow_static' flag is used by MemberAccess only
2085 /// and it is used to inform us that it is ok for us to
2086 /// avoid the static check, because MemberAccess might end
2087 /// up resolving the Name as a Type name and the access as
2088 /// a static type access.
2090 /// ie: Type Type; .... { Type.GetType (""); }
2092 /// Type is both an instance variable and a Type; Type.GetType
2093 /// is the static method not an instance method of type.
2095 Expression SimpleNameResolve (EmitContext ec, Expression right_side, bool allow_static)
2097 Expression e = null;
2100 // Stage 1: Performed by the parser (binding to locals or parameters).
2102 Block current_block = ec.CurrentBlock;
2103 if (current_block != null){
2104 LocalInfo vi = current_block.GetLocalInfo (Name);
2108 var = new LocalVariableReference (ec.CurrentBlock, Name, loc);
2110 if (right_side != null)
2111 return var.ResolveLValue (ec, right_side);
2113 return var.Resolve (ec);
2117 Parameter par = null;
2118 Parameters pars = current_block.Parameters;
2120 par = pars.GetParameterByName (Name, out idx);
2123 ParameterReference param;
2125 param = new ParameterReference (pars, current_block, idx, Name, loc);
2127 if (right_side != null)
2128 return param.ResolveLValue (ec, right_side);
2130 return param.Resolve (ec);
2135 // Stage 2: Lookup members
2138 DeclSpace lookup_ds = ec.DeclSpace;
2140 if (lookup_ds.TypeBuilder == null)
2143 e = MemberLookup (ec, lookup_ds.TypeBuilder, Name, loc);
2147 lookup_ds =lookup_ds.Parent;
2148 } while (lookup_ds != null);
2150 if (e == null && ec.ContainerType != null)
2151 e = MemberLookup (ec, ec.ContainerType, Name, loc);
2155 // Since we are cheating (is_base is our hint
2156 // that we are the beginning of the name): we
2157 // only do the Alias lookup for namespaces if
2158 // the name does not include any dots in it
2160 NamespaceEntry ns = ec.DeclSpace.NamespaceEntry;
2161 if (is_base && ns != null){
2162 IAlias alias_value = ns.LookupAlias (Name);
2163 if (alias_value != null){
2164 if (alias_value.IsType)
2165 return alias_value.Type;
2167 Name = alias_value.Name;
2170 if ((t = TypeManager.LookupType (Name)) != null)
2171 return new TypeExpression (t, loc);
2173 // No match, maybe our parent can compose us
2174 // into something meaningful.
2179 return ResolveAsTypeStep (ec);
2185 if (e is IMemberExpr) {
2186 e = MemberAccess.ResolveMemberAccess (ec, e, null, loc, this);
2190 IMemberExpr me = e as IMemberExpr;
2194 // This fails if ResolveMemberAccess() was unable to decide whether
2195 // it's a field or a type of the same name.
2196 if (!me.IsStatic && (me.InstanceExpression == null))
2200 TypeManager.IsNestedChildOf (me.InstanceExpression.Type, me.DeclaringType) &&
2201 !me.InstanceExpression.Type.IsSubclassOf (me.DeclaringType)) {
2202 Error (38, "Cannot access nonstatic member `" + me.Name + "' of " +
2203 "outer type `" + me.DeclaringType + "' via nested type `" +
2204 me.InstanceExpression.Type + "'");
2208 if (right_side != null)
2209 e = e.DoResolveLValue (ec, right_side);
2211 e = e.DoResolve (ec);
2216 if (ec.IsStatic || ec.IsFieldInitializer){
2220 return MemberStaticCheck (ec, e);
2225 public override void Emit (EmitContext ec)
2228 // If this is ever reached, then we failed to
2229 // find the name as a namespace
2232 Error (103, "The name `" + Name +
2233 "' does not exist in the class `" +
2234 ec.DeclSpace.Name + "'");
2237 public override string ToString ()
2244 /// Fully resolved expression that evaluates to a type
2246 public abstract class TypeExpr : Expression, IAlias {
2247 override public Expression ResolveAsTypeStep (EmitContext ec)
2249 TypeExpr t = DoResolveAsTypeStep (ec);
2253 eclass = ExprClass.Type;
2257 override public Expression DoResolve (EmitContext ec)
2259 return ResolveAsTypeTerminal (ec);
2262 override public void Emit (EmitContext ec)
2264 throw new Exception ("Should never be called");
2267 public virtual bool CheckAccessLevel (DeclSpace ds)
2269 return ds.CheckAccessLevel (Type);
2272 public virtual bool AsAccessible (DeclSpace ds, int flags)
2274 return ds.AsAccessible (Type, flags);
2277 public virtual bool IsClass {
2278 get { return Type.IsClass; }
2281 public virtual bool IsValueType {
2282 get { return Type.IsValueType; }
2285 public virtual bool IsInterface {
2286 get { return Type.IsInterface; }
2289 public virtual bool IsSealed {
2290 get { return Type.IsSealed; }
2293 public virtual bool CanInheritFrom ()
2295 if (Type == TypeManager.enum_type ||
2296 (Type == TypeManager.value_type && RootContext.StdLib) ||
2297 Type == TypeManager.multicast_delegate_type ||
2298 Type == TypeManager.delegate_type ||
2299 Type == TypeManager.array_type)
2305 public virtual bool IsAttribute {
2307 return Type == TypeManager.attribute_type ||
2308 Type.IsSubclassOf (TypeManager.attribute_type);
2312 public virtual TypeExpr[] GetInterfaces ()
2314 return TypeManager.GetInterfaces (Type);
2317 public abstract TypeExpr DoResolveAsTypeStep (EmitContext ec);
2319 public virtual Type ResolveType (EmitContext ec)
2321 TypeExpr t = ResolveAsTypeTerminal (ec);
2328 public abstract string Name {
2332 public override bool Equals (object obj)
2334 TypeExpr tobj = obj as TypeExpr;
2338 return Type == tobj.Type;
2341 public override int GetHashCode ()
2343 return Type.GetHashCode ();
2346 public override string ToString ()
2351 bool IAlias.IsType {
2352 get { return true; }
2355 TypeExpr IAlias.Type {
2362 public class TypeExpression : TypeExpr, IAlias {
2363 public TypeExpression (Type t, Location l)
2366 eclass = ExprClass.Type;
2370 public override TypeExpr DoResolveAsTypeStep (EmitContext ec)
2375 public override string Name {
2377 return Type.ToString ();
2381 string IAlias.Name {
2383 return Type.FullName != null ? Type.FullName : Type.Name;
2389 /// Used to create types from a fully qualified name. These are just used
2390 /// by the parser to setup the core types. A TypeLookupExpression is always
2391 /// classified as a type.
2393 public class TypeLookupExpression : TypeExpr {
2396 public TypeLookupExpression (string name)
2401 public override TypeExpr DoResolveAsTypeStep (EmitContext ec)
2404 TypeExpr texpr = RootContext.LookupType (
2405 ec.DeclSpace, name, false, Location.Null);
2409 type = texpr.ResolveType (ec);
2417 public override string Name {
2424 public class TypeAliasExpression : TypeExpr, IAlias {
2429 public TypeAliasExpression (TypeExpr texpr, TypeArguments args, Location l)
2433 loc = texpr.Location;
2435 eclass = ExprClass.Type;
2437 name = texpr.Name + "<" + args.ToString () + ">";
2442 public override string Name {
2443 get { return name; }
2446 public override TypeExpr DoResolveAsTypeStep (EmitContext ec)
2448 Type type = texpr.ResolveType (ec);
2452 int num_args = TypeManager.GetNumberOfTypeArguments (type);
2455 if (num_args == 0) {
2456 Report.Error (308, loc,
2457 "The non-generic type `{0}' cannot " +
2458 "be used with type arguments.",
2459 TypeManager.CSharpName (type));
2463 ConstructedType ctype = new ConstructedType (type, args, loc);
2464 return ctype.ResolveAsTypeTerminal (ec);
2465 } else if (num_args > 0) {
2466 Report.Error (305, loc,
2467 "Using the generic type `{0}' " +
2468 "requires {1} type arguments",
2469 TypeManager.GetFullName (type), num_args);
2473 return new TypeExpression (type, loc);
2476 public override Type ResolveType (EmitContext ec)
2478 TypeExpr t = ResolveAsTypeTerminal (ec);
2482 type = t.ResolveType (ec);
2486 public override bool CheckAccessLevel (DeclSpace ds)
2488 return texpr.CheckAccessLevel (ds);
2491 public override bool AsAccessible (DeclSpace ds, int flags)
2493 return texpr.AsAccessible (ds, flags);
2496 public override bool IsClass {
2497 get { return texpr.IsClass; }
2500 public override bool IsValueType {
2501 get { return texpr.IsValueType; }
2504 public override bool IsInterface {
2505 get { return texpr.IsInterface; }
2508 public override bool IsSealed {
2509 get { return texpr.IsSealed; }
2512 public override bool IsAttribute {
2513 get { return texpr.IsAttribute; }
2518 /// MethodGroup Expression.
2520 /// This is a fully resolved expression that evaluates to a type
2522 public class MethodGroupExpr : Expression, IMemberExpr {
2523 public MethodBase [] Methods;
2524 Expression instance_expression = null;
2525 bool is_explicit_impl = false;
2526 bool has_type_arguments = false;
2528 public MethodGroupExpr (MemberInfo [] mi, Location l)
2530 Methods = new MethodBase [mi.Length];
2531 mi.CopyTo (Methods, 0);
2532 eclass = ExprClass.MethodGroup;
2533 type = TypeManager.object_type;
2537 public MethodGroupExpr (ArrayList list, Location l)
2539 Methods = new MethodBase [list.Count];
2542 list.CopyTo (Methods, 0);
2544 foreach (MemberInfo m in list){
2545 if (!(m is MethodBase)){
2546 Console.WriteLine ("Name " + m.Name);
2547 Console.WriteLine ("Found a: " + m.GetType ().FullName);
2554 eclass = ExprClass.MethodGroup;
2555 type = TypeManager.object_type;
2558 public Type DeclaringType {
2561 // We assume that the top-level type is in the end
2563 return Methods [Methods.Length - 1].DeclaringType;
2564 //return Methods [0].DeclaringType;
2569 // `A method group may have associated an instance expression'
2571 public Expression InstanceExpression {
2573 return instance_expression;
2577 instance_expression = value;
2581 public bool IsExplicitImpl {
2583 return is_explicit_impl;
2587 is_explicit_impl = value;
2591 public bool HasTypeArguments {
2593 return has_type_arguments;
2597 has_type_arguments = value;
2601 public string Name {
2603 return TypeManager.CSharpSignature (
2604 Methods [Methods.Length - 1]);
2608 public bool IsInstance {
2610 foreach (MethodBase mb in Methods)
2618 public bool IsStatic {
2620 foreach (MethodBase mb in Methods)
2628 override public Expression DoResolve (EmitContext ec)
2631 instance_expression = null;
2633 if (instance_expression != null) {
2634 instance_expression = instance_expression.DoResolve (ec);
2635 if (instance_expression == null)
2642 public void ReportUsageError ()
2644 Report.Error (654, loc, "Method `" + DeclaringType + "." +
2645 Name + "()' is referenced without parentheses");
2648 override public void Emit (EmitContext ec)
2650 ReportUsageError ();
2653 bool RemoveMethods (bool keep_static)
2655 ArrayList smethods = new ArrayList ();
2657 foreach (MethodBase mb in Methods){
2658 if (mb.IsStatic == keep_static)
2662 if (smethods.Count == 0)
2665 Methods = new MethodBase [smethods.Count];
2666 smethods.CopyTo (Methods, 0);
2672 /// Removes any instance methods from the MethodGroup, returns
2673 /// false if the resulting set is empty.
2675 public bool RemoveInstanceMethods ()
2677 return RemoveMethods (true);
2681 /// Removes any static methods from the MethodGroup, returns
2682 /// false if the resulting set is empty.
2684 public bool RemoveStaticMethods ()
2686 return RemoveMethods (false);
2691 /// Fully resolved expression that evaluates to a Field
2693 public class FieldExpr : Expression, IAssignMethod, IMemoryLocation, IMemberExpr, IVariable {
2694 public readonly FieldInfo FieldInfo;
2695 Expression instance_expr;
2696 VariableInfo variable_info;
2698 public FieldExpr (FieldInfo fi, Location l)
2701 eclass = ExprClass.Variable;
2702 type = TypeManager.TypeToCoreType (fi.FieldType);
2706 public string Name {
2708 return FieldInfo.Name;
2712 public bool IsInstance {
2714 return !FieldInfo.IsStatic;
2718 public bool IsStatic {
2720 return FieldInfo.IsStatic;
2724 public Type DeclaringType {
2726 return FieldInfo.DeclaringType;
2730 public Expression InstanceExpression {
2732 return instance_expr;
2736 instance_expr = value;
2740 public VariableInfo VariableInfo {
2742 return variable_info;
2746 override public Expression DoResolve (EmitContext ec)
2748 if (!FieldInfo.IsStatic){
2749 if (instance_expr == null){
2751 // This can happen when referencing an instance field using
2752 // a fully qualified type expression: TypeName.InstanceField = xxx
2754 SimpleName.Error_ObjectRefRequired (ec, loc, FieldInfo.Name);
2758 // Resolve the field's instance expression while flow analysis is turned
2759 // off: when accessing a field "a.b", we must check whether the field
2760 // "a.b" is initialized, not whether the whole struct "a" is initialized.
2761 instance_expr = instance_expr.Resolve (ec, ResolveFlags.VariableOrValue |
2762 ResolveFlags.DisableFlowAnalysis);
2763 if (instance_expr == null)
2767 // If the instance expression is a local variable or parameter.
2768 IVariable var = instance_expr as IVariable;
2769 if ((var == null) || (var.VariableInfo == null))
2772 VariableInfo vi = var.VariableInfo;
2773 if (!vi.IsFieldAssigned (ec, FieldInfo.Name, loc))
2776 variable_info = vi.GetSubStruct (FieldInfo.Name);
2780 void Report_AssignToReadonly (bool is_instance)
2785 msg = "Readonly field can not be assigned outside " +
2786 "of constructor or variable initializer";
2788 msg = "A static readonly field can only be assigned in " +
2789 "a static constructor";
2791 Report.Error (is_instance ? 191 : 198, loc, msg);
2794 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
2796 IVariable var = instance_expr as IVariable;
2797 if ((var != null) && (var.VariableInfo != null))
2798 var.VariableInfo.SetFieldAssigned (ec, FieldInfo.Name);
2800 Expression e = DoResolve (ec);
2805 if (!FieldInfo.IsStatic && (instance_expr.Type.IsValueType && !(instance_expr is IMemoryLocation))) {
2806 // FIXME: Provide better error reporting.
2807 Error (1612, "Cannot modify expression because it is not a variable.");
2811 if (!FieldInfo.IsInitOnly)
2814 FieldBase fb = TypeManager.GetField (FieldInfo);
2819 // InitOnly fields can only be assigned in constructors
2822 if (ec.IsConstructor){
2823 if (IsStatic && !ec.IsStatic)
2824 Report_AssignToReadonly (false);
2827 if (ec.TypeContainer.CurrentType != null)
2828 ctype = ec.TypeContainer.CurrentType.ResolveType (ec);
2830 ctype = ec.ContainerType;
2832 if (TypeManager.IsEqual (ctype, FieldInfo.DeclaringType))
2836 Report_AssignToReadonly (true);
2841 public bool VerifyFixed (bool is_expression)
2843 IVariable variable = instance_expr as IVariable;
2844 if ((variable == null) || !variable.VerifyFixed (true))
2850 override public void Emit (EmitContext ec)
2852 ILGenerator ig = ec.ig;
2853 bool is_volatile = false;
2855 if (FieldInfo is FieldBuilder){
2856 FieldBase f = TypeManager.GetField (FieldInfo);
2858 if ((f.ModFlags & Modifiers.VOLATILE) != 0)
2861 f.status |= Field.Status.USED;
2865 if (FieldInfo.IsStatic){
2867 ig.Emit (OpCodes.Volatile);
2869 ig.Emit (OpCodes.Ldsfld, FieldInfo);
2873 if (instance_expr.Type.IsValueType){
2875 LocalTemporary tempo = null;
2877 if (!(instance_expr is IMemoryLocation)){
2878 tempo = new LocalTemporary (ec, instance_expr.Type);
2880 if (ec.RemapToProxy)
2883 InstanceExpression.Emit (ec);
2887 ml = (IMemoryLocation) instance_expr;
2889 ml.AddressOf (ec, AddressOp.Load);
2891 if (ec.RemapToProxy)
2894 instance_expr.Emit (ec);
2897 ig.Emit (OpCodes.Volatile);
2899 ig.Emit (OpCodes.Ldfld, FieldInfo);
2902 public void EmitAssign (EmitContext ec, Expression source)
2904 FieldAttributes fa = FieldInfo.Attributes;
2905 bool is_static = (fa & FieldAttributes.Static) != 0;
2906 bool is_readonly = (fa & FieldAttributes.InitOnly) != 0;
2907 ILGenerator ig = ec.ig;
2909 if (is_readonly && !ec.IsConstructor){
2910 Report_AssignToReadonly (!is_static);
2915 Expression instance = instance_expr;
2917 if (instance.Type.IsValueType){
2918 IMemoryLocation ml = (IMemoryLocation) instance;
2920 ml.AddressOf (ec, AddressOp.Store);
2922 if (ec.RemapToProxy)
2931 if (FieldInfo is FieldBuilder){
2932 FieldBase f = TypeManager.GetField (FieldInfo);
2934 if ((f.ModFlags & Modifiers.VOLATILE) != 0)
2935 ig.Emit (OpCodes.Volatile);
2937 f.status |= Field.Status.ASSIGNED;
2942 ig.Emit (OpCodes.Stsfld, FieldInfo);
2944 ig.Emit (OpCodes.Stfld, FieldInfo);
2947 public void AddressOf (EmitContext ec, AddressOp mode)
2949 ILGenerator ig = ec.ig;
2951 if (FieldInfo is FieldBuilder){
2952 FieldBase f = TypeManager.GetField (FieldInfo);
2954 if ((f.ModFlags & Modifiers.VOLATILE) != 0){
2955 Error (676, "volatile variable: can not take its address, or pass as ref/out parameter");
2959 if ((mode & AddressOp.Store) != 0)
2960 f.status |= Field.Status.ASSIGNED;
2961 if ((mode & AddressOp.Load) != 0)
2962 f.status |= Field.Status.USED;
2967 // Handle initonly fields specially: make a copy and then
2968 // get the address of the copy.
2971 if (FieldInfo.IsInitOnly){
2973 if (ec.IsConstructor){
2974 if (FieldInfo.IsStatic){
2986 local = ig.DeclareLocal (type);
2987 ig.Emit (OpCodes.Stloc, local);
2988 ig.Emit (OpCodes.Ldloca, local);
2993 if (FieldInfo.IsStatic){
2994 ig.Emit (OpCodes.Ldsflda, FieldInfo);
2997 // In the case of `This', we call the AddressOf method, which will
2998 // only load the pointer, and not perform an Ldobj immediately after
2999 // the value has been loaded into the stack.
3001 if (instance_expr is This)
3002 ((This)instance_expr).AddressOf (ec, AddressOp.LoadStore);
3003 else if (instance_expr.Type.IsValueType && instance_expr is IMemoryLocation){
3004 IMemoryLocation ml = (IMemoryLocation) instance_expr;
3006 ml.AddressOf (ec, AddressOp.LoadStore);
3008 instance_expr.Emit (ec);
3009 ig.Emit (OpCodes.Ldflda, FieldInfo);
3015 // A FieldExpr whose address can not be taken
3017 public class FieldExprNoAddress : FieldExpr, IMemoryLocation {
3018 public FieldExprNoAddress (FieldInfo fi, Location loc) : base (fi, loc)
3022 public new void AddressOf (EmitContext ec, AddressOp mode)
3024 Report.Error (-215, "Report this: Taking the address of a remapped parameter not supported");
3029 /// Expression that evaluates to a Property. The Assign class
3030 /// might set the `Value' expression if we are in an assignment.
3032 /// This is not an LValue because we need to re-write the expression, we
3033 /// can not take data from the stack and store it.
3035 public class PropertyExpr : ExpressionStatement, IAssignMethod, IMemberExpr {
3036 public readonly PropertyInfo PropertyInfo;
3039 // This is set externally by the `BaseAccess' class
3042 MethodInfo getter, setter;
3044 bool must_do_cs1540_check;
3046 Expression instance_expr;
3048 public PropertyExpr (EmitContext ec, PropertyInfo pi, Location l)
3051 eclass = ExprClass.PropertyAccess;
3055 type = TypeManager.TypeToCoreType (pi.PropertyType);
3057 ResolveAccessors (ec);
3060 public string Name {
3062 return PropertyInfo.Name;
3066 public bool IsInstance {
3072 public bool IsStatic {
3078 public Type DeclaringType {
3080 return PropertyInfo.DeclaringType;
3085 // The instance expression associated with this expression
3087 public Expression InstanceExpression {
3089 instance_expr = value;
3093 return instance_expr;
3097 public bool VerifyAssignable ()
3099 if (setter == null) {
3100 Report.Error (200, loc,
3101 "The property `" + PropertyInfo.Name +
3102 "' can not be assigned to, as it has not set accessor");
3109 MethodInfo GetAccessor (Type invocation_type, string accessor_name)
3111 BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic |
3112 BindingFlags.Static | BindingFlags.Instance;
3115 group = TypeManager.MemberLookup (
3116 invocation_type, invocation_type, PropertyInfo.DeclaringType,
3117 MemberTypes.Method, flags, accessor_name + "_" + PropertyInfo.Name);
3120 // The first method is the closest to us
3125 foreach (MethodInfo mi in group) {
3126 MethodAttributes ma = mi.Attributes & MethodAttributes.MemberAccessMask;
3129 // If only accessible to the current class or children
3131 if (ma == MethodAttributes.Private) {
3132 Type declaring_type = mi.DeclaringType;
3134 if (invocation_type != declaring_type){
3135 if (TypeManager.IsSubclassOrNestedChildOf (invocation_type, mi.DeclaringType))
3143 // FamAndAssem requires that we not only derivate, but we are on the
3146 if (ma == MethodAttributes.FamANDAssem){
3147 if (mi.DeclaringType.Assembly != invocation_type.Assembly)
3153 // Assembly and FamORAssem succeed if we're in the same assembly.
3154 if ((ma == MethodAttributes.Assembly) || (ma == MethodAttributes.FamORAssem)){
3155 if (mi.DeclaringType.Assembly == invocation_type.Assembly)
3159 // We already know that we aren't in the same assembly.
3160 if (ma == MethodAttributes.Assembly)
3163 // Family and FamANDAssem require that we derive.
3164 if ((ma == MethodAttributes.Family) || (ma == MethodAttributes.FamANDAssem) || (ma == MethodAttributes.FamORAssem)){
3165 if (!TypeManager.IsSubclassOrNestedChildOf (invocation_type, mi.DeclaringType))
3168 must_do_cs1540_check = true;
3181 // We also perform the permission checking here, as the PropertyInfo does not
3182 // hold the information for the accessibility of its setter/getter
3184 void ResolveAccessors (EmitContext ec)
3186 getter = GetAccessor (ec.ContainerType, "get");
3187 if ((getter != null) && getter.IsStatic)
3190 setter = GetAccessor (ec.ContainerType, "set");
3191 if ((setter != null) && setter.IsStatic)
3194 if (setter == null && getter == null){
3195 Error (122, "`" + PropertyInfo.Name + "' " +
3196 "is inaccessible because of its protection level");
3201 bool InstanceResolve (EmitContext ec)
3203 if ((instance_expr == null) && ec.IsStatic && !is_static) {
3204 SimpleName.Error_ObjectRefRequired (ec, loc, PropertyInfo.Name);
3208 if (instance_expr != null) {
3209 instance_expr = instance_expr.DoResolve (ec);
3210 if (instance_expr == null)
3214 if (must_do_cs1540_check && (instance_expr != null)) {
3215 if ((instance_expr.Type != ec.ContainerType) &&
3216 ec.ContainerType.IsSubclassOf (instance_expr.Type)) {
3217 Report.Error (1540, loc, "Cannot access protected member `" +
3218 PropertyInfo.DeclaringType + "." + PropertyInfo.Name +
3219 "' via a qualifier of type `" +
3220 TypeManager.CSharpName (instance_expr.Type) +
3221 "'; the qualifier must be of type `" +
3222 TypeManager.CSharpName (ec.ContainerType) +
3223 "' (or derived from it)");
3231 override public Expression DoResolve (EmitContext ec)
3233 if (getter == null){
3235 // The following condition happens if the PropertyExpr was
3236 // created, but is invalid (ie, the property is inaccessible),
3237 // and we did not want to embed the knowledge about this in
3238 // the caller routine. This only avoids double error reporting.
3243 Report.Error (154, loc,
3244 "The property `" + PropertyInfo.Name +
3245 "' can not be used in " +
3246 "this context because it lacks a get accessor");
3250 if (!InstanceResolve (ec))
3254 // Only base will allow this invocation to happen.
3256 if (IsBase && getter.IsAbstract){
3257 Report.Error (205, loc, "Cannot call an abstract base property: " +
3258 PropertyInfo.DeclaringType + "." +PropertyInfo.Name);
3265 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
3267 if (setter == null){
3269 // The following condition happens if the PropertyExpr was
3270 // created, but is invalid (ie, the property is inaccessible),
3271 // and we did not want to embed the knowledge about this in
3272 // the caller routine. This only avoids double error reporting.
3277 Report.Error (154, loc,
3278 "The property `" + PropertyInfo.Name +
3279 "' can not be used in " +
3280 "this context because it lacks a set accessor");
3284 if (!InstanceResolve (ec))
3288 // Only base will allow this invocation to happen.
3290 if (IsBase && setter.IsAbstract){
3291 Report.Error (205, loc, "Cannot call an abstract base property: " +
3292 PropertyInfo.DeclaringType + "." +PropertyInfo.Name);
3298 override public void Emit (EmitContext ec)
3301 // Special case: length of single dimension array property is turned into ldlen
3303 if ((getter == TypeManager.system_int_array_get_length) ||
3304 (getter == TypeManager.int_array_get_length)){
3305 Type iet = instance_expr.Type;
3308 // System.Array.Length can be called, but the Type does not
3309 // support invoking GetArrayRank, so test for that case first
3311 if (iet != TypeManager.array_type && (iet.GetArrayRank () == 1)){
3312 instance_expr.Emit (ec);
3313 ec.ig.Emit (OpCodes.Ldlen);
3314 ec.ig.Emit (OpCodes.Conv_I4);
3319 Invocation.EmitCall (ec, IsBase, IsStatic, instance_expr, getter, null, loc);
3324 // Implements the IAssignMethod interface for assignments
3326 public void EmitAssign (EmitContext ec, Expression source)
3328 Argument arg = new Argument (source, Argument.AType.Expression);
3329 ArrayList args = new ArrayList ();
3332 Invocation.EmitCall (ec, IsBase, IsStatic, instance_expr, setter, args, loc);
3335 override public void EmitStatement (EmitContext ec)
3338 ec.ig.Emit (OpCodes.Pop);
3343 /// Fully resolved expression that evaluates to an Event
3345 public class EventExpr : Expression, IMemberExpr {
3346 public readonly EventInfo EventInfo;
3347 public Expression instance_expr;
3350 MethodInfo add_accessor, remove_accessor;
3352 public EventExpr (EventInfo ei, Location loc)
3356 eclass = ExprClass.EventAccess;
3358 add_accessor = TypeManager.GetAddMethod (ei);
3359 remove_accessor = TypeManager.GetRemoveMethod (ei);
3361 if (add_accessor.IsStatic || remove_accessor.IsStatic)
3364 if (EventInfo is MyEventBuilder){
3365 MyEventBuilder eb = (MyEventBuilder) EventInfo;
3366 type = eb.EventType;
3369 type = EventInfo.EventHandlerType;
3372 public string Name {
3374 return EventInfo.Name;
3378 public bool IsInstance {
3384 public bool IsStatic {
3390 public Type DeclaringType {
3392 return EventInfo.DeclaringType;
3396 public Expression InstanceExpression {
3398 return instance_expr;
3402 instance_expr = value;
3406 public override Expression DoResolve (EmitContext ec)
3408 if (instance_expr != null) {
3409 instance_expr = instance_expr.DoResolve (ec);
3410 if (instance_expr == null)
3418 public override void Emit (EmitContext ec)
3420 Report.Error (70, loc, "The event `" + Name + "' can only appear on the left hand side of += or -= (except on the defining type)");
3423 public void EmitAddOrRemove (EmitContext ec, Expression source)
3425 BinaryDelegate source_del = (BinaryDelegate) source;
3426 Expression handler = source_del.Right;
3428 Argument arg = new Argument (handler, Argument.AType.Expression);
3429 ArrayList args = new ArrayList ();
3433 if (source_del.IsAddition)
3434 Invocation.EmitCall (
3435 ec, false, IsStatic, instance_expr, add_accessor, args, loc);
3437 Invocation.EmitCall (
3438 ec, false, IsStatic, instance_expr, remove_accessor, args, loc);