2 // ecore.cs: Core of the Expression representation for the intermediate tree.
5 // Miguel de Icaza (miguel@ximian.com)
7 // (C) 2001, 2002, 2003 Ximian, Inc.
11 namespace Mono.CSharp {
13 using System.Collections;
14 using System.Diagnostics;
15 using System.Reflection;
16 using System.Reflection.Emit;
20 /// The ExprClass class contains the is used to pass the
21 /// classification of an expression (value, variable, namespace,
22 /// type, method group, property access, event access, indexer access,
25 public enum ExprClass : byte {
40 /// This is used to tell Resolve in which types of expressions we're
44 public enum ResolveFlags {
45 // Returns Value, Variable, PropertyAccess, EventAccess or IndexerAccess.
48 // Returns a type expression.
51 // Returns a method group.
54 // Allows SimpleNames to be returned.
55 // This is used by MemberAccess to construct long names that can not be
56 // partially resolved (namespace-qualified names for example).
59 // Mask of all the expression class flags.
62 // Disable control flow analysis while resolving the expression.
63 // This is used when resolving the instance expression of a field expression.
64 DisableFlowAnalysis = 16,
66 // Set if this is resolving the first part of a MemberAccess.
71 // This is just as a hint to AddressOf of what will be done with the
74 public enum AddressOp {
81 /// This interface is implemented by variables
83 public interface IMemoryLocation {
85 /// The AddressOf method should generate code that loads
86 /// the address of the object and leaves it on the stack.
88 /// The `mode' argument is used to notify the expression
89 /// of whether this will be used to read from the address or
90 /// write to the address.
92 /// This is just a hint that can be used to provide good error
93 /// reporting, and should have no other side effects.
95 void AddressOf (EmitContext ec, AddressOp mode);
99 /// We are either a namespace or a type.
100 /// If we're a type, `IsType' is true and we may use `Type' to get
101 /// a TypeExpr representing that type.
103 public interface IAlias {
118 /// This interface is implemented by variables
120 public interface IVariable {
121 VariableInfo VariableInfo {
125 bool VerifyFixed (bool is_expression);
129 /// This interface denotes an expression which evaluates to a member
130 /// of a struct or a class.
132 public interface IMemberExpr
135 /// The name of this member.
142 /// Whether this is an instance member.
149 /// Whether this is a static member.
156 /// The type which declares this member.
163 /// The instance expression associated with this member, if it's a
164 /// non-static member.
166 Expression InstanceExpression {
172 /// Base class for expressions
174 public abstract class Expression {
175 public ExprClass eclass;
177 protected Location loc;
189 public Location Location {
196 /// Utility wrapper routine for Error, just to beautify the code
198 public void Error (int error, string s)
200 if (!Location.IsNull (loc))
201 Report.Error (error, loc, s);
203 Report.Error (error, s);
207 /// Utility wrapper routine for Warning, just to beautify the code
209 public void Warning (int warning, string s)
211 if (!Location.IsNull (loc))
212 Report.Warning (warning, loc, s);
214 Report.Warning (warning, s);
218 /// Utility wrapper routine for Warning, only prints the warning if
219 /// warnings of level `level' are enabled.
221 public void Warning (int warning, int level, string s)
223 if (level <= RootContext.WarningLevel)
224 Warning (warning, s);
228 /// Tests presence of ObsoleteAttribute and report proper error
230 protected void CheckObsoleteAttribute (Type type)
232 ObsoleteAttribute obsolete_attr = AttributeTester.GetObsoleteAttribute (type);
233 if (obsolete_attr == null)
236 AttributeTester.Report_ObsoleteMessage (obsolete_attr, type.FullName, loc);
240 /// Performs semantic analysis on the Expression
244 /// The Resolve method is invoked to perform the semantic analysis
247 /// The return value is an expression (it can be the
248 /// same expression in some cases) or a new
249 /// expression that better represents this node.
251 /// For example, optimizations of Unary (LiteralInt)
252 /// would return a new LiteralInt with a negated
255 /// If there is an error during semantic analysis,
256 /// then an error should be reported (using Report)
257 /// and a null value should be returned.
259 /// There are two side effects expected from calling
260 /// Resolve(): the the field variable "eclass" should
261 /// be set to any value of the enumeration
262 /// `ExprClass' and the type variable should be set
263 /// to a valid type (this is the type of the
266 public abstract Expression DoResolve (EmitContext ec);
268 public virtual Expression DoResolveLValue (EmitContext ec, Expression right_side)
270 return DoResolve (ec);
274 // This is used if the expression should be resolved as a type.
275 // the default implementation fails. Use this method in
276 // those participants in the SimpleName chain system.
278 public virtual Expression ResolveAsTypeStep (EmitContext ec)
284 // This is used to resolve the expression as a type, a null
285 // value will be returned if the expression is not a type
288 public TypeExpr ResolveAsTypeTerminal (EmitContext ec)
290 return ResolveAsTypeStep (ec) as TypeExpr;
294 /// Resolves an expression and performs semantic analysis on it.
298 /// Currently Resolve wraps DoResolve to perform sanity
299 /// checking and assertion checking on what we expect from Resolve.
301 public Expression Resolve (EmitContext ec, ResolveFlags flags)
303 if ((flags & ResolveFlags.MaskExprClass) == ResolveFlags.Type)
304 return ResolveAsTypeStep (ec);
306 bool old_do_flow_analysis = ec.DoFlowAnalysis;
307 if ((flags & ResolveFlags.DisableFlowAnalysis) != 0)
308 ec.DoFlowAnalysis = false;
311 bool intermediate = (flags & ResolveFlags.Intermediate) == ResolveFlags.Intermediate;
312 if (this is SimpleName)
313 e = ((SimpleName) this).DoResolveAllowStatic (ec, intermediate);
318 ec.DoFlowAnalysis = old_do_flow_analysis;
323 if (e is SimpleName){
324 SimpleName s = (SimpleName) e;
326 if ((flags & ResolveFlags.SimpleName) == 0) {
327 MemberLookupFailed (ec, null, ec.ContainerType, s.Name,
328 ec.DeclSpace.Name, loc);
335 if ((e is TypeExpr) || (e is ComposedCast)) {
336 if ((flags & ResolveFlags.Type) == 0) {
337 e.Error_UnexpectedKind (flags);
346 if ((flags & ResolveFlags.VariableOrValue) == 0) {
347 e.Error_UnexpectedKind (flags);
352 case ExprClass.MethodGroup:
353 if (!RootContext.V2){
354 if ((flags & ResolveFlags.MethodGroup) == 0) {
355 ((MethodGroupExpr) e).ReportUsageError ();
361 case ExprClass.Value:
362 case ExprClass.Variable:
363 case ExprClass.PropertyAccess:
364 case ExprClass.EventAccess:
365 case ExprClass.IndexerAccess:
366 if ((flags & ResolveFlags.VariableOrValue) == 0) {
367 Console.WriteLine ("I got: {0} and {1}", e.GetType (), e);
368 Console.WriteLine ("I am {0} and {1}", this.GetType (), this);
369 FieldInfo fi = ((FieldExpr) e).FieldInfo;
371 Console.WriteLine ("{0} and {1}", fi.DeclaringType, fi.Name);
372 e.Error_UnexpectedKind (flags);
378 throw new Exception ("Expression " + e.GetType () +
379 " ExprClass is Invalid after resolve");
383 throw new Exception (
384 "Expression " + e.GetType () +
385 " did not set its type after Resolve\n" +
386 "called from: " + this.GetType ());
392 /// Resolves an expression and performs semantic analysis on it.
394 public Expression Resolve (EmitContext ec)
396 return Resolve (ec, ResolveFlags.VariableOrValue);
400 /// Resolves an expression for LValue assignment
404 /// Currently ResolveLValue wraps DoResolveLValue to perform sanity
405 /// checking and assertion checking on what we expect from Resolve
407 public Expression ResolveLValue (EmitContext ec, Expression right_side)
409 Expression e = DoResolveLValue (ec, right_side);
412 if (e is SimpleName){
413 SimpleName s = (SimpleName) e;
414 MemberLookupFailed (ec, null, ec.ContainerType, s.Name,
415 ec.DeclSpace.Name, loc);
419 if (e.eclass == ExprClass.Invalid)
420 throw new Exception ("Expression " + e +
421 " ExprClass is Invalid after resolve");
423 if (e.eclass == ExprClass.MethodGroup) {
424 ((MethodGroupExpr) e).ReportUsageError ();
428 if ((e.type == null) && !(e is ConstructedType))
429 throw new Exception ("Expression " + e +
430 " did not set its type after Resolve");
437 /// Emits the code for the expression
441 /// The Emit method is invoked to generate the code
442 /// for the expression.
444 public abstract void Emit (EmitContext ec);
446 public virtual void EmitBranchable (EmitContext ec, Label target, bool onTrue)
449 ec.ig.Emit (onTrue ? OpCodes.Brtrue : OpCodes.Brfalse, target);
453 /// Protected constructor. Only derivate types should
454 /// be able to be created
457 protected Expression ()
459 eclass = ExprClass.Invalid;
464 /// Returns a literalized version of a literal FieldInfo
468 /// The possible return values are:
469 /// IntConstant, UIntConstant
470 /// LongLiteral, ULongConstant
471 /// FloatConstant, DoubleConstant
474 /// The value returned is already resolved.
476 public static Constant Constantify (object v, Type t)
478 if (t == TypeManager.int32_type)
479 return new IntConstant ((int) v);
480 else if (t == TypeManager.uint32_type)
481 return new UIntConstant ((uint) v);
482 else if (t == TypeManager.int64_type)
483 return new LongConstant ((long) v);
484 else if (t == TypeManager.uint64_type)
485 return new ULongConstant ((ulong) v);
486 else if (t == TypeManager.float_type)
487 return new FloatConstant ((float) v);
488 else if (t == TypeManager.double_type)
489 return new DoubleConstant ((double) v);
490 else if (t == TypeManager.string_type)
491 return new StringConstant ((string) v);
492 else if (t == TypeManager.short_type)
493 return new ShortConstant ((short)v);
494 else if (t == TypeManager.ushort_type)
495 return new UShortConstant ((ushort)v);
496 else if (t == TypeManager.sbyte_type)
497 return new SByteConstant (((sbyte)v));
498 else if (t == TypeManager.byte_type)
499 return new ByteConstant ((byte)v);
500 else if (t == TypeManager.char_type)
501 return new CharConstant ((char)v);
502 else if (t == TypeManager.bool_type)
503 return new BoolConstant ((bool) v);
504 else if (TypeManager.IsEnumType (t)){
505 Type real_type = TypeManager.TypeToCoreType (v.GetType ());
507 real_type = real_type.UnderlyingSystemType;
509 Constant e = Constantify (v, real_type);
511 return new EnumConstant (e, t);
513 throw new Exception ("Unknown type for constant (" + t +
518 /// Returns a fully formed expression after a MemberLookup
520 public static Expression ExprClassFromMemberInfo (EmitContext ec, MemberInfo mi, Location loc)
523 return new EventExpr ((EventInfo) mi, loc);
524 else if (mi is FieldInfo)
525 return new FieldExpr ((FieldInfo) mi, loc);
526 else if (mi is PropertyInfo)
527 return new PropertyExpr (ec, (PropertyInfo) mi, loc);
528 else if (mi is Type){
529 return new TypeExpression ((System.Type) mi, loc);
536 private static ArrayList almostMatchedMembers = new ArrayList (4);
539 // FIXME: Probably implement a cache for (t,name,current_access_set)?
541 // This code could use some optimizations, but we need to do some
542 // measurements. For example, we could use a delegate to `flag' when
543 // something can not any longer be a method-group (because it is something
547 // If the return value is an Array, then it is an array of
550 // If the return value is an MemberInfo, it is anything, but a Method
554 // FIXME: When calling MemberLookup inside an `Invocation', we should pass
555 // the arguments here and have MemberLookup return only the methods that
556 // match the argument count/type, unlike we are doing now (we delay this
559 // This is so we can catch correctly attempts to invoke instance methods
560 // from a static body (scan for error 120 in ResolveSimpleName).
563 // FIXME: Potential optimization, have a static ArrayList
566 public static Expression MemberLookup (EmitContext ec, Type queried_type, string name,
567 MemberTypes mt, BindingFlags bf, Location loc)
569 return MemberLookup (ec, ec.ContainerType, null, queried_type, name, mt, bf, loc);
573 // Lookup type `queried_type' for code in class `container_type' with a qualifier of
574 // `qualifier_type' or null to lookup members in the current class.
577 public static Expression MemberLookup (EmitContext ec, Type container_type,
578 Type qualifier_type, Type queried_type,
579 string name, MemberTypes mt,
580 BindingFlags bf, Location loc)
582 almostMatchedMembers.Clear ();
584 MemberInfo [] mi = TypeManager.MemberLookup (
585 container_type, qualifier_type,queried_type, mt, bf, name,
586 almostMatchedMembers);
591 int count = mi.Length;
593 if (mi [0] is MethodBase)
594 return new MethodGroupExpr (mi, loc);
599 return ExprClassFromMemberInfo (ec, mi [0], loc);
602 public const MemberTypes AllMemberTypes =
603 MemberTypes.Constructor |
607 MemberTypes.NestedType |
608 MemberTypes.Property;
610 public const BindingFlags AllBindingFlags =
611 BindingFlags.Public |
612 BindingFlags.Static |
613 BindingFlags.Instance;
615 public static Expression MemberLookup (EmitContext ec, Type queried_type,
616 string name, Location loc)
618 return MemberLookup (ec, ec.ContainerType, null, queried_type, name,
619 AllMemberTypes, AllBindingFlags, loc);
622 public static Expression MemberLookup (EmitContext ec, Type qualifier_type,
623 Type queried_type, string name, Location loc)
625 return MemberLookup (ec, ec.ContainerType, qualifier_type, queried_type,
626 name, AllMemberTypes, AllBindingFlags, loc);
629 public static Expression MethodLookup (EmitContext ec, Type queried_type,
630 string name, Location loc)
632 return MemberLookup (ec, ec.ContainerType, null, queried_type, name,
633 MemberTypes.Method, AllBindingFlags, loc);
637 /// This is a wrapper for MemberLookup that is not used to "probe", but
638 /// to find a final definition. If the final definition is not found, we
639 /// look for private members and display a useful debugging message if we
642 public static Expression MemberLookupFinal (EmitContext ec, Type qualifier_type,
643 Type queried_type, string name,
646 return MemberLookupFinal (ec, qualifier_type, queried_type, name,
647 AllMemberTypes, AllBindingFlags, loc);
650 public static Expression MemberLookupFinal (EmitContext ec, Type qualifier_type,
651 Type queried_type, string name,
652 MemberTypes mt, BindingFlags bf,
657 int errors = Report.Errors;
659 e = MemberLookup (ec, ec.ContainerType, qualifier_type, queried_type,
662 if (e == null && errors == Report.Errors)
663 // No errors were reported by MemberLookup, but there was an error.
664 MemberLookupFailed (ec, qualifier_type, queried_type, name,
670 public static void MemberLookupFailed (EmitContext ec, Type qualifier_type,
671 Type queried_type, string name,
672 string class_name, Location loc)
674 if (almostMatchedMembers.Count != 0) {
675 if (qualifier_type == null) {
676 foreach (MemberInfo m in almostMatchedMembers)
677 Report.Error (38, loc,
678 "Cannot access non-static member `{0}' via nested type `{1}'",
679 TypeManager.GetFullNameSignature (m),
680 TypeManager.CSharpName (ec.ContainerType));
685 if (qualifier_type != ec.ContainerType) {
686 // Although a derived class can access protected members of
687 // its base class it cannot do so through an instance of the
688 // base class (CS1540). If the qualifier_type is a parent of the
689 // ec.ContainerType and the lookup succeeds with the latter one,
690 // then we are in this situation.
691 foreach (MemberInfo m in almostMatchedMembers)
692 Report.Error (1540, loc,
693 "Cannot access protected member `{0}' via a qualifier of type `{1}';"
694 + " the qualifier must be of type `{2}' (or derived from it)",
695 TypeManager.GetFullNameSignature (m),
696 TypeManager.CSharpName (qualifier_type),
697 TypeManager.CSharpName (ec.ContainerType));
700 almostMatchedMembers.Clear ();
703 MemberInfo[] mi = TypeManager.MemberLookup (queried_type, null, queried_type,
704 AllMemberTypes, AllBindingFlags |
705 BindingFlags.NonPublic, name, null);
708 if (class_name != null)
709 Report.Error (103, loc, "The name `" + name + "' could not be " +
710 "found in `" + class_name + "'");
713 117, loc, "`" + queried_type + "' does not contain a " +
714 "definition for `" + name + "'");
718 if (TypeManager.MemberLookup (queried_type, null, queried_type,
719 AllMemberTypes, AllBindingFlags |
720 BindingFlags.NonPublic, name, null) == null) {
721 if ((mi.Length == 1) && (mi [0] is Type)) {
722 Type t = (Type) mi [0];
724 Report.Error (305, loc,
725 "Using the generic type `{0}' " +
726 "requires {1} type arguments",
727 TypeManager.GetFullName (t),
728 TypeManager.GetNumberOfTypeArguments (t));
735 if (qualifier_type != null)
736 Report.Error_T (122, loc, TypeManager.CSharpName (qualifier_type) + "." + name);
737 else if (name == ".ctor") {
738 Report.Error (143, loc, String.Format ("The type {0} has no constructors defined",
739 TypeManager.CSharpName (queried_type)));
741 Report.Error_T (122, loc, name);
745 static public MemberInfo GetFieldFromEvent (EventExpr event_expr)
747 EventInfo ei = event_expr.EventInfo;
749 return TypeManager.GetPrivateFieldOfEvent (ei);
753 /// Returns an expression that can be used to invoke operator true
754 /// on the expression if it exists.
756 static public StaticCallExpr GetOperatorTrue (EmitContext ec, Expression e, Location loc)
758 return GetOperatorTrueOrFalse (ec, e, true, loc);
762 /// Returns an expression that can be used to invoke operator false
763 /// on the expression if it exists.
765 static public StaticCallExpr GetOperatorFalse (EmitContext ec, Expression e, Location loc)
767 return GetOperatorTrueOrFalse (ec, e, false, loc);
770 static StaticCallExpr GetOperatorTrueOrFalse (EmitContext ec, Expression e, bool is_true, Location loc)
773 Expression operator_group;
775 operator_group = MethodLookup (ec, e.Type, is_true ? "op_True" : "op_False", loc);
776 if (operator_group == null)
779 ArrayList arguments = new ArrayList ();
780 arguments.Add (new Argument (e, Argument.AType.Expression));
781 method = Invocation.OverloadResolve (
782 ec, (MethodGroupExpr) operator_group, arguments, false, loc);
787 return new StaticCallExpr ((MethodInfo) method, arguments, loc);
791 /// Resolves the expression `e' into a boolean expression: either through
792 /// an implicit conversion, or through an `operator true' invocation
794 public static Expression ResolveBoolean (EmitContext ec, Expression e, Location loc)
800 Expression converted = e;
801 if (e.Type != TypeManager.bool_type)
802 converted = Convert.ImplicitConversion (ec, e, TypeManager.bool_type, new Location (-1));
805 // If no implicit conversion to bool exists, try using `operator true'
807 if (converted == null){
808 Expression operator_true = Expression.GetOperatorTrue (ec, e, loc);
809 if (operator_true == null){
811 31, loc, "Can not convert the expression to a boolean");
821 static string ExprClassName (ExprClass c)
824 case ExprClass.Invalid:
826 case ExprClass.Value:
828 case ExprClass.Variable:
830 case ExprClass.Namespace:
834 case ExprClass.MethodGroup:
835 return "method group";
836 case ExprClass.PropertyAccess:
837 return "property access";
838 case ExprClass.EventAccess:
839 return "event access";
840 case ExprClass.IndexerAccess:
841 return "indexer access";
842 case ExprClass.Nothing:
845 throw new Exception ("Should not happen");
849 /// Reports that we were expecting `expr' to be of class `expected'
851 public void Error_UnexpectedKind (string expected)
853 string kind = "Unknown";
855 kind = ExprClassName (eclass);
857 Error (118, "Expression denotes a `" + kind +
858 "' where a `" + expected + "' was expected");
861 public void Error_UnexpectedKind (ResolveFlags flags)
863 ArrayList valid = new ArrayList (10);
865 if ((flags & ResolveFlags.VariableOrValue) != 0) {
866 valid.Add ("variable");
870 if ((flags & ResolveFlags.Type) != 0)
873 if ((flags & ResolveFlags.MethodGroup) != 0)
874 valid.Add ("method group");
876 if ((flags & ResolveFlags.SimpleName) != 0)
877 valid.Add ("simple name");
879 if (valid.Count == 0)
880 valid.Add ("unknown");
882 StringBuilder sb = new StringBuilder ();
883 for (int i = 0; i < valid.Count; i++) {
886 else if (i == valid.Count)
888 sb.Append (valid [i]);
891 string kind = ExprClassName (eclass);
893 Error (119, "Expression denotes a `" + kind + "' where " +
894 "a `" + sb.ToString () + "' was expected");
897 static public void Error_ConstantValueCannotBeConverted (Location l, string val, Type t)
899 Report.Error (31, l, "Constant value `" + val + "' cannot be converted to " +
900 TypeManager.CSharpName (t));
903 public static void UnsafeError (Location loc)
905 Report.Error (214, loc, "Pointers may only be used in an unsafe context");
909 /// Converts the IntConstant, UIntConstant, LongConstant or
910 /// ULongConstant into the integral target_type. Notice
911 /// that we do not return an `Expression' we do return
912 /// a boxed integral type.
914 /// FIXME: Since I added the new constants, we need to
915 /// also support conversions from CharConstant, ByteConstant,
916 /// SByteConstant, UShortConstant, ShortConstant
918 /// This is used by the switch statement, so the domain
919 /// of work is restricted to the literals above, and the
920 /// targets are int32, uint32, char, byte, sbyte, ushort,
921 /// short, uint64 and int64
923 public static object ConvertIntLiteral (Constant c, Type target_type, Location loc)
925 if (!Convert.ImplicitStandardConversionExists (c, target_type)){
926 Convert.Error_CannotImplicitConversion (loc, c.Type, target_type);
932 if (c.Type == target_type)
933 return ((Constant) c).GetValue ();
936 // Make into one of the literals we handle, we dont really care
937 // about this value as we will just return a few limited types
939 if (c is EnumConstant)
940 c = ((EnumConstant)c).WidenToCompilerConstant ();
942 if (c is IntConstant){
943 int v = ((IntConstant) c).Value;
945 if (target_type == TypeManager.uint32_type){
948 } else if (target_type == TypeManager.char_type){
949 if (v >= Char.MinValue && v <= Char.MaxValue)
951 } else if (target_type == TypeManager.byte_type){
952 if (v >= Byte.MinValue && v <= Byte.MaxValue)
954 } else if (target_type == TypeManager.sbyte_type){
955 if (v >= SByte.MinValue && v <= SByte.MaxValue)
957 } else if (target_type == TypeManager.short_type){
958 if (v >= Int16.MinValue && v <= UInt16.MaxValue)
960 } else if (target_type == TypeManager.ushort_type){
961 if (v >= UInt16.MinValue && v <= UInt16.MaxValue)
963 } else if (target_type == TypeManager.int64_type)
965 else if (target_type == TypeManager.uint64_type){
971 } else if (c is UIntConstant){
972 uint v = ((UIntConstant) c).Value;
974 if (target_type == TypeManager.int32_type){
975 if (v <= Int32.MaxValue)
977 } else if (target_type == TypeManager.char_type){
978 if (v >= Char.MinValue && v <= Char.MaxValue)
980 } else if (target_type == TypeManager.byte_type){
981 if (v <= Byte.MaxValue)
983 } else if (target_type == TypeManager.sbyte_type){
984 if (v <= SByte.MaxValue)
986 } else if (target_type == TypeManager.short_type){
987 if (v <= UInt16.MaxValue)
989 } else if (target_type == TypeManager.ushort_type){
990 if (v <= UInt16.MaxValue)
992 } else if (target_type == TypeManager.int64_type)
994 else if (target_type == TypeManager.uint64_type)
997 } else if (c is LongConstant){
998 long v = ((LongConstant) c).Value;
1000 if (target_type == TypeManager.int32_type){
1001 if (v >= UInt32.MinValue && v <= UInt32.MaxValue)
1003 } else if (target_type == TypeManager.uint32_type){
1004 if (v >= 0 && v <= UInt32.MaxValue)
1006 } else if (target_type == TypeManager.char_type){
1007 if (v >= Char.MinValue && v <= Char.MaxValue)
1009 } else if (target_type == TypeManager.byte_type){
1010 if (v >= Byte.MinValue && v <= Byte.MaxValue)
1012 } else if (target_type == TypeManager.sbyte_type){
1013 if (v >= SByte.MinValue && v <= SByte.MaxValue)
1015 } else if (target_type == TypeManager.short_type){
1016 if (v >= Int16.MinValue && v <= UInt16.MaxValue)
1018 } else if (target_type == TypeManager.ushort_type){
1019 if (v >= UInt16.MinValue && v <= UInt16.MaxValue)
1021 } else if (target_type == TypeManager.uint64_type){
1026 } else if (c is ULongConstant){
1027 ulong v = ((ULongConstant) c).Value;
1029 if (target_type == TypeManager.int32_type){
1030 if (v <= Int32.MaxValue)
1032 } else if (target_type == TypeManager.uint32_type){
1033 if (v <= UInt32.MaxValue)
1035 } else if (target_type == TypeManager.char_type){
1036 if (v >= Char.MinValue && v <= Char.MaxValue)
1038 } else if (target_type == TypeManager.byte_type){
1039 if (v >= Byte.MinValue && v <= Byte.MaxValue)
1041 } else if (target_type == TypeManager.sbyte_type){
1042 if (v <= (int) SByte.MaxValue)
1044 } else if (target_type == TypeManager.short_type){
1045 if (v <= UInt16.MaxValue)
1047 } else if (target_type == TypeManager.ushort_type){
1048 if (v <= UInt16.MaxValue)
1050 } else if (target_type == TypeManager.int64_type){
1051 if (v <= Int64.MaxValue)
1055 } else if (c is ByteConstant){
1056 byte v = ((ByteConstant) c).Value;
1058 if (target_type == TypeManager.int32_type)
1060 else if (target_type == TypeManager.uint32_type)
1062 else if (target_type == TypeManager.char_type)
1064 else if (target_type == TypeManager.sbyte_type){
1065 if (v <= SByte.MaxValue)
1067 } else if (target_type == TypeManager.short_type)
1069 else if (target_type == TypeManager.ushort_type)
1071 else if (target_type == TypeManager.int64_type)
1073 else if (target_type == TypeManager.uint64_type)
1076 } else if (c is SByteConstant){
1077 sbyte v = ((SByteConstant) 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){
1090 } else if (target_type == TypeManager.short_type)
1092 else if (target_type == TypeManager.ushort_type){
1095 } else if (target_type == TypeManager.int64_type)
1097 else if (target_type == TypeManager.uint64_type){
1102 } else if (c is ShortConstant){
1103 short v = ((ShortConstant) c).Value;
1105 if (target_type == TypeManager.int32_type){
1107 } else if (target_type == TypeManager.uint32_type){
1110 } else if (target_type == TypeManager.char_type){
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.MinValue && v <= SByte.MaxValue)
1119 } else if (target_type == TypeManager.ushort_type){
1122 } else if (target_type == TypeManager.int64_type)
1124 else if (target_type == TypeManager.uint64_type)
1128 } else if (c is UShortConstant){
1129 ushort v = ((UShortConstant) c).Value;
1131 if (target_type == TypeManager.int32_type)
1133 else if (target_type == TypeManager.uint32_type)
1135 else if (target_type == TypeManager.char_type){
1136 if (v >= Char.MinValue && v <= Char.MaxValue)
1138 } else if (target_type == TypeManager.byte_type){
1139 if (v >= Byte.MinValue && v <= Byte.MaxValue)
1141 } else if (target_type == TypeManager.sbyte_type){
1142 if (v <= SByte.MaxValue)
1144 } else if (target_type == TypeManager.short_type){
1145 if (v <= Int16.MaxValue)
1147 } else if (target_type == TypeManager.int64_type)
1149 else if (target_type == TypeManager.uint64_type)
1153 } else if (c is CharConstant){
1154 char v = ((CharConstant) c).Value;
1156 if (target_type == TypeManager.int32_type)
1158 else if (target_type == TypeManager.uint32_type)
1160 else if (target_type == TypeManager.byte_type){
1161 if (v >= Byte.MinValue && v <= Byte.MaxValue)
1163 } else if (target_type == TypeManager.sbyte_type){
1164 if (v <= SByte.MaxValue)
1166 } else if (target_type == TypeManager.short_type){
1167 if (v <= Int16.MaxValue)
1169 } else if (target_type == TypeManager.ushort_type)
1171 else if (target_type == TypeManager.int64_type)
1173 else if (target_type == TypeManager.uint64_type)
1178 Error_ConstantValueCannotBeConverted (loc, s, target_type);
1183 // Load the object from the pointer.
1185 public static void LoadFromPtr (ILGenerator ig, Type t)
1187 if (t == TypeManager.int32_type)
1188 ig.Emit (OpCodes.Ldind_I4);
1189 else if (t == TypeManager.uint32_type)
1190 ig.Emit (OpCodes.Ldind_U4);
1191 else if (t == TypeManager.short_type)
1192 ig.Emit (OpCodes.Ldind_I2);
1193 else if (t == TypeManager.ushort_type)
1194 ig.Emit (OpCodes.Ldind_U2);
1195 else if (t == TypeManager.char_type)
1196 ig.Emit (OpCodes.Ldind_U2);
1197 else if (t == TypeManager.byte_type)
1198 ig.Emit (OpCodes.Ldind_U1);
1199 else if (t == TypeManager.sbyte_type)
1200 ig.Emit (OpCodes.Ldind_I1);
1201 else if (t == TypeManager.uint64_type)
1202 ig.Emit (OpCodes.Ldind_I8);
1203 else if (t == TypeManager.int64_type)
1204 ig.Emit (OpCodes.Ldind_I8);
1205 else if (t == TypeManager.float_type)
1206 ig.Emit (OpCodes.Ldind_R4);
1207 else if (t == TypeManager.double_type)
1208 ig.Emit (OpCodes.Ldind_R8);
1209 else if (t == TypeManager.bool_type)
1210 ig.Emit (OpCodes.Ldind_I1);
1211 else if (t == TypeManager.intptr_type)
1212 ig.Emit (OpCodes.Ldind_I);
1213 else if (TypeManager.IsEnumType (t)) {
1214 if (t == TypeManager.enum_type)
1215 ig.Emit (OpCodes.Ldind_Ref);
1217 LoadFromPtr (ig, TypeManager.EnumToUnderlying (t));
1218 } else if (t.IsValueType)
1219 ig.Emit (OpCodes.Ldobj, t);
1220 else if (t.IsPointer)
1221 ig.Emit (OpCodes.Ldind_I);
1223 ig.Emit (OpCodes.Ldind_Ref);
1227 // The stack contains the pointer and the value of type `type'
1229 public static void StoreFromPtr (ILGenerator ig, Type type)
1231 if (TypeManager.IsEnumType (type))
1232 type = TypeManager.EnumToUnderlying (type);
1233 if (type == TypeManager.int32_type || type == TypeManager.uint32_type)
1234 ig.Emit (OpCodes.Stind_I4);
1235 else if (type == TypeManager.int64_type || type == TypeManager.uint64_type)
1236 ig.Emit (OpCodes.Stind_I8);
1237 else if (type == TypeManager.char_type || type == TypeManager.short_type ||
1238 type == TypeManager.ushort_type)
1239 ig.Emit (OpCodes.Stind_I2);
1240 else if (type == TypeManager.float_type)
1241 ig.Emit (OpCodes.Stind_R4);
1242 else if (type == TypeManager.double_type)
1243 ig.Emit (OpCodes.Stind_R8);
1244 else if (type == TypeManager.byte_type || type == TypeManager.sbyte_type ||
1245 type == TypeManager.bool_type)
1246 ig.Emit (OpCodes.Stind_I1);
1247 else if (type == TypeManager.intptr_type)
1248 ig.Emit (OpCodes.Stind_I);
1249 else if (type.IsValueType)
1250 ig.Emit (OpCodes.Stobj, type);
1252 ig.Emit (OpCodes.Stind_Ref);
1256 // Returns the size of type `t' if known, otherwise, 0
1258 public static int GetTypeSize (Type t)
1260 t = TypeManager.TypeToCoreType (t);
1261 if (t == TypeManager.int32_type ||
1262 t == TypeManager.uint32_type ||
1263 t == TypeManager.float_type)
1265 else if (t == TypeManager.int64_type ||
1266 t == TypeManager.uint64_type ||
1267 t == TypeManager.double_type)
1269 else if (t == TypeManager.byte_type ||
1270 t == TypeManager.sbyte_type ||
1271 t == TypeManager.bool_type)
1273 else if (t == TypeManager.short_type ||
1274 t == TypeManager.char_type ||
1275 t == TypeManager.ushort_type)
1277 else if (t == TypeManager.decimal_type)
1284 // Default implementation of IAssignMethod.CacheTemporaries
1286 public virtual void CacheTemporaries (EmitContext ec)
1290 static void Error_NegativeArrayIndex (Location loc)
1292 Report.Error (284, loc, "Can not create array with a negative size");
1296 // Converts `source' to an int, uint, long or ulong.
1298 public Expression ExpressionToArrayArgument (EmitContext ec, Expression source, Location loc)
1302 bool old_checked = ec.CheckState;
1303 ec.CheckState = true;
1305 target = Convert.ImplicitConversion (ec, source, TypeManager.int32_type, loc);
1306 if (target == null){
1307 target = Convert.ImplicitConversion (ec, source, TypeManager.uint32_type, loc);
1308 if (target == null){
1309 target = Convert.ImplicitConversion (ec, source, TypeManager.int64_type, loc);
1310 if (target == null){
1311 target = Convert.ImplicitConversion (ec, source, TypeManager.uint64_type, loc);
1313 Convert.Error_CannotImplicitConversion (loc, source.Type, TypeManager.int32_type);
1317 ec.CheckState = old_checked;
1320 // Only positive constants are allowed at compile time
1322 if (target is Constant){
1323 if (target is IntConstant){
1324 if (((IntConstant) target).Value < 0){
1325 Error_NegativeArrayIndex (loc);
1330 if (target is LongConstant){
1331 if (((LongConstant) target).Value < 0){
1332 Error_NegativeArrayIndex (loc);
1345 /// This is just a base class for expressions that can
1346 /// appear on statements (invocations, object creation,
1347 /// assignments, post/pre increment and decrement). The idea
1348 /// being that they would support an extra Emition interface that
1349 /// does not leave a result on the stack.
1351 public abstract class ExpressionStatement : Expression {
1353 public virtual ExpressionStatement ResolveStatement (EmitContext ec)
1355 Expression e = Resolve (ec);
1359 ExpressionStatement es = e as ExpressionStatement;
1361 Error (201, "Only assignment, call, increment, decrement and new object " +
1362 "expressions can be used as a statement");
1368 /// Requests the expression to be emitted in a `statement'
1369 /// context. This means that no new value is left on the
1370 /// stack after invoking this method (constrasted with
1371 /// Emit that will always leave a value on the stack).
1373 public abstract void EmitStatement (EmitContext ec);
1377 /// This kind of cast is used to encapsulate the child
1378 /// whose type is child.Type into an expression that is
1379 /// reported to return "return_type". This is used to encapsulate
1380 /// expressions which have compatible types, but need to be dealt
1381 /// at higher levels with.
1383 /// For example, a "byte" expression could be encapsulated in one
1384 /// of these as an "unsigned int". The type for the expression
1385 /// would be "unsigned int".
1388 public class EmptyCast : Expression {
1389 protected Expression child;
1391 public Expression Child {
1397 public EmptyCast (Expression child, Type return_type)
1399 eclass = child.eclass;
1404 public override Expression DoResolve (EmitContext ec)
1406 // This should never be invoked, we are born in fully
1407 // initialized state.
1412 public override void Emit (EmitContext ec)
1419 // We need to special case this since an empty cast of
1420 // a NullLiteral is still a Constant
1422 public class NullCast : Constant {
1423 protected Expression child;
1425 public NullCast (Expression child, Type return_type)
1427 eclass = child.eclass;
1432 override public string AsString ()
1437 public override object GetValue ()
1442 public override Expression DoResolve (EmitContext ec)
1444 // This should never be invoked, we are born in fully
1445 // initialized state.
1450 public override void Emit (EmitContext ec)
1458 /// This class is used to wrap literals which belong inside Enums
1460 public class EnumConstant : Constant {
1461 public Constant Child;
1463 public EnumConstant (Constant child, Type enum_type)
1465 eclass = child.eclass;
1470 public override Expression DoResolve (EmitContext ec)
1472 // This should never be invoked, we are born in fully
1473 // initialized state.
1478 public override void Emit (EmitContext ec)
1483 public override object GetValue ()
1485 return Child.GetValue ();
1489 // Converts from one of the valid underlying types for an enumeration
1490 // (int32, uint32, int64, uint64, short, ushort, byte, sbyte) to
1491 // one of the internal compiler literals: Int/UInt/Long/ULong Literals.
1493 public Constant WidenToCompilerConstant ()
1495 Type t = TypeManager.EnumToUnderlying (Child.Type);
1496 object v = ((Constant) Child).GetValue ();;
1498 if (t == TypeManager.int32_type)
1499 return new IntConstant ((int) v);
1500 if (t == TypeManager.uint32_type)
1501 return new UIntConstant ((uint) v);
1502 if (t == TypeManager.int64_type)
1503 return new LongConstant ((long) v);
1504 if (t == TypeManager.uint64_type)
1505 return new ULongConstant ((ulong) v);
1506 if (t == TypeManager.short_type)
1507 return new ShortConstant ((short) v);
1508 if (t == TypeManager.ushort_type)
1509 return new UShortConstant ((ushort) v);
1510 if (t == TypeManager.byte_type)
1511 return new ByteConstant ((byte) v);
1512 if (t == TypeManager.sbyte_type)
1513 return new SByteConstant ((sbyte) v);
1515 throw new Exception ("Invalid enumeration underlying type: " + t);
1519 // Extracts the value in the enumeration on its native representation
1521 public object GetPlainValue ()
1523 Type t = TypeManager.EnumToUnderlying (Child.Type);
1524 object v = ((Constant) Child).GetValue ();;
1526 if (t == TypeManager.int32_type)
1528 if (t == TypeManager.uint32_type)
1530 if (t == TypeManager.int64_type)
1532 if (t == TypeManager.uint64_type)
1534 if (t == TypeManager.short_type)
1536 if (t == TypeManager.ushort_type)
1538 if (t == TypeManager.byte_type)
1540 if (t == TypeManager.sbyte_type)
1546 public override string AsString ()
1548 return Child.AsString ();
1551 public override DoubleConstant ConvertToDouble ()
1553 return Child.ConvertToDouble ();
1556 public override FloatConstant ConvertToFloat ()
1558 return Child.ConvertToFloat ();
1561 public override ULongConstant ConvertToULong ()
1563 return Child.ConvertToULong ();
1566 public override LongConstant ConvertToLong ()
1568 return Child.ConvertToLong ();
1571 public override UIntConstant ConvertToUInt ()
1573 return Child.ConvertToUInt ();
1576 public override IntConstant ConvertToInt ()
1578 return Child.ConvertToInt ();
1581 public override bool IsZeroInteger {
1582 get { return Child.IsZeroInteger; }
1587 /// This kind of cast is used to encapsulate Value Types in objects.
1589 /// The effect of it is to box the value type emitted by the previous
1592 public class BoxedCast : EmptyCast {
1594 public BoxedCast (Expression expr)
1595 : base (expr, TypeManager.object_type)
1597 eclass = ExprClass.Value;
1600 public BoxedCast (Expression expr, Type target_type)
1601 : base (expr, target_type)
1603 eclass = ExprClass.Value;
1606 public override Expression DoResolve (EmitContext ec)
1608 // This should never be invoked, we are born in fully
1609 // initialized state.
1614 public override void Emit (EmitContext ec)
1618 ec.ig.Emit (OpCodes.Box, child.Type);
1622 public class UnboxCast : EmptyCast {
1623 public UnboxCast (Expression expr, Type return_type)
1624 : base (expr, return_type)
1628 public override Expression DoResolve (EmitContext ec)
1630 // This should never be invoked, we are born in fully
1631 // initialized state.
1636 public override void Emit (EmitContext ec)
1639 ILGenerator ig = ec.ig;
1642 if (t.IsGenericParameter)
1643 ig.Emit (OpCodes.Unbox_Any, t);
1645 ig.Emit (OpCodes.Unbox, t);
1647 LoadFromPtr (ig, t);
1653 /// This is used to perform explicit numeric conversions.
1655 /// Explicit numeric conversions might trigger exceptions in a checked
1656 /// context, so they should generate the conv.ovf opcodes instead of
1659 public class ConvCast : EmptyCast {
1660 public enum Mode : byte {
1661 I1_U1, I1_U2, I1_U4, I1_U8, I1_CH,
1663 I2_I1, I2_U1, I2_U2, I2_U4, I2_U8, I2_CH,
1664 U2_I1, U2_U1, U2_I2, U2_CH,
1665 I4_I1, I4_U1, I4_I2, I4_U2, I4_U4, I4_U8, I4_CH,
1666 U4_I1, U4_U1, U4_I2, U4_U2, U4_I4, U4_CH,
1667 I8_I1, I8_U1, I8_I2, I8_U2, I8_I4, I8_U4, I8_U8, I8_CH,
1668 U8_I1, U8_U1, U8_I2, U8_U2, U8_I4, U8_U4, U8_I8, U8_CH,
1669 CH_I1, CH_U1, CH_I2,
1670 R4_I1, R4_U1, R4_I2, R4_U2, R4_I4, R4_U4, R4_I8, R4_U8, R4_CH,
1671 R8_I1, R8_U1, R8_I2, R8_U2, R8_I4, R8_U4, R8_I8, R8_U8, R8_CH, R8_R4
1677 public ConvCast (EmitContext ec, Expression child, Type return_type, Mode m)
1678 : base (child, return_type)
1680 checked_state = ec.CheckState;
1684 public override Expression DoResolve (EmitContext ec)
1686 // This should never be invoked, we are born in fully
1687 // initialized state.
1692 public override string ToString ()
1694 return String.Format ("ConvCast ({0}, {1})", mode, child);
1697 public override void Emit (EmitContext ec)
1699 ILGenerator ig = ec.ig;
1705 case Mode.I1_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1706 case Mode.I1_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1707 case Mode.I1_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1708 case Mode.I1_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1709 case Mode.I1_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1711 case Mode.U1_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1712 case Mode.U1_CH: /* nothing */ break;
1714 case Mode.I2_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1715 case Mode.I2_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1716 case Mode.I2_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1717 case Mode.I2_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1718 case Mode.I2_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1719 case Mode.I2_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1721 case Mode.U2_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1722 case Mode.U2_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
1723 case Mode.U2_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
1724 case Mode.U2_CH: /* nothing */ break;
1726 case Mode.I4_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1727 case Mode.I4_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1728 case Mode.I4_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
1729 case Mode.I4_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1730 case Mode.I4_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1731 case Mode.I4_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1732 case Mode.I4_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1734 case Mode.U4_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1735 case Mode.U4_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
1736 case Mode.U4_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
1737 case Mode.U4_U2: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
1738 case Mode.U4_I4: ig.Emit (OpCodes.Conv_Ovf_I4_Un); break;
1739 case Mode.U4_CH: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
1741 case Mode.I8_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1742 case Mode.I8_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1743 case Mode.I8_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
1744 case Mode.I8_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1745 case Mode.I8_I4: ig.Emit (OpCodes.Conv_Ovf_I4); break;
1746 case Mode.I8_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1747 case Mode.I8_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1748 case Mode.I8_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1750 case Mode.U8_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1751 case Mode.U8_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
1752 case Mode.U8_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
1753 case Mode.U8_U2: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
1754 case Mode.U8_I4: ig.Emit (OpCodes.Conv_Ovf_I4_Un); break;
1755 case Mode.U8_U4: ig.Emit (OpCodes.Conv_Ovf_U4_Un); break;
1756 case Mode.U8_I8: ig.Emit (OpCodes.Conv_Ovf_I8_Un); break;
1757 case Mode.U8_CH: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
1759 case Mode.CH_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1760 case Mode.CH_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
1761 case Mode.CH_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
1763 case Mode.R4_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1764 case Mode.R4_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1765 case Mode.R4_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
1766 case Mode.R4_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1767 case Mode.R4_I4: ig.Emit (OpCodes.Conv_Ovf_I4); break;
1768 case Mode.R4_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1769 case Mode.R4_I8: ig.Emit (OpCodes.Conv_Ovf_I8); break;
1770 case Mode.R4_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1771 case Mode.R4_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1773 case Mode.R8_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1774 case Mode.R8_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1775 case Mode.R8_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
1776 case Mode.R8_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1777 case Mode.R8_I4: ig.Emit (OpCodes.Conv_Ovf_I4); break;
1778 case Mode.R8_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1779 case Mode.R8_I8: ig.Emit (OpCodes.Conv_Ovf_I8); break;
1780 case Mode.R8_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1781 case Mode.R8_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1782 case Mode.R8_R4: ig.Emit (OpCodes.Conv_R4); break;
1786 case Mode.I1_U1: ig.Emit (OpCodes.Conv_U1); break;
1787 case Mode.I1_U2: ig.Emit (OpCodes.Conv_U2); break;
1788 case Mode.I1_U4: ig.Emit (OpCodes.Conv_U4); break;
1789 case Mode.I1_U8: ig.Emit (OpCodes.Conv_I8); break;
1790 case Mode.I1_CH: ig.Emit (OpCodes.Conv_U2); break;
1792 case Mode.U1_I1: ig.Emit (OpCodes.Conv_I1); break;
1793 case Mode.U1_CH: ig.Emit (OpCodes.Conv_U2); break;
1795 case Mode.I2_I1: ig.Emit (OpCodes.Conv_I1); break;
1796 case Mode.I2_U1: ig.Emit (OpCodes.Conv_U1); break;
1797 case Mode.I2_U2: ig.Emit (OpCodes.Conv_U2); break;
1798 case Mode.I2_U4: ig.Emit (OpCodes.Conv_U4); break;
1799 case Mode.I2_U8: ig.Emit (OpCodes.Conv_I8); break;
1800 case Mode.I2_CH: ig.Emit (OpCodes.Conv_U2); break;
1802 case Mode.U2_I1: ig.Emit (OpCodes.Conv_I1); break;
1803 case Mode.U2_U1: ig.Emit (OpCodes.Conv_U1); break;
1804 case Mode.U2_I2: ig.Emit (OpCodes.Conv_I2); break;
1805 case Mode.U2_CH: /* nothing */ break;
1807 case Mode.I4_I1: ig.Emit (OpCodes.Conv_I1); break;
1808 case Mode.I4_U1: ig.Emit (OpCodes.Conv_U1); break;
1809 case Mode.I4_I2: ig.Emit (OpCodes.Conv_I2); break;
1810 case Mode.I4_U4: /* nothing */ break;
1811 case Mode.I4_U2: ig.Emit (OpCodes.Conv_U2); break;
1812 case Mode.I4_U8: ig.Emit (OpCodes.Conv_I8); break;
1813 case Mode.I4_CH: ig.Emit (OpCodes.Conv_U2); break;
1815 case Mode.U4_I1: ig.Emit (OpCodes.Conv_I1); break;
1816 case Mode.U4_U1: ig.Emit (OpCodes.Conv_U1); break;
1817 case Mode.U4_I2: ig.Emit (OpCodes.Conv_I2); break;
1818 case Mode.U4_U2: ig.Emit (OpCodes.Conv_U2); break;
1819 case Mode.U4_I4: /* nothing */ break;
1820 case Mode.U4_CH: ig.Emit (OpCodes.Conv_U2); break;
1822 case Mode.I8_I1: ig.Emit (OpCodes.Conv_I1); break;
1823 case Mode.I8_U1: ig.Emit (OpCodes.Conv_U1); break;
1824 case Mode.I8_I2: ig.Emit (OpCodes.Conv_I2); break;
1825 case Mode.I8_U2: ig.Emit (OpCodes.Conv_U2); break;
1826 case Mode.I8_I4: ig.Emit (OpCodes.Conv_I4); break;
1827 case Mode.I8_U4: ig.Emit (OpCodes.Conv_U4); break;
1828 case Mode.I8_U8: /* nothing */ break;
1829 case Mode.I8_CH: ig.Emit (OpCodes.Conv_U2); break;
1831 case Mode.U8_I1: ig.Emit (OpCodes.Conv_I1); break;
1832 case Mode.U8_U1: ig.Emit (OpCodes.Conv_U1); break;
1833 case Mode.U8_I2: ig.Emit (OpCodes.Conv_I2); break;
1834 case Mode.U8_U2: ig.Emit (OpCodes.Conv_U2); break;
1835 case Mode.U8_I4: ig.Emit (OpCodes.Conv_I4); break;
1836 case Mode.U8_U4: ig.Emit (OpCodes.Conv_U4); break;
1837 case Mode.U8_I8: /* nothing */ break;
1838 case Mode.U8_CH: ig.Emit (OpCodes.Conv_U2); break;
1840 case Mode.CH_I1: ig.Emit (OpCodes.Conv_I1); break;
1841 case Mode.CH_U1: ig.Emit (OpCodes.Conv_U1); break;
1842 case Mode.CH_I2: ig.Emit (OpCodes.Conv_I2); break;
1844 case Mode.R4_I1: ig.Emit (OpCodes.Conv_I1); break;
1845 case Mode.R4_U1: ig.Emit (OpCodes.Conv_U1); break;
1846 case Mode.R4_I2: ig.Emit (OpCodes.Conv_I2); break;
1847 case Mode.R4_U2: ig.Emit (OpCodes.Conv_U2); break;
1848 case Mode.R4_I4: ig.Emit (OpCodes.Conv_I4); break;
1849 case Mode.R4_U4: ig.Emit (OpCodes.Conv_U4); break;
1850 case Mode.R4_I8: ig.Emit (OpCodes.Conv_I8); break;
1851 case Mode.R4_U8: ig.Emit (OpCodes.Conv_U8); break;
1852 case Mode.R4_CH: ig.Emit (OpCodes.Conv_U2); break;
1854 case Mode.R8_I1: ig.Emit (OpCodes.Conv_I1); break;
1855 case Mode.R8_U1: ig.Emit (OpCodes.Conv_U1); break;
1856 case Mode.R8_I2: ig.Emit (OpCodes.Conv_I2); break;
1857 case Mode.R8_U2: ig.Emit (OpCodes.Conv_U2); break;
1858 case Mode.R8_I4: ig.Emit (OpCodes.Conv_I4); break;
1859 case Mode.R8_U4: ig.Emit (OpCodes.Conv_U4); break;
1860 case Mode.R8_I8: ig.Emit (OpCodes.Conv_I8); break;
1861 case Mode.R8_U8: ig.Emit (OpCodes.Conv_U8); break;
1862 case Mode.R8_CH: ig.Emit (OpCodes.Conv_U2); break;
1863 case Mode.R8_R4: ig.Emit (OpCodes.Conv_R4); break;
1869 public class OpcodeCast : EmptyCast {
1873 public OpcodeCast (Expression child, Type return_type, OpCode op)
1874 : base (child, return_type)
1878 second_valid = false;
1881 public OpcodeCast (Expression child, Type return_type, OpCode op, OpCode op2)
1882 : base (child, return_type)
1887 second_valid = true;
1890 public override Expression DoResolve (EmitContext ec)
1892 // This should never be invoked, we are born in fully
1893 // initialized state.
1898 public override void Emit (EmitContext ec)
1909 /// This kind of cast is used to encapsulate a child and cast it
1910 /// to the class requested
1912 public class ClassCast : EmptyCast {
1913 public ClassCast (Expression child, Type return_type)
1914 : base (child, return_type)
1919 public override Expression DoResolve (EmitContext ec)
1921 // This should never be invoked, we are born in fully
1922 // initialized state.
1927 public override void Emit (EmitContext ec)
1931 if (child.Type.IsGenericParameter)
1932 ec.ig.Emit (OpCodes.Box, child.Type);
1934 if (type.IsGenericParameter)
1935 ec.ig.Emit (OpCodes.Unbox_Any, type);
1937 ec.ig.Emit (OpCodes.Castclass, type);
1942 /// SimpleName expressions are initially formed of a single
1943 /// word and it only happens at the beginning of the expression.
1947 /// The expression will try to be bound to a Field, a Method
1948 /// group or a Property. If those fail we pass the name to our
1949 /// caller and the SimpleName is compounded to perform a type
1950 /// lookup. The idea behind this process is that we want to avoid
1951 /// creating a namespace map from the assemblies, as that requires
1952 /// the GetExportedTypes function to be called and a hashtable to
1953 /// be constructed which reduces startup time. If later we find
1954 /// that this is slower, we should create a `NamespaceExpr' expression
1955 /// that fully participates in the resolution process.
1957 /// For example `System.Console.WriteLine' is decomposed into
1958 /// MemberAccess (MemberAccess (SimpleName ("System"), "Console"), "WriteLine")
1960 /// The first SimpleName wont produce a match on its own, so it will
1962 /// MemberAccess (SimpleName ("System.Console"), "WriteLine").
1964 /// System.Console will produce a TypeExpr match.
1966 /// The downside of this is that we might be hitting `LookupType' too many
1967 /// times with this scheme.
1969 public class SimpleName : Expression {
1971 public readonly TypeArguments Arguments;
1974 // If true, then we are a simple name, not composed with a ".
1978 public SimpleName (string a, string b, Location l)
1980 Name = String.Concat (a, ".", b);
1985 public SimpleName (string name, Location l)
1992 public SimpleName (string name, TypeArguments args, Location l)
2000 public static void Error_ObjectRefRequired (EmitContext ec, Location l, string name)
2002 if (ec.IsFieldInitializer)
2005 "A field initializer cannot reference the non-static field, " +
2006 "method or property `"+name+"'");
2010 "An object reference is required " +
2011 "for the non-static field `"+name+"'");
2015 // Checks whether we are trying to access an instance
2016 // property, method or field from a static body.
2018 Expression MemberStaticCheck (EmitContext ec, Expression e)
2020 if (e is IMemberExpr){
2021 IMemberExpr member = (IMemberExpr) e;
2023 if (!member.IsStatic){
2024 Error_ObjectRefRequired (ec, loc, Name);
2032 public override Expression DoResolve (EmitContext ec)
2034 return SimpleNameResolve (ec, null, false, false);
2037 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
2039 return SimpleNameResolve (ec, right_side, false, false);
2043 public Expression DoResolveAllowStatic (EmitContext ec, bool intermediate)
2045 return SimpleNameResolve (ec, null, true, intermediate);
2048 public override Expression ResolveAsTypeStep (EmitContext ec)
2050 DeclSpace ds = ec.DeclSpace;
2051 NamespaceEntry ns = ds.NamespaceEntry;
2056 // Since we are cheating: we only do the Alias lookup for
2057 // namespaces if the name does not include any dots in it
2059 if (ns != null && is_base)
2060 alias_value = ns.LookupAlias (Name);
2064 TypeParameterExpr generic_type = ds.LookupGeneric (Name, loc);
2065 if (generic_type != null)
2066 return generic_type.ResolveAsTypeTerminal (ec);
2068 if (ec.ResolvingTypeTree){
2069 int errors = Report.Errors;
2070 Type dt = ds.FindType (loc, Name);
2072 if (Report.Errors != errors)
2076 return new TypeExpression (dt, loc);
2078 if (alias_value != null){
2079 if (alias_value.IsType)
2080 return alias_value.Type;
2081 if ((t = RootContext.LookupType (ds, alias_value.Name, true, loc)) != null)
2087 // First, the using aliases
2089 if (alias_value != null){
2090 if (alias_value.IsType)
2091 return alias_value.Type;
2092 if ((t = RootContext.LookupType (ds, alias_value.Name, true, loc)) != null)
2095 // we have alias value, but it isn't Type, so try if it's namespace
2096 return new SimpleName (alias_value.Name, loc);
2100 // Stage 2: Lookup up if we are an alias to a type
2104 if ((t = RootContext.LookupType (ds, Name, true, loc)) != null)
2107 // No match, maybe our parent can compose us
2108 // into something meaningful.
2112 Expression SimpleNameResolve (EmitContext ec, Expression right_side,
2113 bool allow_static, bool intermediate)
2115 Expression e = DoSimpleNameResolve (ec, right_side, allow_static, intermediate);
2119 Block current_block = ec.CurrentBlock;
2120 if (current_block != null){
2121 LocalInfo vi = current_block.GetLocalInfo (Name);
2123 current_block.IsVariableNameUsedInChildBlock(Name)) {
2124 Report.Error (135, Location,
2125 "'{0}' has a different meaning in a " +
2126 "child block", Name);
2131 if (e.Type != null && e.Type.IsPointer && !ec.InUnsafe) {
2140 /// 7.5.2: Simple Names.
2142 /// Local Variables and Parameters are handled at
2143 /// parse time, so they never occur as SimpleNames.
2145 /// The `allow_static' flag is used by MemberAccess only
2146 /// and it is used to inform us that it is ok for us to
2147 /// avoid the static check, because MemberAccess might end
2148 /// up resolving the Name as a Type name and the access as
2149 /// a static type access.
2151 /// ie: Type Type; .... { Type.GetType (""); }
2153 /// Type is both an instance variable and a Type; Type.GetType
2154 /// is the static method not an instance method of type.
2156 Expression DoSimpleNameResolve (EmitContext ec, Expression right_side, bool allow_static, bool intermediate)
2158 Expression e = null;
2161 // Stage 1: Performed by the parser (binding to locals or parameters).
2163 Block current_block = ec.CurrentBlock;
2164 if (current_block != null){
2165 LocalInfo vi = current_block.GetLocalInfo (Name);
2169 var = new LocalVariableReference (ec.CurrentBlock, Name, loc);
2171 if (right_side != null)
2172 return var.ResolveLValue (ec, right_side);
2174 return var.Resolve (ec);
2178 Parameter par = null;
2179 Parameters pars = current_block.Parameters;
2181 par = pars.GetParameterByName (Name, out idx);
2184 ParameterReference param;
2186 param = new ParameterReference (pars, current_block, idx, Name, loc);
2188 if (right_side != null)
2189 return param.ResolveLValue (ec, right_side);
2191 return param.Resolve (ec);
2196 // Stage 2: Lookup members
2199 DeclSpace lookup_ds = ec.DeclSpace;
2201 if (lookup_ds.TypeBuilder == null)
2204 e = MemberLookup (ec, lookup_ds.TypeBuilder, Name, loc);
2208 lookup_ds =lookup_ds.Parent;
2209 } while (lookup_ds != null);
2211 if (e == null && ec.ContainerType != null)
2212 e = MemberLookup (ec, ec.ContainerType, Name, loc);
2216 // Since we are cheating (is_base is our hint
2217 // that we are the beginning of the name): we
2218 // only do the Alias lookup for namespaces if
2219 // the name does not include any dots in it
2221 NamespaceEntry ns = ec.DeclSpace.NamespaceEntry;
2222 if (is_base && ns != null){
2223 IAlias alias_value = ns.LookupAlias (Name);
2224 if (alias_value != null){
2225 if (alias_value.IsType)
2226 return alias_value.Type;
2228 Name = alias_value.Name;
2231 if ((t = TypeManager.LookupType (Name)) != null)
2232 return new TypeExpression (t, loc);
2234 // No match, maybe our parent can compose us
2235 // into something meaningful.
2240 return ResolveAsTypeStep (ec);
2246 if (e is IMemberExpr) {
2247 e = MemberAccess.ResolveMemberAccess (ec, e, null, loc, this);
2251 IMemberExpr me = e as IMemberExpr;
2255 if (Arguments != null) {
2256 MethodGroupExpr mg = me as MethodGroupExpr;
2260 return mg.ResolveGeneric (ec, Arguments);
2263 // This fails if ResolveMemberAccess() was unable to decide whether
2264 // it's a field or a type of the same name.
2266 if (!me.IsStatic && (me.InstanceExpression == null))
2270 TypeManager.IsNestedChildOf (me.InstanceExpression.Type, me.DeclaringType) &&
2271 !me.InstanceExpression.Type.IsSubclassOf (me.DeclaringType) &&
2272 (!intermediate || !MemberAccess.IdenticalNameAndTypeName (ec, this, e, loc))) {
2273 Error (38, "Cannot access nonstatic member `" + me.Name + "' of " +
2274 "outer type `" + me.DeclaringType + "' via nested type `" +
2275 me.InstanceExpression.Type + "'");
2279 return (right_side != null)
2280 ? e.DoResolveLValue (ec, right_side)
2284 if (ec.IsStatic || ec.IsFieldInitializer){
2288 return MemberStaticCheck (ec, e);
2293 public override void Emit (EmitContext ec)
2296 // If this is ever reached, then we failed to
2297 // find the name as a namespace
2300 Error (103, "The name `" + Name +
2301 "' does not exist in the class `" +
2302 ec.DeclSpace.Name + "'");
2305 public override string ToString ()
2312 /// Fully resolved expression that evaluates to a type
2314 public abstract class TypeExpr : Expression, IAlias {
2315 override public Expression ResolveAsTypeStep (EmitContext ec)
2317 TypeExpr t = DoResolveAsTypeStep (ec);
2321 eclass = ExprClass.Type;
2325 override public Expression DoResolve (EmitContext ec)
2327 return ResolveAsTypeTerminal (ec);
2330 override public void Emit (EmitContext ec)
2332 throw new Exception ("Should never be called");
2335 public virtual bool CheckAccessLevel (DeclSpace ds)
2337 return ds.CheckAccessLevel (Type);
2340 public virtual bool AsAccessible (DeclSpace ds, int flags)
2342 return ds.AsAccessible (Type, flags);
2345 public virtual bool IsClass {
2346 get { return Type.IsClass; }
2349 public virtual bool IsValueType {
2350 get { return Type.IsValueType; }
2353 public virtual bool IsInterface {
2354 get { return Type.IsInterface; }
2357 public virtual bool IsSealed {
2358 get { return Type.IsSealed; }
2361 public virtual bool CanInheritFrom ()
2363 if (Type == TypeManager.enum_type ||
2364 (Type == TypeManager.value_type && RootContext.StdLib) ||
2365 Type == TypeManager.multicast_delegate_type ||
2366 Type == TypeManager.delegate_type ||
2367 Type == TypeManager.array_type)
2373 public virtual bool IsAttribute {
2375 return Type == TypeManager.attribute_type ||
2376 Type.IsSubclassOf (TypeManager.attribute_type);
2380 public virtual TypeExpr[] GetInterfaces ()
2382 return TypeManager.GetInterfaces (Type);
2385 public abstract TypeExpr DoResolveAsTypeStep (EmitContext ec);
2387 public virtual Type ResolveType (EmitContext ec)
2389 TypeExpr t = ResolveAsTypeTerminal (ec);
2396 public abstract string Name {
2400 public override bool Equals (object obj)
2402 TypeExpr tobj = obj as TypeExpr;
2406 return Type == tobj.Type;
2409 public override int GetHashCode ()
2411 return Type.GetHashCode ();
2414 public override string ToString ()
2419 bool IAlias.IsType {
2420 get { return true; }
2423 TypeExpr IAlias.Type {
2430 public class TypeExpression : TypeExpr, IAlias {
2431 public TypeExpression (Type t, Location l)
2434 eclass = ExprClass.Type;
2438 public override TypeExpr DoResolveAsTypeStep (EmitContext ec)
2443 public override string Name {
2445 return Type.ToString ();
2449 string IAlias.Name {
2451 return Type.FullName != null ? Type.FullName : Type.Name;
2457 /// Used to create types from a fully qualified name. These are just used
2458 /// by the parser to setup the core types. A TypeLookupExpression is always
2459 /// classified as a type.
2461 public class TypeLookupExpression : TypeExpr {
2464 public TypeLookupExpression (string name)
2469 public override TypeExpr DoResolveAsTypeStep (EmitContext ec)
2472 TypeExpr texpr = RootContext.LookupType (
2473 ec.DeclSpace, name, false, Location.Null);
2477 type = texpr.ResolveType (ec);
2485 public override string Name {
2492 public class TypeAliasExpression : TypeExpr, IAlias {
2497 public TypeAliasExpression (TypeExpr texpr, TypeArguments args, Location l)
2501 loc = texpr.Location;
2503 eclass = ExprClass.Type;
2505 name = texpr.Name + "<" + args.ToString () + ">";
2510 public override string Name {
2511 get { return name; }
2514 public override TypeExpr DoResolveAsTypeStep (EmitContext ec)
2516 Type type = texpr.ResolveType (ec);
2520 int num_args = TypeManager.GetNumberOfTypeArguments (type);
2523 if (num_args == 0) {
2524 Report.Error (308, loc,
2525 "The non-generic type `{0}' cannot " +
2526 "be used with type arguments.",
2527 TypeManager.CSharpName (type));
2531 ConstructedType ctype = new ConstructedType (type, args, loc);
2532 return ctype.ResolveAsTypeTerminal (ec);
2533 } else if (num_args > 0) {
2534 Report.Error (305, loc,
2535 "Using the generic type `{0}' " +
2536 "requires {1} type arguments",
2537 TypeManager.GetFullName (type), num_args);
2541 return new TypeExpression (type, loc);
2544 public override Type ResolveType (EmitContext ec)
2546 TypeExpr t = ResolveAsTypeTerminal (ec);
2550 type = t.ResolveType (ec);
2554 public override bool CheckAccessLevel (DeclSpace ds)
2556 return texpr.CheckAccessLevel (ds);
2559 public override bool AsAccessible (DeclSpace ds, int flags)
2561 return texpr.AsAccessible (ds, flags);
2564 public override bool IsClass {
2565 get { return texpr.IsClass; }
2568 public override bool IsValueType {
2569 get { return texpr.IsValueType; }
2572 public override bool IsInterface {
2573 get { return texpr.IsInterface; }
2576 public override bool IsSealed {
2577 get { return texpr.IsSealed; }
2580 public override bool IsAttribute {
2581 get { return texpr.IsAttribute; }
2586 /// MethodGroup Expression.
2588 /// This is a fully resolved expression that evaluates to a type
2590 public class MethodGroupExpr : Expression, IMemberExpr {
2591 public MethodBase [] Methods;
2592 Expression instance_expression = null;
2593 bool is_explicit_impl = false;
2594 bool has_type_arguments = false;
2595 bool identical_type_name = false;
2597 public MethodGroupExpr (MemberInfo [] mi, Location l)
2599 Methods = new MethodBase [mi.Length];
2600 mi.CopyTo (Methods, 0);
2601 eclass = ExprClass.MethodGroup;
2602 type = TypeManager.object_type;
2606 public MethodGroupExpr (ArrayList list, Location l)
2608 Methods = new MethodBase [list.Count];
2611 list.CopyTo (Methods, 0);
2613 foreach (MemberInfo m in list){
2614 if (!(m is MethodBase)){
2615 Console.WriteLine ("Name " + m.Name);
2616 Console.WriteLine ("Found a: " + m.GetType ().FullName);
2623 eclass = ExprClass.MethodGroup;
2624 type = TypeManager.object_type;
2627 public Type DeclaringType {
2630 // We assume that the top-level type is in the end
2632 return Methods [Methods.Length - 1].DeclaringType;
2633 //return Methods [0].DeclaringType;
2638 // `A method group may have associated an instance expression'
2640 public Expression InstanceExpression {
2642 return instance_expression;
2646 instance_expression = value;
2650 public bool IsExplicitImpl {
2652 return is_explicit_impl;
2656 is_explicit_impl = value;
2660 public bool HasTypeArguments {
2662 return has_type_arguments;
2666 has_type_arguments = value;
2670 public bool IdenticalTypeName {
2672 return identical_type_name;
2676 identical_type_name = value;
2680 public string Name {
2682 //return Methods [0].Name;
2683 return Methods [Methods.Length - 1].Name;
2687 public bool IsInstance {
2689 foreach (MethodBase mb in Methods)
2697 public bool IsStatic {
2699 foreach (MethodBase mb in Methods)
2707 override public Expression DoResolve (EmitContext ec)
2710 instance_expression = null;
2712 if (instance_expression != null) {
2713 instance_expression = instance_expression.DoResolve (ec);
2714 if (instance_expression == null)
2721 public void ReportUsageError ()
2723 Report.Error (654, loc, "Method `" + DeclaringType + "." +
2724 Name + "()' is referenced without parentheses");
2727 override public void Emit (EmitContext ec)
2729 ReportUsageError ();
2732 bool RemoveMethods (bool keep_static)
2734 ArrayList smethods = new ArrayList ();
2736 foreach (MethodBase mb in Methods){
2737 if (mb.IsStatic == keep_static)
2741 if (smethods.Count == 0)
2744 Methods = new MethodBase [smethods.Count];
2745 smethods.CopyTo (Methods, 0);
2751 /// Removes any instance methods from the MethodGroup, returns
2752 /// false if the resulting set is empty.
2754 public bool RemoveInstanceMethods ()
2756 return RemoveMethods (true);
2760 /// Removes any static methods from the MethodGroup, returns
2761 /// false if the resulting set is empty.
2763 public bool RemoveStaticMethods ()
2765 return RemoveMethods (false);
2768 public Expression ResolveGeneric (EmitContext ec, TypeArguments args)
2770 if (args.Resolve (ec) == false)
2773 Type[] atypes = args.Arguments;
2775 int first_count = 0;
2776 MethodInfo first = null;
2778 ArrayList list = new ArrayList ();
2779 foreach (MethodBase mb in Methods) {
2780 MethodInfo mi = mb as MethodInfo;
2781 if ((mi == null) || !mi.HasGenericParameters)
2784 Type[] gen_params = mi.GetGenericArguments ();
2786 if (first == null) {
2788 first_count = gen_params.Length;
2791 if (gen_params.Length != atypes.Length)
2794 list.Add (mi.BindGenericParameters (atypes));
2797 if (list.Count > 0) {
2798 MethodGroupExpr new_mg = new MethodGroupExpr (list, Location);
2799 new_mg.InstanceExpression = InstanceExpression;
2800 new_mg.HasTypeArguments = true;
2806 305, loc, "Using the generic method `{0}' " +
2807 "requires {1} type arguments", Name,
2811 308, loc, "The non-generic method `{0}' " +
2812 "cannot be used with type arguments", Name);
2819 /// Fully resolved expression that evaluates to a Field
2821 public class FieldExpr : Expression, IAssignMethod, IMemoryLocation, IMemberExpr, IVariable {
2822 public readonly FieldInfo FieldInfo;
2823 Expression instance_expr;
2824 VariableInfo variable_info;
2826 LocalTemporary temporary;
2827 IMemoryLocation instance_ml;
2828 bool have_temporary;
2830 public FieldExpr (FieldInfo fi, Location l)
2833 eclass = ExprClass.Variable;
2834 type = TypeManager.TypeToCoreType (fi.FieldType);
2838 public string Name {
2840 return FieldInfo.Name;
2844 public bool IsInstance {
2846 return !FieldInfo.IsStatic;
2850 public bool IsStatic {
2852 return FieldInfo.IsStatic;
2856 public Type DeclaringType {
2858 return FieldInfo.DeclaringType;
2862 public Expression InstanceExpression {
2864 return instance_expr;
2868 instance_expr = value;
2872 public VariableInfo VariableInfo {
2874 return variable_info;
2878 override public Expression DoResolve (EmitContext ec)
2880 if (!FieldInfo.IsStatic){
2881 if (instance_expr == null){
2883 // This can happen when referencing an instance field using
2884 // a fully qualified type expression: TypeName.InstanceField = xxx
2886 SimpleName.Error_ObjectRefRequired (ec, loc, FieldInfo.Name);
2890 // Resolve the field's instance expression while flow analysis is turned
2891 // off: when accessing a field "a.b", we must check whether the field
2892 // "a.b" is initialized, not whether the whole struct "a" is initialized.
2893 instance_expr = instance_expr.Resolve (ec, ResolveFlags.VariableOrValue |
2894 ResolveFlags.DisableFlowAnalysis);
2895 if (instance_expr == null)
2899 ObsoleteAttribute oa;
2900 FieldBase f = TypeManager.GetField (FieldInfo);
2902 oa = f.GetObsoleteAttribute (ec.DeclSpace);
2904 AttributeTester.Report_ObsoleteMessage (oa, f.GetSignatureForError (), loc);
2905 // To be sure that type is external because we do not register generated fields
2906 } else if (!(FieldInfo.DeclaringType is TypeBuilder)) {
2907 oa = AttributeTester.GetMemberObsoleteAttribute (FieldInfo);
2909 AttributeTester.Report_ObsoleteMessage (oa, TypeManager.GetFullNameSignature (FieldInfo), loc);
2912 // If the instance expression is a local variable or parameter.
2913 IVariable var = instance_expr as IVariable;
2914 if ((var == null) || (var.VariableInfo == null))
2917 VariableInfo vi = var.VariableInfo;
2918 if (!vi.IsFieldAssigned (ec, FieldInfo.Name, loc))
2921 variable_info = vi.GetSubStruct (FieldInfo.Name);
2925 void Report_AssignToReadonly (bool is_instance)
2930 msg = "Readonly field can not be assigned outside " +
2931 "of constructor or variable initializer";
2933 msg = "A static readonly field can only be assigned in " +
2934 "a static constructor";
2936 Report.Error (is_instance ? 191 : 198, loc, msg);
2939 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
2941 IVariable var = instance_expr as IVariable;
2942 if ((var != null) && (var.VariableInfo != null))
2943 var.VariableInfo.SetFieldAssigned (ec, FieldInfo.Name);
2945 Expression e = DoResolve (ec);
2950 if (!FieldInfo.IsStatic && (instance_expr.Type.IsValueType && !(instance_expr is IMemoryLocation))) {
2951 // FIXME: Provide better error reporting.
2952 Error (1612, "Cannot modify expression because it is not a variable.");
2956 if (!FieldInfo.IsInitOnly)
2959 FieldBase fb = TypeManager.GetField (FieldInfo);
2964 // InitOnly fields can only be assigned in constructors
2967 if (ec.IsConstructor){
2968 if (IsStatic && !ec.IsStatic)
2969 Report_AssignToReadonly (false);
2972 if (ec.TypeContainer.CurrentType != null)
2973 ctype = ec.TypeContainer.CurrentType.ResolveType (ec);
2975 ctype = ec.ContainerType;
2977 if (TypeManager.IsEqual (ctype, FieldInfo.DeclaringType))
2981 Report_AssignToReadonly (true);
2986 public bool VerifyFixed (bool is_expression)
2988 IVariable variable = instance_expr as IVariable;
2989 if ((variable == null) || !variable.VerifyFixed (true))
2995 public override void CacheTemporaries (EmitContext ec)
2997 if (!FieldInfo.IsStatic && (temporary == null))
2998 temporary = new LocalTemporary (ec, instance_expr.Type);
3001 void EmitInstance (EmitContext ec)
3003 if (instance_expr.Type.IsValueType)
3004 CacheTemporaries (ec);
3006 if ((temporary == null) || have_temporary)
3009 if (instance_expr.Type.IsValueType) {
3010 instance_ml = instance_expr as IMemoryLocation;
3011 if (instance_ml == null) {
3012 instance_expr.Emit (ec);
3013 temporary.Store (ec);
3014 instance_ml = temporary;
3017 instance_expr.Emit (ec);
3018 temporary.Store (ec);
3021 have_temporary = true;
3024 override public void Emit (EmitContext ec)
3026 ILGenerator ig = ec.ig;
3027 bool is_volatile = false;
3029 if (FieldInfo is FieldBuilder){
3030 FieldBase f = TypeManager.GetField (FieldInfo);
3032 if ((f.ModFlags & Modifiers.VOLATILE) != 0)
3035 f.status |= Field.Status.USED;
3039 if (FieldInfo.IsStatic){
3041 ig.Emit (OpCodes.Volatile);
3043 ig.Emit (OpCodes.Ldsfld, FieldInfo);
3048 if (instance_ml != null)
3049 instance_ml.AddressOf (ec, AddressOp.Load);
3050 else if (temporary != null)
3051 temporary.Emit (ec);
3053 instance_expr.Emit (ec);
3056 ig.Emit (OpCodes.Volatile);
3058 ig.Emit (OpCodes.Ldfld, FieldInfo);
3061 public void EmitAssign (EmitContext ec, Expression source)
3063 FieldAttributes fa = FieldInfo.Attributes;
3064 bool is_static = (fa & FieldAttributes.Static) != 0;
3065 bool is_readonly = (fa & FieldAttributes.InitOnly) != 0;
3066 ILGenerator ig = ec.ig;
3068 if (is_readonly && !ec.IsConstructor){
3069 Report_AssignToReadonly (!is_static);
3075 if (instance_ml != null)
3076 instance_ml.AddressOf (ec, AddressOp.Store);
3077 else if (temporary != null)
3078 temporary.Emit (ec);
3080 instance_expr.Emit (ec);
3085 if (FieldInfo is FieldBuilder){
3086 FieldBase f = TypeManager.GetField (FieldInfo);
3088 if ((f.ModFlags & Modifiers.VOLATILE) != 0)
3089 ig.Emit (OpCodes.Volatile);
3091 f.status |= Field.Status.ASSIGNED;
3096 ig.Emit (OpCodes.Stsfld, FieldInfo);
3098 ig.Emit (OpCodes.Stfld, FieldInfo);
3101 public void AddressOf (EmitContext ec, AddressOp mode)
3103 ILGenerator ig = ec.ig;
3105 if (FieldInfo is FieldBuilder){
3106 FieldBase f = TypeManager.GetField (FieldInfo);
3108 if ((f.ModFlags & Modifiers.VOLATILE) != 0){
3109 Error (676, "volatile variable: can not take its address, or pass as ref/out parameter");
3113 if ((mode & AddressOp.Store) != 0)
3114 f.status |= Field.Status.ASSIGNED;
3115 if ((mode & AddressOp.Load) != 0)
3116 f.status |= Field.Status.USED;
3121 // Handle initonly fields specially: make a copy and then
3122 // get the address of the copy.
3125 if (FieldInfo.IsInitOnly){
3127 if (ec.IsConstructor){
3128 if (FieldInfo.IsStatic){
3140 local = ig.DeclareLocal (type);
3141 ig.Emit (OpCodes.Stloc, local);
3142 ig.Emit (OpCodes.Ldloca, local);
3147 if (FieldInfo.IsStatic){
3148 ig.Emit (OpCodes.Ldsflda, FieldInfo);
3151 // In the case of `This', we call the AddressOf method, which will
3152 // only load the pointer, and not perform an Ldobj immediately after
3153 // the value has been loaded into the stack.
3156 if (instance_ml != null)
3157 instance_ml.AddressOf (ec, AddressOp.LoadStore);
3158 else if (temporary != null)
3159 temporary.Emit (ec);
3160 else if (instance_expr is This)
3161 ((This)instance_expr).AddressOf (ec, AddressOp.LoadStore);
3163 instance_expr.Emit (ec);
3164 ig.Emit (OpCodes.Ldflda, FieldInfo);
3170 // A FieldExpr whose address can not be taken
3172 public class FieldExprNoAddress : FieldExpr, IMemoryLocation {
3173 public FieldExprNoAddress (FieldInfo fi, Location loc) : base (fi, loc)
3177 public new void AddressOf (EmitContext ec, AddressOp mode)
3179 Report.Error (-215, "Report this: Taking the address of a remapped parameter not supported");
3184 /// Expression that evaluates to a Property. The Assign class
3185 /// might set the `Value' expression if we are in an assignment.
3187 /// This is not an LValue because we need to re-write the expression, we
3188 /// can not take data from the stack and store it.
3190 public class PropertyExpr : ExpressionStatement, IAssignMethod, IMemberExpr {
3191 public readonly PropertyInfo PropertyInfo;
3194 // This is set externally by the `BaseAccess' class
3197 MethodInfo getter, setter;
3199 bool must_do_cs1540_check;
3201 Expression instance_expr;
3202 LocalTemporary temporary;
3203 bool have_temporary;
3205 public PropertyExpr (EmitContext ec, PropertyInfo pi, Location l)
3208 eclass = ExprClass.PropertyAccess;
3212 type = TypeManager.TypeToCoreType (pi.PropertyType);
3214 ResolveAccessors (ec);
3217 public string Name {
3219 return PropertyInfo.Name;
3223 public bool IsInstance {
3229 public bool IsStatic {
3235 public Type DeclaringType {
3237 return PropertyInfo.DeclaringType;
3242 // The instance expression associated with this expression
3244 public Expression InstanceExpression {
3246 instance_expr = value;
3250 return instance_expr;
3254 public bool VerifyAssignable ()
3256 if (setter == null) {
3257 Report.Error (200, loc,
3258 "The property `" + PropertyInfo.Name +
3259 "' can not be assigned to, as it has not set accessor");
3266 MethodInfo FindAccessor (Type invocation_type, bool is_set)
3268 BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic |
3269 BindingFlags.Static | BindingFlags.Instance |
3270 BindingFlags.DeclaredOnly;
3272 Type current = PropertyInfo.DeclaringType;
3273 for (; current != null; current = current.BaseType) {
3274 MemberInfo[] group = TypeManager.MemberLookup (
3275 invocation_type, invocation_type, current,
3276 MemberTypes.Property, flags, PropertyInfo.Name, null);
3281 if (group.Length != 1)
3282 // Oooops, can this ever happen ?
3285 PropertyInfo pi = (PropertyInfo) group [0];
3287 MethodInfo get = pi.GetGetMethod (true);
3288 MethodInfo set = pi.GetSetMethod (true);
3298 MethodInfo accessor = get != null ? get : set;
3299 if (accessor == null)
3301 if ((accessor.Attributes & MethodAttributes.NewSlot) != 0)
3308 MethodInfo GetAccessor (Type invocation_type, bool is_set)
3310 MethodInfo mi = FindAccessor (invocation_type, is_set);
3314 MethodAttributes ma = mi.Attributes & MethodAttributes.MemberAccessMask;
3317 // If only accessible to the current class or children
3319 if (ma == MethodAttributes.Private) {
3320 Type declaring_type = mi.DeclaringType;
3322 if (invocation_type != declaring_type){
3323 if (TypeManager.IsSubclassOrNestedChildOf (invocation_type, mi.DeclaringType))
3331 // FamAndAssem requires that we not only derivate, but we are on the
3334 if (ma == MethodAttributes.FamANDAssem){
3335 if (mi.DeclaringType.Assembly != invocation_type.Assembly)
3341 // Assembly and FamORAssem succeed if we're in the same assembly.
3342 if ((ma == MethodAttributes.Assembly) || (ma == MethodAttributes.FamORAssem)){
3343 if (mi.DeclaringType.Assembly == invocation_type.Assembly)
3347 // We already know that we aren't in the same assembly.
3348 if (ma == MethodAttributes.Assembly)
3351 // Family and FamANDAssem require that we derive.
3352 if ((ma == MethodAttributes.Family) || (ma == MethodAttributes.FamANDAssem) || (ma == MethodAttributes.FamORAssem)){
3353 if (!TypeManager.IsSubclassOrNestedChildOf (invocation_type, mi.DeclaringType))
3356 if (!TypeManager.IsNestedChildOf (invocation_type, mi.DeclaringType))
3357 must_do_cs1540_check = true;
3367 // We also perform the permission checking here, as the PropertyInfo does not
3368 // hold the information for the accessibility of its setter/getter
3370 void ResolveAccessors (EmitContext ec)
3372 getter = GetAccessor (ec.ContainerType, false);
3373 if ((getter != null) && getter.IsStatic)
3376 setter = GetAccessor (ec.ContainerType, true);
3377 if ((setter != null) && setter.IsStatic)
3380 if (setter == null && getter == null){
3381 Report.Error_T (122, loc, PropertyInfo.Name);
3385 bool InstanceResolve (EmitContext ec)
3387 if ((instance_expr == null) && ec.IsStatic && !is_static) {
3388 SimpleName.Error_ObjectRefRequired (ec, loc, PropertyInfo.Name);
3392 if (instance_expr != null) {
3393 instance_expr = instance_expr.DoResolve (ec);
3394 if (instance_expr == null)
3398 if (must_do_cs1540_check && (instance_expr != null)) {
3399 if ((instance_expr.Type != ec.ContainerType) &&
3400 ec.ContainerType.IsSubclassOf (instance_expr.Type)) {
3401 Report.Error (1540, loc, "Cannot access protected member `" +
3402 PropertyInfo.DeclaringType + "." + PropertyInfo.Name +
3403 "' via a qualifier of type `" +
3404 TypeManager.CSharpName (instance_expr.Type) +
3405 "'; the qualifier must be of type `" +
3406 TypeManager.CSharpName (ec.ContainerType) +
3407 "' (or derived from it)");
3415 override public Expression DoResolve (EmitContext ec)
3417 if (getter != null){
3418 if (TypeManager.GetArgumentTypes (getter).Length != 0){
3420 117, loc, "`{0}' does not contain a " +
3421 "definition for `{1}'.", getter.DeclaringType,
3427 if (getter == null){
3429 // The following condition happens if the PropertyExpr was
3430 // created, but is invalid (ie, the property is inaccessible),
3431 // and we did not want to embed the knowledge about this in
3432 // the caller routine. This only avoids double error reporting.
3437 Report.Error (154, loc,
3438 "The property `" + PropertyInfo.Name +
3439 "' can not be used in " +
3440 "this context because it lacks a get accessor");
3444 if (!InstanceResolve (ec))
3448 // Only base will allow this invocation to happen.
3450 if (IsBase && getter.IsAbstract){
3451 Report.Error (205, loc, "Cannot call an abstract base property: " +
3452 PropertyInfo.DeclaringType + "." +PropertyInfo.Name);
3459 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
3461 if (setter == null){
3463 // The following condition happens if the PropertyExpr was
3464 // created, but is invalid (ie, the property is inaccessible),
3465 // and we did not want to embed the knowledge about this in
3466 // the caller routine. This only avoids double error reporting.
3471 Report.Error (154, loc,
3472 "The property `" + PropertyInfo.Name +
3473 "' can not be used in " +
3474 "this context because it lacks a set accessor");
3478 if (TypeManager.GetArgumentTypes (setter).Length != 1){
3480 117, loc, "`{0}' does not contain a " +
3481 "definition for `{1}'.", getter.DeclaringType,
3486 if (!InstanceResolve (ec))
3490 // Only base will allow this invocation to happen.
3492 if (IsBase && setter.IsAbstract){
3493 Report.Error (205, loc, "Cannot call an abstract base property: " +
3494 PropertyInfo.DeclaringType + "." +PropertyInfo.Name);
3500 public override void CacheTemporaries (EmitContext ec)
3503 temporary = new LocalTemporary (ec, instance_expr.Type);
3506 Expression EmitInstance (EmitContext ec)
3508 if (temporary != null){
3509 if (!have_temporary){
3510 instance_expr.Emit (ec);
3511 temporary.Store (ec);
3512 have_temporary = true;
3516 return instance_expr;
3519 override public void Emit (EmitContext ec)
3521 Expression expr = EmitInstance (ec);
3524 // Special case: length of single dimension array property is turned into ldlen
3526 if ((getter == TypeManager.system_int_array_get_length) ||
3527 (getter == TypeManager.int_array_get_length)){
3528 Type iet = instance_expr.Type;
3531 // System.Array.Length can be called, but the Type does not
3532 // support invoking GetArrayRank, so test for that case first
3534 if (iet != TypeManager.array_type && (iet.GetArrayRank () == 1)){
3536 ec.ig.Emit (OpCodes.Ldlen);
3537 ec.ig.Emit (OpCodes.Conv_I4);
3542 Invocation.EmitCall (ec, IsBase, IsStatic, expr, getter, null, loc);
3547 // Implements the IAssignMethod interface for assignments
3549 public void EmitAssign (EmitContext ec, Expression source)
3551 Expression expr = EmitInstance (ec);
3553 Argument arg = new Argument (source, Argument.AType.Expression);
3554 ArrayList args = new ArrayList ();
3557 Invocation.EmitCall (ec, IsBase, IsStatic, expr, setter, args, loc);
3560 override public void EmitStatement (EmitContext ec)
3563 ec.ig.Emit (OpCodes.Pop);
3568 /// Fully resolved expression that evaluates to an Event
3570 public class EventExpr : Expression, IMemberExpr {
3571 public readonly EventInfo EventInfo;
3572 Expression instance_expr;
3575 MethodInfo add_accessor, remove_accessor;
3577 public EventExpr (EventInfo ei, Location loc)
3581 eclass = ExprClass.EventAccess;
3583 add_accessor = TypeManager.GetAddMethod (ei);
3584 remove_accessor = TypeManager.GetRemoveMethod (ei);
3586 if (add_accessor.IsStatic || remove_accessor.IsStatic)
3589 if (EventInfo is MyEventBuilder){
3590 MyEventBuilder eb = (MyEventBuilder) EventInfo;
3591 type = eb.EventType;
3594 type = EventInfo.EventHandlerType;
3597 public string Name {
3599 return EventInfo.Name;
3603 public bool IsInstance {
3609 public bool IsStatic {
3615 public Type DeclaringType {
3617 return EventInfo.DeclaringType;
3621 public Expression InstanceExpression {
3623 return instance_expr;
3627 instance_expr = value;
3631 public override Expression DoResolve (EmitContext ec)
3633 if (instance_expr != null) {
3634 instance_expr = instance_expr.DoResolve (ec);
3635 if (instance_expr == null)
3643 public override void Emit (EmitContext ec)
3645 Report.Error (70, loc, "The event `" + Name + "' can only appear on the left hand side of += or -= (except on the defining type)");
3648 public void EmitAddOrRemove (EmitContext ec, Expression source)
3650 BinaryDelegate source_del = (BinaryDelegate) source;
3651 Expression handler = source_del.Right;
3653 Argument arg = new Argument (handler, Argument.AType.Expression);
3654 ArrayList args = new ArrayList ();
3658 if (source_del.IsAddition)
3659 Invocation.EmitCall (
3660 ec, false, IsStatic, instance_expr, add_accessor, args, loc);
3662 Invocation.EmitCall (
3663 ec, false, IsStatic, instance_expr, remove_accessor, args, loc);