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)
1283 static void Error_NegativeArrayIndex (Location loc)
1285 Report.Error (284, loc, "Can not create array with a negative size");
1289 // Converts `source' to an int, uint, long or ulong.
1291 public Expression ExpressionToArrayArgument (EmitContext ec, Expression source, Location loc)
1295 bool old_checked = ec.CheckState;
1296 ec.CheckState = true;
1298 target = Convert.ImplicitConversion (ec, source, TypeManager.int32_type, loc);
1299 if (target == null){
1300 target = Convert.ImplicitConversion (ec, source, TypeManager.uint32_type, loc);
1301 if (target == null){
1302 target = Convert.ImplicitConversion (ec, source, TypeManager.int64_type, loc);
1303 if (target == null){
1304 target = Convert.ImplicitConversion (ec, source, TypeManager.uint64_type, loc);
1306 Convert.Error_CannotImplicitConversion (loc, source.Type, TypeManager.int32_type);
1310 ec.CheckState = old_checked;
1313 // Only positive constants are allowed at compile time
1315 if (target is Constant){
1316 if (target is IntConstant){
1317 if (((IntConstant) target).Value < 0){
1318 Error_NegativeArrayIndex (loc);
1323 if (target is LongConstant){
1324 if (((LongConstant) target).Value < 0){
1325 Error_NegativeArrayIndex (loc);
1338 /// This is just a base class for expressions that can
1339 /// appear on statements (invocations, object creation,
1340 /// assignments, post/pre increment and decrement). The idea
1341 /// being that they would support an extra Emition interface that
1342 /// does not leave a result on the stack.
1344 public abstract class ExpressionStatement : Expression {
1346 public virtual ExpressionStatement ResolveStatement (EmitContext ec)
1348 Expression e = Resolve (ec);
1352 ExpressionStatement es = e as ExpressionStatement;
1354 Error (201, "Only assignment, call, increment, decrement and new object " +
1355 "expressions can be used as a statement");
1361 /// Requests the expression to be emitted in a `statement'
1362 /// context. This means that no new value is left on the
1363 /// stack after invoking this method (constrasted with
1364 /// Emit that will always leave a value on the stack).
1366 public abstract void EmitStatement (EmitContext ec);
1370 /// This kind of cast is used to encapsulate the child
1371 /// whose type is child.Type into an expression that is
1372 /// reported to return "return_type". This is used to encapsulate
1373 /// expressions which have compatible types, but need to be dealt
1374 /// at higher levels with.
1376 /// For example, a "byte" expression could be encapsulated in one
1377 /// of these as an "unsigned int". The type for the expression
1378 /// would be "unsigned int".
1381 public class EmptyCast : Expression {
1382 protected Expression child;
1384 public Expression Child {
1390 public EmptyCast (Expression child, Type return_type)
1392 eclass = child.eclass;
1397 public override Expression DoResolve (EmitContext ec)
1399 // This should never be invoked, we are born in fully
1400 // initialized state.
1405 public override void Emit (EmitContext ec)
1412 // We need to special case this since an empty cast of
1413 // a NullLiteral is still a Constant
1415 public class NullCast : Constant {
1416 protected Expression child;
1418 public NullCast (Expression child, Type return_type)
1420 eclass = child.eclass;
1425 override public string AsString ()
1430 public override object GetValue ()
1435 public override Expression DoResolve (EmitContext ec)
1437 // This should never be invoked, we are born in fully
1438 // initialized state.
1443 public override void Emit (EmitContext ec)
1451 /// This class is used to wrap literals which belong inside Enums
1453 public class EnumConstant : Constant {
1454 public Constant Child;
1456 public EnumConstant (Constant child, Type enum_type)
1458 eclass = child.eclass;
1463 public override Expression DoResolve (EmitContext ec)
1465 // This should never be invoked, we are born in fully
1466 // initialized state.
1471 public override void Emit (EmitContext ec)
1476 public override object GetValue ()
1478 return Child.GetValue ();
1482 // Converts from one of the valid underlying types for an enumeration
1483 // (int32, uint32, int64, uint64, short, ushort, byte, sbyte) to
1484 // one of the internal compiler literals: Int/UInt/Long/ULong Literals.
1486 public Constant WidenToCompilerConstant ()
1488 Type t = TypeManager.EnumToUnderlying (Child.Type);
1489 object v = ((Constant) Child).GetValue ();;
1491 if (t == TypeManager.int32_type)
1492 return new IntConstant ((int) v);
1493 if (t == TypeManager.uint32_type)
1494 return new UIntConstant ((uint) v);
1495 if (t == TypeManager.int64_type)
1496 return new LongConstant ((long) v);
1497 if (t == TypeManager.uint64_type)
1498 return new ULongConstant ((ulong) v);
1499 if (t == TypeManager.short_type)
1500 return new ShortConstant ((short) v);
1501 if (t == TypeManager.ushort_type)
1502 return new UShortConstant ((ushort) v);
1503 if (t == TypeManager.byte_type)
1504 return new ByteConstant ((byte) v);
1505 if (t == TypeManager.sbyte_type)
1506 return new SByteConstant ((sbyte) v);
1508 throw new Exception ("Invalid enumeration underlying type: " + t);
1512 // Extracts the value in the enumeration on its native representation
1514 public object GetPlainValue ()
1516 Type t = TypeManager.EnumToUnderlying (Child.Type);
1517 object v = ((Constant) Child).GetValue ();;
1519 if (t == TypeManager.int32_type)
1521 if (t == TypeManager.uint32_type)
1523 if (t == TypeManager.int64_type)
1525 if (t == TypeManager.uint64_type)
1527 if (t == TypeManager.short_type)
1529 if (t == TypeManager.ushort_type)
1531 if (t == TypeManager.byte_type)
1533 if (t == TypeManager.sbyte_type)
1539 public override string AsString ()
1541 return Child.AsString ();
1544 public override DoubleConstant ConvertToDouble ()
1546 return Child.ConvertToDouble ();
1549 public override FloatConstant ConvertToFloat ()
1551 return Child.ConvertToFloat ();
1554 public override ULongConstant ConvertToULong ()
1556 return Child.ConvertToULong ();
1559 public override LongConstant ConvertToLong ()
1561 return Child.ConvertToLong ();
1564 public override UIntConstant ConvertToUInt ()
1566 return Child.ConvertToUInt ();
1569 public override IntConstant ConvertToInt ()
1571 return Child.ConvertToInt ();
1574 public override bool IsZeroInteger {
1575 get { return Child.IsZeroInteger; }
1580 /// This kind of cast is used to encapsulate Value Types in objects.
1582 /// The effect of it is to box the value type emitted by the previous
1585 public class BoxedCast : EmptyCast {
1587 public BoxedCast (Expression expr)
1588 : base (expr, TypeManager.object_type)
1590 eclass = ExprClass.Value;
1593 public BoxedCast (Expression expr, Type target_type)
1594 : base (expr, target_type)
1596 eclass = ExprClass.Value;
1599 public override Expression DoResolve (EmitContext ec)
1601 // This should never be invoked, we are born in fully
1602 // initialized state.
1607 public override void Emit (EmitContext ec)
1611 ec.ig.Emit (OpCodes.Box, child.Type);
1615 public class UnboxCast : EmptyCast {
1616 public UnboxCast (Expression expr, Type return_type)
1617 : base (expr, return_type)
1621 public override Expression DoResolve (EmitContext ec)
1623 // This should never be invoked, we are born in fully
1624 // initialized state.
1629 public override void Emit (EmitContext ec)
1632 ILGenerator ig = ec.ig;
1635 if (t.IsGenericParameter)
1636 ig.Emit (OpCodes.Unbox_Any, t);
1638 ig.Emit (OpCodes.Unbox, t);
1640 LoadFromPtr (ig, t);
1646 /// This is used to perform explicit numeric conversions.
1648 /// Explicit numeric conversions might trigger exceptions in a checked
1649 /// context, so they should generate the conv.ovf opcodes instead of
1652 public class ConvCast : EmptyCast {
1653 public enum Mode : byte {
1654 I1_U1, I1_U2, I1_U4, I1_U8, I1_CH,
1656 I2_I1, I2_U1, I2_U2, I2_U4, I2_U8, I2_CH,
1657 U2_I1, U2_U1, U2_I2, U2_CH,
1658 I4_I1, I4_U1, I4_I2, I4_U2, I4_U4, I4_U8, I4_CH,
1659 U4_I1, U4_U1, U4_I2, U4_U2, U4_I4, U4_CH,
1660 I8_I1, I8_U1, I8_I2, I8_U2, I8_I4, I8_U4, I8_U8, I8_CH,
1661 U8_I1, U8_U1, U8_I2, U8_U2, U8_I4, U8_U4, U8_I8, U8_CH,
1662 CH_I1, CH_U1, CH_I2,
1663 R4_I1, R4_U1, R4_I2, R4_U2, R4_I4, R4_U4, R4_I8, R4_U8, R4_CH,
1664 R8_I1, R8_U1, R8_I2, R8_U2, R8_I4, R8_U4, R8_I8, R8_U8, R8_CH, R8_R4
1670 public ConvCast (EmitContext ec, Expression child, Type return_type, Mode m)
1671 : base (child, return_type)
1673 checked_state = ec.CheckState;
1677 public override Expression DoResolve (EmitContext ec)
1679 // This should never be invoked, we are born in fully
1680 // initialized state.
1685 public override string ToString ()
1687 return String.Format ("ConvCast ({0}, {1})", mode, child);
1690 public override void Emit (EmitContext ec)
1692 ILGenerator ig = ec.ig;
1698 case Mode.I1_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1699 case Mode.I1_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1700 case Mode.I1_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1701 case Mode.I1_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1702 case Mode.I1_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1704 case Mode.U1_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1705 case Mode.U1_CH: /* nothing */ break;
1707 case Mode.I2_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1708 case Mode.I2_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1709 case Mode.I2_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1710 case Mode.I2_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1711 case Mode.I2_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1712 case Mode.I2_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1714 case Mode.U2_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1715 case Mode.U2_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
1716 case Mode.U2_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
1717 case Mode.U2_CH: /* nothing */ break;
1719 case Mode.I4_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1720 case Mode.I4_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1721 case Mode.I4_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
1722 case Mode.I4_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1723 case Mode.I4_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1724 case Mode.I4_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1725 case Mode.I4_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1727 case Mode.U4_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1728 case Mode.U4_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
1729 case Mode.U4_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
1730 case Mode.U4_U2: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
1731 case Mode.U4_I4: ig.Emit (OpCodes.Conv_Ovf_I4_Un); break;
1732 case Mode.U4_CH: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
1734 case Mode.I8_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1735 case Mode.I8_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1736 case Mode.I8_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
1737 case Mode.I8_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1738 case Mode.I8_I4: ig.Emit (OpCodes.Conv_Ovf_I4); break;
1739 case Mode.I8_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1740 case Mode.I8_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1741 case Mode.I8_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1743 case Mode.U8_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1744 case Mode.U8_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
1745 case Mode.U8_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
1746 case Mode.U8_U2: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
1747 case Mode.U8_I4: ig.Emit (OpCodes.Conv_Ovf_I4_Un); break;
1748 case Mode.U8_U4: ig.Emit (OpCodes.Conv_Ovf_U4_Un); break;
1749 case Mode.U8_I8: ig.Emit (OpCodes.Conv_Ovf_I8_Un); break;
1750 case Mode.U8_CH: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
1752 case Mode.CH_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1753 case Mode.CH_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
1754 case Mode.CH_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
1756 case Mode.R4_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1757 case Mode.R4_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1758 case Mode.R4_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
1759 case Mode.R4_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1760 case Mode.R4_I4: ig.Emit (OpCodes.Conv_Ovf_I4); break;
1761 case Mode.R4_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1762 case Mode.R4_I8: ig.Emit (OpCodes.Conv_Ovf_I8); break;
1763 case Mode.R4_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1764 case Mode.R4_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1766 case Mode.R8_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1767 case Mode.R8_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1768 case Mode.R8_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
1769 case Mode.R8_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1770 case Mode.R8_I4: ig.Emit (OpCodes.Conv_Ovf_I4); break;
1771 case Mode.R8_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1772 case Mode.R8_I8: ig.Emit (OpCodes.Conv_Ovf_I8); break;
1773 case Mode.R8_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1774 case Mode.R8_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1775 case Mode.R8_R4: ig.Emit (OpCodes.Conv_R4); break;
1779 case Mode.I1_U1: ig.Emit (OpCodes.Conv_U1); break;
1780 case Mode.I1_U2: ig.Emit (OpCodes.Conv_U2); break;
1781 case Mode.I1_U4: ig.Emit (OpCodes.Conv_U4); break;
1782 case Mode.I1_U8: ig.Emit (OpCodes.Conv_I8); break;
1783 case Mode.I1_CH: ig.Emit (OpCodes.Conv_U2); break;
1785 case Mode.U1_I1: ig.Emit (OpCodes.Conv_I1); break;
1786 case Mode.U1_CH: ig.Emit (OpCodes.Conv_U2); break;
1788 case Mode.I2_I1: ig.Emit (OpCodes.Conv_I1); break;
1789 case Mode.I2_U1: ig.Emit (OpCodes.Conv_U1); break;
1790 case Mode.I2_U2: ig.Emit (OpCodes.Conv_U2); break;
1791 case Mode.I2_U4: ig.Emit (OpCodes.Conv_U4); break;
1792 case Mode.I2_U8: ig.Emit (OpCodes.Conv_I8); break;
1793 case Mode.I2_CH: ig.Emit (OpCodes.Conv_U2); break;
1795 case Mode.U2_I1: ig.Emit (OpCodes.Conv_I1); break;
1796 case Mode.U2_U1: ig.Emit (OpCodes.Conv_U1); break;
1797 case Mode.U2_I2: ig.Emit (OpCodes.Conv_I2); break;
1798 case Mode.U2_CH: /* nothing */ break;
1800 case Mode.I4_I1: ig.Emit (OpCodes.Conv_I1); break;
1801 case Mode.I4_U1: ig.Emit (OpCodes.Conv_U1); break;
1802 case Mode.I4_I2: ig.Emit (OpCodes.Conv_I2); break;
1803 case Mode.I4_U4: /* nothing */ break;
1804 case Mode.I4_U2: ig.Emit (OpCodes.Conv_U2); break;
1805 case Mode.I4_U8: ig.Emit (OpCodes.Conv_I8); break;
1806 case Mode.I4_CH: ig.Emit (OpCodes.Conv_U2); break;
1808 case Mode.U4_I1: ig.Emit (OpCodes.Conv_I1); break;
1809 case Mode.U4_U1: ig.Emit (OpCodes.Conv_U1); break;
1810 case Mode.U4_I2: ig.Emit (OpCodes.Conv_I2); break;
1811 case Mode.U4_U2: ig.Emit (OpCodes.Conv_U2); break;
1812 case Mode.U4_I4: /* nothing */ break;
1813 case Mode.U4_CH: ig.Emit (OpCodes.Conv_U2); break;
1815 case Mode.I8_I1: ig.Emit (OpCodes.Conv_I1); break;
1816 case Mode.I8_U1: ig.Emit (OpCodes.Conv_U1); break;
1817 case Mode.I8_I2: ig.Emit (OpCodes.Conv_I2); break;
1818 case Mode.I8_U2: ig.Emit (OpCodes.Conv_U2); break;
1819 case Mode.I8_I4: ig.Emit (OpCodes.Conv_I4); break;
1820 case Mode.I8_U4: ig.Emit (OpCodes.Conv_U4); break;
1821 case Mode.I8_U8: /* nothing */ break;
1822 case Mode.I8_CH: ig.Emit (OpCodes.Conv_U2); break;
1824 case Mode.U8_I1: ig.Emit (OpCodes.Conv_I1); break;
1825 case Mode.U8_U1: ig.Emit (OpCodes.Conv_U1); break;
1826 case Mode.U8_I2: ig.Emit (OpCodes.Conv_I2); break;
1827 case Mode.U8_U2: ig.Emit (OpCodes.Conv_U2); break;
1828 case Mode.U8_I4: ig.Emit (OpCodes.Conv_I4); break;
1829 case Mode.U8_U4: ig.Emit (OpCodes.Conv_U4); break;
1830 case Mode.U8_I8: /* nothing */ break;
1831 case Mode.U8_CH: ig.Emit (OpCodes.Conv_U2); break;
1833 case Mode.CH_I1: ig.Emit (OpCodes.Conv_I1); break;
1834 case Mode.CH_U1: ig.Emit (OpCodes.Conv_U1); break;
1835 case Mode.CH_I2: ig.Emit (OpCodes.Conv_I2); break;
1837 case Mode.R4_I1: ig.Emit (OpCodes.Conv_I1); break;
1838 case Mode.R4_U1: ig.Emit (OpCodes.Conv_U1); break;
1839 case Mode.R4_I2: ig.Emit (OpCodes.Conv_I2); break;
1840 case Mode.R4_U2: ig.Emit (OpCodes.Conv_U2); break;
1841 case Mode.R4_I4: ig.Emit (OpCodes.Conv_I4); break;
1842 case Mode.R4_U4: ig.Emit (OpCodes.Conv_U4); break;
1843 case Mode.R4_I8: ig.Emit (OpCodes.Conv_I8); break;
1844 case Mode.R4_U8: ig.Emit (OpCodes.Conv_U8); break;
1845 case Mode.R4_CH: ig.Emit (OpCodes.Conv_U2); break;
1847 case Mode.R8_I1: ig.Emit (OpCodes.Conv_I1); break;
1848 case Mode.R8_U1: ig.Emit (OpCodes.Conv_U1); break;
1849 case Mode.R8_I2: ig.Emit (OpCodes.Conv_I2); break;
1850 case Mode.R8_U2: ig.Emit (OpCodes.Conv_U2); break;
1851 case Mode.R8_I4: ig.Emit (OpCodes.Conv_I4); break;
1852 case Mode.R8_U4: ig.Emit (OpCodes.Conv_U4); break;
1853 case Mode.R8_I8: ig.Emit (OpCodes.Conv_I8); break;
1854 case Mode.R8_U8: ig.Emit (OpCodes.Conv_U8); break;
1855 case Mode.R8_CH: ig.Emit (OpCodes.Conv_U2); break;
1856 case Mode.R8_R4: ig.Emit (OpCodes.Conv_R4); break;
1862 public class OpcodeCast : EmptyCast {
1866 public OpcodeCast (Expression child, Type return_type, OpCode op)
1867 : base (child, return_type)
1871 second_valid = false;
1874 public OpcodeCast (Expression child, Type return_type, OpCode op, OpCode op2)
1875 : base (child, return_type)
1880 second_valid = true;
1883 public override Expression DoResolve (EmitContext ec)
1885 // This should never be invoked, we are born in fully
1886 // initialized state.
1891 public override void Emit (EmitContext ec)
1902 /// This kind of cast is used to encapsulate a child and cast it
1903 /// to the class requested
1905 public class ClassCast : EmptyCast {
1906 public ClassCast (Expression child, Type return_type)
1907 : base (child, return_type)
1912 public override Expression DoResolve (EmitContext ec)
1914 // This should never be invoked, we are born in fully
1915 // initialized state.
1920 public override void Emit (EmitContext ec)
1924 if (child.Type.IsGenericParameter)
1925 ec.ig.Emit (OpCodes.Box, child.Type);
1927 if (type.IsGenericParameter)
1928 ec.ig.Emit (OpCodes.Unbox_Any, type);
1930 ec.ig.Emit (OpCodes.Castclass, type);
1935 /// SimpleName expressions are initially formed of a single
1936 /// word and it only happens at the beginning of the expression.
1940 /// The expression will try to be bound to a Field, a Method
1941 /// group or a Property. If those fail we pass the name to our
1942 /// caller and the SimpleName is compounded to perform a type
1943 /// lookup. The idea behind this process is that we want to avoid
1944 /// creating a namespace map from the assemblies, as that requires
1945 /// the GetExportedTypes function to be called and a hashtable to
1946 /// be constructed which reduces startup time. If later we find
1947 /// that this is slower, we should create a `NamespaceExpr' expression
1948 /// that fully participates in the resolution process.
1950 /// For example `System.Console.WriteLine' is decomposed into
1951 /// MemberAccess (MemberAccess (SimpleName ("System"), "Console"), "WriteLine")
1953 /// The first SimpleName wont produce a match on its own, so it will
1955 /// MemberAccess (SimpleName ("System.Console"), "WriteLine").
1957 /// System.Console will produce a TypeExpr match.
1959 /// The downside of this is that we might be hitting `LookupType' too many
1960 /// times with this scheme.
1962 public class SimpleName : Expression {
1964 public readonly TypeArguments Arguments;
1967 // If true, then we are a simple name, not composed with a ".
1971 public SimpleName (string a, string b, Location l)
1973 Name = String.Concat (a, ".", b);
1978 public SimpleName (string name, Location l)
1985 public SimpleName (string name, TypeArguments args, Location l)
1993 public static void Error_ObjectRefRequired (EmitContext ec, Location l, string name)
1995 if (ec.IsFieldInitializer)
1998 "A field initializer cannot reference the non-static field, " +
1999 "method or property `"+name+"'");
2003 "An object reference is required " +
2004 "for the non-static field `"+name+"'");
2008 // Checks whether we are trying to access an instance
2009 // property, method or field from a static body.
2011 Expression MemberStaticCheck (EmitContext ec, Expression e)
2013 if (e is IMemberExpr){
2014 IMemberExpr member = (IMemberExpr) e;
2016 if (!member.IsStatic){
2017 Error_ObjectRefRequired (ec, loc, Name);
2025 public override Expression DoResolve (EmitContext ec)
2027 return SimpleNameResolve (ec, null, false, false);
2030 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
2032 return SimpleNameResolve (ec, right_side, false, false);
2036 public Expression DoResolveAllowStatic (EmitContext ec, bool intermediate)
2038 return SimpleNameResolve (ec, null, true, intermediate);
2041 public override Expression ResolveAsTypeStep (EmitContext ec)
2043 DeclSpace ds = ec.DeclSpace;
2044 NamespaceEntry ns = ds.NamespaceEntry;
2049 // Since we are cheating: we only do the Alias lookup for
2050 // namespaces if the name does not include any dots in it
2052 if (ns != null && is_base)
2053 alias_value = ns.LookupAlias (Name);
2057 TypeParameterExpr generic_type = ds.LookupGeneric (Name, loc);
2058 if (generic_type != null)
2059 return generic_type.ResolveAsTypeTerminal (ec);
2061 if (ec.ResolvingTypeTree){
2062 int errors = Report.Errors;
2063 Type dt = ds.FindType (loc, Name);
2065 if (Report.Errors != errors)
2069 return new TypeExpression (dt, loc);
2071 if (alias_value != null){
2072 if (alias_value.IsType)
2073 return alias_value.Type;
2074 if ((t = RootContext.LookupType (ds, alias_value.Name, true, loc)) != null)
2080 // First, the using aliases
2082 if (alias_value != null){
2083 if (alias_value.IsType)
2084 return alias_value.Type;
2085 if ((t = RootContext.LookupType (ds, alias_value.Name, true, loc)) != null)
2088 // we have alias value, but it isn't Type, so try if it's namespace
2089 return new SimpleName (alias_value.Name, loc);
2093 // Stage 2: Lookup up if we are an alias to a type
2097 if ((t = RootContext.LookupType (ds, Name, true, loc)) != null)
2100 // No match, maybe our parent can compose us
2101 // into something meaningful.
2105 Expression SimpleNameResolve (EmitContext ec, Expression right_side,
2106 bool allow_static, bool intermediate)
2108 Expression e = DoSimpleNameResolve (ec, right_side, allow_static, intermediate);
2112 Block current_block = ec.CurrentBlock;
2113 if (current_block != null){
2114 LocalInfo vi = current_block.GetLocalInfo (Name);
2116 current_block.IsVariableNameUsedInChildBlock(Name)) {
2117 Report.Error (135, Location,
2118 "'{0}' has a different meaning in a " +
2119 "child block", Name);
2124 if (e.Type != null && e.Type.IsPointer && !ec.InUnsafe) {
2133 /// 7.5.2: Simple Names.
2135 /// Local Variables and Parameters are handled at
2136 /// parse time, so they never occur as SimpleNames.
2138 /// The `allow_static' flag is used by MemberAccess only
2139 /// and it is used to inform us that it is ok for us to
2140 /// avoid the static check, because MemberAccess might end
2141 /// up resolving the Name as a Type name and the access as
2142 /// a static type access.
2144 /// ie: Type Type; .... { Type.GetType (""); }
2146 /// Type is both an instance variable and a Type; Type.GetType
2147 /// is the static method not an instance method of type.
2149 Expression DoSimpleNameResolve (EmitContext ec, Expression right_side, bool allow_static, bool intermediate)
2151 Expression e = null;
2154 // Stage 1: Performed by the parser (binding to locals or parameters).
2156 Block current_block = ec.CurrentBlock;
2157 if (current_block != null){
2158 LocalInfo vi = current_block.GetLocalInfo (Name);
2162 var = new LocalVariableReference (ec.CurrentBlock, Name, loc);
2164 if (right_side != null)
2165 return var.ResolveLValue (ec, right_side);
2167 return var.Resolve (ec);
2171 Parameter par = null;
2172 Parameters pars = current_block.Parameters;
2174 par = pars.GetParameterByName (Name, out idx);
2177 ParameterReference param;
2179 param = new ParameterReference (pars, current_block, idx, Name, loc);
2181 if (right_side != null)
2182 return param.ResolveLValue (ec, right_side);
2184 return param.Resolve (ec);
2189 // Stage 2: Lookup members
2192 DeclSpace lookup_ds = ec.DeclSpace;
2194 if (lookup_ds.TypeBuilder == null)
2197 e = MemberLookup (ec, lookup_ds.TypeBuilder, Name, loc);
2201 lookup_ds =lookup_ds.Parent;
2202 } while (lookup_ds != null);
2204 if (e == null && ec.ContainerType != null)
2205 e = MemberLookup (ec, ec.ContainerType, Name, loc);
2209 // Since we are cheating (is_base is our hint
2210 // that we are the beginning of the name): we
2211 // only do the Alias lookup for namespaces if
2212 // the name does not include any dots in it
2214 NamespaceEntry ns = ec.DeclSpace.NamespaceEntry;
2215 if (is_base && ns != null){
2216 IAlias alias_value = ns.LookupAlias (Name);
2217 if (alias_value != null){
2218 if (alias_value.IsType)
2219 return alias_value.Type;
2221 Name = alias_value.Name;
2224 if ((t = TypeManager.LookupType (Name)) != null)
2225 return new TypeExpression (t, loc);
2227 // No match, maybe our parent can compose us
2228 // into something meaningful.
2233 return ResolveAsTypeStep (ec);
2239 if (e is IMemberExpr) {
2240 e = MemberAccess.ResolveMemberAccess (ec, e, null, loc, this);
2244 IMemberExpr me = e as IMemberExpr;
2248 if (Arguments != null) {
2249 MethodGroupExpr mg = me as MethodGroupExpr;
2253 return mg.ResolveGeneric (ec, Arguments);
2256 // This fails if ResolveMemberAccess() was unable to decide whether
2257 // it's a field or a type of the same name.
2259 if (!me.IsStatic && (me.InstanceExpression == null))
2263 TypeManager.IsSubclassOrNestedChildOf (me.InstanceExpression.Type, me.DeclaringType) &&
2264 me.InstanceExpression.Type != me.DeclaringType &&
2265 !TypeManager.IsSubclassOf (me.InstanceExpression.Type, me.DeclaringType) &&
2266 (!intermediate || !MemberAccess.IdenticalNameAndTypeName (ec, this, e, loc))) {
2267 Error (38, "Cannot access nonstatic member `" + me.Name + "' of " +
2268 "outer type `" + me.DeclaringType + "' via nested type `" +
2269 me.InstanceExpression.Type + "'");
2273 return (right_side != null)
2274 ? e.DoResolveLValue (ec, right_side)
2278 if (ec.IsStatic || ec.IsFieldInitializer){
2282 return MemberStaticCheck (ec, e);
2287 public override void Emit (EmitContext ec)
2290 // If this is ever reached, then we failed to
2291 // find the name as a namespace
2294 Error (103, "The name `" + Name +
2295 "' does not exist in the class `" +
2296 ec.DeclSpace.Name + "'");
2299 public override string ToString ()
2306 /// Fully resolved expression that evaluates to a type
2308 public abstract class TypeExpr : Expression, IAlias {
2309 override public Expression ResolveAsTypeStep (EmitContext ec)
2311 TypeExpr t = DoResolveAsTypeStep (ec);
2315 eclass = ExprClass.Type;
2319 override public Expression DoResolve (EmitContext ec)
2321 return ResolveAsTypeTerminal (ec);
2324 override public void Emit (EmitContext ec)
2326 throw new Exception ("Should never be called");
2329 public virtual bool CheckAccessLevel (DeclSpace ds)
2331 return ds.CheckAccessLevel (Type);
2334 public virtual bool AsAccessible (DeclSpace ds, int flags)
2336 return ds.AsAccessible (Type, flags);
2339 public virtual bool IsClass {
2340 get { return Type.IsClass; }
2343 public virtual bool IsValueType {
2344 get { return Type.IsValueType; }
2347 public virtual bool IsInterface {
2348 get { return Type.IsInterface; }
2351 public virtual bool IsSealed {
2352 get { return Type.IsSealed; }
2355 public virtual bool CanInheritFrom ()
2357 if (Type == TypeManager.enum_type ||
2358 (Type == TypeManager.value_type && RootContext.StdLib) ||
2359 Type == TypeManager.multicast_delegate_type ||
2360 Type == TypeManager.delegate_type ||
2361 Type == TypeManager.array_type)
2367 public virtual bool IsAttribute {
2369 return Type == TypeManager.attribute_type ||
2370 Type.IsSubclassOf (TypeManager.attribute_type);
2374 public abstract TypeExpr DoResolveAsTypeStep (EmitContext ec);
2376 public virtual Type ResolveType (EmitContext ec)
2378 TypeExpr t = ResolveAsTypeTerminal (ec);
2385 public abstract string Name {
2389 public override bool Equals (object obj)
2391 TypeExpr tobj = obj as TypeExpr;
2395 return Type == tobj.Type;
2398 public override int GetHashCode ()
2400 return Type.GetHashCode ();
2403 public override string ToString ()
2408 bool IAlias.IsType {
2409 get { return true; }
2412 TypeExpr IAlias.Type {
2419 public class TypeExpression : TypeExpr, IAlias {
2420 public TypeExpression (Type t, Location l)
2423 eclass = ExprClass.Type;
2427 public override TypeExpr DoResolveAsTypeStep (EmitContext ec)
2432 public override string Name {
2434 return Type.ToString ();
2438 string IAlias.Name {
2440 return Type.FullName != null ? Type.FullName : Type.Name;
2446 /// Used to create types from a fully qualified name. These are just used
2447 /// by the parser to setup the core types. A TypeLookupExpression is always
2448 /// classified as a type.
2450 public class TypeLookupExpression : TypeExpr {
2453 public TypeLookupExpression (string name)
2458 public override TypeExpr DoResolveAsTypeStep (EmitContext ec)
2461 TypeExpr texpr = RootContext.LookupType (
2462 ec.DeclSpace, name, false, Location.Null);
2466 type = texpr.ResolveType (ec);
2474 public override string Name {
2482 /// Represents an "unbound generic type", ie. typeof (Foo<>).
2485 public class UnboundTypeExpression : TypeLookupExpression {
2486 public UnboundTypeExpression (string name, int num_type_args)
2487 : base (MemberName.MakeName (name, num_type_args))
2491 public class TypeAliasExpression : TypeExpr, IAlias {
2496 public TypeAliasExpression (TypeExpr texpr, TypeArguments args, Location l)
2500 loc = texpr.Location;
2502 eclass = ExprClass.Type;
2504 name = texpr.Name + "<" + args.ToString () + ">";
2509 public override string Name {
2510 get { return name; }
2513 public override TypeExpr DoResolveAsTypeStep (EmitContext ec)
2515 Type type = texpr.ResolveType (ec);
2519 int num_args = TypeManager.GetNumberOfTypeArguments (type);
2522 if (num_args == 0) {
2523 Report.Error (308, loc,
2524 "The non-generic type `{0}' cannot " +
2525 "be used with type arguments.",
2526 TypeManager.CSharpName (type));
2530 ConstructedType ctype = new ConstructedType (type, args, loc);
2531 return ctype.ResolveAsTypeTerminal (ec);
2532 } else if (num_args > 0) {
2533 Report.Error (305, loc,
2534 "Using the generic type `{0}' " +
2535 "requires {1} type arguments",
2536 TypeManager.GetFullName (type), num_args);
2540 return new TypeExpression (type, loc);
2543 public override Type ResolveType (EmitContext ec)
2545 TypeExpr t = ResolveAsTypeTerminal (ec);
2549 type = t.ResolveType (ec);
2553 public override bool CheckAccessLevel (DeclSpace ds)
2555 return texpr.CheckAccessLevel (ds);
2558 public override bool AsAccessible (DeclSpace ds, int flags)
2560 return texpr.AsAccessible (ds, flags);
2563 public override bool IsClass {
2564 get { return texpr.IsClass; }
2567 public override bool IsValueType {
2568 get { return texpr.IsValueType; }
2571 public override bool IsInterface {
2572 get { return texpr.IsInterface; }
2575 public override bool IsSealed {
2576 get { return texpr.IsSealed; }
2579 public override bool IsAttribute {
2580 get { return texpr.IsAttribute; }
2585 /// MethodGroup Expression.
2587 /// This is a fully resolved expression that evaluates to a type
2589 public class MethodGroupExpr : Expression, IMemberExpr {
2590 public MethodBase [] Methods;
2591 Expression instance_expression = null;
2592 bool is_explicit_impl = false;
2593 bool has_type_arguments = false;
2594 bool identical_type_name = false;
2596 public MethodGroupExpr (MemberInfo [] mi, Location l)
2598 Methods = new MethodBase [mi.Length];
2599 mi.CopyTo (Methods, 0);
2600 eclass = ExprClass.MethodGroup;
2601 type = TypeManager.object_type;
2605 public MethodGroupExpr (ArrayList list, Location l)
2607 Methods = new MethodBase [list.Count];
2610 list.CopyTo (Methods, 0);
2612 foreach (MemberInfo m in list){
2613 if (!(m is MethodBase)){
2614 Console.WriteLine ("Name " + m.Name);
2615 Console.WriteLine ("Found a: " + m.GetType ().FullName);
2622 eclass = ExprClass.MethodGroup;
2623 type = TypeManager.object_type;
2626 public Type DeclaringType {
2629 // We assume that the top-level type is in the end
2631 return Methods [Methods.Length - 1].DeclaringType;
2632 //return Methods [0].DeclaringType;
2637 // `A method group may have associated an instance expression'
2639 public Expression InstanceExpression {
2641 return instance_expression;
2645 instance_expression = value;
2649 public bool IsExplicitImpl {
2651 return is_explicit_impl;
2655 is_explicit_impl = value;
2659 public bool HasTypeArguments {
2661 return has_type_arguments;
2665 has_type_arguments = value;
2669 public bool IdenticalTypeName {
2671 return identical_type_name;
2675 identical_type_name = value;
2679 public string Name {
2681 //return Methods [0].Name;
2682 return Methods [Methods.Length - 1].Name;
2686 public bool IsInstance {
2688 foreach (MethodBase mb in Methods)
2696 public bool IsStatic {
2698 foreach (MethodBase mb in Methods)
2706 override public Expression DoResolve (EmitContext ec)
2709 instance_expression = null;
2711 if (instance_expression != null) {
2712 instance_expression = instance_expression.DoResolve (ec);
2713 if (instance_expression == null)
2720 public void ReportUsageError ()
2722 Report.Error (654, loc, "Method `" + DeclaringType + "." +
2723 Name + "()' is referenced without parentheses");
2726 override public void Emit (EmitContext ec)
2728 ReportUsageError ();
2731 bool RemoveMethods (bool keep_static)
2733 ArrayList smethods = new ArrayList ();
2735 foreach (MethodBase mb in Methods){
2736 if (mb.IsStatic == keep_static)
2740 if (smethods.Count == 0)
2743 Methods = new MethodBase [smethods.Count];
2744 smethods.CopyTo (Methods, 0);
2750 /// Removes any instance methods from the MethodGroup, returns
2751 /// false if the resulting set is empty.
2753 public bool RemoveInstanceMethods ()
2755 return RemoveMethods (true);
2759 /// Removes any static methods from the MethodGroup, returns
2760 /// false if the resulting set is empty.
2762 public bool RemoveStaticMethods ()
2764 return RemoveMethods (false);
2767 public Expression ResolveGeneric (EmitContext ec, TypeArguments args)
2769 if (args.Resolve (ec) == false)
2772 Type[] atypes = args.Arguments;
2774 int first_count = 0;
2775 MethodInfo first = null;
2777 ArrayList list = new ArrayList ();
2778 foreach (MethodBase mb in Methods) {
2779 MethodInfo mi = mb as MethodInfo;
2780 if ((mi == null) || !mi.HasGenericParameters)
2783 Type[] gen_params = mi.GetGenericArguments ();
2785 if (first == null) {
2787 first_count = gen_params.Length;
2790 if (gen_params.Length != atypes.Length)
2793 list.Add (mi.BindGenericParameters (atypes));
2796 if (list.Count > 0) {
2797 MethodGroupExpr new_mg = new MethodGroupExpr (list, Location);
2798 new_mg.InstanceExpression = InstanceExpression;
2799 new_mg.HasTypeArguments = true;
2805 305, loc, "Using the generic method `{0}' " +
2806 "requires {1} type arguments", Name,
2810 308, loc, "The non-generic method `{0}' " +
2811 "cannot be used with type arguments", Name);
2818 /// Fully resolved expression that evaluates to a Field
2820 public class FieldExpr : Expression, IAssignMethod, IMemoryLocation, IMemberExpr, IVariable {
2821 public readonly FieldInfo FieldInfo;
2822 Expression instance_expr;
2823 VariableInfo variable_info;
2825 LocalTemporary temp;
2827 bool is_field_initializer;
2829 public FieldExpr (FieldInfo fi, Location l)
2832 eclass = ExprClass.Variable;
2833 type = TypeManager.TypeToCoreType (fi.FieldType);
2837 public string Name {
2839 return FieldInfo.Name;
2843 public bool IsInstance {
2845 return !FieldInfo.IsStatic;
2849 public bool IsStatic {
2851 return FieldInfo.IsStatic;
2855 public Type DeclaringType {
2857 return FieldInfo.DeclaringType;
2861 public Expression InstanceExpression {
2863 return instance_expr;
2867 instance_expr = value;
2871 public bool IsFieldInitializer {
2873 return is_field_initializer;
2877 is_field_initializer = value;
2881 public VariableInfo VariableInfo {
2883 return variable_info;
2887 override public Expression DoResolve (EmitContext ec)
2889 if (!FieldInfo.IsStatic){
2890 if (instance_expr == null){
2892 // This can happen when referencing an instance field using
2893 // a fully qualified type expression: TypeName.InstanceField = xxx
2895 SimpleName.Error_ObjectRefRequired (ec, loc, FieldInfo.Name);
2899 // Resolve the field's instance expression while flow analysis is turned
2900 // off: when accessing a field "a.b", we must check whether the field
2901 // "a.b" is initialized, not whether the whole struct "a" is initialized.
2902 instance_expr = instance_expr.Resolve (ec, ResolveFlags.VariableOrValue |
2903 ResolveFlags.DisableFlowAnalysis);
2904 if (instance_expr == null)
2908 ObsoleteAttribute oa;
2909 FieldBase f = TypeManager.GetField (FieldInfo);
2911 oa = f.GetObsoleteAttribute (ec.DeclSpace);
2913 AttributeTester.Report_ObsoleteMessage (oa, f.GetSignatureForError (), loc);
2914 // To be sure that type is external because we do not register generated fields
2915 } else if (!(FieldInfo.DeclaringType is TypeBuilder)) {
2916 oa = AttributeTester.GetMemberObsoleteAttribute (FieldInfo);
2918 AttributeTester.Report_ObsoleteMessage (oa, TypeManager.GetFullNameSignature (FieldInfo), loc);
2921 // If the instance expression is a local variable or parameter.
2922 IVariable var = instance_expr as IVariable;
2923 if ((var == null) || (var.VariableInfo == null))
2926 VariableInfo vi = var.VariableInfo;
2927 if (!vi.IsFieldAssigned (ec, FieldInfo.Name, loc))
2930 variable_info = vi.GetSubStruct (FieldInfo.Name);
2934 void Report_AssignToReadonly (bool is_instance)
2939 msg = "Readonly field can not be assigned outside " +
2940 "of constructor or variable initializer";
2942 msg = "A static readonly field can only be assigned in " +
2943 "a static constructor";
2945 Report.Error (is_instance ? 191 : 198, loc, msg);
2948 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
2950 IVariable var = instance_expr as IVariable;
2951 if ((var != null) && (var.VariableInfo != null))
2952 var.VariableInfo.SetFieldAssigned (ec, FieldInfo.Name);
2954 Expression e = DoResolve (ec);
2959 if (!FieldInfo.IsStatic && (instance_expr.Type.IsValueType && !(instance_expr is IMemoryLocation))) {
2960 // FIXME: Provide better error reporting.
2961 Error (1612, "Cannot modify expression because it is not a variable.");
2965 if (!FieldInfo.IsInitOnly)
2968 FieldBase fb = TypeManager.GetField (FieldInfo);
2973 // InitOnly fields can only be assigned in constructors
2976 if (ec.IsConstructor){
2977 if (IsStatic && !ec.IsStatic)
2978 Report_AssignToReadonly (false);
2981 if (!is_field_initializer &&
2982 (ec.TypeContainer.CurrentType != null))
2983 ctype = ec.TypeContainer.CurrentType.ResolveType (ec);
2985 ctype = ec.ContainerType;
2987 if (TypeManager.IsEqual (ctype, FieldInfo.DeclaringType))
2991 Report_AssignToReadonly (true);
2996 public bool VerifyFixed (bool is_expression)
2998 IVariable variable = instance_expr as IVariable;
2999 if ((variable == null) || !variable.VerifyFixed (true))
3005 public void Emit (EmitContext ec, bool leave_copy)
3007 ILGenerator ig = ec.ig;
3008 bool is_volatile = false;
3010 if (FieldInfo is FieldBuilder){
3011 FieldBase f = TypeManager.GetField (FieldInfo);
3013 if ((f.ModFlags & Modifiers.VOLATILE) != 0)
3016 f.status |= Field.Status.USED;
3020 if (FieldInfo.IsStatic){
3022 ig.Emit (OpCodes.Volatile);
3024 ig.Emit (OpCodes.Ldsfld, FieldInfo);
3030 ig.Emit (OpCodes.Volatile);
3032 ig.Emit (OpCodes.Ldfld, FieldInfo);
3036 ec.ig.Emit (OpCodes.Dup);
3037 if (!FieldInfo.IsStatic) {
3038 temp = new LocalTemporary (ec, this.Type);
3044 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
3046 FieldAttributes fa = FieldInfo.Attributes;
3047 bool is_static = (fa & FieldAttributes.Static) != 0;
3048 bool is_readonly = (fa & FieldAttributes.InitOnly) != 0;
3049 ILGenerator ig = ec.ig;
3050 prepared = prepare_for_load;
3052 if (is_readonly && !ec.IsConstructor){
3053 Report_AssignToReadonly (!is_static);
3059 if (prepare_for_load)
3060 ig.Emit (OpCodes.Dup);
3065 ec.ig.Emit (OpCodes.Dup);
3066 if (!FieldInfo.IsStatic) {
3067 temp = new LocalTemporary (ec, this.Type);
3072 if (FieldInfo is FieldBuilder){
3073 FieldBase f = TypeManager.GetField (FieldInfo);
3075 if ((f.ModFlags & Modifiers.VOLATILE) != 0)
3076 ig.Emit (OpCodes.Volatile);
3078 f.status |= Field.Status.ASSIGNED;
3083 ig.Emit (OpCodes.Stsfld, FieldInfo);
3085 ig.Emit (OpCodes.Stfld, FieldInfo);
3091 void EmitInstance (EmitContext ec)
3093 if (instance_expr.Type.IsValueType) {
3094 if (instance_expr is IMemoryLocation) {
3095 ((IMemoryLocation) instance_expr).AddressOf (ec, AddressOp.LoadStore);
3097 LocalTemporary t = new LocalTemporary (ec, instance_expr.Type);
3098 instance_expr.Emit (ec);
3100 t.AddressOf (ec, AddressOp.Store);
3103 instance_expr.Emit (ec);
3106 public override void Emit (EmitContext ec)
3111 public void AddressOf (EmitContext ec, AddressOp mode)
3113 ILGenerator ig = ec.ig;
3115 if (FieldInfo is FieldBuilder){
3116 FieldBase f = TypeManager.GetField (FieldInfo);
3118 if ((f.ModFlags & Modifiers.VOLATILE) != 0){
3119 Error (676, "volatile variable: can not take its address, or pass as ref/out parameter");
3123 if ((mode & AddressOp.Store) != 0)
3124 f.status |= Field.Status.ASSIGNED;
3125 if ((mode & AddressOp.Load) != 0)
3126 f.status |= Field.Status.USED;
3131 // Handle initonly fields specially: make a copy and then
3132 // get the address of the copy.
3135 if (FieldInfo.IsInitOnly){
3137 if (ec.IsConstructor){
3138 if (FieldInfo.IsStatic){
3150 local = ig.DeclareLocal (type);
3151 ig.Emit (OpCodes.Stloc, local);
3152 ig.Emit (OpCodes.Ldloca, local);
3157 if (FieldInfo.IsStatic){
3158 ig.Emit (OpCodes.Ldsflda, FieldInfo);
3161 ig.Emit (OpCodes.Ldflda, FieldInfo);
3167 // A FieldExpr whose address can not be taken
3169 public class FieldExprNoAddress : FieldExpr, IMemoryLocation {
3170 public FieldExprNoAddress (FieldInfo fi, Location loc) : base (fi, loc)
3174 public new void AddressOf (EmitContext ec, AddressOp mode)
3176 Report.Error (-215, "Report this: Taking the address of a remapped parameter not supported");
3181 /// Expression that evaluates to a Property. The Assign class
3182 /// might set the `Value' expression if we are in an assignment.
3184 /// This is not an LValue because we need to re-write the expression, we
3185 /// can not take data from the stack and store it.
3187 public class PropertyExpr : ExpressionStatement, IAssignMethod, IMemberExpr {
3188 public readonly PropertyInfo PropertyInfo;
3191 // This is set externally by the `BaseAccess' class
3194 MethodInfo getter, setter;
3196 bool must_do_cs1540_check;
3198 Expression instance_expr;
3199 LocalTemporary temp;
3202 public PropertyExpr (EmitContext ec, PropertyInfo pi, Location l)
3205 eclass = ExprClass.PropertyAccess;
3209 type = TypeManager.TypeToCoreType (pi.PropertyType);
3211 ResolveAccessors (ec);
3214 public string Name {
3216 return PropertyInfo.Name;
3220 public bool IsInstance {
3226 public bool IsStatic {
3232 public Type DeclaringType {
3234 return PropertyInfo.DeclaringType;
3239 // The instance expression associated with this expression
3241 public Expression InstanceExpression {
3243 instance_expr = value;
3247 return instance_expr;
3251 public bool VerifyAssignable ()
3253 if (setter == null) {
3254 Report.Error (200, loc,
3255 "The property `" + PropertyInfo.Name +
3256 "' can not be assigned to, as it has not set accessor");
3263 MethodInfo FindAccessor (Type invocation_type, bool is_set)
3265 BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic |
3266 BindingFlags.Static | BindingFlags.Instance |
3267 BindingFlags.DeclaredOnly;
3269 Type current = PropertyInfo.DeclaringType;
3270 for (; current != null; current = current.BaseType) {
3271 MemberInfo[] group = TypeManager.MemberLookup (
3272 invocation_type, invocation_type, current,
3273 MemberTypes.Property, flags, PropertyInfo.Name, null);
3278 if (group.Length != 1)
3279 // Oooops, can this ever happen ?
3282 PropertyInfo pi = (PropertyInfo) group [0];
3284 MethodInfo get = pi.GetGetMethod (true);
3285 MethodInfo set = pi.GetSetMethod (true);
3295 MethodInfo accessor = get != null ? get : set;
3296 if (accessor == null)
3298 if ((accessor.Attributes & MethodAttributes.NewSlot) != 0)
3305 MethodInfo GetAccessor (Type invocation_type, bool is_set)
3307 MethodInfo mi = FindAccessor (invocation_type, is_set);
3311 MethodAttributes ma = mi.Attributes & MethodAttributes.MemberAccessMask;
3314 // If only accessible to the current class or children
3316 if (ma == MethodAttributes.Private) {
3317 Type declaring_type = mi.DeclaringType;
3319 if (invocation_type != declaring_type){
3320 if (TypeManager.IsSubclassOrNestedChildOf (invocation_type, mi.DeclaringType))
3328 // FamAndAssem requires that we not only derivate, but we are on the
3331 if (ma == MethodAttributes.FamANDAssem){
3332 if (mi.DeclaringType.Assembly != invocation_type.Assembly)
3338 // Assembly and FamORAssem succeed if we're in the same assembly.
3339 if ((ma == MethodAttributes.Assembly) || (ma == MethodAttributes.FamORAssem)){
3340 if (mi.DeclaringType.Assembly == invocation_type.Assembly)
3344 // We already know that we aren't in the same assembly.
3345 if (ma == MethodAttributes.Assembly)
3348 // Family and FamANDAssem require that we derive.
3349 if ((ma == MethodAttributes.Family) || (ma == MethodAttributes.FamANDAssem) || (ma == MethodAttributes.FamORAssem)){
3350 if (!TypeManager.IsSubclassOrNestedChildOf (invocation_type, mi.DeclaringType))
3353 if (!TypeManager.IsNestedChildOf (invocation_type, mi.DeclaringType))
3354 must_do_cs1540_check = true;
3364 // We also perform the permission checking here, as the PropertyInfo does not
3365 // hold the information for the accessibility of its setter/getter
3367 void ResolveAccessors (EmitContext ec)
3369 getter = GetAccessor (ec.ContainerType, false);
3370 if ((getter != null) && getter.IsStatic)
3373 setter = GetAccessor (ec.ContainerType, true);
3374 if ((setter != null) && setter.IsStatic)
3377 if (setter == null && getter == null){
3378 Report.Error_T (122, loc, PropertyInfo.Name);
3382 bool InstanceResolve (EmitContext ec)
3384 if ((instance_expr == null) && ec.IsStatic && !is_static) {
3385 SimpleName.Error_ObjectRefRequired (ec, loc, PropertyInfo.Name);
3389 if (instance_expr != null) {
3390 instance_expr = instance_expr.DoResolve (ec);
3391 if (instance_expr == null)
3395 if (must_do_cs1540_check && (instance_expr != null)) {
3396 if ((instance_expr.Type != ec.ContainerType) &&
3397 ec.ContainerType.IsSubclassOf (instance_expr.Type)) {
3398 Report.Error (1540, loc, "Cannot access protected member `" +
3399 PropertyInfo.DeclaringType + "." + PropertyInfo.Name +
3400 "' via a qualifier of type `" +
3401 TypeManager.CSharpName (instance_expr.Type) +
3402 "'; the qualifier must be of type `" +
3403 TypeManager.CSharpName (ec.ContainerType) +
3404 "' (or derived from it)");
3412 override public Expression DoResolve (EmitContext ec)
3414 if (getter != null){
3415 if (TypeManager.GetArgumentTypes (getter).Length != 0){
3417 117, loc, "`{0}' does not contain a " +
3418 "definition for `{1}'.", getter.DeclaringType,
3424 if (getter == null){
3426 // The following condition happens if the PropertyExpr was
3427 // created, but is invalid (ie, the property is inaccessible),
3428 // and we did not want to embed the knowledge about this in
3429 // the caller routine. This only avoids double error reporting.
3434 Report.Error (154, loc,
3435 "The property `" + PropertyInfo.Name +
3436 "' can not be used in " +
3437 "this context because it lacks a get accessor");
3441 if (!InstanceResolve (ec))
3445 // Only base will allow this invocation to happen.
3447 if (IsBase && getter.IsAbstract){
3448 Report.Error (205, loc, "Cannot call an abstract base property: " +
3449 PropertyInfo.DeclaringType + "." +PropertyInfo.Name);
3456 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
3458 if (setter == null){
3460 // The following condition happens if the PropertyExpr was
3461 // created, but is invalid (ie, the property is inaccessible),
3462 // and we did not want to embed the knowledge about this in
3463 // the caller routine. This only avoids double error reporting.
3468 Report.Error (154, loc,
3469 "The property `" + PropertyInfo.Name +
3470 "' can not be used in " +
3471 "this context because it lacks a set accessor");
3475 if (TypeManager.GetArgumentTypes (setter).Length != 1){
3477 117, loc, "`{0}' does not contain a " +
3478 "definition for `{1}'.", getter.DeclaringType,
3483 if (!InstanceResolve (ec))
3487 // Only base will allow this invocation to happen.
3489 if (IsBase && setter.IsAbstract){
3490 Report.Error (205, loc, "Cannot call an abstract base property: " +
3491 PropertyInfo.DeclaringType + "." +PropertyInfo.Name);
3496 // Check that we are not making changes to a temporary memory location
3498 if (instance_expr != null && instance_expr.Type.IsValueType && !(instance_expr is IMemoryLocation)) {
3499 // FIXME: Provide better error reporting.
3500 Error (1612, "Cannot modify expression because it is not a variable.");
3509 public override void Emit (EmitContext ec)
3514 void EmitInstance (EmitContext ec)
3519 if (instance_expr.Type.IsValueType) {
3520 if (instance_expr is IMemoryLocation) {
3521 ((IMemoryLocation) instance_expr).AddressOf (ec, AddressOp.LoadStore);
3523 LocalTemporary t = new LocalTemporary (ec, instance_expr.Type);
3524 instance_expr.Emit (ec);
3526 t.AddressOf (ec, AddressOp.Store);
3529 instance_expr.Emit (ec);
3532 ec.ig.Emit (OpCodes.Dup);
3536 public void Emit (EmitContext ec, bool leave_copy)
3542 // Special case: length of single dimension array property is turned into ldlen
3544 if ((getter == TypeManager.system_int_array_get_length) ||
3545 (getter == TypeManager.int_array_get_length)){
3546 Type iet = instance_expr.Type;
3549 // System.Array.Length can be called, but the Type does not
3550 // support invoking GetArrayRank, so test for that case first
3552 if (iet != TypeManager.array_type && (iet.GetArrayRank () == 1)) {
3553 ec.ig.Emit (OpCodes.Ldlen);
3554 ec.ig.Emit (OpCodes.Conv_I4);
3559 Invocation.EmitCall (ec, IsBase, IsStatic, new EmptyAddressOf (), getter, null, loc);
3564 ec.ig.Emit (OpCodes.Dup);
3566 temp = new LocalTemporary (ec, this.Type);
3572 // Implements the IAssignMethod interface for assignments
3574 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
3576 prepared = prepare_for_load;
3582 ec.ig.Emit (OpCodes.Dup);
3584 temp = new LocalTemporary (ec, this.Type);
3589 ArrayList args = new ArrayList (1);
3590 args.Add (new Argument (new EmptyAddressOf (), Argument.AType.Expression));
3592 Invocation.EmitCall (ec, IsBase, IsStatic, new EmptyAddressOf (), setter, args, loc);
3598 override public void EmitStatement (EmitContext ec)
3601 ec.ig.Emit (OpCodes.Pop);
3606 /// Fully resolved expression that evaluates to an Event
3608 public class EventExpr : Expression, IMemberExpr {
3609 public readonly EventInfo EventInfo;
3610 Expression instance_expr;
3613 MethodInfo add_accessor, remove_accessor;
3615 public EventExpr (EventInfo ei, Location loc)
3619 eclass = ExprClass.EventAccess;
3621 add_accessor = TypeManager.GetAddMethod (ei);
3622 remove_accessor = TypeManager.GetRemoveMethod (ei);
3624 if (add_accessor.IsStatic || remove_accessor.IsStatic)
3627 if (EventInfo is MyEventBuilder){
3628 MyEventBuilder eb = (MyEventBuilder) EventInfo;
3629 type = eb.EventType;
3632 type = EventInfo.EventHandlerType;
3635 public string Name {
3637 return EventInfo.Name;
3641 public bool IsInstance {
3647 public bool IsStatic {
3653 public Type DeclaringType {
3655 return EventInfo.DeclaringType;
3659 public Expression InstanceExpression {
3661 return instance_expr;
3665 instance_expr = value;
3669 public override Expression DoResolve (EmitContext ec)
3671 if (instance_expr != null) {
3672 instance_expr = instance_expr.DoResolve (ec);
3673 if (instance_expr == null)
3681 public override void Emit (EmitContext ec)
3683 Report.Error (70, loc, "The event `" + Name + "' can only appear on the left hand side of += or -= (except on the defining type)");
3686 public void EmitAddOrRemove (EmitContext ec, Expression source)
3688 BinaryDelegate source_del = (BinaryDelegate) source;
3689 Expression handler = source_del.Right;
3691 Argument arg = new Argument (handler, Argument.AType.Expression);
3692 ArrayList args = new ArrayList ();
3696 if (source_del.IsAddition)
3697 Invocation.EmitCall (
3698 ec, false, IsStatic, instance_expr, add_accessor, args, loc);
3700 Invocation.EmitCall (
3701 ec, false, IsStatic, instance_expr, remove_accessor, args, loc);