2009-11-24 Jb Evain <jbevain@novell.com>
[mcs.git] / mcs / ecore.cs
blobf2c4bb2e9f374bb0f372df87555e85b90cdb4e3d
1 //
2 // ecore.cs: Core of the Expression representation for the intermediate tree.
3 //
4 // Author:
5 // Miguel de Icaza (miguel@ximian.com)
6 // Marek Safar (marek.safar@seznam.cz)
7 //
8 // Copyright 2001, 2002, 2003 Ximian, Inc.
9 // Copyright 2003-2008 Novell, Inc.
13 namespace Mono.CSharp {
14 using System;
15 using System.Collections;
16 using System.Diagnostics;
17 using System.Reflection;
18 using System.Reflection.Emit;
19 using System.Text;
21 #if NET_4_0
22 using SLE = System.Linq.Expressions;
23 #endif
25 /// <remarks>
26 /// The ExprClass class contains the is used to pass the
27 /// classification of an expression (value, variable, namespace,
28 /// type, method group, property access, event access, indexer access,
29 /// nothing).
30 /// </remarks>
31 public enum ExprClass : byte {
32 Unresolved = 0,
34 Value,
35 Variable,
36 Namespace,
37 Type,
38 TypeParameter,
39 MethodGroup,
40 PropertyAccess,
41 EventAccess,
42 IndexerAccess,
43 Nothing,
46 /// <remarks>
47 /// This is used to tell Resolve in which types of expressions we're
48 /// interested.
49 /// </remarks>
50 [Flags]
51 public enum ResolveFlags {
52 // Returns Value, Variable, PropertyAccess, EventAccess or IndexerAccess.
53 VariableOrValue = 1,
55 // Returns a type expression.
56 Type = 1 << 1,
58 // Returns a method group.
59 MethodGroup = 1 << 2,
61 TypeParameter = 1 << 3,
63 // Mask of all the expression class flags.
64 MaskExprClass = VariableOrValue | Type | MethodGroup | TypeParameter,
66 // Set if this is resolving the first part of a MemberAccess.
67 Intermediate = 1 << 11,
71 // This is just as a hint to AddressOf of what will be done with the
72 // address.
73 [Flags]
74 public enum AddressOp {
75 Store = 1,
76 Load = 2,
77 LoadStore = 3
80 /// <summary>
81 /// This interface is implemented by variables
82 /// </summary>
83 public interface IMemoryLocation {
84 /// <summary>
85 /// The AddressOf method should generate code that loads
86 /// the address of the object and leaves it on the stack.
87 ///
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.
91 ///
92 /// This is just a hint that can be used to provide good error
93 /// reporting, and should have no other side effects.
94 /// </summary>
95 void AddressOf (EmitContext ec, AddressOp mode);
99 // An expressions resolved as a direct variable reference
101 public interface IVariableReference : IFixedExpression
103 bool IsHoisted { get; }
104 string Name { get; }
105 VariableInfo VariableInfo { get; }
107 void SetHasAddressTaken ();
111 // Implemented by an expression which could be or is always
112 // fixed
114 public interface IFixedExpression
116 bool IsFixed { get; }
119 /// <remarks>
120 /// Base class for expressions
121 /// </remarks>
122 public abstract class Expression {
123 public ExprClass eclass;
124 protected Type type;
125 protected Location loc;
127 public Type Type {
128 get { return type; }
129 set { type = value; }
132 public virtual Location Location {
133 get { return loc; }
136 // Not nice but we have broken hierarchy.
137 public virtual void CheckMarshalByRefAccess (ResolveContext ec)
141 public virtual bool GetAttributableValue (ResolveContext ec, Type value_type, out object value)
143 Attribute.Error_AttributeArgumentNotValid (ec, loc);
144 value = null;
145 return false;
148 public virtual string GetSignatureForError ()
150 return TypeManager.CSharpName (type);
153 public static bool IsAccessorAccessible (Type invocation_type, MethodInfo mi, out bool must_do_cs1540_check)
155 MethodAttributes ma = mi.Attributes & MethodAttributes.MemberAccessMask;
157 must_do_cs1540_check = false; // by default we do not check for this
159 if (ma == MethodAttributes.Public)
160 return true;
163 // If only accessible to the current class or children
165 if (ma == MethodAttributes.Private)
166 return TypeManager.IsPrivateAccessible (invocation_type, mi.DeclaringType) ||
167 TypeManager.IsNestedChildOf (invocation_type, mi.DeclaringType);
169 if (TypeManager.IsThisOrFriendAssembly (invocation_type.Assembly, mi.DeclaringType.Assembly)) {
170 if (ma == MethodAttributes.Assembly || ma == MethodAttributes.FamORAssem)
171 return true;
172 } else {
173 if (ma == MethodAttributes.Assembly || ma == MethodAttributes.FamANDAssem)
174 return false;
177 // Family and FamANDAssem require that we derive.
178 // FamORAssem requires that we derive if in different assemblies.
179 if (!TypeManager.IsNestedFamilyAccessible (invocation_type, mi.DeclaringType))
180 return false;
182 if (!TypeManager.IsNestedChildOf (invocation_type, mi.DeclaringType))
183 must_do_cs1540_check = true;
185 return true;
188 public virtual bool IsNull {
189 get {
190 return false;
194 /// <summary>
195 /// Performs semantic analysis on the Expression
196 /// </summary>
198 /// <remarks>
199 /// The Resolve method is invoked to perform the semantic analysis
200 /// on the node.
202 /// The return value is an expression (it can be the
203 /// same expression in some cases) or a new
204 /// expression that better represents this node.
205 ///
206 /// For example, optimizations of Unary (LiteralInt)
207 /// would return a new LiteralInt with a negated
208 /// value.
209 ///
210 /// If there is an error during semantic analysis,
211 /// then an error should be reported (using Report)
212 /// and a null value should be returned.
213 ///
214 /// There are two side effects expected from calling
215 /// Resolve(): the the field variable "eclass" should
216 /// be set to any value of the enumeration
217 /// `ExprClass' and the type variable should be set
218 /// to a valid type (this is the type of the
219 /// expression).
220 /// </remarks>
221 protected abstract Expression DoResolve (ResolveContext rc);
223 public virtual Expression DoResolveLValue (ResolveContext rc, Expression right_side)
225 return null;
229 // This is used if the expression should be resolved as a type or namespace name.
230 // the default implementation fails.
232 public virtual FullNamedExpression ResolveAsTypeStep (IMemberContext rc, bool silent)
234 if (!silent) {
235 ResolveContext ec = new ResolveContext (rc);
236 Expression e = Resolve (ec);
237 if (e != null)
238 e.Error_UnexpectedKind (ec, ResolveFlags.Type, loc);
241 return null;
245 // C# 3.0 introduced contextual keywords (var) which behaves like a type if type with
246 // same name exists or as a keyword when no type was found
248 public virtual TypeExpr ResolveAsContextualType (IMemberContext rc, bool silent)
250 return ResolveAsTypeTerminal (rc, silent);
254 // This is used to resolve the expression as a type, a null
255 // value will be returned if the expression is not a type
256 // reference
258 public virtual TypeExpr ResolveAsTypeTerminal (IMemberContext ec, bool silent)
260 TypeExpr te = ResolveAsBaseTerminal (ec, silent);
261 if (te == null)
262 return null;
264 if (!silent) { // && !(te is TypeParameterExpr)) {
265 ObsoleteAttribute obsolete_attr = AttributeTester.GetObsoleteAttribute (te.Type);
266 if (obsolete_attr != null && !ec.IsObsolete) {
267 AttributeTester.Report_ObsoleteMessage (obsolete_attr, te.GetSignatureForError (), Location, ec.Compiler.Report);
271 GenericTypeExpr ct = te as GenericTypeExpr;
272 if (ct != null) {
274 // TODO: Constrained type parameters check for parameters of generic method overrides is broken
275 // There are 2 solutions.
276 // 1, Skip this check completely when we are in override/explicit impl scope
277 // 2, Copy type parameters constraints from base implementation and pass (they have to be emitted anyway)
279 MemberCore gm = ec as GenericMethod;
280 if (gm == null)
281 gm = ec as Method;
282 if (gm != null && ((gm.ModFlags & Modifiers.OVERRIDE) != 0 || gm.MemberName.Left != null)) {
283 te.loc = loc;
284 return te;
287 // TODO: silent flag is ignored
288 ct.CheckConstraints (ec);
291 return te;
294 public TypeExpr ResolveAsBaseTerminal (IMemberContext ec, bool silent)
296 int errors = ec.Compiler.Report.Errors;
298 FullNamedExpression fne = ResolveAsTypeStep (ec, silent);
300 if (fne == null)
301 return null;
303 TypeExpr te = fne as TypeExpr;
304 if (te == null) {
305 if (!silent && errors == ec.Compiler.Report.Errors)
306 fne.Error_UnexpectedKind (ec.Compiler.Report, null, "type", loc);
307 return null;
310 if (!te.CheckAccessLevel (ec)) {
311 ec.Compiler.Report.SymbolRelatedToPreviousError (te.Type);
312 ErrorIsInaccesible (loc, TypeManager.CSharpName (te.Type), ec.Compiler.Report);
313 return null;
316 te.loc = loc;
317 return te;
320 public static void ErrorIsInaccesible (Location loc, string name, Report Report)
322 Report.Error (122, loc, "`{0}' is inaccessible due to its protection level", name);
325 protected static void Error_CannotAccessProtected (ResolveContext ec, Location loc, MemberInfo m, Type qualifier, Type container)
327 ec.Report.Error (1540, loc, "Cannot access protected member `{0}' via a qualifier of type `{1}'."
328 + " The qualifier must be of type `{2}' or derived from it",
329 TypeManager.GetFullNameSignature (m),
330 TypeManager.CSharpName (qualifier),
331 TypeManager.CSharpName (container));
335 public static void Error_InvalidExpressionStatement (Report Report, Location loc)
337 Report.Error (201, loc, "Only assignment, call, increment, decrement, and new object " +
338 "expressions can be used as a statement");
341 public void Error_InvalidExpressionStatement (BlockContext ec)
343 Error_InvalidExpressionStatement (ec.Report, loc);
346 public static void Error_VoidInvalidInTheContext (Location loc, Report Report)
348 Report.Error (1547, loc, "Keyword `void' cannot be used in this context");
351 public virtual void Error_ValueCannotBeConverted (ResolveContext ec, Location loc, Type target, bool expl)
353 Error_ValueCannotBeConvertedCore (ec, loc, target, expl);
356 protected void Error_ValueCannotBeConvertedCore (ResolveContext ec, Location loc, Type target, bool expl)
358 // The error was already reported as CS1660
359 if (type == InternalType.AnonymousMethod)
360 return;
362 if (TypeManager.IsGenericParameter (Type) && TypeManager.IsGenericParameter (target) && type.Name == target.Name) {
363 string sig1 = type.DeclaringMethod == null ?
364 TypeManager.CSharpName (type.DeclaringType) :
365 TypeManager.CSharpSignature (type.DeclaringMethod);
366 string sig2 = target.DeclaringMethod == null ?
367 TypeManager.CSharpName (target.DeclaringType) :
368 TypeManager.CSharpSignature (target.DeclaringMethod);
369 ec.Report.ExtraInformation (loc,
370 String.Format (
371 "The generic parameter `{0}' of `{1}' cannot be converted to the generic parameter `{0}' of `{2}' (in the previous ",
372 Type.Name, sig1, sig2));
373 } else if (Type.FullName == target.FullName){
374 ec.Report.ExtraInformation (loc,
375 String.Format (
376 "The type `{0}' has two conflicting definitions, one comes from `{1}' and the other from `{2}' (in the previous ",
377 Type.FullName, Type.Assembly.FullName, target.Assembly.FullName));
380 if (expl) {
381 ec.Report.Error (30, loc, "Cannot convert type `{0}' to `{1}'",
382 TypeManager.CSharpName (type), TypeManager.CSharpName (target));
383 return;
386 ec.Report.DisableReporting ();
387 bool expl_exists = Convert.ExplicitConversion (ec, this, target, Location.Null) != null;
388 ec.Report.EnableReporting ();
390 if (expl_exists) {
391 ec.Report.Error (266, loc, "Cannot implicitly convert type `{0}' to `{1}'. " +
392 "An explicit conversion exists (are you missing a cast?)",
393 TypeManager.CSharpName (Type), TypeManager.CSharpName (target));
394 return;
397 ec.Report.Error (29, loc, "Cannot implicitly convert type `{0}' to `{1}'",
398 TypeManager.CSharpName (type),
399 TypeManager.CSharpName (target));
402 public virtual void Error_VariableIsUsedBeforeItIsDeclared (Report Report, string name)
404 Report.Error (841, loc, "A local variable `{0}' cannot be used before it is declared", name);
407 public void Error_TypeArgumentsCannotBeUsed (Report report, Location loc)
409 // Better message for possible generic expressions
410 if (eclass == ExprClass.MethodGroup || eclass == ExprClass.Type) {
411 if (this is TypeExpr)
412 report.SymbolRelatedToPreviousError (type);
414 string name = eclass == ExprClass.Type ? ExprClassName : "method";
415 report.Error (308, loc, "The non-generic {0} `{1}' cannot be used with the type arguments",
416 name, GetSignatureForError ());
417 } else {
418 report.Error (307, loc, "The {0} `{1}' cannot be used with type arguments",
419 ExprClassName, GetSignatureForError ());
423 protected virtual void Error_TypeDoesNotContainDefinition (ResolveContext ec, Type type, string name)
425 Error_TypeDoesNotContainDefinition (ec, loc, type, name);
428 public static void Error_TypeDoesNotContainDefinition (ResolveContext ec, Location loc, Type type, string name)
430 ec.Report.SymbolRelatedToPreviousError (type);
431 ec.Report.Error (117, loc, "`{0}' does not contain a definition for `{1}'",
432 TypeManager.CSharpName (type), name);
435 protected static void Error_ValueAssignment (ResolveContext ec, Location loc)
437 ec.Report.Error (131, loc, "The left-hand side of an assignment must be a variable, a property or an indexer");
440 ResolveFlags ExprClassToResolveFlags {
441 get {
442 switch (eclass) {
443 case ExprClass.Type:
444 case ExprClass.Namespace:
445 return ResolveFlags.Type;
447 case ExprClass.MethodGroup:
448 return ResolveFlags.MethodGroup;
450 case ExprClass.TypeParameter:
451 return ResolveFlags.TypeParameter;
453 case ExprClass.Value:
454 case ExprClass.Variable:
455 case ExprClass.PropertyAccess:
456 case ExprClass.EventAccess:
457 case ExprClass.IndexerAccess:
458 return ResolveFlags.VariableOrValue;
460 default:
461 throw new InternalErrorException (loc.ToString () + " " + GetType () + " ExprClass is Invalid after resolve");
466 /// <summary>
467 /// Resolves an expression and performs semantic analysis on it.
468 /// </summary>
470 /// <remarks>
471 /// Currently Resolve wraps DoResolve to perform sanity
472 /// checking and assertion checking on what we expect from Resolve.
473 /// </remarks>
474 public Expression Resolve (ResolveContext ec, ResolveFlags flags)
476 if (eclass != ExprClass.Unresolved)
477 return this;
479 Expression e;
480 if (this is SimpleName) {
481 e = ((SimpleName) this).DoResolve (ec, (flags & ResolveFlags.Intermediate) != 0);
482 } else {
483 e = DoResolve (ec);
486 if (e == null)
487 return null;
489 if ((flags & e.ExprClassToResolveFlags) == 0) {
490 e.Error_UnexpectedKind (ec, flags, loc);
491 return null;
494 if (e.type == null)
495 throw new InternalErrorException ("Expression `{0}' didn't set its type in DoResolve", e.GetType ());
497 return e;
500 /// <summary>
501 /// Resolves an expression and performs semantic analysis on it.
502 /// </summary>
503 public Expression Resolve (ResolveContext rc)
505 return Resolve (rc, ResolveFlags.VariableOrValue | ResolveFlags.MethodGroup);
508 public Constant ResolveAsConstant (ResolveContext ec, MemberCore mc)
510 Expression e = Resolve (ec);
511 if (e == null)
512 return null;
514 Constant c = e as Constant;
515 if (c != null)
516 return c;
518 if (type != null && TypeManager.IsReferenceType (type))
519 Const.Error_ConstantCanBeInitializedWithNullOnly (type, loc, mc.GetSignatureForError (), ec.Report);
520 else
521 Const.Error_ExpressionMustBeConstant (loc, mc.GetSignatureForError (), ec.Report);
523 return null;
526 /// <summary>
527 /// Resolves an expression for LValue assignment
528 /// </summary>
530 /// <remarks>
531 /// Currently ResolveLValue wraps DoResolveLValue to perform sanity
532 /// checking and assertion checking on what we expect from Resolve
533 /// </remarks>
534 public Expression ResolveLValue (ResolveContext ec, Expression right_side)
536 int errors = ec.Report.Errors;
537 bool out_access = right_side == EmptyExpression.OutAccess.Instance;
539 Expression e = DoResolveLValue (ec, right_side);
541 if (e != null && out_access && !(e is IMemoryLocation)) {
542 // FIXME: There's no problem with correctness, the 'Expr = null' handles that.
543 // Enabling this 'throw' will "only" result in deleting useless code elsewhere,
545 //throw new InternalErrorException ("ResolveLValue didn't return an IMemoryLocation: " +
546 // e.GetType () + " " + e.GetSignatureForError ());
547 e = null;
550 if (e == null) {
551 if (errors == ec.Report.Errors) {
552 if (out_access)
553 ec.Report.Error (1510, loc, "A ref or out argument must be an assignable variable");
554 else
555 Error_ValueAssignment (ec, loc);
557 return null;
560 if (e.eclass == ExprClass.Unresolved)
561 throw new Exception ("Expression " + e + " ExprClass is Invalid after resolve");
563 if ((e.type == null) && !(e is GenericTypeExpr))
564 throw new Exception ("Expression " + e + " did not set its type after Resolve");
566 return e;
569 /// <summary>
570 /// Emits the code for the expression
571 /// </summary>
573 /// <remarks>
574 /// The Emit method is invoked to generate the code
575 /// for the expression.
576 /// </remarks>
577 public abstract void Emit (EmitContext ec);
579 // Emit code to branch to @target if this expression is equivalent to @on_true.
580 // The default implementation is to emit the value, and then emit a brtrue or brfalse.
581 // Subclasses can provide more efficient implementations, but those MUST be equivalent,
582 // including the use of conditional branches. Note also that a branch MUST be emitted
583 public virtual void EmitBranchable (EmitContext ec, Label target, bool on_true)
585 Emit (ec);
586 ec.ig.Emit (on_true ? OpCodes.Brtrue : OpCodes.Brfalse, target);
589 // Emit this expression for its side effects, not for its value.
590 // The default implementation is to emit the value, and then throw it away.
591 // Subclasses can provide more efficient implementations, but those MUST be equivalent
592 public virtual void EmitSideEffect (EmitContext ec)
594 Emit (ec);
595 ec.ig.Emit (OpCodes.Pop);
598 /// <summary>
599 /// Protected constructor. Only derivate types should
600 /// be able to be created
601 /// </summary>
603 protected Expression ()
607 /// <summary>
608 /// Returns a fully formed expression after a MemberLookup
609 /// </summary>
610 ///
611 public static Expression ExprClassFromMemberInfo (Type container_type, MemberInfo mi, Location loc)
613 if (mi is EventInfo)
614 return new EventExpr ((EventInfo) mi, loc);
615 else if (mi is FieldInfo) {
616 FieldInfo fi = (FieldInfo) mi;
617 if (fi.IsLiteral || (fi.IsInitOnly && fi.FieldType == TypeManager.decimal_type))
618 return new ConstantExpr (fi, loc);
619 return new FieldExpr (fi, loc);
620 } else if (mi is PropertyInfo)
621 return new PropertyExpr (container_type, (PropertyInfo) mi, loc);
622 else if (mi is Type) {
623 return new TypeExpression ((System.Type) mi, loc);
626 return null;
629 // TODO: [Obsolete ("Can be removed")]
630 protected static ArrayList almost_matched_members = new ArrayList (4);
633 // FIXME: Probably implement a cache for (t,name,current_access_set)?
635 // This code could use some optimizations, but we need to do some
636 // measurements. For example, we could use a delegate to `flag' when
637 // something can not any longer be a method-group (because it is something
638 // else).
640 // Return values:
641 // If the return value is an Array, then it is an array of
642 // MethodBases
644 // If the return value is an MemberInfo, it is anything, but a Method
646 // null on error.
648 // FIXME: When calling MemberLookup inside an `Invocation', we should pass
649 // the arguments here and have MemberLookup return only the methods that
650 // match the argument count/type, unlike we are doing now (we delay this
651 // decision).
653 // This is so we can catch correctly attempts to invoke instance methods
654 // from a static body (scan for error 120 in ResolveSimpleName).
657 // FIXME: Potential optimization, have a static ArrayList
660 public static Expression MemberLookup (CompilerContext ctx, Type container_type, Type queried_type, string name,
661 MemberTypes mt, BindingFlags bf, Location loc)
663 return MemberLookup (ctx, container_type, null, queried_type, name, mt, bf, loc);
667 // Lookup type `queried_type' for code in class `container_type' with a qualifier of
668 // `qualifier_type' or null to lookup members in the current class.
671 public static Expression MemberLookup (CompilerContext ctx, Type container_type,
672 Type qualifier_type, Type queried_type,
673 string name, MemberTypes mt,
674 BindingFlags bf, Location loc)
676 almost_matched_members.Clear ();
678 MemberInfo [] mi = TypeManager.MemberLookup (container_type, qualifier_type,
679 queried_type, mt, bf, name, almost_matched_members);
681 if (mi == null)
682 return null;
684 if (mi.Length > 1) {
685 bool is_interface = qualifier_type != null && qualifier_type.IsInterface;
686 ArrayList methods = new ArrayList (2);
687 ArrayList non_methods = null;
689 foreach (MemberInfo m in mi) {
690 if (m is MethodBase) {
691 methods.Add (m);
692 continue;
695 if (non_methods == null)
696 non_methods = new ArrayList (2);
698 bool is_candidate = true;
699 for (int i = 0; i < non_methods.Count; ++i) {
700 MemberInfo n_m = (MemberInfo) non_methods [i];
701 if (n_m.DeclaringType.IsInterface && TypeManager.ImplementsInterface (m.DeclaringType, n_m.DeclaringType)) {
702 non_methods.Remove (n_m);
703 --i;
704 } else if (m.DeclaringType.IsInterface && TypeManager.ImplementsInterface (n_m.DeclaringType, m.DeclaringType)) {
705 is_candidate = false;
706 break;
710 if (is_candidate) {
711 non_methods.Add (m);
715 if (methods.Count == 0 && non_methods != null && non_methods.Count > 1) {
716 ctx.Report.SymbolRelatedToPreviousError ((MemberInfo)non_methods [1]);
717 ctx.Report.SymbolRelatedToPreviousError ((MemberInfo)non_methods [0]);
718 ctx.Report.Error (229, loc, "Ambiguity between `{0}' and `{1}'",
719 TypeManager.GetFullNameSignature ((MemberInfo)non_methods [1]),
720 TypeManager.GetFullNameSignature ((MemberInfo)non_methods [0]));
721 return null;
724 if (methods.Count == 0)
725 return ExprClassFromMemberInfo (container_type, (MemberInfo)non_methods [0], loc);
727 if (non_methods != null && non_methods.Count > 0) {
728 MethodBase method = (MethodBase) methods [0];
729 MemberInfo non_method = (MemberInfo) non_methods [0];
730 if (method.DeclaringType == non_method.DeclaringType) {
731 // Cannot happen with C# code, but is valid in IL
732 ctx.Report.SymbolRelatedToPreviousError (method);
733 ctx.Report.SymbolRelatedToPreviousError (non_method);
734 ctx.Report.Error (229, loc, "Ambiguity between `{0}' and `{1}'",
735 TypeManager.GetFullNameSignature (non_method),
736 TypeManager.CSharpSignature (method));
737 return null;
740 if (is_interface) {
741 ctx.Report.SymbolRelatedToPreviousError (method);
742 ctx.Report.SymbolRelatedToPreviousError (non_method);
743 ctx.Report.Warning (467, 2, loc, "Ambiguity between method `{0}' and non-method `{1}'. Using method `{0}'",
744 TypeManager.CSharpSignature (method), TypeManager.GetFullNameSignature (non_method));
748 return new MethodGroupExpr (methods, queried_type, loc);
751 if (mi [0] is MethodBase)
752 return new MethodGroupExpr (mi, queried_type, loc);
754 return ExprClassFromMemberInfo (container_type, mi [0], loc);
757 public const MemberTypes AllMemberTypes =
758 MemberTypes.Constructor |
759 MemberTypes.Event |
760 MemberTypes.Field |
761 MemberTypes.Method |
762 MemberTypes.NestedType |
763 MemberTypes.Property;
765 public const BindingFlags AllBindingFlags =
766 BindingFlags.Public |
767 BindingFlags.Static |
768 BindingFlags.Instance;
770 public static Expression MemberLookup (CompilerContext ctx, Type container_type, Type queried_type,
771 string name, Location loc)
773 return MemberLookup (ctx, container_type, null, queried_type, name,
774 AllMemberTypes, AllBindingFlags, loc);
777 public static Expression MemberLookup (CompilerContext ctx, Type container_type, Type qualifier_type,
778 Type queried_type, string name, Location loc)
780 return MemberLookup (ctx, container_type, qualifier_type, queried_type,
781 name, AllMemberTypes, AllBindingFlags, loc);
784 public static MethodGroupExpr MethodLookup (CompilerContext ctx, Type container_type, Type queried_type,
785 string name, Location loc)
787 return (MethodGroupExpr)MemberLookup (ctx, container_type, null, queried_type, name,
788 MemberTypes.Method, AllBindingFlags, loc);
791 /// <summary>
792 /// This is a wrapper for MemberLookup that is not used to "probe", but
793 /// to find a final definition. If the final definition is not found, we
794 /// look for private members and display a useful debugging message if we
795 /// find it.
796 /// </summary>
797 protected Expression MemberLookupFinal (ResolveContext ec, Type qualifier_type,
798 Type queried_type, string name,
799 MemberTypes mt, BindingFlags bf,
800 Location loc)
802 Expression e;
804 int errors = ec.Report.Errors;
805 e = MemberLookup (ec.Compiler, ec.CurrentType, qualifier_type, queried_type, name, mt, bf, loc);
807 if (e != null || errors != ec.Report.Errors)
808 return e;
810 // No errors were reported by MemberLookup, but there was an error.
811 return Error_MemberLookupFailed (ec, ec.CurrentType, qualifier_type, queried_type,
812 name, null, mt, bf);
815 protected virtual Expression Error_MemberLookupFailed (ResolveContext ec, Type container_type, Type qualifier_type,
816 Type queried_type, string name, string class_name,
817 MemberTypes mt, BindingFlags bf)
819 MemberInfo[] lookup = null;
820 if (queried_type == null) {
821 class_name = "global::";
822 } else {
823 lookup = TypeManager.MemberLookup (queried_type, null, queried_type,
824 mt, (bf & ~BindingFlags.Public) | BindingFlags.NonPublic,
825 name, null);
827 if (lookup != null) {
828 Expression e = Error_MemberLookupFailed (ec, queried_type, lookup);
831 // FIXME: This is still very wrong, it should be done inside
832 // OverloadResolve to do correct arguments matching.
833 // Requires MemberLookup accessiblity check removal
835 if (e == null || (mt & (MemberTypes.Method | MemberTypes.Constructor)) == 0) {
836 MemberInfo mi = lookup[0];
837 ec.Report.SymbolRelatedToPreviousError (mi);
838 if (qualifier_type != null && container_type != null && qualifier_type != container_type &&
839 TypeManager.IsNestedFamilyAccessible (container_type, mi.DeclaringType)) {
840 // Although a derived class can access protected members of
841 // its base class it cannot do so through an instance of the
842 // base class (CS1540). If the qualifier_type is a base of the
843 // ec.CurrentType and the lookup succeeds with the latter one,
844 // then we are in this situation.
845 Error_CannotAccessProtected (ec, loc, mi, qualifier_type, container_type);
846 } else {
847 ErrorIsInaccesible (loc, TypeManager.GetFullNameSignature (mi), ec.Report);
851 return e;
854 lookup = TypeManager.MemberLookup (queried_type, null, queried_type,
855 AllMemberTypes, AllBindingFlags | BindingFlags.NonPublic,
856 name, null);
859 if (lookup == null) {
860 if (class_name != null) {
861 ec.Report.Error (103, loc, "The name `{0}' does not exist in the current context",
862 name);
863 } else {
864 Error_TypeDoesNotContainDefinition (ec, queried_type, name);
866 return null;
869 if (TypeManager.MemberLookup (queried_type, null, queried_type,
870 AllMemberTypes, AllBindingFlags |
871 BindingFlags.NonPublic, name, null) == null) {
872 if ((lookup.Length == 1) && (lookup [0] is Type)) {
873 Type t = (Type) lookup [0];
875 ec.Report.Error (305, loc,
876 "Using the generic type `{0}' " +
877 "requires {1} type arguments",
878 TypeManager.CSharpName (t),
879 TypeManager.GetNumberOfTypeArguments (t).ToString ());
880 return null;
884 return Error_MemberLookupFailed (ec, queried_type, lookup);
887 protected virtual Expression Error_MemberLookupFailed (ResolveContext ec, Type type, MemberInfo[] members)
889 for (int i = 0; i < members.Length; ++i) {
890 if (!(members [i] is MethodBase))
891 return null;
894 // By default propagate the closest candidates upwards
895 return new MethodGroupExpr (members, type, loc, true);
898 protected virtual void Error_NegativeArrayIndex (ResolveContext ec, Location loc)
900 throw new NotImplementedException ();
903 protected void Error_PointerInsideExpressionTree (ResolveContext ec)
905 ec.Report.Error (1944, loc, "An expression tree cannot contain an unsafe pointer operation");
908 /// <summary>
909 /// Returns an expression that can be used to invoke operator true
910 /// on the expression if it exists.
911 /// </summary>
912 protected static Expression GetOperatorTrue (ResolveContext ec, Expression e, Location loc)
914 return GetOperatorTrueOrFalse (ec, e, true, loc);
917 /// <summary>
918 /// Returns an expression that can be used to invoke operator false
919 /// on the expression if it exists.
920 /// </summary>
921 static public Expression GetOperatorFalse (ResolveContext ec, Expression e, Location loc)
923 return GetOperatorTrueOrFalse (ec, e, false, loc);
926 static Expression GetOperatorTrueOrFalse (ResolveContext ec, Expression e, bool is_true, Location loc)
928 MethodGroupExpr operator_group;
929 string mname = Operator.GetMetadataName (is_true ? Operator.OpType.True : Operator.OpType.False);
930 operator_group = MethodLookup (ec.Compiler, ec.CurrentType, e.Type, mname, loc) as MethodGroupExpr;
931 if (operator_group == null)
932 return null;
934 Arguments arguments = new Arguments (1);
935 arguments.Add (new Argument (e));
936 operator_group = operator_group.OverloadResolve (
937 ec, ref arguments, false, loc);
939 if (operator_group == null)
940 return null;
942 return new UserOperatorCall (operator_group, arguments, null, loc);
945 public virtual string ExprClassName
947 get {
948 switch (eclass){
949 case ExprClass.Unresolved:
950 return "Unresolved";
951 case ExprClass.Value:
952 return "value";
953 case ExprClass.Variable:
954 return "variable";
955 case ExprClass.Namespace:
956 return "namespace";
957 case ExprClass.Type:
958 return "type";
959 case ExprClass.MethodGroup:
960 return "method group";
961 case ExprClass.PropertyAccess:
962 return "property access";
963 case ExprClass.EventAccess:
964 return "event access";
965 case ExprClass.IndexerAccess:
966 return "indexer access";
967 case ExprClass.Nothing:
968 return "null";
969 case ExprClass.TypeParameter:
970 return "type parameter";
972 throw new Exception ("Should not happen");
976 /// <summary>
977 /// Reports that we were expecting `expr' to be of class `expected'
978 /// </summary>
979 public void Error_UnexpectedKind (Report r, MemberCore mc, string expected, Location loc)
981 Error_UnexpectedKind (r, mc, expected, ExprClassName, loc);
984 public void Error_UnexpectedKind (Report r, MemberCore mc, string expected, string was, Location loc)
986 string name;
987 if (mc != null)
988 name = mc.GetSignatureForError ();
989 else
990 name = GetSignatureForError ();
992 r.Error (118, loc, "`{0}' is a `{1}' but a `{2}' was expected",
993 name, was, expected);
996 public void Error_UnexpectedKind (ResolveContext ec, ResolveFlags flags, Location loc)
998 string [] valid = new string [4];
999 int count = 0;
1001 if ((flags & ResolveFlags.VariableOrValue) != 0) {
1002 valid [count++] = "variable";
1003 valid [count++] = "value";
1006 if ((flags & ResolveFlags.Type) != 0)
1007 valid [count++] = "type";
1009 if ((flags & ResolveFlags.MethodGroup) != 0)
1010 valid [count++] = "method group";
1012 if (count == 0)
1013 valid [count++] = "unknown";
1015 StringBuilder sb = new StringBuilder (valid [0]);
1016 for (int i = 1; i < count - 1; i++) {
1017 sb.Append ("', `");
1018 sb.Append (valid [i]);
1020 if (count > 1) {
1021 sb.Append ("' or `");
1022 sb.Append (valid [count - 1]);
1025 ec.Report.Error (119, loc,
1026 "Expression denotes a `{0}', where a `{1}' was expected", ExprClassName, sb.ToString ());
1029 public static void UnsafeError (ResolveContext ec, Location loc)
1031 UnsafeError (ec.Report, loc);
1034 public static void UnsafeError (Report Report, Location loc)
1036 Report.Error (214, loc, "Pointers and fixed size buffers may only be used in an unsafe context");
1040 // Load the object from the pointer.
1042 public static void LoadFromPtr (ILGenerator ig, Type t)
1044 if (t == TypeManager.int32_type)
1045 ig.Emit (OpCodes.Ldind_I4);
1046 else if (t == TypeManager.uint32_type)
1047 ig.Emit (OpCodes.Ldind_U4);
1048 else if (t == TypeManager.short_type)
1049 ig.Emit (OpCodes.Ldind_I2);
1050 else if (t == TypeManager.ushort_type)
1051 ig.Emit (OpCodes.Ldind_U2);
1052 else if (t == TypeManager.char_type)
1053 ig.Emit (OpCodes.Ldind_U2);
1054 else if (t == TypeManager.byte_type)
1055 ig.Emit (OpCodes.Ldind_U1);
1056 else if (t == TypeManager.sbyte_type)
1057 ig.Emit (OpCodes.Ldind_I1);
1058 else if (t == TypeManager.uint64_type)
1059 ig.Emit (OpCodes.Ldind_I8);
1060 else if (t == TypeManager.int64_type)
1061 ig.Emit (OpCodes.Ldind_I8);
1062 else if (t == TypeManager.float_type)
1063 ig.Emit (OpCodes.Ldind_R4);
1064 else if (t == TypeManager.double_type)
1065 ig.Emit (OpCodes.Ldind_R8);
1066 else if (t == TypeManager.bool_type)
1067 ig.Emit (OpCodes.Ldind_I1);
1068 else if (t == TypeManager.intptr_type)
1069 ig.Emit (OpCodes.Ldind_I);
1070 else if (TypeManager.IsEnumType (t)) {
1071 if (t == TypeManager.enum_type)
1072 ig.Emit (OpCodes.Ldind_Ref);
1073 else
1074 LoadFromPtr (ig, TypeManager.GetEnumUnderlyingType (t));
1075 } else if (TypeManager.IsStruct (t) || TypeManager.IsGenericParameter (t))
1076 ig.Emit (OpCodes.Ldobj, t);
1077 else if (t.IsPointer)
1078 ig.Emit (OpCodes.Ldind_I);
1079 else
1080 ig.Emit (OpCodes.Ldind_Ref);
1084 // The stack contains the pointer and the value of type `type'
1086 public static void StoreFromPtr (ILGenerator ig, Type type)
1088 if (TypeManager.IsEnumType (type))
1089 type = TypeManager.GetEnumUnderlyingType (type);
1090 if (type == TypeManager.int32_type || type == TypeManager.uint32_type)
1091 ig.Emit (OpCodes.Stind_I4);
1092 else if (type == TypeManager.int64_type || type == TypeManager.uint64_type)
1093 ig.Emit (OpCodes.Stind_I8);
1094 else if (type == TypeManager.char_type || type == TypeManager.short_type ||
1095 type == TypeManager.ushort_type)
1096 ig.Emit (OpCodes.Stind_I2);
1097 else if (type == TypeManager.float_type)
1098 ig.Emit (OpCodes.Stind_R4);
1099 else if (type == TypeManager.double_type)
1100 ig.Emit (OpCodes.Stind_R8);
1101 else if (type == TypeManager.byte_type || type == TypeManager.sbyte_type ||
1102 type == TypeManager.bool_type)
1103 ig.Emit (OpCodes.Stind_I1);
1104 else if (type == TypeManager.intptr_type)
1105 ig.Emit (OpCodes.Stind_I);
1106 else if (TypeManager.IsStruct (type) || TypeManager.IsGenericParameter (type))
1107 ig.Emit (OpCodes.Stobj, type);
1108 else
1109 ig.Emit (OpCodes.Stind_Ref);
1113 // Returns the size of type `t' if known, otherwise, 0
1115 public static int GetTypeSize (Type t)
1117 t = TypeManager.TypeToCoreType (t);
1118 if (t == TypeManager.int32_type ||
1119 t == TypeManager.uint32_type ||
1120 t == TypeManager.float_type)
1121 return 4;
1122 else if (t == TypeManager.int64_type ||
1123 t == TypeManager.uint64_type ||
1124 t == TypeManager.double_type)
1125 return 8;
1126 else if (t == TypeManager.byte_type ||
1127 t == TypeManager.sbyte_type ||
1128 t == TypeManager.bool_type)
1129 return 1;
1130 else if (t == TypeManager.short_type ||
1131 t == TypeManager.char_type ||
1132 t == TypeManager.ushort_type)
1133 return 2;
1134 else if (t == TypeManager.decimal_type)
1135 return 16;
1136 else
1137 return 0;
1140 protected void Error_CannotCallAbstractBase (ResolveContext ec, string name)
1142 ec.Report.Error (205, loc, "Cannot call an abstract base member `{0}'", name);
1145 protected void Error_CannotModifyIntermediateExpressionValue (ResolveContext ec)
1147 ec.Report.SymbolRelatedToPreviousError (type);
1148 if (ec.CurrentInitializerVariable != null) {
1149 ec.Report.Error (1918, loc, "Members of value type `{0}' cannot be assigned using a property `{1}' object initializer",
1150 TypeManager.CSharpName (type), GetSignatureForError ());
1151 } else {
1152 ec.Report.Error (1612, loc, "Cannot modify a value type return value of `{0}'. Consider storing the value in a temporary variable",
1153 GetSignatureForError ());
1158 // Converts `source' to an int, uint, long or ulong.
1160 protected Expression ConvertExpressionToArrayIndex (ResolveContext ec, Expression source)
1162 if (TypeManager.IsDynamicType (source.type)) {
1163 Arguments args = new Arguments (1);
1164 args.Add (new Argument (source));
1165 return new DynamicConversion (TypeManager.int32_type, CSharpBinderFlags.ConvertArrayIndex, args, loc).Resolve (ec);
1168 Expression converted;
1170 using (ec.Set (ResolveContext.Options.CheckedScope)) {
1171 converted = Convert.ImplicitConversion (ec, source, TypeManager.int32_type, source.loc);
1172 if (converted == null)
1173 converted = Convert.ImplicitConversion (ec, source, TypeManager.uint32_type, source.loc);
1174 if (converted == null)
1175 converted = Convert.ImplicitConversion (ec, source, TypeManager.int64_type, source.loc);
1176 if (converted == null)
1177 converted = Convert.ImplicitConversion (ec, source, TypeManager.uint64_type, source.loc);
1179 if (converted == null) {
1180 source.Error_ValueCannotBeConverted (ec, source.loc, TypeManager.int32_type, false);
1181 return null;
1186 // Only positive constants are allowed at compile time
1188 Constant c = converted as Constant;
1189 if (c != null && c.IsNegative)
1190 Error_NegativeArrayIndex (ec, source.loc);
1192 // No conversion needed to array index
1193 if (converted.Type == TypeManager.int32_type)
1194 return converted;
1196 return new ArrayIndexCast (converted).Resolve (ec);
1200 // Derived classes implement this method by cloning the fields that
1201 // could become altered during the Resolve stage
1203 // Only expressions that are created for the parser need to implement
1204 // this.
1206 protected virtual void CloneTo (CloneContext clonectx, Expression target)
1208 throw new NotImplementedException (
1209 String.Format (
1210 "CloneTo not implemented for expression {0}", this.GetType ()));
1214 // Clones an expression created by the parser.
1216 // We only support expressions created by the parser so far, not
1217 // expressions that have been resolved (many more classes would need
1218 // to implement CloneTo).
1220 // This infrastructure is here merely for Lambda expressions which
1221 // compile the same code using different type values for the same
1222 // arguments to find the correct overload
1224 public Expression Clone (CloneContext clonectx)
1226 Expression cloned = (Expression) MemberwiseClone ();
1227 CloneTo (clonectx, cloned);
1229 return cloned;
1233 // Implementation of expression to expression tree conversion
1235 public abstract Expression CreateExpressionTree (ResolveContext ec);
1237 protected Expression CreateExpressionFactoryCall (ResolveContext ec, string name, Arguments args)
1239 return CreateExpressionFactoryCall (ec, name, null, args, loc);
1242 protected Expression CreateExpressionFactoryCall (ResolveContext ec, string name, TypeArguments typeArguments, Arguments args)
1244 return CreateExpressionFactoryCall (ec, name, typeArguments, args, loc);
1247 public static Expression CreateExpressionFactoryCall (ResolveContext ec, string name, TypeArguments typeArguments, Arguments args, Location loc)
1249 return new Invocation (new MemberAccess (CreateExpressionTypeExpression (ec, loc), name, typeArguments, loc), args);
1252 protected static TypeExpr CreateExpressionTypeExpression (ResolveContext ec, Location loc)
1254 TypeExpr texpr = TypeManager.expression_type_expr;
1255 if (texpr == null) {
1256 Type t = TypeManager.CoreLookupType (ec.Compiler, "System.Linq.Expressions", "Expression", Kind.Class, true);
1257 if (t == null)
1258 return null;
1260 TypeManager.expression_type_expr = texpr = new TypeExpression (t, Location.Null);
1263 return texpr;
1266 #if NET_4_0
1268 // Implemented by all expressions which support conversion from
1269 // compiler expression to invokable runtime expression. Used by
1270 // dynamic C# binder.
1272 public virtual SLE.Expression MakeExpression (BuilderContext ctx)
1274 throw new NotImplementedException ("MakeExpression for " + GetType ());
1276 #endif
1278 public virtual void MutateHoistedGenericType (AnonymousMethodStorey storey)
1280 // TODO: It should probably be type = storey.MutateType (type);
1284 /// <summary>
1285 /// This is just a base class for expressions that can
1286 /// appear on statements (invocations, object creation,
1287 /// assignments, post/pre increment and decrement). The idea
1288 /// being that they would support an extra Emition interface that
1289 /// does not leave a result on the stack.
1290 /// </summary>
1291 public abstract class ExpressionStatement : Expression {
1293 public virtual ExpressionStatement ResolveStatement (BlockContext ec)
1295 Expression e = Resolve (ec);
1296 if (e == null)
1297 return null;
1299 ExpressionStatement es = e as ExpressionStatement;
1300 if (es == null)
1301 Error_InvalidExpressionStatement (ec);
1303 return es;
1306 /// <summary>
1307 /// Requests the expression to be emitted in a `statement'
1308 /// context. This means that no new value is left on the
1309 /// stack after invoking this method (constrasted with
1310 /// Emit that will always leave a value on the stack).
1311 /// </summary>
1312 public abstract void EmitStatement (EmitContext ec);
1314 public override void EmitSideEffect (EmitContext ec)
1316 EmitStatement (ec);
1320 /// <summary>
1321 /// This kind of cast is used to encapsulate the child
1322 /// whose type is child.Type into an expression that is
1323 /// reported to return "return_type". This is used to encapsulate
1324 /// expressions which have compatible types, but need to be dealt
1325 /// at higher levels with.
1327 /// For example, a "byte" expression could be encapsulated in one
1328 /// of these as an "unsigned int". The type for the expression
1329 /// would be "unsigned int".
1331 /// </summary>
1332 public abstract class TypeCast : Expression
1334 protected readonly Expression child;
1336 protected TypeCast (Expression child, Type return_type)
1338 eclass = child.eclass;
1339 loc = child.Location;
1340 type = return_type;
1341 this.child = child;
1344 public override Expression CreateExpressionTree (ResolveContext ec)
1346 Arguments args = new Arguments (2);
1347 args.Add (new Argument (child.CreateExpressionTree (ec)));
1348 args.Add (new Argument (new TypeOf (new TypeExpression (type, loc), loc)));
1350 if (type.IsPointer || child.Type.IsPointer)
1351 Error_PointerInsideExpressionTree (ec);
1353 return CreateExpressionFactoryCall (ec, ec.HasSet (ResolveContext.Options.CheckedScope) ? "ConvertChecked" : "Convert", args);
1356 protected override Expression DoResolve (ResolveContext ec)
1358 // This should never be invoked, we are born in fully
1359 // initialized state.
1361 return this;
1364 public override void Emit (EmitContext ec)
1366 child.Emit (ec);
1369 public override bool GetAttributableValue (ResolveContext ec, Type value_type, out object value)
1371 return child.GetAttributableValue (ec, value_type, out value);
1374 #if NET_4_0
1375 public override SLE.Expression MakeExpression (BuilderContext ctx)
1377 return ctx.HasSet (BuilderContext.Options.CheckedScope) ?
1378 SLE.Expression.ConvertChecked (child.MakeExpression (ctx), type) :
1379 SLE.Expression.Convert (child.MakeExpression (ctx), type);
1381 #endif
1383 public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
1385 type = storey.MutateType (type);
1386 child.MutateHoistedGenericType (storey);
1389 protected override void CloneTo (CloneContext clonectx, Expression t)
1391 // Nothing to clone
1394 public override bool IsNull {
1395 get { return child.IsNull; }
1399 public class EmptyCast : TypeCast {
1400 EmptyCast (Expression child, Type target_type)
1401 : base (child, target_type)
1405 public static Expression Create (Expression child, Type type)
1407 Constant c = child as Constant;
1408 if (c != null)
1409 return new EmptyConstantCast (c, type);
1411 EmptyCast e = child as EmptyCast;
1412 if (e != null)
1413 return new EmptyCast (e.child, type);
1415 return new EmptyCast (child, type);
1418 public override void EmitBranchable (EmitContext ec, Label label, bool on_true)
1420 child.EmitBranchable (ec, label, on_true);
1423 public override void EmitSideEffect (EmitContext ec)
1425 child.EmitSideEffect (ec);
1430 // Used for predefined class library user casts (no obsolete check, etc.)
1432 public class OperatorCast : TypeCast {
1433 MethodInfo conversion_operator;
1435 public OperatorCast (Expression child, Type target_type)
1436 : this (child, target_type, false)
1440 public OperatorCast (Expression child, Type target_type, bool find_explicit)
1441 : base (child, target_type)
1443 conversion_operator = GetConversionOperator (find_explicit);
1444 if (conversion_operator == null)
1445 throw new InternalErrorException ("Outer conversion routine is out of sync");
1448 // Returns the implicit operator that converts from
1449 // 'child.Type' to our target type (type)
1450 MethodInfo GetConversionOperator (bool find_explicit)
1452 string operator_name = find_explicit ? "op_Explicit" : "op_Implicit";
1454 MemberInfo [] mi;
1456 mi = TypeManager.MemberLookup (child.Type, child.Type, child.Type, MemberTypes.Method,
1457 BindingFlags.Static | BindingFlags.Public, operator_name, null);
1459 if (mi == null){
1460 mi = TypeManager.MemberLookup (type, type, type, MemberTypes.Method,
1461 BindingFlags.Static | BindingFlags.Public, operator_name, null);
1464 foreach (MethodInfo oper in mi) {
1465 AParametersCollection pd = TypeManager.GetParameterData (oper);
1467 if (pd.Types [0] == child.Type && TypeManager.TypeToCoreType (oper.ReturnType) == type)
1468 return oper;
1471 return null;
1474 public override void Emit (EmitContext ec)
1476 child.Emit (ec);
1477 ec.ig.Emit (OpCodes.Call, conversion_operator);
1481 /// <summary>
1482 /// This is a numeric cast to a Decimal
1483 /// </summary>
1484 public class CastToDecimal : OperatorCast {
1485 public CastToDecimal (Expression child)
1486 : this (child, false)
1490 public CastToDecimal (Expression child, bool find_explicit)
1491 : base (child, TypeManager.decimal_type, find_explicit)
1496 /// <summary>
1497 /// This is an explicit numeric cast from a Decimal
1498 /// </summary>
1499 public class CastFromDecimal : TypeCast
1501 static IDictionary operators;
1503 public CastFromDecimal (Expression child, Type return_type)
1504 : base (child, return_type)
1506 if (child.Type != TypeManager.decimal_type)
1507 throw new InternalErrorException (
1508 "The expected type is Decimal, instead it is " + child.Type.FullName);
1511 // Returns the explicit operator that converts from an
1512 // express of type System.Decimal to 'type'.
1513 public Expression Resolve ()
1515 if (operators == null) {
1516 MemberInfo[] all_oper = TypeManager.MemberLookup (TypeManager.decimal_type,
1517 TypeManager.decimal_type, TypeManager.decimal_type, MemberTypes.Method,
1518 BindingFlags.Static | BindingFlags.Public, "op_Explicit", null);
1520 operators = new System.Collections.Specialized.HybridDictionary ();
1521 foreach (MethodInfo oper in all_oper) {
1522 AParametersCollection pd = TypeManager.GetParameterData (oper);
1523 if (pd.Types [0] == TypeManager.decimal_type)
1524 operators.Add (TypeManager.TypeToCoreType (oper.ReturnType), oper);
1528 return operators.Contains (type) ? this : null;
1531 public override void Emit (EmitContext ec)
1533 ILGenerator ig = ec.ig;
1534 child.Emit (ec);
1536 ig.Emit (OpCodes.Call, (MethodInfo)operators [type]);
1542 // Constant specialization of EmptyCast.
1543 // We need to special case this since an empty cast of
1544 // a constant is still a constant.
1546 public class EmptyConstantCast : Constant
1548 public Constant child;
1550 public EmptyConstantCast (Constant child, Type type)
1551 : base (child.Location)
1553 if (child == null)
1554 throw new ArgumentNullException ("child");
1556 this.child = child;
1557 this.eclass = child.eclass;
1558 this.type = type;
1561 public override string AsString ()
1563 return child.AsString ();
1566 public override object GetValue ()
1568 return child.GetValue ();
1571 public override Constant ConvertExplicitly (bool in_checked_context, Type target_type)
1573 if (child.Type == target_type)
1574 return child;
1576 // FIXME: check that 'type' can be converted to 'target_type' first
1577 return child.ConvertExplicitly (in_checked_context, target_type);
1580 public override Expression CreateExpressionTree (ResolveContext ec)
1582 Arguments args = Arguments.CreateForExpressionTree (ec, null,
1583 child.CreateExpressionTree (ec),
1584 new TypeOf (new TypeExpression (type, loc), loc));
1586 if (type.IsPointer)
1587 Error_PointerInsideExpressionTree (ec);
1589 return CreateExpressionFactoryCall (ec, "Convert", args);
1592 public override bool IsDefaultValue {
1593 get { return child.IsDefaultValue; }
1596 public override bool IsNegative {
1597 get { return child.IsNegative; }
1600 public override bool IsNull {
1601 get { return child.IsNull; }
1604 public override bool IsZeroInteger {
1605 get { return child.IsZeroInteger; }
1608 protected override Expression DoResolve (ResolveContext rc)
1610 return this;
1613 public override void Emit (EmitContext ec)
1615 child.Emit (ec);
1618 public override void EmitBranchable (EmitContext ec, Label label, bool on_true)
1620 child.EmitBranchable (ec, label, on_true);
1622 // Only to make verifier happy
1623 if (TypeManager.IsGenericParameter (type) && child.IsNull)
1624 ec.ig.Emit (OpCodes.Unbox_Any, type);
1627 public override void EmitSideEffect (EmitContext ec)
1629 child.EmitSideEffect (ec);
1632 public override Constant ConvertImplicitly (ResolveContext rc, Type target_type)
1634 // FIXME: Do we need to check user conversions?
1635 if (!Convert.ImplicitStandardConversionExists (this, target_type))
1636 return null;
1637 return child.ConvertImplicitly (rc, target_type);
1640 public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
1642 child.MutateHoistedGenericType (storey);
1646 /// <summary>
1647 /// This class is used to wrap literals which belong inside Enums
1648 /// </summary>
1649 public class EnumConstant : Constant
1651 public Constant Child;
1653 public EnumConstant (Constant child, Type enum_type)
1654 : base (child.Location)
1656 this.Child = child;
1657 this.type = enum_type;
1660 protected EnumConstant (Location loc)
1661 : base (loc)
1665 protected override Expression DoResolve (ResolveContext rc)
1667 Child = Child.Resolve (rc);
1668 this.eclass = ExprClass.Value;
1669 return this;
1672 public override void Emit (EmitContext ec)
1674 Child.Emit (ec);
1677 public override void EmitBranchable (EmitContext ec, Label label, bool on_true)
1679 Child.EmitBranchable (ec, label, on_true);
1682 public override void EmitSideEffect (EmitContext ec)
1684 Child.EmitSideEffect (ec);
1687 public override bool GetAttributableValue (ResolveContext ec, Type value_type, out object value)
1689 value = GetTypedValue ();
1690 return true;
1693 public override string GetSignatureForError()
1695 return TypeManager.CSharpName (Type);
1698 public override object GetValue ()
1700 return Child.GetValue ();
1703 public override object GetTypedValue ()
1705 // FIXME: runtime is not ready to work with just emited enums
1706 if (!RootContext.StdLib) {
1707 return Child.GetValue ();
1710 #if MS_COMPATIBLE
1711 // Small workaround for big problem
1712 // System.Enum.ToObject cannot be called on dynamic types
1713 // EnumBuilder has to be used, but we cannot use EnumBuilder
1714 // because it does not properly support generics
1716 // This works only sometimes
1718 if (TypeManager.IsBeingCompiled (type))
1719 return Child.GetValue ();
1720 #endif
1722 return System.Enum.ToObject (type, Child.GetValue ());
1725 public override string AsString ()
1727 return Child.AsString ();
1730 public EnumConstant Increment()
1732 return new EnumConstant (((IntegralConstant) Child).Increment (), type);
1735 public override bool IsDefaultValue {
1736 get {
1737 return Child.IsDefaultValue;
1741 public override bool IsZeroInteger {
1742 get { return Child.IsZeroInteger; }
1745 public override bool IsNegative {
1746 get {
1747 return Child.IsNegative;
1751 public override Constant ConvertExplicitly(bool in_checked_context, Type target_type)
1753 if (Child.Type == target_type)
1754 return Child;
1756 return Child.ConvertExplicitly (in_checked_context, target_type);
1759 public override Constant ConvertImplicitly (ResolveContext rc, Type type)
1761 Type this_type = TypeManager.DropGenericTypeArguments (Type);
1762 type = TypeManager.DropGenericTypeArguments (type);
1764 if (this_type == type) {
1765 // This is workaround of mono bug. It can be removed when the latest corlib spreads enough
1766 if (TypeManager.IsEnumType (type.UnderlyingSystemType))
1767 return this;
1769 Type child_type = TypeManager.DropGenericTypeArguments (Child.Type);
1770 if (type.UnderlyingSystemType != child_type)
1771 Child = Child.ConvertImplicitly (rc, type.UnderlyingSystemType);
1772 return this;
1775 if (!Convert.ImplicitStandardConversionExists (this, type)){
1776 return null;
1779 return Child.ConvertImplicitly (rc, type);
1783 /// <summary>
1784 /// This kind of cast is used to encapsulate Value Types in objects.
1786 /// The effect of it is to box the value type emitted by the previous
1787 /// operation.
1788 /// </summary>
1789 public class BoxedCast : TypeCast {
1791 public BoxedCast (Expression expr, Type target_type)
1792 : base (expr, target_type)
1794 eclass = ExprClass.Value;
1797 protected override Expression DoResolve (ResolveContext ec)
1799 // This should never be invoked, we are born in fully
1800 // initialized state.
1802 return this;
1805 public override void Emit (EmitContext ec)
1807 base.Emit (ec);
1809 ec.ig.Emit (OpCodes.Box, child.Type);
1812 public override void EmitSideEffect (EmitContext ec)
1814 // boxing is side-effectful, since it involves runtime checks, except when boxing to Object or ValueType
1815 // so, we need to emit the box+pop instructions in most cases
1816 if (TypeManager.IsStruct (child.Type) &&
1817 (type == TypeManager.object_type || type == TypeManager.value_type))
1818 child.EmitSideEffect (ec);
1819 else
1820 base.EmitSideEffect (ec);
1824 public class UnboxCast : TypeCast {
1825 public UnboxCast (Expression expr, Type return_type)
1826 : base (expr, return_type)
1830 protected override Expression DoResolve (ResolveContext ec)
1832 // This should never be invoked, we are born in fully
1833 // initialized state.
1835 return this;
1838 public override Expression DoResolveLValue (ResolveContext ec, Expression right_side)
1840 if (right_side == EmptyExpression.LValueMemberAccess || right_side == EmptyExpression.LValueMemberOutAccess)
1841 ec.Report.Error (445, loc, "Cannot modify the result of an unboxing conversion");
1842 return base.DoResolveLValue (ec, right_side);
1845 public override void Emit (EmitContext ec)
1847 base.Emit (ec);
1849 ILGenerator ig = ec.ig;
1850 ig.Emit (OpCodes.Unbox_Any, type);
1853 public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
1855 type = storey.MutateType (type);
1856 base.MutateHoistedGenericType (storey);
1860 /// <summary>
1861 /// This is used to perform explicit numeric conversions.
1863 /// Explicit numeric conversions might trigger exceptions in a checked
1864 /// context, so they should generate the conv.ovf opcodes instead of
1865 /// conv opcodes.
1866 /// </summary>
1867 public class ConvCast : TypeCast {
1868 public enum Mode : byte {
1869 I1_U1, I1_U2, I1_U4, I1_U8, I1_CH,
1870 U1_I1, U1_CH,
1871 I2_I1, I2_U1, I2_U2, I2_U4, I2_U8, I2_CH,
1872 U2_I1, U2_U1, U2_I2, U2_CH,
1873 I4_I1, I4_U1, I4_I2, I4_U2, I4_U4, I4_U8, I4_CH,
1874 U4_I1, U4_U1, U4_I2, U4_U2, U4_I4, U4_CH,
1875 I8_I1, I8_U1, I8_I2, I8_U2, I8_I4, I8_U4, I8_U8, I8_CH, I8_I,
1876 U8_I1, U8_U1, U8_I2, U8_U2, U8_I4, U8_U4, U8_I8, U8_CH, U8_I,
1877 CH_I1, CH_U1, CH_I2,
1878 R4_I1, R4_U1, R4_I2, R4_U2, R4_I4, R4_U4, R4_I8, R4_U8, R4_CH,
1879 R8_I1, R8_U1, R8_I2, R8_U2, R8_I4, R8_U4, R8_I8, R8_U8, R8_CH, R8_R4,
1880 I_I8,
1883 Mode mode;
1885 public ConvCast (Expression child, Type return_type, Mode m)
1886 : base (child, return_type)
1888 mode = m;
1891 protected override Expression DoResolve (ResolveContext ec)
1893 // This should never be invoked, we are born in fully
1894 // initialized state.
1896 return this;
1899 public override string ToString ()
1901 return String.Format ("ConvCast ({0}, {1})", mode, child);
1904 public override void Emit (EmitContext ec)
1906 ILGenerator ig = ec.ig;
1908 base.Emit (ec);
1910 if (ec.HasSet (EmitContext.Options.CheckedScope)) {
1911 switch (mode){
1912 case Mode.I1_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1913 case Mode.I1_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1914 case Mode.I1_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1915 case Mode.I1_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1916 case Mode.I1_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1918 case Mode.U1_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1919 case Mode.U1_CH: /* nothing */ break;
1921 case Mode.I2_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1922 case Mode.I2_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1923 case Mode.I2_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1924 case Mode.I2_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1925 case Mode.I2_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1926 case Mode.I2_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1928 case Mode.U2_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1929 case Mode.U2_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
1930 case Mode.U2_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
1931 case Mode.U2_CH: /* nothing */ break;
1933 case Mode.I4_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1934 case Mode.I4_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1935 case Mode.I4_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
1936 case Mode.I4_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1937 case Mode.I4_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1938 case Mode.I4_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1939 case Mode.I4_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1941 case Mode.U4_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1942 case Mode.U4_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
1943 case Mode.U4_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
1944 case Mode.U4_U2: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
1945 case Mode.U4_I4: ig.Emit (OpCodes.Conv_Ovf_I4_Un); break;
1946 case Mode.U4_CH: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
1948 case Mode.I8_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1949 case Mode.I8_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1950 case Mode.I8_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
1951 case Mode.I8_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1952 case Mode.I8_I4: ig.Emit (OpCodes.Conv_Ovf_I4); break;
1953 case Mode.I8_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1954 case Mode.I8_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1955 case Mode.I8_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1956 case Mode.I8_I: ig.Emit (OpCodes.Conv_Ovf_U); break;
1958 case Mode.U8_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1959 case Mode.U8_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
1960 case Mode.U8_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
1961 case Mode.U8_U2: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
1962 case Mode.U8_I4: ig.Emit (OpCodes.Conv_Ovf_I4_Un); break;
1963 case Mode.U8_U4: ig.Emit (OpCodes.Conv_Ovf_U4_Un); break;
1964 case Mode.U8_I8: ig.Emit (OpCodes.Conv_Ovf_I8_Un); break;
1965 case Mode.U8_CH: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
1966 case Mode.U8_I: ig.Emit (OpCodes.Conv_Ovf_U_Un); break;
1968 case Mode.CH_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1969 case Mode.CH_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
1970 case Mode.CH_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
1972 case Mode.R4_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1973 case Mode.R4_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1974 case Mode.R4_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
1975 case Mode.R4_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1976 case Mode.R4_I4: ig.Emit (OpCodes.Conv_Ovf_I4); break;
1977 case Mode.R4_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1978 case Mode.R4_I8: ig.Emit (OpCodes.Conv_Ovf_I8); break;
1979 case Mode.R4_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1980 case Mode.R4_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1982 case Mode.R8_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1983 case Mode.R8_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1984 case Mode.R8_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
1985 case Mode.R8_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1986 case Mode.R8_I4: ig.Emit (OpCodes.Conv_Ovf_I4); break;
1987 case Mode.R8_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1988 case Mode.R8_I8: ig.Emit (OpCodes.Conv_Ovf_I8); break;
1989 case Mode.R8_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1990 case Mode.R8_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1991 case Mode.R8_R4: ig.Emit (OpCodes.Conv_R4); break;
1993 case Mode.I_I8: ig.Emit (OpCodes.Conv_Ovf_I8_Un); break;
1995 } else {
1996 switch (mode){
1997 case Mode.I1_U1: ig.Emit (OpCodes.Conv_U1); break;
1998 case Mode.I1_U2: ig.Emit (OpCodes.Conv_U2); break;
1999 case Mode.I1_U4: ig.Emit (OpCodes.Conv_U4); break;
2000 case Mode.I1_U8: ig.Emit (OpCodes.Conv_I8); break;
2001 case Mode.I1_CH: ig.Emit (OpCodes.Conv_U2); break;
2003 case Mode.U1_I1: ig.Emit (OpCodes.Conv_I1); break;
2004 case Mode.U1_CH: ig.Emit (OpCodes.Conv_U2); break;
2006 case Mode.I2_I1: ig.Emit (OpCodes.Conv_I1); break;
2007 case Mode.I2_U1: ig.Emit (OpCodes.Conv_U1); break;
2008 case Mode.I2_U2: ig.Emit (OpCodes.Conv_U2); break;
2009 case Mode.I2_U4: ig.Emit (OpCodes.Conv_U4); break;
2010 case Mode.I2_U8: ig.Emit (OpCodes.Conv_I8); break;
2011 case Mode.I2_CH: ig.Emit (OpCodes.Conv_U2); break;
2013 case Mode.U2_I1: ig.Emit (OpCodes.Conv_I1); break;
2014 case Mode.U2_U1: ig.Emit (OpCodes.Conv_U1); break;
2015 case Mode.U2_I2: ig.Emit (OpCodes.Conv_I2); break;
2016 case Mode.U2_CH: /* nothing */ break;
2018 case Mode.I4_I1: ig.Emit (OpCodes.Conv_I1); break;
2019 case Mode.I4_U1: ig.Emit (OpCodes.Conv_U1); break;
2020 case Mode.I4_I2: ig.Emit (OpCodes.Conv_I2); break;
2021 case Mode.I4_U4: /* nothing */ break;
2022 case Mode.I4_U2: ig.Emit (OpCodes.Conv_U2); break;
2023 case Mode.I4_U8: ig.Emit (OpCodes.Conv_I8); break;
2024 case Mode.I4_CH: ig.Emit (OpCodes.Conv_U2); break;
2026 case Mode.U4_I1: ig.Emit (OpCodes.Conv_I1); break;
2027 case Mode.U4_U1: ig.Emit (OpCodes.Conv_U1); break;
2028 case Mode.U4_I2: ig.Emit (OpCodes.Conv_I2); break;
2029 case Mode.U4_U2: ig.Emit (OpCodes.Conv_U2); break;
2030 case Mode.U4_I4: /* nothing */ break;
2031 case Mode.U4_CH: ig.Emit (OpCodes.Conv_U2); break;
2033 case Mode.I8_I1: ig.Emit (OpCodes.Conv_I1); break;
2034 case Mode.I8_U1: ig.Emit (OpCodes.Conv_U1); break;
2035 case Mode.I8_I2: ig.Emit (OpCodes.Conv_I2); break;
2036 case Mode.I8_U2: ig.Emit (OpCodes.Conv_U2); break;
2037 case Mode.I8_I4: ig.Emit (OpCodes.Conv_I4); break;
2038 case Mode.I8_U4: ig.Emit (OpCodes.Conv_U4); break;
2039 case Mode.I8_U8: /* nothing */ break;
2040 case Mode.I8_CH: ig.Emit (OpCodes.Conv_U2); break;
2041 case Mode.I8_I: ig.Emit (OpCodes.Conv_U); break;
2043 case Mode.U8_I1: ig.Emit (OpCodes.Conv_I1); break;
2044 case Mode.U8_U1: ig.Emit (OpCodes.Conv_U1); break;
2045 case Mode.U8_I2: ig.Emit (OpCodes.Conv_I2); break;
2046 case Mode.U8_U2: ig.Emit (OpCodes.Conv_U2); break;
2047 case Mode.U8_I4: ig.Emit (OpCodes.Conv_I4); break;
2048 case Mode.U8_U4: ig.Emit (OpCodes.Conv_U4); break;
2049 case Mode.U8_I8: /* nothing */ break;
2050 case Mode.U8_CH: ig.Emit (OpCodes.Conv_U2); break;
2051 case Mode.U8_I: ig.Emit (OpCodes.Conv_U); break;
2053 case Mode.CH_I1: ig.Emit (OpCodes.Conv_I1); break;
2054 case Mode.CH_U1: ig.Emit (OpCodes.Conv_U1); break;
2055 case Mode.CH_I2: ig.Emit (OpCodes.Conv_I2); break;
2057 case Mode.R4_I1: ig.Emit (OpCodes.Conv_I1); break;
2058 case Mode.R4_U1: ig.Emit (OpCodes.Conv_U1); break;
2059 case Mode.R4_I2: ig.Emit (OpCodes.Conv_I2); break;
2060 case Mode.R4_U2: ig.Emit (OpCodes.Conv_U2); break;
2061 case Mode.R4_I4: ig.Emit (OpCodes.Conv_I4); break;
2062 case Mode.R4_U4: ig.Emit (OpCodes.Conv_U4); break;
2063 case Mode.R4_I8: ig.Emit (OpCodes.Conv_I8); break;
2064 case Mode.R4_U8: ig.Emit (OpCodes.Conv_U8); break;
2065 case Mode.R4_CH: ig.Emit (OpCodes.Conv_U2); break;
2067 case Mode.R8_I1: ig.Emit (OpCodes.Conv_I1); break;
2068 case Mode.R8_U1: ig.Emit (OpCodes.Conv_U1); break;
2069 case Mode.R8_I2: ig.Emit (OpCodes.Conv_I2); break;
2070 case Mode.R8_U2: ig.Emit (OpCodes.Conv_U2); break;
2071 case Mode.R8_I4: ig.Emit (OpCodes.Conv_I4); break;
2072 case Mode.R8_U4: ig.Emit (OpCodes.Conv_U4); break;
2073 case Mode.R8_I8: ig.Emit (OpCodes.Conv_I8); break;
2074 case Mode.R8_U8: ig.Emit (OpCodes.Conv_U8); break;
2075 case Mode.R8_CH: ig.Emit (OpCodes.Conv_U2); break;
2076 case Mode.R8_R4: ig.Emit (OpCodes.Conv_R4); break;
2078 case Mode.I_I8: ig.Emit (OpCodes.Conv_U8); break;
2084 public class OpcodeCast : TypeCast {
2085 readonly OpCode op;
2087 public OpcodeCast (Expression child, Type return_type, OpCode op)
2088 : base (child, return_type)
2090 this.op = op;
2093 protected override Expression DoResolve (ResolveContext ec)
2095 // This should never be invoked, we are born in fully
2096 // initialized state.
2098 return this;
2101 public override void Emit (EmitContext ec)
2103 base.Emit (ec);
2104 ec.ig.Emit (op);
2107 public Type UnderlyingType {
2108 get { return child.Type; }
2112 /// <summary>
2113 /// This kind of cast is used to encapsulate a child and cast it
2114 /// to the class requested
2115 /// </summary>
2116 public sealed class ClassCast : TypeCast {
2117 readonly bool forced;
2119 public ClassCast (Expression child, Type return_type)
2120 : base (child, return_type)
2124 public ClassCast (Expression child, Type return_type, bool forced)
2125 : base (child, return_type)
2127 this.forced = forced;
2130 public override void Emit (EmitContext ec)
2132 base.Emit (ec);
2134 bool gen = TypeManager.IsGenericParameter (child.Type);
2135 if (gen)
2136 ec.ig.Emit (OpCodes.Box, child.Type);
2138 if (type.IsGenericParameter) {
2139 ec.ig.Emit (OpCodes.Unbox_Any, type);
2140 return;
2143 if (gen && !forced)
2144 return;
2146 ec.ig.Emit (OpCodes.Castclass, type);
2151 // Created during resolving pahse when an expression is wrapped or constantified
2152 // and original expression can be used later (e.g. for expression trees)
2154 public class ReducedExpression : Expression
2156 sealed class ReducedConstantExpression : EmptyConstantCast
2158 readonly Expression orig_expr;
2160 public ReducedConstantExpression (Constant expr, Expression orig_expr)
2161 : base (expr, expr.Type)
2163 this.orig_expr = orig_expr;
2166 public override Constant ConvertImplicitly (ResolveContext rc, Type target_type)
2168 Constant c = base.ConvertImplicitly (rc, target_type);
2169 if (c != null)
2170 c = new ReducedConstantExpression (c, orig_expr);
2172 return c;
2175 public override Expression CreateExpressionTree (ResolveContext ec)
2177 return orig_expr.CreateExpressionTree (ec);
2180 public override bool GetAttributableValue (ResolveContext ec, Type value_type, out object value)
2183 // Even if resolved result is a constant original expression was not
2184 // and attribute accepts constants only
2186 Attribute.Error_AttributeArgumentNotValid (ec, orig_expr.Location);
2187 value = null;
2188 return false;
2191 public override Constant ConvertExplicitly (bool in_checked_context, Type target_type)
2193 Constant c = base.ConvertExplicitly (in_checked_context, target_type);
2194 if (c != null)
2195 c = new ReducedConstantExpression (c, orig_expr);
2196 return c;
2200 sealed class ReducedExpressionStatement : ExpressionStatement
2202 readonly Expression orig_expr;
2203 readonly ExpressionStatement stm;
2205 public ReducedExpressionStatement (ExpressionStatement stm, Expression orig)
2207 this.orig_expr = orig;
2208 this.stm = stm;
2209 this.loc = orig.Location;
2212 public override Expression CreateExpressionTree (ResolveContext ec)
2214 return orig_expr.CreateExpressionTree (ec);
2217 protected override Expression DoResolve (ResolveContext ec)
2219 eclass = stm.eclass;
2220 type = stm.Type;
2221 return this;
2224 public override void Emit (EmitContext ec)
2226 stm.Emit (ec);
2229 public override void EmitStatement (EmitContext ec)
2231 stm.EmitStatement (ec);
2234 public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
2236 stm.MutateHoistedGenericType (storey);
2240 readonly Expression expr, orig_expr;
2242 private ReducedExpression (Expression expr, Expression orig_expr)
2244 this.expr = expr;
2245 this.eclass = expr.eclass;
2246 this.type = expr.Type;
2247 this.orig_expr = orig_expr;
2248 this.loc = orig_expr.Location;
2252 // Creates fully resolved expression switcher
2254 public static Constant Create (Constant expr, Expression original_expr)
2256 if (expr.eclass == ExprClass.Unresolved)
2257 throw new ArgumentException ("Unresolved expression");
2259 return new ReducedConstantExpression (expr, original_expr);
2262 public static ExpressionStatement Create (ExpressionStatement s, Expression orig)
2264 return new ReducedExpressionStatement (s, orig);
2268 // Creates unresolved reduce expression. The original expression has to be
2269 // already resolved
2271 public static Expression Create (Expression expr, Expression original_expr)
2273 Constant c = expr as Constant;
2274 if (c != null)
2275 return Create (c, original_expr);
2277 ExpressionStatement s = expr as ExpressionStatement;
2278 if (s != null)
2279 return Create (s, original_expr);
2281 if (expr.eclass == ExprClass.Unresolved)
2282 throw new ArgumentException ("Unresolved expression");
2284 return new ReducedExpression (expr, original_expr);
2287 public override Expression CreateExpressionTree (ResolveContext ec)
2289 return orig_expr.CreateExpressionTree (ec);
2292 protected override Expression DoResolve (ResolveContext ec)
2294 return this;
2297 public override void Emit (EmitContext ec)
2299 expr.Emit (ec);
2302 public override void EmitBranchable (EmitContext ec, Label target, bool on_true)
2304 expr.EmitBranchable (ec, target, on_true);
2307 #if NET_4_0
2308 public override SLE.Expression MakeExpression (BuilderContext ctx)
2310 return orig_expr.MakeExpression (ctx);
2312 #endif
2314 public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
2316 expr.MutateHoistedGenericType (storey);
2321 // Standard composite pattern
2323 public abstract class CompositeExpression : Expression
2325 Expression expr;
2327 protected CompositeExpression (Expression expr)
2329 this.expr = expr;
2330 this.loc = expr.Location;
2333 public override Expression CreateExpressionTree (ResolveContext ec)
2335 return expr.CreateExpressionTree (ec);
2338 public Expression Child {
2339 get { return expr; }
2342 protected override Expression DoResolve (ResolveContext ec)
2344 expr = expr.Resolve (ec);
2345 if (expr != null) {
2346 type = expr.Type;
2347 eclass = expr.eclass;
2350 return this;
2353 public override void Emit (EmitContext ec)
2355 expr.Emit (ec);
2358 public override bool IsNull {
2359 get { return expr.IsNull; }
2364 // Base of expressions used only to narrow resolve flow
2366 public abstract class ShimExpression : Expression
2368 protected Expression expr;
2370 protected ShimExpression (Expression expr)
2372 this.expr = expr;
2375 protected override void CloneTo (CloneContext clonectx, Expression t)
2377 if (expr == null)
2378 return;
2380 ShimExpression target = (ShimExpression) t;
2381 target.expr = expr.Clone (clonectx);
2384 public override Expression CreateExpressionTree (ResolveContext ec)
2386 throw new NotSupportedException ("ET");
2389 public override void Emit (EmitContext ec)
2391 throw new InternalErrorException ("Missing Resolve call");
2394 public Expression Expr {
2395 get { return expr; }
2398 public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
2400 throw new InternalErrorException ("Missing Resolve call");
2405 // Unresolved type name expressions
2407 public abstract class ATypeNameExpression : FullNamedExpression
2409 string name;
2410 protected TypeArguments targs;
2412 protected ATypeNameExpression (string name, Location l)
2414 this.name = name;
2415 loc = l;
2418 protected ATypeNameExpression (string name, TypeArguments targs, Location l)
2420 this.name = name;
2421 this.targs = targs;
2422 loc = l;
2425 public bool HasTypeArguments {
2426 get {
2427 return targs != null;
2431 public override bool Equals (object obj)
2433 ATypeNameExpression atne = obj as ATypeNameExpression;
2434 return atne != null && atne.Name == Name &&
2435 (targs == null || targs.Equals (atne.targs));
2438 public override int GetHashCode ()
2440 return Name.GetHashCode ();
2443 public override string GetSignatureForError ()
2445 if (targs != null) {
2446 return TypeManager.RemoveGenericArity (Name) + "<" +
2447 targs.GetSignatureForError () + ">";
2450 return Name;
2453 public string Name {
2454 get {
2455 return name;
2457 set {
2458 name = value;
2462 public TypeArguments TypeArguments {
2463 get {
2464 return targs;
2469 /// <summary>
2470 /// SimpleName expressions are formed of a single word and only happen at the beginning
2471 /// of a dotted-name.
2472 /// </summary>
2473 public class SimpleName : ATypeNameExpression {
2474 bool in_transit;
2476 public SimpleName (string name, Location l)
2477 : base (name, l)
2481 public SimpleName (string name, TypeArguments args, Location l)
2482 : base (name, args, l)
2486 public SimpleName (string name, TypeParameter[] type_params, Location l)
2487 : base (name, l)
2489 targs = new TypeArguments ();
2490 foreach (TypeParameter type_param in type_params)
2491 targs.Add (new TypeParameterExpr (type_param, l));
2494 public static string RemoveGenericArity (string name)
2496 int start = 0;
2497 StringBuilder sb = null;
2498 do {
2499 int pos = name.IndexOf ('`', start);
2500 if (pos < 0) {
2501 if (start == 0)
2502 return name;
2504 sb.Append (name.Substring (start));
2505 break;
2508 if (sb == null)
2509 sb = new StringBuilder ();
2510 sb.Append (name.Substring (start, pos-start));
2512 pos++;
2513 while ((pos < name.Length) && Char.IsNumber (name [pos]))
2514 pos++;
2516 start = pos;
2517 } while (start < name.Length);
2519 return sb.ToString ();
2522 public SimpleName GetMethodGroup ()
2524 return new SimpleName (RemoveGenericArity (Name), targs, loc);
2527 public static void Error_ObjectRefRequired (ResolveContext ec, Location l, string name)
2529 if (ec.HasSet (ResolveContext.Options.FieldInitializerScope))
2530 ec.Report.Error (236, l,
2531 "A field initializer cannot reference the nonstatic field, method, or property `{0}'",
2532 name);
2533 else
2534 ec.Report.Error (120, l,
2535 "An object reference is required to access non-static member `{0}'",
2536 name);
2539 public bool IdenticalNameAndTypeName (IMemberContext mc, Expression resolved_to, Location loc)
2541 return resolved_to != null && resolved_to.Type != null &&
2542 resolved_to.Type.Name == Name &&
2543 (mc.LookupNamespaceOrType (Name, loc, /* ignore_cs0104 = */ true) != null);
2546 protected override Expression DoResolve (ResolveContext ec)
2548 return SimpleNameResolve (ec, null, false);
2551 public override Expression DoResolveLValue (ResolveContext ec, Expression right_side)
2553 return SimpleNameResolve (ec, right_side, false);
2557 public Expression DoResolve (ResolveContext ec, bool intermediate)
2559 return SimpleNameResolve (ec, null, intermediate);
2562 static bool IsNestedChild (Type t, Type parent)
2564 while (parent != null) {
2565 if (TypeManager.IsNestedChildOf (t, TypeManager.DropGenericTypeArguments (parent)))
2566 return true;
2568 parent = parent.BaseType;
2571 return false;
2574 FullNamedExpression ResolveNested (Type t)
2576 if (!TypeManager.IsGenericTypeDefinition (t) && !TypeManager.IsGenericType (t))
2577 return null;
2579 Type ds = t;
2580 while (ds != null && !IsNestedChild (t, ds))
2581 ds = ds.DeclaringType;
2583 if (ds == null)
2584 return null;
2586 Type[] gen_params = TypeManager.GetTypeArguments (t);
2588 int arg_count = targs != null ? targs.Count : 0;
2590 for (; (ds != null) && TypeManager.IsGenericType (ds); ds = ds.DeclaringType) {
2591 Type[] gargs = TypeManager.GetTypeArguments (ds);
2592 if (arg_count + gargs.Length == gen_params.Length) {
2593 TypeArguments new_args = new TypeArguments ();
2594 foreach (Type param in gargs)
2595 new_args.Add (new TypeExpression (param, loc));
2597 if (targs != null)
2598 new_args.Add (targs);
2600 return new GenericTypeExpr (t, new_args, loc);
2604 return null;
2607 public override FullNamedExpression ResolveAsTypeStep (IMemberContext ec, bool silent)
2609 int errors = ec.Compiler.Report.Errors;
2610 FullNamedExpression fne = ec.LookupNamespaceOrType (Name, loc, /*ignore_cs0104=*/ false);
2612 if (fne != null) {
2613 if (fne.Type == null)
2614 return fne;
2616 FullNamedExpression nested = ResolveNested (fne.Type);
2617 if (nested != null)
2618 return nested.ResolveAsTypeStep (ec, false);
2620 if (targs != null) {
2621 if (TypeManager.IsGenericType (fne.Type)) {
2622 GenericTypeExpr ct = new GenericTypeExpr (fne.Type, targs, loc);
2623 return ct.ResolveAsTypeStep (ec, false);
2626 fne.Error_TypeArgumentsCannotBeUsed (ec.Compiler.Report, loc);
2629 return fne;
2632 if (!HasTypeArguments && Name == "dynamic" &&
2633 RootContext.Version > LanguageVersion.V_3 &&
2634 RootContext.MetadataCompatibilityVersion > MetadataVersion.v2) {
2636 if (!PredefinedAttributes.Get.Dynamic.IsDefined) {
2637 ec.Compiler.Report.Error (1980, Location,
2638 "Dynamic keyword requires `{0}' to be defined. Are you missing System.Core.dll assembly reference?",
2639 PredefinedAttributes.Get.Dynamic.GetSignatureForError ());
2642 return new DynamicTypeExpr (loc);
2645 if (silent || errors != ec.Compiler.Report.Errors)
2646 return null;
2648 Error_TypeOrNamespaceNotFound (ec);
2649 return null;
2652 protected virtual void Error_TypeOrNamespaceNotFound (IMemberContext ec)
2654 if (ec.CurrentType != null) {
2655 if (ec.CurrentTypeDefinition != null) {
2656 MemberCore mc = ec.CurrentTypeDefinition.GetDefinition (Name);
2657 if (mc != null) {
2658 Error_UnexpectedKind (ec.Compiler.Report, mc, "type", GetMemberType (mc), loc);
2659 return;
2663 string ns = ec.CurrentType.Namespace;
2664 string fullname = (ns.Length > 0) ? ns + "." + Name : Name;
2665 foreach (Assembly a in GlobalRootNamespace.Instance.Assemblies) {
2666 Type type = a.GetType (fullname);
2667 if (type != null) {
2668 ec.Compiler.Report.SymbolRelatedToPreviousError (type);
2669 Expression.ErrorIsInaccesible (loc, TypeManager.CSharpName (type), ec.Compiler.Report);
2670 return;
2674 if (ec.CurrentTypeDefinition != null) {
2675 Type t = ec.CurrentTypeDefinition.LookupAnyGeneric (Name);
2676 if (t != null) {
2677 Namespace.Error_InvalidNumberOfTypeArguments (ec.Compiler.Report, t, loc);
2678 return;
2683 if (targs != null) {
2684 FullNamedExpression retval = ec.LookupNamespaceOrType (SimpleName.RemoveGenericArity (Name), loc, true);
2685 if (retval != null) {
2686 retval.Error_TypeArgumentsCannotBeUsed (ec.Compiler.Report, loc);
2687 return;
2691 NamespaceEntry.Error_NamespaceNotFound (loc, Name, ec.Compiler.Report);
2694 // TODO: I am still not convinced about this. If someone else will need it
2695 // implement this as virtual property in MemberCore hierarchy
2696 public static string GetMemberType (MemberCore mc)
2698 if (mc is Property)
2699 return "property";
2700 if (mc is Indexer)
2701 return "indexer";
2702 if (mc is FieldBase)
2703 return "field";
2704 if (mc is MethodCore)
2705 return "method";
2706 if (mc is EnumMember)
2707 return "enum";
2708 if (mc is Event)
2709 return "event";
2711 return "type";
2714 Expression SimpleNameResolve (ResolveContext ec, Expression right_side, bool intermediate)
2716 if (in_transit)
2717 return null;
2719 in_transit = true;
2720 Expression e = DoSimpleNameResolve (ec, right_side, intermediate);
2721 in_transit = false;
2723 if (e == null)
2724 return null;
2726 if (ec.CurrentBlock == null || ec.CurrentBlock.CheckInvariantMeaningInBlock (Name, e, Location))
2727 return e;
2729 return null;
2732 /// <remarks>
2733 /// 7.5.2: Simple Names.
2735 /// Local Variables and Parameters are handled at
2736 /// parse time, so they never occur as SimpleNames.
2738 /// The `intermediate' flag is used by MemberAccess only
2739 /// and it is used to inform us that it is ok for us to
2740 /// avoid the static check, because MemberAccess might end
2741 /// up resolving the Name as a Type name and the access as
2742 /// a static type access.
2744 /// ie: Type Type; .... { Type.GetType (""); }
2746 /// Type is both an instance variable and a Type; Type.GetType
2747 /// is the static method not an instance method of type.
2748 /// </remarks>
2749 Expression DoSimpleNameResolve (ResolveContext ec, Expression right_side, bool intermediate)
2751 Expression e = null;
2754 // Stage 1: Performed by the parser (binding to locals or parameters).
2756 Block current_block = ec.CurrentBlock;
2757 if (current_block != null){
2758 LocalInfo vi = current_block.GetLocalInfo (Name);
2759 if (vi != null){
2760 e = new LocalVariableReference (ec.CurrentBlock, Name, loc);
2762 if (right_side != null) {
2763 e = e.ResolveLValue (ec, right_side);
2764 } else {
2765 if (intermediate) {
2766 using (ec.With (ResolveContext.Options.DoFlowAnalysis, false)) {
2767 e = e.Resolve (ec, ResolveFlags.VariableOrValue);
2769 } else {
2770 e = e.Resolve (ec, ResolveFlags.VariableOrValue);
2774 if (targs != null && e != null)
2775 e.Error_TypeArgumentsCannotBeUsed (ec.Report, loc);
2777 return e;
2780 e = current_block.Toplevel.GetParameterReference (Name, loc);
2781 if (e != null) {
2782 if (right_side != null)
2783 e = e.ResolveLValue (ec, right_side);
2784 else
2785 e = e.Resolve (ec);
2787 if (targs != null && e != null)
2788 e.Error_TypeArgumentsCannotBeUsed (ec.Report, loc);
2790 return e;
2795 // Stage 2: Lookup members
2798 Type almost_matched_type = null;
2799 ArrayList almost_matched = null;
2800 for (Type lookup_ds = ec.CurrentType; lookup_ds != null; lookup_ds = lookup_ds.DeclaringType) {
2801 e = MemberLookup (ec.Compiler, ec.CurrentType, lookup_ds, Name, loc);
2802 if (e != null) {
2803 PropertyExpr pe = e as PropertyExpr;
2804 if (pe != null) {
2805 AParametersCollection param = TypeManager.GetParameterData (pe.PropertyInfo);
2807 // since TypeManager.MemberLookup doesn't know if we're doing a lvalue access or not,
2808 // it doesn't know which accessor to check permissions against
2809 if (param.IsEmpty && pe.IsAccessibleFrom (ec.CurrentType, right_side != null))
2810 break;
2811 } else if (e is EventExpr) {
2812 if (((EventExpr) e).IsAccessibleFrom (ec.CurrentType))
2813 break;
2814 } else if (targs != null && e is TypeExpression) {
2815 e = new GenericTypeExpr (e.Type, targs, loc).ResolveAsTypeStep (ec, false);
2816 break;
2817 } else {
2818 break;
2820 e = null;
2823 if (almost_matched == null && almost_matched_members.Count > 0) {
2824 almost_matched_type = lookup_ds;
2825 almost_matched = (ArrayList) almost_matched_members.Clone ();
2829 if (e == null) {
2830 if (almost_matched == null && almost_matched_members.Count > 0) {
2831 almost_matched_type = ec.CurrentType;
2832 almost_matched = (ArrayList) almost_matched_members.Clone ();
2834 e = ResolveAsTypeStep (ec, true);
2837 if (e == null) {
2838 if (current_block != null) {
2839 IKnownVariable ikv = current_block.Explicit.GetKnownVariable (Name);
2840 if (ikv != null) {
2841 LocalInfo li = ikv as LocalInfo;
2842 // Supress CS0219 warning
2843 if (li != null)
2844 li.Used = true;
2846 Error_VariableIsUsedBeforeItIsDeclared (ec.Report, Name);
2847 return null;
2851 if (RootContext.EvalMode){
2852 FieldInfo fi = Evaluator.LookupField (Name);
2853 if (fi != null)
2854 return new FieldExpr (fi, loc).Resolve (ec);
2857 if (almost_matched != null)
2858 almost_matched_members = almost_matched;
2859 if (almost_matched_type == null)
2860 almost_matched_type = ec.CurrentType;
2862 string type_name = ec.MemberContext.CurrentType == null ? null : ec.MemberContext.CurrentType.Name;
2863 return Error_MemberLookupFailed (ec, ec.CurrentType, null, almost_matched_type, Name,
2864 type_name, AllMemberTypes, AllBindingFlags);
2867 if (e is MemberExpr) {
2868 MemberExpr me = (MemberExpr) e;
2870 Expression left;
2871 if (me.IsInstance) {
2872 if (ec.IsStatic || ec.HasAny (ResolveContext.Options.FieldInitializerScope | ResolveContext.Options.BaseInitializer | ResolveContext.Options.ConstantScope)) {
2874 // Note that an MemberExpr can be both IsInstance and IsStatic.
2875 // An unresolved MethodGroupExpr can contain both kinds of methods
2876 // and each predicate is true if the MethodGroupExpr contains
2877 // at least one of that kind of method.
2880 if (!me.IsStatic &&
2881 (!intermediate || !IdenticalNameAndTypeName (ec, me, loc))) {
2882 Error_ObjectRefRequired (ec, loc, me.GetSignatureForError ());
2883 return null;
2887 // Pass the buck to MemberAccess and Invocation.
2889 left = EmptyExpression.Null;
2890 } else {
2891 left = ec.GetThis (loc);
2893 } else {
2894 left = new TypeExpression (ec.CurrentType, loc);
2897 me = me.ResolveMemberAccess (ec, left, loc, null);
2898 if (me == null)
2899 return null;
2901 if (targs != null) {
2902 if (!targs.Resolve (ec))
2903 return null;
2905 me.SetTypeArguments (ec, targs);
2908 if (!me.IsStatic && (me.InstanceExpression != null && me.InstanceExpression != EmptyExpression.Null) &&
2909 TypeManager.IsNestedFamilyAccessible (me.InstanceExpression.Type, me.DeclaringType) &&
2910 me.InstanceExpression.Type != me.DeclaringType &&
2911 !TypeManager.IsFamilyAccessible (me.InstanceExpression.Type, me.DeclaringType) &&
2912 (!intermediate || !IdenticalNameAndTypeName (ec, e, loc))) {
2913 ec.Report.Error (38, loc, "Cannot access a nonstatic member of outer type `{0}' via nested type `{1}'",
2914 TypeManager.CSharpName (me.DeclaringType), TypeManager.CSharpName (me.InstanceExpression.Type));
2915 return null;
2918 return (right_side != null)
2919 ? me.DoResolveLValue (ec, right_side)
2920 : me.Resolve (ec);
2923 return e;
2927 /// <summary>
2928 /// Represents a namespace or a type. The name of the class was inspired by
2929 /// section 10.8.1 (Fully Qualified Names).
2930 /// </summary>
2931 public abstract class FullNamedExpression : Expression
2933 protected override void CloneTo (CloneContext clonectx, Expression target)
2935 // Do nothing, most unresolved type expressions cannot be
2936 // resolved to different type
2939 public override Expression CreateExpressionTree (ResolveContext ec)
2941 throw new NotSupportedException ("ET");
2944 public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
2946 throw new NotSupportedException ();
2949 public override FullNamedExpression ResolveAsTypeStep (IMemberContext ec, bool silent)
2951 return this;
2954 public override void Emit (EmitContext ec)
2956 throw new InternalErrorException ("FullNamedExpression `{0}' found in resolved tree",
2957 GetSignatureForError ());
2961 /// <summary>
2962 /// Expression that evaluates to a type
2963 /// </summary>
2964 public abstract class TypeExpr : FullNamedExpression {
2965 public override FullNamedExpression ResolveAsTypeStep (IMemberContext ec, bool silent)
2967 TypeExpr t = DoResolveAsTypeStep (ec);
2968 if (t == null)
2969 return null;
2971 eclass = ExprClass.Type;
2972 return t;
2975 protected override Expression DoResolve (ResolveContext ec)
2977 return ResolveAsTypeTerminal (ec, false);
2980 public virtual bool CheckAccessLevel (IMemberContext mc)
2982 return mc.CurrentTypeDefinition.CheckAccessLevel (Type);
2985 public virtual bool IsClass {
2986 get { return Type.IsClass; }
2989 public virtual bool IsValueType {
2990 get { return TypeManager.IsStruct (Type); }
2993 public virtual bool IsInterface {
2994 get { return Type.IsInterface; }
2997 public virtual bool IsSealed {
2998 get { return Type.IsSealed; }
3001 public virtual bool CanInheritFrom ()
3003 if (Type == TypeManager.enum_type ||
3004 (Type == TypeManager.value_type && RootContext.StdLib) ||
3005 Type == TypeManager.multicast_delegate_type ||
3006 Type == TypeManager.delegate_type ||
3007 Type == TypeManager.array_type)
3008 return false;
3010 return true;
3013 protected abstract TypeExpr DoResolveAsTypeStep (IMemberContext ec);
3015 public override bool Equals (object obj)
3017 TypeExpr tobj = obj as TypeExpr;
3018 if (tobj == null)
3019 return false;
3021 return Type == tobj.Type;
3024 public override int GetHashCode ()
3026 return Type.GetHashCode ();
3029 public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
3031 type = storey.MutateType (type);
3035 /// <summary>
3036 /// Fully resolved Expression that already evaluated to a type
3037 /// </summary>
3038 public class TypeExpression : TypeExpr {
3039 public TypeExpression (Type t, Location l)
3041 Type = t;
3042 eclass = ExprClass.Type;
3043 loc = l;
3046 protected override TypeExpr DoResolveAsTypeStep (IMemberContext ec)
3048 return this;
3051 public override TypeExpr ResolveAsTypeTerminal (IMemberContext ec, bool silent)
3053 return this;
3058 // Used to create types from a fully qualified name. These are just used
3059 // by the parser to setup the core types.
3061 public sealed class TypeLookupExpression : TypeExpr {
3062 readonly string ns_name;
3063 readonly string name;
3065 public TypeLookupExpression (string ns, string name)
3067 this.name = name;
3068 this.ns_name = ns;
3069 eclass = ExprClass.Type;
3072 public override TypeExpr ResolveAsTypeTerminal (IMemberContext ec, bool silent)
3075 // It's null only during mscorlib bootstrap when DefineType
3076 // nees to resolve base type of same type
3078 // For instance struct Char : IComparable<char>
3080 // TODO: it could be removed when Resolve starts to use
3081 // DeclSpace instead of Type
3083 if (type == null) {
3084 Namespace ns = GlobalRootNamespace.Instance.GetNamespace (ns_name, false);
3085 FullNamedExpression fne = ns.Lookup (ec.Compiler, name, loc);
3086 if (fne != null)
3087 type = fne.Type;
3090 return this;
3093 protected override TypeExpr DoResolveAsTypeStep (IMemberContext ec)
3095 return this;
3098 public override string GetSignatureForError ()
3100 if (type == null)
3101 return TypeManager.CSharpName (ns_name + "." + name, null);
3103 return base.GetSignatureForError ();
3107 /// <summary>
3108 /// This class denotes an expression which evaluates to a member
3109 /// of a struct or a class.
3110 /// </summary>
3111 public abstract class MemberExpr : Expression
3113 protected bool is_base;
3115 /// <summary>
3116 /// The name of this member.
3117 /// </summary>
3118 public abstract string Name {
3119 get;
3123 // When base.member is used
3125 public bool IsBase {
3126 get { return is_base; }
3127 set { is_base = value; }
3130 /// <summary>
3131 /// Whether this is an instance member.
3132 /// </summary>
3133 public abstract bool IsInstance {
3134 get;
3137 /// <summary>
3138 /// Whether this is a static member.
3139 /// </summary>
3140 public abstract bool IsStatic {
3141 get;
3144 /// <summary>
3145 /// The type which declares this member.
3146 /// </summary>
3147 public abstract Type DeclaringType {
3148 get;
3151 /// <summary>
3152 /// The instance expression associated with this member, if it's a
3153 /// non-static member.
3154 /// </summary>
3155 public Expression InstanceExpression;
3157 public static void error176 (ResolveContext ec, Location loc, string name)
3159 ec.Report.Error (176, loc, "Static member `{0}' cannot be accessed " +
3160 "with an instance reference, qualify it with a type name instead", name);
3163 public static void Error_BaseAccessInExpressionTree (ResolveContext ec, Location loc)
3165 ec.Report.Error (831, loc, "An expression tree may not contain a base access");
3168 public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
3170 if (InstanceExpression != null)
3171 InstanceExpression.MutateHoistedGenericType (storey);
3174 // TODO: possible optimalization
3175 // Cache resolved constant result in FieldBuilder <-> expression map
3176 public virtual MemberExpr ResolveMemberAccess (ResolveContext ec, Expression left, Location loc,
3177 SimpleName original)
3180 // Precondition:
3181 // original == null || original.Resolve (...) ==> left
3184 if (left is TypeExpr) {
3185 left = left.ResolveAsBaseTerminal (ec, false);
3186 if (left == null)
3187 return null;
3189 // TODO: Same problem as in class.cs, TypeTerminal does not
3190 // always do all necessary checks
3191 ObsoleteAttribute oa = AttributeTester.GetObsoleteAttribute (left.Type);
3192 if (oa != null && !ec.IsObsolete) {
3193 AttributeTester.Report_ObsoleteMessage (oa, left.GetSignatureForError (), loc, ec.Report);
3196 GenericTypeExpr ct = left as GenericTypeExpr;
3197 if (ct != null && !ct.CheckConstraints (ec))
3198 return null;
3201 if (!IsStatic) {
3202 SimpleName.Error_ObjectRefRequired (ec, loc, GetSignatureForError ());
3203 return null;
3206 return this;
3209 if (!IsInstance) {
3210 if (original != null && original.IdenticalNameAndTypeName (ec, left, loc))
3211 return this;
3213 return ResolveExtensionMemberAccess (ec, left);
3216 InstanceExpression = left;
3217 return this;
3220 protected virtual MemberExpr ResolveExtensionMemberAccess (ResolveContext ec, Expression left)
3222 error176 (ec, loc, GetSignatureForError ());
3223 return this;
3226 protected void EmitInstance (EmitContext ec, bool prepare_for_load)
3228 if (IsStatic)
3229 return;
3231 if (InstanceExpression == EmptyExpression.Null) {
3232 // FIXME: This should not be here at all
3233 SimpleName.Error_ObjectRefRequired (new ResolveContext (ec.MemberContext), loc, GetSignatureForError ());
3234 return;
3237 if (TypeManager.IsValueType (InstanceExpression.Type)) {
3238 if (InstanceExpression is IMemoryLocation) {
3239 ((IMemoryLocation) InstanceExpression).AddressOf (ec, AddressOp.LoadStore);
3240 } else {
3241 LocalTemporary t = new LocalTemporary (InstanceExpression.Type);
3242 InstanceExpression.Emit (ec);
3243 t.Store (ec);
3244 t.AddressOf (ec, AddressOp.Store);
3246 } else
3247 InstanceExpression.Emit (ec);
3249 if (prepare_for_load)
3250 ec.ig.Emit (OpCodes.Dup);
3253 public virtual void SetTypeArguments (ResolveContext ec, TypeArguments ta)
3255 // TODO: need to get correct member type
3256 ec.Report.Error (307, loc, "The property `{0}' cannot be used with type arguments",
3257 GetSignatureForError ());
3261 ///
3262 /// Represents group of extension methods
3263 ///
3264 public class ExtensionMethodGroupExpr : MethodGroupExpr
3266 readonly NamespaceEntry namespace_entry;
3267 public Expression ExtensionExpression;
3268 Argument extension_argument;
3270 public ExtensionMethodGroupExpr (ArrayList list, NamespaceEntry n, Type extensionType, Location l)
3271 : base (list, extensionType, l)
3273 this.namespace_entry = n;
3276 public override bool IsStatic {
3277 get { return true; }
3280 public bool IsTopLevel {
3281 get { return namespace_entry == null; }
3284 public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
3286 extension_argument.Expr.MutateHoistedGenericType (storey);
3287 base.MutateHoistedGenericType (storey);
3290 public override MethodGroupExpr OverloadResolve (ResolveContext ec, ref Arguments arguments, bool may_fail, Location loc)
3292 if (arguments == null)
3293 arguments = new Arguments (1);
3295 arguments.Insert (0, new Argument (ExtensionExpression));
3296 MethodGroupExpr mg = ResolveOverloadExtensions (ec, ref arguments, namespace_entry, loc);
3298 // Store resolved argument and restore original arguments
3299 if (mg != null)
3300 ((ExtensionMethodGroupExpr)mg).extension_argument = arguments [0];
3301 else
3302 arguments.RemoveAt (0); // Clean-up modified arguments for error reporting
3304 return mg;
3307 MethodGroupExpr ResolveOverloadExtensions (ResolveContext ec, ref Arguments arguments, NamespaceEntry ns, Location loc)
3309 // Use normal resolve rules
3310 MethodGroupExpr mg = base.OverloadResolve (ec, ref arguments, ns != null, loc);
3311 if (mg != null)
3312 return mg;
3314 if (ns == null)
3315 return null;
3317 // Search continues
3318 ExtensionMethodGroupExpr e = ns.LookupExtensionMethod (type, Name, loc);
3319 if (e == null)
3320 return base.OverloadResolve (ec, ref arguments, false, loc);
3322 e.ExtensionExpression = ExtensionExpression;
3323 e.SetTypeArguments (ec, type_arguments);
3324 return e.ResolveOverloadExtensions (ec, ref arguments, e.namespace_entry, loc);
3328 /// <summary>
3329 /// MethodGroupExpr represents a group of method candidates which
3330 /// can be resolved to the best method overload
3331 /// </summary>
3332 public class MethodGroupExpr : MemberExpr
3334 public interface IErrorHandler
3336 bool AmbiguousCall (ResolveContext ec, MethodBase ambiguous);
3337 bool NoExactMatch (ResolveContext ec, MethodBase method);
3340 public IErrorHandler CustomErrorHandler;
3341 public MethodBase [] Methods;
3342 MethodBase best_candidate;
3343 // TODO: make private
3344 public TypeArguments type_arguments;
3345 bool identical_type_name;
3346 bool has_inaccessible_candidates_only;
3347 Type delegate_type;
3348 Type queried_type;
3350 public MethodGroupExpr (MemberInfo [] mi, Type type, Location l)
3351 : this (type, l)
3353 Methods = new MethodBase [mi.Length];
3354 mi.CopyTo (Methods, 0);
3357 public MethodGroupExpr (MemberInfo[] mi, Type type, Location l, bool inacessibleCandidatesOnly)
3358 : this (mi, type, l)
3360 has_inaccessible_candidates_only = inacessibleCandidatesOnly;
3363 public MethodGroupExpr (ArrayList list, Type type, Location l)
3364 : this (type, l)
3366 try {
3367 Methods = (MethodBase[])list.ToArray (typeof (MethodBase));
3368 } catch {
3369 foreach (MemberInfo m in list){
3370 if (!(m is MethodBase)){
3371 Console.WriteLine ("Name " + m.Name);
3372 Console.WriteLine ("Found a: " + m.GetType ().FullName);
3375 throw;
3381 protected MethodGroupExpr (Type type, Location loc)
3383 this.loc = loc;
3384 eclass = ExprClass.MethodGroup;
3385 this.type = InternalType.MethodGroup;
3386 queried_type = type;
3389 public override Type DeclaringType {
3390 get {
3391 return queried_type;
3395 public Type DelegateType {
3396 set {
3397 delegate_type = value;
3401 public bool IdenticalTypeName {
3402 get {
3403 return identical_type_name;
3407 public override string GetSignatureForError ()
3409 if (best_candidate != null)
3410 return TypeManager.CSharpSignature (best_candidate);
3412 return TypeManager.CSharpSignature (Methods [0]);
3415 public override string Name {
3416 get {
3417 return Methods [0].Name;
3421 public override bool IsInstance {
3422 get {
3423 if (best_candidate != null)
3424 return !best_candidate.IsStatic;
3426 foreach (MethodBase mb in Methods)
3427 if (!mb.IsStatic)
3428 return true;
3430 return false;
3434 public override bool IsStatic {
3435 get {
3436 if (best_candidate != null)
3437 return best_candidate.IsStatic;
3439 foreach (MethodBase mb in Methods)
3440 if (mb.IsStatic)
3441 return true;
3443 return false;
3447 public static explicit operator ConstructorInfo (MethodGroupExpr mg)
3449 return (ConstructorInfo)mg.best_candidate;
3452 public static explicit operator MethodInfo (MethodGroupExpr mg)
3454 return (MethodInfo)mg.best_candidate;
3458 // 7.4.3.3 Better conversion from expression
3459 // Returns : 1 if a->p is better,
3460 // 2 if a->q is better,
3461 // 0 if neither is better
3463 static int BetterExpressionConversion (ResolveContext ec, Argument a, Type p, Type q)
3465 Type argument_type = TypeManager.TypeToCoreType (a.Type);
3466 if (argument_type == InternalType.AnonymousMethod && RootContext.Version > LanguageVersion.ISO_2) {
3468 // Uwrap delegate from Expression<T>
3470 if (TypeManager.DropGenericTypeArguments (p) == TypeManager.expression_type) {
3471 p = TypeManager.GetTypeArguments (p) [0];
3473 if (TypeManager.DropGenericTypeArguments (q) == TypeManager.expression_type) {
3474 q = TypeManager.GetTypeArguments (q) [0];
3477 p = Delegate.GetInvokeMethod (ec.Compiler, null, p).ReturnType;
3478 q = Delegate.GetInvokeMethod (ec.Compiler, null, q).ReturnType;
3479 if (p == TypeManager.void_type && q != TypeManager.void_type)
3480 return 2;
3481 if (q == TypeManager.void_type && p != TypeManager.void_type)
3482 return 1;
3483 } else {
3484 if (argument_type == p)
3485 return 1;
3487 if (argument_type == q)
3488 return 2;
3491 return BetterTypeConversion (ec, p, q);
3495 // 7.4.3.4 Better conversion from type
3497 public static int BetterTypeConversion (ResolveContext ec, Type p, Type q)
3499 if (p == null || q == null)
3500 throw new InternalErrorException ("BetterTypeConversion got a null conversion");
3502 if (p == TypeManager.int32_type) {
3503 if (q == TypeManager.uint32_type || q == TypeManager.uint64_type)
3504 return 1;
3505 } else if (p == TypeManager.int64_type) {
3506 if (q == TypeManager.uint64_type)
3507 return 1;
3508 } else if (p == TypeManager.sbyte_type) {
3509 if (q == TypeManager.byte_type || q == TypeManager.ushort_type ||
3510 q == TypeManager.uint32_type || q == TypeManager.uint64_type)
3511 return 1;
3512 } else if (p == TypeManager.short_type) {
3513 if (q == TypeManager.ushort_type || q == TypeManager.uint32_type ||
3514 q == TypeManager.uint64_type)
3515 return 1;
3516 } else if (p == InternalType.Dynamic) {
3517 if (q == TypeManager.object_type)
3518 return 2;
3521 if (q == TypeManager.int32_type) {
3522 if (p == TypeManager.uint32_type || p == TypeManager.uint64_type)
3523 return 2;
3524 } if (q == TypeManager.int64_type) {
3525 if (p == TypeManager.uint64_type)
3526 return 2;
3527 } else if (q == TypeManager.sbyte_type) {
3528 if (p == TypeManager.byte_type || p == TypeManager.ushort_type ||
3529 p == TypeManager.uint32_type || p == TypeManager.uint64_type)
3530 return 2;
3531 } if (q == TypeManager.short_type) {
3532 if (p == TypeManager.ushort_type || p == TypeManager.uint32_type ||
3533 p == TypeManager.uint64_type)
3534 return 2;
3535 } else if (q == InternalType.Dynamic) {
3536 if (p == TypeManager.object_type)
3537 return 1;
3540 // TODO: this is expensive
3541 Expression p_tmp = new EmptyExpression (p);
3542 Expression q_tmp = new EmptyExpression (q);
3544 bool p_to_q = Convert.ImplicitConversionExists (ec, p_tmp, q);
3545 bool q_to_p = Convert.ImplicitConversionExists (ec, q_tmp, p);
3547 if (p_to_q && !q_to_p)
3548 return 1;
3550 if (q_to_p && !p_to_q)
3551 return 2;
3553 return 0;
3556 /// <summary>
3557 /// Determines "Better function" between candidate
3558 /// and the current best match
3559 /// </summary>
3560 /// <remarks>
3561 /// Returns a boolean indicating :
3562 /// false if candidate ain't better
3563 /// true if candidate is better than the current best match
3564 /// </remarks>
3565 static bool BetterFunction (ResolveContext ec, Arguments args, int argument_count,
3566 MethodBase candidate, bool candidate_params,
3567 MethodBase best, bool best_params)
3569 AParametersCollection candidate_pd = TypeManager.GetParameterData (candidate);
3570 AParametersCollection best_pd = TypeManager.GetParameterData (best);
3572 bool better_at_least_one = false;
3573 bool same = true;
3574 for (int j = 0, c_idx = 0, b_idx = 0; j < argument_count; ++j, ++c_idx, ++b_idx)
3576 Argument a = args [j];
3578 // Provided default argument value is never better
3579 if (a.IsDefaultArgument && candidate_params == best_params)
3580 return false;
3582 Type ct = candidate_pd.Types [c_idx];
3583 Type bt = best_pd.Types [b_idx];
3585 if (candidate_params && candidate_pd.FixedParameters [c_idx].ModFlags == Parameter.Modifier.PARAMS)
3587 ct = TypeManager.GetElementType (ct);
3588 --c_idx;
3591 if (best_params && best_pd.FixedParameters [b_idx].ModFlags == Parameter.Modifier.PARAMS)
3593 bt = TypeManager.GetElementType (bt);
3594 --b_idx;
3597 if (ct == bt)
3598 continue;
3600 same = false;
3601 int result = BetterExpressionConversion (ec, a, ct, bt);
3603 // for each argument, the conversion to 'ct' should be no worse than
3604 // the conversion to 'bt'.
3605 if (result == 2)
3606 return false;
3608 // for at least one argument, the conversion to 'ct' should be better than
3609 // the conversion to 'bt'.
3610 if (result != 0)
3611 better_at_least_one = true;
3614 if (better_at_least_one)
3615 return true;
3618 // This handles the case
3620 // Add (float f1, float f2, float f3);
3621 // Add (params decimal [] foo);
3623 // The call Add (3, 4, 5) should be ambiguous. Without this check, the
3624 // first candidate would've chosen as better.
3626 if (!same)
3627 return false;
3630 // The two methods have equal parameter types. Now apply tie-breaking rules
3632 if (TypeManager.IsGenericMethod (best)) {
3633 if (!TypeManager.IsGenericMethod (candidate))
3634 return true;
3635 } else if (TypeManager.IsGenericMethod (candidate)) {
3636 return false;
3640 // This handles the following cases:
3642 // Trim () is better than Trim (params char[] chars)
3643 // Concat (string s1, string s2, string s3) is better than
3644 // Concat (string s1, params string [] srest)
3645 // Foo (int, params int [] rest) is better than Foo (params int [] rest)
3647 if (!candidate_params && best_params)
3648 return true;
3649 if (candidate_params && !best_params)
3650 return false;
3652 int candidate_param_count = candidate_pd.Count;
3653 int best_param_count = best_pd.Count;
3655 if (candidate_param_count != best_param_count)
3656 // can only happen if (candidate_params && best_params)
3657 return candidate_param_count > best_param_count && best_pd.HasParams;
3660 // now, both methods have the same number of parameters, and the parameters have the same types
3661 // Pick the "more specific" signature
3664 MethodBase orig_candidate = TypeManager.DropGenericMethodArguments (candidate);
3665 MethodBase orig_best = TypeManager.DropGenericMethodArguments (best);
3667 AParametersCollection orig_candidate_pd = TypeManager.GetParameterData (orig_candidate);
3668 AParametersCollection orig_best_pd = TypeManager.GetParameterData (orig_best);
3670 bool specific_at_least_once = false;
3671 for (int j = 0; j < candidate_param_count; ++j)
3673 Type ct = orig_candidate_pd.Types [j];
3674 Type bt = orig_best_pd.Types [j];
3675 if (ct.Equals (bt))
3676 continue;
3677 Type specific = MoreSpecific (ct, bt);
3678 if (specific == bt)
3679 return false;
3680 if (specific == ct)
3681 specific_at_least_once = true;
3684 if (specific_at_least_once)
3685 return true;
3687 // FIXME: handle lifted operators
3688 // ...
3690 return false;
3693 protected override MemberExpr ResolveExtensionMemberAccess (ResolveContext ec, Expression left)
3695 if (!IsStatic)
3696 return base.ResolveExtensionMemberAccess (ec, left);
3699 // When left side is an expression and at least one candidate method is
3700 // static, it can be extension method
3702 InstanceExpression = left;
3703 return this;
3706 public override MemberExpr ResolveMemberAccess (ResolveContext ec, Expression left, Location loc,
3707 SimpleName original)
3709 if (!(left is TypeExpr) &&
3710 original != null && original.IdenticalNameAndTypeName (ec, left, loc))
3711 identical_type_name = true;
3713 return base.ResolveMemberAccess (ec, left, loc, original);
3716 public override Expression CreateExpressionTree (ResolveContext ec)
3718 if (best_candidate == null) {
3719 ec.Report.Error (1953, loc, "An expression tree cannot contain an expression with method group");
3720 return null;
3723 IMethodData md = TypeManager.GetMethod (best_candidate);
3724 if (md != null && md.IsExcluded ())
3725 ec.Report.Error (765, loc,
3726 "Partial methods with only a defining declaration or removed conditional methods cannot be used in an expression tree");
3728 return new TypeOfMethod (best_candidate, loc);
3731 protected override Expression DoResolve (ResolveContext ec)
3733 this.eclass = ExprClass.MethodGroup;
3735 if (InstanceExpression != null) {
3736 InstanceExpression = InstanceExpression.Resolve (ec);
3737 if (InstanceExpression == null)
3738 return null;
3741 return this;
3744 public void ReportUsageError (ResolveContext ec)
3746 ec.Report.Error (654, loc, "Method `" + DeclaringType + "." +
3747 Name + "()' is referenced without parentheses");
3750 override public void Emit (EmitContext ec)
3752 throw new NotSupportedException ();
3753 // ReportUsageError ();
3756 public void EmitCall (EmitContext ec, Arguments arguments)
3758 Invocation.EmitCall (ec, IsBase, InstanceExpression, best_candidate, arguments, loc);
3761 void Error_AmbiguousCall (ResolveContext ec, MethodBase ambiguous)
3763 if (CustomErrorHandler != null && CustomErrorHandler.AmbiguousCall (ec, ambiguous))
3764 return;
3766 ec.Report.SymbolRelatedToPreviousError (best_candidate);
3767 ec.Report.Error (121, loc, "The call is ambiguous between the following methods or properties: `{0}' and `{1}'",
3768 TypeManager.CSharpSignature (ambiguous), TypeManager.CSharpSignature (best_candidate));
3771 protected virtual void Error_InvalidArguments (ResolveContext ec, Location loc, int idx, MethodBase method,
3772 Argument a, AParametersCollection expected_par, Type paramType)
3774 ExtensionMethodGroupExpr emg = this as ExtensionMethodGroupExpr;
3776 if (a is CollectionElementInitializer.ElementInitializerArgument) {
3777 ec.Report.SymbolRelatedToPreviousError (method);
3778 if ((expected_par.FixedParameters [idx].ModFlags & Parameter.Modifier.ISBYREF) != 0) {
3779 ec.Report.Error (1954, loc, "The best overloaded collection initalizer method `{0}' cannot have 'ref', or `out' modifier",
3780 TypeManager.CSharpSignature (method));
3781 return;
3783 ec.Report.Error (1950, loc, "The best overloaded collection initalizer method `{0}' has some invalid arguments",
3784 TypeManager.CSharpSignature (method));
3785 } else if (TypeManager.IsDelegateType (method.DeclaringType)) {
3786 ec.Report.Error (1594, loc, "Delegate `{0}' has some invalid arguments",
3787 TypeManager.CSharpName (method.DeclaringType));
3788 } else {
3789 ec.Report.SymbolRelatedToPreviousError (method);
3790 if (emg != null) {
3791 ec.Report.Error (1928, loc,
3792 "Type `{0}' does not contain a member `{1}' and the best extension method overload `{2}' has some invalid arguments",
3793 emg.ExtensionExpression.GetSignatureForError (),
3794 emg.Name, TypeManager.CSharpSignature (method));
3795 } else {
3796 ec.Report.Error (1502, loc, "The best overloaded method match for `{0}' has some invalid arguments",
3797 TypeManager.CSharpSignature (method));
3801 Parameter.Modifier mod = idx >= expected_par.Count ? 0 : expected_par.FixedParameters [idx].ModFlags;
3803 string index = (idx + 1).ToString ();
3804 if (((mod & (Parameter.Modifier.REF | Parameter.Modifier.OUT)) ^
3805 (a.Modifier & (Parameter.Modifier.REF | Parameter.Modifier.OUT))) != 0) {
3806 if ((mod & Parameter.Modifier.ISBYREF) == 0)
3807 ec.Report.Error (1615, loc, "Argument `#{0}' does not require `{1}' modifier. Consider removing `{1}' modifier",
3808 index, Parameter.GetModifierSignature (a.Modifier));
3809 else
3810 ec.Report.Error (1620, loc, "Argument `#{0}' is missing `{1}' modifier",
3811 index, Parameter.GetModifierSignature (mod));
3812 } else {
3813 string p1 = a.GetSignatureForError ();
3814 string p2 = TypeManager.CSharpName (paramType);
3816 if (p1 == p2) {
3817 ec.Report.ExtraInformation (loc, "(equally named types possibly from different assemblies in previous ");
3818 ec.Report.SymbolRelatedToPreviousError (a.Expr.Type);
3819 ec.Report.SymbolRelatedToPreviousError (paramType);
3822 if (idx == 0 && emg != null) {
3823 ec.Report.Error (1929, loc,
3824 "Extension method instance type `{0}' cannot be converted to `{1}'", p1, p2);
3825 } else {
3826 ec.Report.Error (1503, loc,
3827 "Argument `#{0}' cannot convert `{1}' expression to type `{2}'", index, p1, p2);
3832 public override void Error_ValueCannotBeConverted (ResolveContext ec, Location loc, Type target, bool expl)
3834 ec.Report.Error (428, loc, "Cannot convert method group `{0}' to non-delegate type `{1}'. Consider using parentheses to invoke the method",
3835 Name, TypeManager.CSharpName (target));
3838 void Error_ArgumentCountWrong (ResolveContext ec, int arg_count)
3840 ec.Report.Error (1501, loc, "No overload for method `{0}' takes `{1}' arguments",
3841 Name, arg_count.ToString ());
3844 protected virtual int GetApplicableParametersCount (MethodBase method, AParametersCollection parameters)
3846 return parameters.Count;
3849 public static bool IsAncestralType (Type first_type, Type second_type)
3851 return first_type != second_type &&
3852 (TypeManager.IsSubclassOf (second_type, first_type) ||
3853 TypeManager.ImplementsInterface (second_type, first_type));
3857 /// Determines if the candidate method is applicable (section 14.4.2.1)
3858 /// to the given set of arguments
3859 /// A return value rates candidate method compatibility,
3860 /// 0 = the best, int.MaxValue = the worst
3862 public int IsApplicable (ResolveContext ec,
3863 ref Arguments arguments, int arg_count, ref MethodBase method, ref bool params_expanded_form)
3865 MethodBase candidate = method;
3867 AParametersCollection pd = TypeManager.GetParameterData (candidate);
3868 int param_count = GetApplicableParametersCount (candidate, pd);
3869 int optional_count = 0;
3871 if (arg_count != param_count) {
3872 for (int i = 0; i < pd.Count; ++i) {
3873 if (pd.FixedParameters [i].HasDefaultValue) {
3874 optional_count = pd.Count - i;
3875 break;
3879 int args_gap = Math.Abs (arg_count - param_count);
3880 if (optional_count != 0) {
3881 if (args_gap > optional_count)
3882 return int.MaxValue - 10000 + args_gap - optional_count;
3884 // Readjust expected number when params used
3885 if (pd.HasParams) {
3886 optional_count--;
3887 if (arg_count < param_count)
3888 param_count--;
3889 } else if (arg_count > param_count) {
3890 return int.MaxValue - 10000 + args_gap;
3892 } else if (arg_count != param_count) {
3893 if (!pd.HasParams)
3894 return int.MaxValue - 10000 + args_gap;
3895 if (arg_count < param_count - 1)
3896 return int.MaxValue - 10000 + args_gap;
3899 // Initialize expanded form of a method with 1 params parameter
3900 params_expanded_form = param_count == 1 && pd.HasParams;
3902 // Resize to fit optional arguments
3903 if (optional_count != 0) {
3904 Arguments resized;
3905 if (arguments == null) {
3906 resized = new Arguments (optional_count);
3907 } else {
3908 resized = new Arguments (param_count);
3909 resized.AddRange (arguments);
3912 for (int i = arg_count; i < param_count; ++i)
3913 resized.Add (null);
3914 arguments = resized;
3918 if (arg_count > 0) {
3920 // Shuffle named arguments to the right positions if there are any
3922 if (arguments [arg_count - 1] is NamedArgument) {
3923 arg_count = arguments.Count;
3925 for (int i = 0; i < arg_count; ++i) {
3926 bool arg_moved = false;
3927 while (true) {
3928 NamedArgument na = arguments[i] as NamedArgument;
3929 if (na == null)
3930 break;
3932 int index = pd.GetParameterIndexByName (na.Name.Value);
3934 // Named parameter not found or already reordered
3935 if (index <= i)
3936 break;
3938 // When using parameters which should not be available to the user
3939 if (index >= param_count)
3940 break;
3942 if (!arg_moved) {
3943 arguments.MarkReorderedArgument (na);
3944 arg_moved = true;
3947 Argument temp = arguments[index];
3948 arguments[index] = arguments[i];
3949 arguments[i] = temp;
3951 if (temp == null)
3952 break;
3955 } else {
3956 arg_count = arguments.Count;
3958 } else if (arguments != null) {
3959 arg_count = arguments.Count;
3963 // 1. Handle generic method using type arguments when specified or type inference
3965 if (TypeManager.IsGenericMethod (candidate)) {
3966 if (type_arguments != null) {
3967 Type [] g_args = candidate.GetGenericArguments ();
3968 if (g_args.Length != type_arguments.Count)
3969 return int.MaxValue - 20000 + Math.Abs (type_arguments.Count - g_args.Length);
3971 // TODO: Don't create new method, create Parameters only
3972 method = ((MethodInfo) candidate).MakeGenericMethod (type_arguments.Arguments);
3973 candidate = method;
3974 pd = TypeManager.GetParameterData (candidate);
3975 } else {
3976 int score = TypeManager.InferTypeArguments (ec, arguments, ref candidate);
3977 if (score != 0)
3978 return score - 20000;
3980 if (TypeManager.IsGenericMethodDefinition (candidate))
3981 throw new InternalErrorException ("A generic method `{0}' definition took part in overload resolution",
3982 TypeManager.CSharpSignature (candidate));
3984 pd = TypeManager.GetParameterData (candidate);
3986 } else {
3987 if (type_arguments != null)
3988 return int.MaxValue - 15000;
3992 // 2. Each argument has to be implicitly convertible to method parameter
3994 method = candidate;
3995 Parameter.Modifier p_mod = 0;
3996 Type pt = null;
3997 for (int i = 0; i < arg_count; i++) {
3998 Argument a = arguments [i];
3999 if (a == null) {
4000 if (!pd.FixedParameters [i].HasDefaultValue)
4001 throw new InternalErrorException ();
4003 Expression e = pd.FixedParameters [i].DefaultValue as Constant;
4004 if (e == null)
4005 e = new DefaultValueExpression (new TypeExpression (pd.Types [i], loc), loc).Resolve (ec);
4007 arguments [i] = new Argument (e, Argument.AType.Default);
4008 continue;
4011 if (p_mod != Parameter.Modifier.PARAMS) {
4012 p_mod = pd.FixedParameters [i].ModFlags & ~(Parameter.Modifier.OUTMASK | Parameter.Modifier.REFMASK);
4013 pt = pd.Types [i];
4014 } else {
4015 params_expanded_form = true;
4018 Parameter.Modifier a_mod = a.Modifier & ~(Parameter.Modifier.OUTMASK | Parameter.Modifier.REFMASK);
4019 int score = 1;
4020 if (!params_expanded_form)
4021 score = IsArgumentCompatible (ec, a_mod, a, p_mod & ~Parameter.Modifier.PARAMS, pt);
4023 if (score != 0 && (p_mod & Parameter.Modifier.PARAMS) != 0 && delegate_type == null) {
4024 // It can be applicable in expanded form
4025 score = IsArgumentCompatible (ec, a_mod, a, 0, TypeManager.GetElementType (pt));
4026 if (score == 0)
4027 params_expanded_form = true;
4030 if (score != 0) {
4031 if (params_expanded_form)
4032 ++score;
4033 return (arg_count - i) * 2 + score;
4037 if (arg_count != param_count)
4038 params_expanded_form = true;
4040 return 0;
4043 int IsArgumentCompatible (ResolveContext ec, Parameter.Modifier arg_mod, Argument argument, Parameter.Modifier param_mod, Type parameter)
4046 // Types have to be identical when ref or out modifer is used
4048 if (arg_mod != 0 || param_mod != 0) {
4049 if (TypeManager.HasElementType (parameter))
4050 parameter = TypeManager.GetElementType (parameter);
4052 Type a_type = argument.Type;
4053 if (TypeManager.HasElementType (a_type))
4054 a_type = TypeManager.GetElementType (a_type);
4056 if (a_type != parameter) {
4057 if (TypeManager.IsDynamicType (a_type))
4058 return 0;
4060 return 2;
4062 } else {
4063 if (!Convert.ImplicitConversionExists (ec, argument.Expr, parameter)) {
4064 if (TypeManager.IsDynamicType (argument.Type))
4065 return 0;
4067 return 2;
4071 if (arg_mod != param_mod)
4072 return 1;
4074 return 0;
4077 public static bool IsOverride (MethodBase cand_method, MethodBase base_method)
4079 if (!IsAncestralType (base_method.DeclaringType, cand_method.DeclaringType))
4080 return false;
4082 AParametersCollection cand_pd = TypeManager.GetParameterData (cand_method);
4083 AParametersCollection base_pd = TypeManager.GetParameterData (base_method);
4085 if (cand_pd.Count != base_pd.Count)
4086 return false;
4088 for (int j = 0; j < cand_pd.Count; ++j)
4090 Parameter.Modifier cm = cand_pd.FixedParameters [j].ModFlags;
4091 Parameter.Modifier bm = base_pd.FixedParameters [j].ModFlags;
4092 Type ct = cand_pd.Types [j];
4093 Type bt = base_pd.Types [j];
4095 if (cm != bm || ct != bt)
4096 return false;
4099 return true;
4102 public static MethodGroupExpr MakeUnionSet (MethodGroupExpr mg1, MethodGroupExpr mg2, Location loc)
4104 if (mg1 == null) {
4105 if (mg2 == null)
4106 return null;
4107 return mg2;
4110 if (mg2 == null)
4111 return mg1;
4113 ArrayList all = new ArrayList (mg1.Methods);
4114 foreach (MethodBase m in mg2.Methods){
4115 if (!TypeManager.ArrayContainsMethod (mg1.Methods, m, false))
4116 all.Add (m);
4119 return new MethodGroupExpr (all, null, loc);
4122 static Type MoreSpecific (Type p, Type q)
4124 if (TypeManager.IsGenericParameter (p) && !TypeManager.IsGenericParameter (q))
4125 return q;
4126 if (!TypeManager.IsGenericParameter (p) && TypeManager.IsGenericParameter (q))
4127 return p;
4129 if (TypeManager.HasElementType (p))
4131 Type pe = TypeManager.GetElementType (p);
4132 Type qe = TypeManager.GetElementType (q);
4133 Type specific = MoreSpecific (pe, qe);
4134 if (specific == pe)
4135 return p;
4136 if (specific == qe)
4137 return q;
4139 else if (TypeManager.IsGenericType (p))
4141 Type[] pargs = TypeManager.GetTypeArguments (p);
4142 Type[] qargs = TypeManager.GetTypeArguments (q);
4144 bool p_specific_at_least_once = false;
4145 bool q_specific_at_least_once = false;
4147 for (int i = 0; i < pargs.Length; i++)
4149 Type specific = MoreSpecific (TypeManager.TypeToCoreType (pargs [i]), TypeManager.TypeToCoreType (qargs [i]));
4150 if (specific == pargs [i])
4151 p_specific_at_least_once = true;
4152 if (specific == qargs [i])
4153 q_specific_at_least_once = true;
4156 if (p_specific_at_least_once && !q_specific_at_least_once)
4157 return p;
4158 if (!p_specific_at_least_once && q_specific_at_least_once)
4159 return q;
4162 return null;
4165 public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
4167 base.MutateHoistedGenericType (storey);
4169 MethodInfo mi = best_candidate as MethodInfo;
4170 if (mi != null) {
4171 best_candidate = storey.MutateGenericMethod (mi);
4172 return;
4175 best_candidate = storey.MutateConstructor ((ConstructorInfo) this);
4178 /// <summary>
4179 /// Find the Applicable Function Members (7.4.2.1)
4181 /// me: Method Group expression with the members to select.
4182 /// it might contain constructors or methods (or anything
4183 /// that maps to a method).
4185 /// Arguments: ArrayList containing resolved Argument objects.
4187 /// loc: The location if we want an error to be reported, or a Null
4188 /// location for "probing" purposes.
4190 /// Returns: The MethodBase (either a ConstructorInfo or a MethodInfo)
4191 /// that is the best match of me on Arguments.
4193 /// </summary>
4194 public virtual MethodGroupExpr OverloadResolve (ResolveContext ec, ref Arguments Arguments,
4195 bool may_fail, Location loc)
4197 bool method_params = false;
4198 Type applicable_type = null;
4199 ArrayList candidates = new ArrayList (2);
4200 ArrayList candidate_overrides = null;
4203 // Used to keep a map between the candidate
4204 // and whether it is being considered in its
4205 // normal or expanded form
4207 // false is normal form, true is expanded form
4209 Hashtable candidate_to_form = null;
4210 Hashtable candidates_expanded = null;
4211 Arguments candidate_args = Arguments;
4213 int arg_count = Arguments != null ? Arguments.Count : 0;
4215 if (RootContext.Version == LanguageVersion.ISO_1 && Name == "Invoke" && TypeManager.IsDelegateType (DeclaringType)) {
4216 if (!may_fail)
4217 ec.Report.Error (1533, loc, "Invoke cannot be called directly on a delegate");
4218 return null;
4221 int nmethods = Methods.Length;
4223 if (!IsBase) {
4225 // Methods marked 'override' don't take part in 'applicable_type'
4226 // computation, nor in the actual overload resolution.
4227 // However, they still need to be emitted instead of a base virtual method.
4228 // So, we salt them away into the 'candidate_overrides' array.
4230 // In case of reflected methods, we replace each overriding method with
4231 // its corresponding base virtual method. This is to improve compatibility
4232 // with non-C# libraries which change the visibility of overrides (#75636)
4234 int j = 0;
4235 for (int i = 0; i < Methods.Length; ++i) {
4236 MethodBase m = Methods [i];
4237 if (TypeManager.IsOverride (m)) {
4238 if (candidate_overrides == null)
4239 candidate_overrides = new ArrayList ();
4240 candidate_overrides.Add (m);
4241 m = TypeManager.TryGetBaseDefinition (m);
4243 if (m != null)
4244 Methods [j++] = m;
4246 nmethods = j;
4250 // Enable message recording, it's used mainly by lambda expressions
4252 SessionReportPrinter msg_recorder = new SessionReportPrinter ();
4253 ReportPrinter prev_recorder = ec.Report.SetPrinter (msg_recorder);
4256 // First we construct the set of applicable methods
4258 bool is_sorted = true;
4259 int best_candidate_rate = int.MaxValue;
4260 for (int i = 0; i < nmethods; i++) {
4261 Type decl_type = Methods [i].DeclaringType;
4264 // If we have already found an applicable method
4265 // we eliminate all base types (Section 14.5.5.1)
4267 if (applicable_type != null && IsAncestralType (decl_type, applicable_type))
4268 continue;
4271 // Check if candidate is applicable (section 14.4.2.1)
4273 bool params_expanded_form = false;
4274 int candidate_rate = IsApplicable (ec, ref candidate_args, arg_count, ref Methods [i], ref params_expanded_form);
4276 if (candidate_rate < best_candidate_rate) {
4277 best_candidate_rate = candidate_rate;
4278 best_candidate = Methods [i];
4281 if (params_expanded_form) {
4282 if (candidate_to_form == null)
4283 candidate_to_form = new PtrHashtable ();
4284 MethodBase candidate = Methods [i];
4285 candidate_to_form [candidate] = candidate;
4288 if (candidate_args != Arguments) {
4289 if (candidates_expanded == null)
4290 candidates_expanded = new Hashtable (2);
4292 candidates_expanded.Add (Methods [i], candidate_args);
4293 candidate_args = Arguments;
4296 if (candidate_rate != 0 || has_inaccessible_candidates_only) {
4297 if (msg_recorder != null)
4298 msg_recorder.EndSession ();
4299 continue;
4302 msg_recorder = null;
4303 candidates.Add (Methods [i]);
4305 if (applicable_type == null)
4306 applicable_type = decl_type;
4307 else if (applicable_type != decl_type) {
4308 is_sorted = false;
4309 if (IsAncestralType (applicable_type, decl_type))
4310 applicable_type = decl_type;
4314 ec.Report.SetPrinter (prev_recorder);
4315 if (msg_recorder != null && !msg_recorder.IsEmpty) {
4316 if (!may_fail)
4317 msg_recorder.Merge (prev_recorder);
4319 return null;
4322 int candidate_top = candidates.Count;
4324 if (applicable_type == null) {
4326 // When we found a top level method which does not match and it's
4327 // not an extension method. We start extension methods lookup from here
4329 if (InstanceExpression != null) {
4330 ExtensionMethodGroupExpr ex_method_lookup = ec.LookupExtensionMethod (type, Name, loc);
4331 if (ex_method_lookup != null) {
4332 ex_method_lookup.ExtensionExpression = InstanceExpression;
4333 ex_method_lookup.SetTypeArguments (ec, type_arguments);
4334 return ex_method_lookup.OverloadResolve (ec, ref Arguments, may_fail, loc);
4338 if (may_fail)
4339 return null;
4342 // Okay so we have failed to find exact match so we
4343 // return error info about the closest match
4345 if (best_candidate != null) {
4346 if (CustomErrorHandler != null && !has_inaccessible_candidates_only && CustomErrorHandler.NoExactMatch (ec, best_candidate))
4347 return null;
4349 if (NoExactMatch (ec, ref Arguments, candidate_to_form))
4350 return null;
4354 // We failed to find any method with correct argument count
4356 if (Name == ConstructorInfo.ConstructorName) {
4357 ec.Report.SymbolRelatedToPreviousError (queried_type);
4358 ec.Report.Error (1729, loc,
4359 "The type `{0}' does not contain a constructor that takes `{1}' arguments",
4360 TypeManager.CSharpName (queried_type), arg_count);
4361 } else {
4362 Error_ArgumentCountWrong (ec, arg_count);
4365 return null;
4368 if (arg_count != 0 && Arguments.HasDynamic) {
4369 best_candidate = null;
4370 return this;
4373 if (!is_sorted) {
4375 // At this point, applicable_type is _one_ of the most derived types
4376 // in the set of types containing the methods in this MethodGroup.
4377 // Filter the candidates so that they only contain methods from the
4378 // most derived types.
4381 int finalized = 0; // Number of finalized candidates
4383 do {
4384 // Invariant: applicable_type is a most derived type
4386 // We'll try to complete Section 14.5.5.1 for 'applicable_type' by
4387 // eliminating all it's base types. At the same time, we'll also move
4388 // every unrelated type to the end of the array, and pick the next
4389 // 'applicable_type'.
4391 Type next_applicable_type = null;
4392 int j = finalized; // where to put the next finalized candidate
4393 int k = finalized; // where to put the next undiscarded candidate
4394 for (int i = finalized; i < candidate_top; ++i) {
4395 MethodBase candidate = (MethodBase) candidates [i];
4396 Type decl_type = candidate.DeclaringType;
4398 if (decl_type == applicable_type) {
4399 candidates [k++] = candidates [j];
4400 candidates [j++] = candidates [i];
4401 continue;
4404 if (IsAncestralType (decl_type, applicable_type))
4405 continue;
4407 if (next_applicable_type != null &&
4408 IsAncestralType (decl_type, next_applicable_type))
4409 continue;
4411 candidates [k++] = candidates [i];
4413 if (next_applicable_type == null ||
4414 IsAncestralType (next_applicable_type, decl_type))
4415 next_applicable_type = decl_type;
4418 applicable_type = next_applicable_type;
4419 finalized = j;
4420 candidate_top = k;
4421 } while (applicable_type != null);
4425 // Now we actually find the best method
4428 best_candidate = (MethodBase) candidates [0];
4429 method_params = candidate_to_form != null && candidate_to_form.Contains (best_candidate);
4432 // TODO: Broken inverse order of candidates logic does not work with optional
4433 // parameters used for method overrides and I am not going to fix it for SRE
4435 if (candidates_expanded != null && candidates_expanded.Contains (best_candidate)) {
4436 candidate_args = (Arguments) candidates_expanded [best_candidate];
4437 arg_count = candidate_args.Count;
4440 for (int ix = 1; ix < candidate_top; ix++) {
4441 MethodBase candidate = (MethodBase) candidates [ix];
4443 if (candidate == best_candidate)
4444 continue;
4446 bool cand_params = candidate_to_form != null && candidate_to_form.Contains (candidate);
4448 if (BetterFunction (ec, candidate_args, arg_count,
4449 candidate, cand_params,
4450 best_candidate, method_params)) {
4451 best_candidate = candidate;
4452 method_params = cand_params;
4456 // Now check that there are no ambiguities i.e the selected method
4457 // should be better than all the others
4459 MethodBase ambiguous = null;
4460 for (int ix = 1; ix < candidate_top; ix++) {
4461 MethodBase candidate = (MethodBase) candidates [ix];
4463 if (candidate == best_candidate)
4464 continue;
4466 bool cand_params = candidate_to_form != null && candidate_to_form.Contains (candidate);
4467 if (!BetterFunction (ec, candidate_args, arg_count,
4468 best_candidate, method_params,
4469 candidate, cand_params))
4471 if (!may_fail)
4472 ec.Report.SymbolRelatedToPreviousError (candidate);
4473 ambiguous = candidate;
4477 if (ambiguous != null) {
4478 Error_AmbiguousCall (ec, ambiguous);
4479 return this;
4483 // If the method is a virtual function, pick an override closer to the LHS type.
4485 if (!IsBase && best_candidate.IsVirtual) {
4486 if (TypeManager.IsOverride (best_candidate))
4487 throw new InternalErrorException (
4488 "Should not happen. An 'override' method took part in overload resolution: " + best_candidate);
4490 if (candidate_overrides != null) {
4491 Type[] gen_args = null;
4492 bool gen_override = false;
4493 if (TypeManager.IsGenericMethod (best_candidate))
4494 gen_args = TypeManager.GetGenericArguments (best_candidate);
4496 foreach (MethodBase candidate in candidate_overrides) {
4497 if (TypeManager.IsGenericMethod (candidate)) {
4498 if (gen_args == null)
4499 continue;
4501 if (gen_args.Length != TypeManager.GetGenericArguments (candidate).Length)
4502 continue;
4503 } else {
4504 if (gen_args != null)
4505 continue;
4508 if (IsOverride (candidate, best_candidate)) {
4509 gen_override = true;
4510 best_candidate = candidate;
4514 if (gen_override && gen_args != null) {
4515 best_candidate = ((MethodInfo) best_candidate).MakeGenericMethod (gen_args);
4521 // And now check if the arguments are all
4522 // compatible, perform conversions if
4523 // necessary etc. and return if everything is
4524 // all right
4526 if (!VerifyArgumentsCompat (ec, ref candidate_args, arg_count, best_candidate,
4527 method_params, may_fail, loc))
4528 return null;
4530 if (best_candidate == null)
4531 return null;
4533 MethodBase the_method = TypeManager.DropGenericMethodArguments (best_candidate);
4534 if (TypeManager.IsGenericMethodDefinition (the_method) &&
4535 !ConstraintChecker.CheckConstraints (ec, the_method, best_candidate, loc))
4536 return null;
4539 // Check ObsoleteAttribute on the best method
4541 ObsoleteAttribute oa = AttributeTester.GetMethodObsoleteAttribute (the_method);
4542 if (oa != null && !ec.IsObsolete)
4543 AttributeTester.Report_ObsoleteMessage (oa, GetSignatureForError (), loc, ec.Report);
4545 IMethodData data = TypeManager.GetMethod (the_method);
4546 if (data != null)
4547 data.SetMemberIsUsed ();
4549 Arguments = candidate_args;
4550 return this;
4553 bool NoExactMatch (ResolveContext ec, ref Arguments Arguments, Hashtable candidate_to_form)
4555 AParametersCollection pd = TypeManager.GetParameterData (best_candidate);
4556 int arg_count = Arguments == null ? 0 : Arguments.Count;
4558 if (arg_count == pd.Count || pd.HasParams) {
4559 if (TypeManager.IsGenericMethodDefinition (best_candidate)) {
4560 if (type_arguments == null) {
4561 ec.Report.Error (411, loc,
4562 "The type arguments for method `{0}' cannot be inferred from " +
4563 "the usage. Try specifying the type arguments explicitly",
4564 TypeManager.CSharpSignature (best_candidate));
4565 return true;
4568 Type[] g_args = TypeManager.GetGenericArguments (best_candidate);
4569 if (type_arguments.Count != g_args.Length) {
4570 ec.Report.SymbolRelatedToPreviousError (best_candidate);
4571 ec.Report.Error (305, loc, "Using the generic method `{0}' requires `{1}' type argument(s)",
4572 TypeManager.CSharpSignature (best_candidate),
4573 g_args.Length.ToString ());
4574 return true;
4576 } else {
4577 if (type_arguments != null && !TypeManager.IsGenericMethod (best_candidate)) {
4578 Error_TypeArgumentsCannotBeUsed (ec.Report, loc);
4579 return true;
4583 if (has_inaccessible_candidates_only) {
4584 if (InstanceExpression != null && type != ec.CurrentType && TypeManager.IsNestedFamilyAccessible (ec.CurrentType, best_candidate.DeclaringType)) {
4585 // Although a derived class can access protected members of
4586 // its base class it cannot do so through an instance of the
4587 // base class (CS1540). If the qualifier_type is a base of the
4588 // ec.CurrentType and the lookup succeeds with the latter one,
4589 // then we are in this situation.
4590 Error_CannotAccessProtected (ec, loc, best_candidate, queried_type, ec.CurrentType);
4591 } else {
4592 ec.Report.SymbolRelatedToPreviousError (best_candidate);
4593 ErrorIsInaccesible (loc, GetSignatureForError (), ec.Report);
4597 bool cand_params = candidate_to_form != null && candidate_to_form.Contains (best_candidate);
4598 if (!VerifyArgumentsCompat (ec, ref Arguments, arg_count, best_candidate, cand_params, false, loc))
4599 return true;
4601 if (has_inaccessible_candidates_only)
4602 return true;
4605 return false;
4608 public override void SetTypeArguments (ResolveContext ec, TypeArguments ta)
4610 type_arguments = ta;
4613 public bool VerifyArgumentsCompat (ResolveContext ec, ref Arguments arguments,
4614 int arg_count, MethodBase method,
4615 bool chose_params_expanded,
4616 bool may_fail, Location loc)
4618 AParametersCollection pd = TypeManager.GetParameterData (method);
4619 int param_count = GetApplicableParametersCount (method, pd);
4621 int errors = ec.Report.Errors;
4622 Parameter.Modifier p_mod = 0;
4623 Type pt = null;
4624 int a_idx = 0, a_pos = 0;
4625 Argument a = null;
4626 ArrayList params_initializers = null;
4627 bool has_unsafe_arg = method is MethodInfo ? ((MethodInfo) method).ReturnType.IsPointer : false;
4629 for (; a_idx < arg_count; a_idx++, ++a_pos) {
4630 a = arguments [a_idx];
4631 if (p_mod != Parameter.Modifier.PARAMS) {
4632 p_mod = pd.FixedParameters [a_idx].ModFlags;
4633 pt = pd.Types [a_idx];
4634 has_unsafe_arg |= pt.IsPointer;
4636 if (p_mod == Parameter.Modifier.PARAMS) {
4637 if (chose_params_expanded) {
4638 params_initializers = new ArrayList (arg_count - a_idx);
4639 pt = TypeManager.GetElementType (pt);
4645 // Types have to be identical when ref or out modifer is used
4647 if (a.Modifier != 0 || (p_mod & ~Parameter.Modifier.PARAMS) != 0) {
4648 if ((p_mod & ~Parameter.Modifier.PARAMS) != a.Modifier)
4649 break;
4651 if (!TypeManager.IsEqual (a.Expr.Type, pt))
4652 break;
4654 continue;
4655 } else {
4656 NamedArgument na = a as NamedArgument;
4657 if (na != null) {
4658 int name_index = pd.GetParameterIndexByName (na.Name.Value);
4659 if (name_index < 0 || name_index >= param_count) {
4660 if (DeclaringType != null && TypeManager.IsDelegateType (DeclaringType)) {
4661 ec.Report.SymbolRelatedToPreviousError (DeclaringType);
4662 ec.Report.Error (1746, na.Name.Location,
4663 "The delegate `{0}' does not contain a parameter named `{1}'",
4664 TypeManager.CSharpName (DeclaringType), na.Name.Value);
4665 } else {
4666 ec.Report.SymbolRelatedToPreviousError (best_candidate);
4667 ec.Report.Error (1739, na.Name.Location,
4668 "The best overloaded method match for `{0}' does not contain a parameter named `{1}'",
4669 TypeManager.CSharpSignature (method), na.Name.Value);
4671 } else if (arguments[name_index] != a) {
4672 if (DeclaringType != null && TypeManager.IsDelegateType (DeclaringType))
4673 ec.Report.SymbolRelatedToPreviousError (DeclaringType);
4674 else
4675 ec.Report.SymbolRelatedToPreviousError (best_candidate);
4677 ec.Report.Error (1744, na.Name.Location,
4678 "Named argument `{0}' cannot be used for a parameter which has positional argument specified",
4679 na.Name.Value);
4684 if (TypeManager.IsDynamicType (a.Expr.Type))
4685 continue;
4687 if (delegate_type != null && !Delegate.IsTypeCovariant (a.Expr, pt))
4688 break;
4690 Expression conv = Convert.ImplicitConversion (ec, a.Expr, pt, loc);
4691 if (conv == null)
4692 break;
4695 // Convert params arguments to an array initializer
4697 if (params_initializers != null) {
4698 // we choose to use 'a.Expr' rather than 'conv' so that
4699 // we don't hide the kind of expression we have (esp. CompoundAssign.Helper)
4700 params_initializers.Add (a.Expr);
4701 arguments.RemoveAt (a_idx--);
4702 --arg_count;
4703 continue;
4706 // Update the argument with the implicit conversion
4707 a.Expr = conv;
4710 if (a_idx != arg_count) {
4711 if (!may_fail && ec.Report.Errors == errors) {
4712 if (CustomErrorHandler != null)
4713 CustomErrorHandler.NoExactMatch (ec, best_candidate);
4714 else
4715 Error_InvalidArguments (ec, loc, a_pos, method, a, pd, pt);
4717 return false;
4721 // Fill not provided arguments required by params modifier
4723 if (params_initializers == null && pd.HasParams && arg_count + 1 == param_count) {
4724 if (arguments == null)
4725 arguments = new Arguments (1);
4727 pt = pd.Types [param_count - 1];
4728 pt = TypeManager.GetElementType (pt);
4729 has_unsafe_arg |= pt.IsPointer;
4730 params_initializers = new ArrayList (0);
4734 // Append an array argument with all params arguments
4736 if (params_initializers != null) {
4737 arguments.Add (new Argument (
4738 new ArrayCreation (new TypeExpression (pt, loc), "[]",
4739 params_initializers, loc).Resolve (ec)));
4740 arg_count++;
4743 if (arg_count < param_count) {
4744 if (!may_fail)
4745 Error_ArgumentCountWrong (ec, arg_count);
4746 return false;
4749 if (has_unsafe_arg && !ec.IsUnsafe) {
4750 if (!may_fail)
4751 UnsafeError (ec, loc);
4752 return false;
4755 return true;
4759 public class ConstantExpr : MemberExpr
4761 FieldInfo constant;
4763 public ConstantExpr (FieldInfo constant, Location loc)
4765 this.constant = constant;
4766 this.loc = loc;
4769 public override string Name {
4770 get { throw new NotImplementedException (); }
4773 public override bool IsInstance {
4774 get { return !IsStatic; }
4777 public override bool IsStatic {
4778 get { return constant.IsStatic; }
4781 public override Type DeclaringType {
4782 get { return constant.DeclaringType; }
4785 public override MemberExpr ResolveMemberAccess (ResolveContext ec, Expression left, Location loc, SimpleName original)
4787 constant = TypeManager.GetGenericFieldDefinition (constant);
4789 IConstant ic = TypeManager.GetConstant (constant);
4790 if (ic == null) {
4791 if (constant.IsLiteral) {
4792 ic = new ExternalConstant (constant, ec.Compiler);
4793 } else {
4794 ic = ExternalConstant.CreateDecimal (constant, ec);
4795 // HACK: decimal field was not resolved as constant
4796 if (ic == null)
4797 return new FieldExpr (constant, loc).ResolveMemberAccess (ec, left, loc, original);
4799 TypeManager.RegisterConstant (constant, ic);
4802 return base.ResolveMemberAccess (ec, left, loc, original);
4805 public override Expression CreateExpressionTree (ResolveContext ec)
4807 throw new NotSupportedException ("ET");
4810 protected override Expression DoResolve (ResolveContext rc)
4812 IConstant ic = TypeManager.GetConstant (constant);
4813 if (ic.ResolveValue ()) {
4814 if (!rc.IsObsolete)
4815 ic.CheckObsoleteness (loc);
4818 return ic.CreateConstantReference (rc, loc);
4821 public override void Emit (EmitContext ec)
4823 throw new NotSupportedException ();
4826 public override string GetSignatureForError ()
4828 return TypeManager.GetFullNameSignature (constant);
4832 /// <summary>
4833 /// Fully resolved expression that evaluates to a Field
4834 /// </summary>
4835 public class FieldExpr : MemberExpr, IDynamicAssign, IMemoryLocation, IVariableReference {
4836 public FieldInfo FieldInfo;
4837 readonly Type constructed_generic_type;
4838 VariableInfo variable_info;
4840 LocalTemporary temp;
4841 bool prepared;
4843 protected FieldExpr (Location l)
4845 loc = l;
4848 public FieldExpr (FieldInfo fi, Location l)
4850 FieldInfo = fi;
4851 type = TypeManager.TypeToCoreType (fi.FieldType);
4852 loc = l;
4855 public FieldExpr (FieldInfo fi, Type genericType, Location l)
4856 : this (fi, l)
4858 if (TypeManager.IsGenericTypeDefinition (genericType))
4859 return;
4860 this.constructed_generic_type = genericType;
4863 public override string Name {
4864 get {
4865 return FieldInfo.Name;
4869 public override bool IsInstance {
4870 get {
4871 return !FieldInfo.IsStatic;
4875 public override bool IsStatic {
4876 get {
4877 return FieldInfo.IsStatic;
4881 public override Type DeclaringType {
4882 get {
4883 return FieldInfo.DeclaringType;
4887 public override string GetSignatureForError ()
4889 return TypeManager.GetFullNameSignature (FieldInfo);
4892 public VariableInfo VariableInfo {
4893 get {
4894 return variable_info;
4898 public override MemberExpr ResolveMemberAccess (ResolveContext ec, Expression left, Location loc,
4899 SimpleName original)
4901 FieldInfo fi = TypeManager.GetGenericFieldDefinition (FieldInfo);
4902 Type t = fi.FieldType;
4904 if (t.IsPointer && !ec.IsUnsafe) {
4905 UnsafeError (ec, loc);
4908 return base.ResolveMemberAccess (ec, left, loc, original);
4911 public void SetHasAddressTaken ()
4913 IVariableReference vr = InstanceExpression as IVariableReference;
4914 if (vr != null)
4915 vr.SetHasAddressTaken ();
4918 public override Expression CreateExpressionTree (ResolveContext ec)
4920 Expression instance;
4921 if (InstanceExpression == null) {
4922 instance = new NullLiteral (loc);
4923 } else {
4924 instance = InstanceExpression.CreateExpressionTree (ec);
4927 Arguments args = Arguments.CreateForExpressionTree (ec, null,
4928 instance,
4929 CreateTypeOfExpression ());
4931 return CreateExpressionFactoryCall (ec, "Field", args);
4934 public Expression CreateTypeOfExpression ()
4936 return new TypeOfField (GetConstructedFieldInfo (), loc);
4939 protected override Expression DoResolve (ResolveContext ec)
4941 return DoResolve (ec, false, false);
4944 Expression DoResolve (ResolveContext ec, bool lvalue_instance, bool out_access)
4946 if (!FieldInfo.IsStatic){
4947 if (InstanceExpression == null){
4949 // This can happen when referencing an instance field using
4950 // a fully qualified type expression: TypeName.InstanceField = xxx
4952 SimpleName.Error_ObjectRefRequired (ec, loc, GetSignatureForError ());
4953 return null;
4956 // Resolve the field's instance expression while flow analysis is turned
4957 // off: when accessing a field "a.b", we must check whether the field
4958 // "a.b" is initialized, not whether the whole struct "a" is initialized.
4960 if (lvalue_instance) {
4961 using (ec.With (ResolveContext.Options.DoFlowAnalysis, false)) {
4962 Expression right_side =
4963 out_access ? EmptyExpression.LValueMemberOutAccess : EmptyExpression.LValueMemberAccess;
4965 if (InstanceExpression != EmptyExpression.Null)
4966 InstanceExpression = InstanceExpression.ResolveLValue (ec, right_side);
4968 } else {
4969 if (InstanceExpression != EmptyExpression.Null) {
4970 using (ec.With (ResolveContext.Options.DoFlowAnalysis, false)) {
4971 InstanceExpression = InstanceExpression.Resolve (ec, ResolveFlags.VariableOrValue);
4976 if (InstanceExpression == null)
4977 return null;
4979 using (ec.Set (ResolveContext.Options.OmitStructFlowAnalysis)) {
4980 InstanceExpression.CheckMarshalByRefAccess (ec);
4984 if (!ec.IsObsolete) {
4985 FieldBase f = TypeManager.GetField (FieldInfo);
4986 if (f != null) {
4987 f.CheckObsoleteness (loc);
4988 } else {
4989 ObsoleteAttribute oa = AttributeTester.GetMemberObsoleteAttribute (FieldInfo);
4990 if (oa != null)
4991 AttributeTester.Report_ObsoleteMessage (oa, TypeManager.GetFullNameSignature (FieldInfo), loc, ec.Report);
4995 IFixedBuffer fb = AttributeTester.GetFixedBuffer (FieldInfo);
4996 IVariableReference var = InstanceExpression as IVariableReference;
4998 if (fb != null) {
4999 IFixedExpression fe = InstanceExpression as IFixedExpression;
5000 if (!ec.HasSet (ResolveContext.Options.FixedInitializerScope) && (fe == null || !fe.IsFixed)) {
5001 ec.Report.Error (1666, loc, "You cannot use fixed size buffers contained in unfixed expressions. Try using the fixed statement");
5004 if (InstanceExpression.eclass != ExprClass.Variable) {
5005 ec.Report.SymbolRelatedToPreviousError (FieldInfo);
5006 ec.Report.Error (1708, loc, "`{0}': Fixed size buffers can only be accessed through locals or fields",
5007 TypeManager.GetFullNameSignature (FieldInfo));
5008 } else if (var != null && var.IsHoisted) {
5009 AnonymousMethodExpression.Error_AddressOfCapturedVar (ec, var, loc);
5012 return new FixedBufferPtr (this, fb.ElementType, loc).Resolve (ec);
5015 eclass = ExprClass.Variable;
5017 // If the instance expression is a local variable or parameter.
5018 if (var == null || var.VariableInfo == null)
5019 return this;
5021 VariableInfo vi = var.VariableInfo;
5022 if (!vi.IsFieldAssigned (ec, FieldInfo.Name, loc))
5023 return null;
5025 variable_info = vi.GetSubStruct (FieldInfo.Name);
5026 return this;
5029 static readonly int [] codes = {
5030 191, // instance, write access
5031 192, // instance, out access
5032 198, // static, write access
5033 199, // static, out access
5034 1648, // member of value instance, write access
5035 1649, // member of value instance, out access
5036 1650, // member of value static, write access
5037 1651 // member of value static, out access
5040 static readonly string [] msgs = {
5041 /*0191*/ "A readonly field `{0}' cannot be assigned to (except in a constructor or a variable initializer)",
5042 /*0192*/ "A readonly field `{0}' cannot be passed ref or out (except in a constructor)",
5043 /*0198*/ "A static readonly field `{0}' cannot be assigned to (except in a static constructor or a variable initializer)",
5044 /*0199*/ "A static readonly field `{0}' cannot be passed ref or out (except in a static constructor)",
5045 /*1648*/ "Members of readonly field `{0}' cannot be modified (except in a constructor or a variable initializer)",
5046 /*1649*/ "Members of readonly field `{0}' cannot be passed ref or out (except in a constructor)",
5047 /*1650*/ "Fields of static readonly field `{0}' cannot be assigned to (except in a static constructor or a variable initializer)",
5048 /*1651*/ "Fields of static readonly field `{0}' cannot be passed ref or out (except in a static constructor)"
5051 // The return value is always null. Returning a value simplifies calling code.
5052 Expression Report_AssignToReadonly (ResolveContext ec, Expression right_side)
5054 int i = 0;
5055 if (right_side == EmptyExpression.OutAccess.Instance || right_side == EmptyExpression.LValueMemberOutAccess)
5056 i += 1;
5057 if (IsStatic)
5058 i += 2;
5059 if (right_side == EmptyExpression.LValueMemberAccess || right_side == EmptyExpression.LValueMemberOutAccess)
5060 i += 4;
5061 ec.Report.Error (codes [i], loc, msgs [i], GetSignatureForError ());
5063 return null;
5066 override public Expression DoResolveLValue (ResolveContext ec, Expression right_side)
5068 IVariableReference var = InstanceExpression as IVariableReference;
5069 if (var != null && var.VariableInfo != null)
5070 var.VariableInfo.SetFieldAssigned (ec, FieldInfo.Name);
5072 bool lvalue_instance = !FieldInfo.IsStatic && TypeManager.IsValueType (FieldInfo.DeclaringType);
5073 bool out_access = right_side == EmptyExpression.OutAccess.Instance || right_side == EmptyExpression.LValueMemberOutAccess;
5075 Expression e = DoResolve (ec, lvalue_instance, out_access);
5077 if (e == null)
5078 return null;
5080 FieldBase fb = TypeManager.GetField (FieldInfo);
5081 if (fb != null) {
5082 fb.SetAssigned ();
5084 if ((right_side == EmptyExpression.UnaryAddress || right_side == EmptyExpression.OutAccess.Instance) &&
5085 (fb.ModFlags & Modifiers.VOLATILE) != 0) {
5086 ec.Report.Warning (420, 1, loc,
5087 "`{0}': A volatile field references will not be treated as volatile",
5088 fb.GetSignatureForError ());
5092 if (FieldInfo.IsInitOnly) {
5093 // InitOnly fields can only be assigned in constructors or initializers
5094 if (!ec.HasAny (ResolveContext.Options.FieldInitializerScope | ResolveContext.Options.ConstructorScope))
5095 return Report_AssignToReadonly (ec, right_side);
5097 if (ec.HasSet (ResolveContext.Options.ConstructorScope)) {
5098 Type ctype = ec.CurrentType;
5100 // InitOnly fields cannot be assigned-to in a different constructor from their declaring type
5101 if (!TypeManager.IsEqual (ctype, FieldInfo.DeclaringType))
5102 return Report_AssignToReadonly (ec, right_side);
5103 // static InitOnly fields cannot be assigned-to in an instance constructor
5104 if (IsStatic && !ec.IsStatic)
5105 return Report_AssignToReadonly (ec, right_side);
5106 // instance constructors can't modify InitOnly fields of other instances of the same type
5107 if (!IsStatic && !(InstanceExpression is This))
5108 return Report_AssignToReadonly (ec, right_side);
5112 if (right_side == EmptyExpression.OutAccess.Instance &&
5113 !IsStatic && !(InstanceExpression is This) && TypeManager.mbr_type != null && TypeManager.IsSubclassOf (DeclaringType, TypeManager.mbr_type)) {
5114 ec.Report.SymbolRelatedToPreviousError (DeclaringType);
5115 ec.Report.Warning (197, 1, loc,
5116 "Passing `{0}' as ref or out or taking its address may cause a runtime exception because it is a field of a marshal-by-reference class",
5117 GetSignatureForError ());
5120 eclass = ExprClass.Variable;
5121 return this;
5124 bool is_marshal_by_ref ()
5126 return !IsStatic && TypeManager.IsStruct (Type) && TypeManager.mbr_type != null && TypeManager.IsSubclassOf (DeclaringType, TypeManager.mbr_type);
5129 public override void CheckMarshalByRefAccess (ResolveContext ec)
5131 if (is_marshal_by_ref () && !(InstanceExpression is This)) {
5132 ec.Report.SymbolRelatedToPreviousError (DeclaringType);
5133 ec.Report.Warning (1690, 1, loc, "Cannot call methods, properties, or indexers on `{0}' because it is a value type member of a marshal-by-reference class",
5134 GetSignatureForError ());
5138 public override int GetHashCode ()
5140 return FieldInfo.GetHashCode ();
5143 public bool IsFixed {
5144 get {
5146 // A variable of the form V.I is fixed when V is a fixed variable of a struct type
5148 IVariableReference variable = InstanceExpression as IVariableReference;
5149 if (variable != null)
5150 return TypeManager.IsStruct (InstanceExpression.Type) && variable.IsFixed;
5152 IFixedExpression fe = InstanceExpression as IFixedExpression;
5153 return fe != null && fe.IsFixed;
5157 public bool IsHoisted {
5158 get {
5159 IVariableReference hv = InstanceExpression as IVariableReference;
5160 return hv != null && hv.IsHoisted;
5164 public override bool Equals (object obj)
5166 FieldExpr fe = obj as FieldExpr;
5167 if (fe == null)
5168 return false;
5170 if (FieldInfo != fe.FieldInfo)
5171 return false;
5173 if (InstanceExpression == null || fe.InstanceExpression == null)
5174 return true;
5176 return InstanceExpression.Equals (fe.InstanceExpression);
5179 public void Emit (EmitContext ec, bool leave_copy)
5181 ILGenerator ig = ec.ig;
5182 bool is_volatile = false;
5184 FieldBase f = TypeManager.GetField (FieldInfo);
5185 if (f != null){
5186 if ((f.ModFlags & Modifiers.VOLATILE) != 0)
5187 is_volatile = true;
5189 f.SetMemberIsUsed ();
5192 if (FieldInfo.IsStatic){
5193 if (is_volatile)
5194 ig.Emit (OpCodes.Volatile);
5196 ig.Emit (OpCodes.Ldsfld, GetConstructedFieldInfo ());
5197 } else {
5198 if (!prepared)
5199 EmitInstance (ec, false);
5201 // Optimization for build-in types
5202 if (TypeManager.IsStruct (type) && TypeManager.IsEqual (type, ec.MemberContext.CurrentType)) {
5203 LoadFromPtr (ig, type);
5204 } else {
5205 IFixedBuffer ff = AttributeTester.GetFixedBuffer (FieldInfo);
5206 if (ff != null) {
5207 ig.Emit (OpCodes.Ldflda, GetConstructedFieldInfo ());
5208 ig.Emit (OpCodes.Ldflda, ff.Element);
5209 } else {
5210 if (is_volatile)
5211 ig.Emit (OpCodes.Volatile);
5213 ig.Emit (OpCodes.Ldfld, GetConstructedFieldInfo ());
5218 if (leave_copy) {
5219 ec.ig.Emit (OpCodes.Dup);
5220 if (!FieldInfo.IsStatic) {
5221 temp = new LocalTemporary (this.Type);
5222 temp.Store (ec);
5227 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
5229 FieldAttributes fa = FieldInfo.Attributes;
5230 bool is_static = (fa & FieldAttributes.Static) != 0;
5231 ILGenerator ig = ec.ig;
5233 prepared = prepare_for_load;
5234 EmitInstance (ec, prepared);
5236 source.Emit (ec);
5237 if (leave_copy) {
5238 ec.ig.Emit (OpCodes.Dup);
5239 if (!FieldInfo.IsStatic) {
5240 temp = new LocalTemporary (this.Type);
5241 temp.Store (ec);
5245 FieldBase f = TypeManager.GetField (FieldInfo);
5246 if (f != null){
5247 if ((f.ModFlags & Modifiers.VOLATILE) != 0)
5248 ig.Emit (OpCodes.Volatile);
5250 f.SetAssigned ();
5253 if (is_static)
5254 ig.Emit (OpCodes.Stsfld, GetConstructedFieldInfo ());
5255 else
5256 ig.Emit (OpCodes.Stfld, GetConstructedFieldInfo ());
5258 if (temp != null) {
5259 temp.Emit (ec);
5260 temp.Release (ec);
5261 temp = null;
5265 public override void Emit (EmitContext ec)
5267 Emit (ec, false);
5270 public override void EmitSideEffect (EmitContext ec)
5272 FieldBase f = TypeManager.GetField (FieldInfo);
5273 bool is_volatile = f != null && (f.ModFlags & Modifiers.VOLATILE) != 0;
5275 if (is_volatile || is_marshal_by_ref ())
5276 base.EmitSideEffect (ec);
5279 public override void Error_VariableIsUsedBeforeItIsDeclared (Report r, string name)
5281 r.Error (844, loc,
5282 "A local variable `{0}' cannot be used before it is declared. Consider renaming the local variable when it hides the field `{1}'",
5283 name, GetSignatureForError ());
5286 public void AddressOf (EmitContext ec, AddressOp mode)
5288 ILGenerator ig = ec.ig;
5290 FieldBase f = TypeManager.GetField (FieldInfo);
5291 if (f != null){
5292 if ((mode & AddressOp.Store) != 0)
5293 f.SetAssigned ();
5294 if ((mode & AddressOp.Load) != 0)
5295 f.SetMemberIsUsed ();
5299 // Handle initonly fields specially: make a copy and then
5300 // get the address of the copy.
5302 bool need_copy;
5303 if (FieldInfo.IsInitOnly){
5304 need_copy = true;
5305 if (ec.HasSet (EmitContext.Options.ConstructorScope)){
5306 if (FieldInfo.IsStatic){
5307 if (ec.IsStatic)
5308 need_copy = false;
5309 } else
5310 need_copy = false;
5312 } else
5313 need_copy = false;
5315 if (need_copy){
5316 LocalBuilder local;
5317 Emit (ec);
5318 local = ig.DeclareLocal (type);
5319 ig.Emit (OpCodes.Stloc, local);
5320 ig.Emit (OpCodes.Ldloca, local);
5321 return;
5325 if (FieldInfo.IsStatic){
5326 ig.Emit (OpCodes.Ldsflda, GetConstructedFieldInfo ());
5327 } else {
5328 if (!prepared)
5329 EmitInstance (ec, false);
5330 ig.Emit (OpCodes.Ldflda, GetConstructedFieldInfo ());
5334 FieldInfo GetConstructedFieldInfo ()
5336 if (constructed_generic_type == null)
5337 return FieldInfo;
5339 return TypeBuilder.GetField (constructed_generic_type, FieldInfo);
5342 #if NET_4_0
5343 public SLE.Expression MakeAssignExpression (BuilderContext ctx)
5345 return MakeExpression (ctx);
5348 public override SLE.Expression MakeExpression (BuilderContext ctx)
5350 return SLE.Expression.Field (InstanceExpression.MakeExpression (ctx), FieldInfo);
5352 #endif
5354 public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
5356 FieldInfo = storey.MutateField (FieldInfo);
5357 base.MutateHoistedGenericType (storey);
5362 /// <summary>
5363 /// Expression that evaluates to a Property. The Assign class
5364 /// might set the `Value' expression if we are in an assignment.
5366 /// This is not an LValue because we need to re-write the expression, we
5367 /// can not take data from the stack and store it.
5368 /// </summary>
5369 public class PropertyExpr : MemberExpr, IDynamicAssign
5371 public readonly PropertyInfo PropertyInfo;
5372 MethodInfo getter, setter;
5373 bool is_static;
5375 TypeArguments targs;
5377 LocalTemporary temp;
5378 bool prepared;
5380 public PropertyExpr (Type container_type, PropertyInfo pi, Location l)
5382 PropertyInfo = pi;
5383 is_static = false;
5384 loc = l;
5386 type = TypeManager.TypeToCoreType (pi.PropertyType);
5388 ResolveAccessors (container_type);
5391 public override string Name {
5392 get {
5393 return PropertyInfo.Name;
5397 public override bool IsInstance {
5398 get {
5399 return !is_static;
5403 public override bool IsStatic {
5404 get {
5405 return is_static;
5409 public override Expression CreateExpressionTree (ResolveContext ec)
5411 Arguments args;
5412 if (IsSingleDimensionalArrayLength ()) {
5413 args = new Arguments (1);
5414 args.Add (new Argument (InstanceExpression.CreateExpressionTree (ec)));
5415 return CreateExpressionFactoryCall (ec, "ArrayLength", args);
5418 if (is_base) {
5419 Error_BaseAccessInExpressionTree (ec, loc);
5420 return null;
5423 args = new Arguments (2);
5424 if (InstanceExpression == null)
5425 args.Add (new Argument (new NullLiteral (loc)));
5426 else
5427 args.Add (new Argument (InstanceExpression.CreateExpressionTree (ec)));
5428 args.Add (new Argument (new TypeOfMethod (getter, loc)));
5429 return CreateExpressionFactoryCall (ec, "Property", args);
5432 public Expression CreateSetterTypeOfExpression ()
5434 return new TypeOfMethod (setter, loc);
5437 public override Type DeclaringType {
5438 get {
5439 return PropertyInfo.DeclaringType;
5443 public override string GetSignatureForError ()
5445 return TypeManager.GetFullNameSignature (PropertyInfo);
5448 void FindAccessors (Type invocation_type)
5450 const BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic |
5451 BindingFlags.Static | BindingFlags.Instance |
5452 BindingFlags.DeclaredOnly;
5454 Type current = PropertyInfo.DeclaringType;
5455 for (; current != null; current = current.BaseType) {
5456 MemberInfo[] group = TypeManager.MemberLookup (
5457 invocation_type, invocation_type, current,
5458 MemberTypes.Property, flags, PropertyInfo.Name, null);
5460 if (group == null)
5461 continue;
5463 if (group.Length != 1)
5464 // Oooops, can this ever happen ?
5465 return;
5467 PropertyInfo pi = (PropertyInfo) group [0];
5469 if (getter == null)
5470 getter = pi.GetGetMethod (true);
5472 if (setter == null)
5473 setter = pi.GetSetMethod (true);
5475 MethodInfo accessor = getter != null ? getter : setter;
5477 if (!accessor.IsVirtual)
5478 return;
5483 // We also perform the permission checking here, as the PropertyInfo does not
5484 // hold the information for the accessibility of its setter/getter
5486 // TODO: Refactor to use some kind of cache together with GetPropertyFromAccessor
5487 void ResolveAccessors (Type container_type)
5489 FindAccessors (container_type);
5491 if (getter != null) {
5492 MethodBase the_getter = TypeManager.DropGenericMethodArguments (getter);
5493 IMethodData md = TypeManager.GetMethod (the_getter);
5494 if (md != null)
5495 md.SetMemberIsUsed ();
5497 is_static = getter.IsStatic;
5500 if (setter != null) {
5501 MethodBase the_setter = TypeManager.DropGenericMethodArguments (setter);
5502 IMethodData md = TypeManager.GetMethod (the_setter);
5503 if (md != null)
5504 md.SetMemberIsUsed ();
5506 is_static = setter.IsStatic;
5510 #if NET_4_0
5511 public SLE.Expression MakeAssignExpression (BuilderContext ctx)
5513 return SLE.Expression.Property (InstanceExpression.MakeExpression (ctx), setter);
5516 public override SLE.Expression MakeExpression (BuilderContext ctx)
5518 return SLE.Expression.Property (InstanceExpression.MakeExpression (ctx), getter);
5520 #endif
5522 public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
5524 if (InstanceExpression != null)
5525 InstanceExpression.MutateHoistedGenericType (storey);
5527 type = storey.MutateType (type);
5528 if (getter != null)
5529 getter = storey.MutateGenericMethod (getter);
5530 if (setter != null)
5531 setter = storey.MutateGenericMethod (setter);
5534 bool InstanceResolve (ResolveContext ec, bool lvalue_instance, bool must_do_cs1540_check)
5536 if (is_static) {
5537 InstanceExpression = null;
5538 return true;
5541 if (InstanceExpression == null) {
5542 SimpleName.Error_ObjectRefRequired (ec, loc, GetSignatureForError ());
5543 return false;
5546 InstanceExpression = InstanceExpression.Resolve (ec);
5547 if (lvalue_instance && InstanceExpression != null)
5548 InstanceExpression = InstanceExpression.ResolveLValue (ec, EmptyExpression.LValueMemberAccess);
5550 if (InstanceExpression == null)
5551 return false;
5553 InstanceExpression.CheckMarshalByRefAccess (ec);
5555 if (must_do_cs1540_check && (InstanceExpression != EmptyExpression.Null) &&
5556 !TypeManager.IsInstantiationOfSameGenericType (InstanceExpression.Type, ec.CurrentType) &&
5557 !TypeManager.IsNestedChildOf (ec.CurrentType, InstanceExpression.Type) &&
5558 !TypeManager.IsSubclassOf (InstanceExpression.Type, ec.CurrentType)) {
5559 ec.Report.SymbolRelatedToPreviousError (PropertyInfo);
5560 Error_CannotAccessProtected (ec, loc, PropertyInfo, InstanceExpression.Type, ec.CurrentType);
5561 return false;
5564 return true;
5567 void Error_PropertyNotFound (ResolveContext ec, MethodInfo mi, bool getter)
5569 // TODO: correctly we should compare arguments but it will lead to bigger changes
5570 if (mi is MethodBuilder) {
5571 Error_TypeDoesNotContainDefinition (ec, loc, PropertyInfo.DeclaringType, Name);
5572 return;
5575 StringBuilder sig = new StringBuilder (TypeManager.CSharpName (mi.DeclaringType));
5576 sig.Append ('.');
5577 AParametersCollection iparams = TypeManager.GetParameterData (mi);
5578 sig.Append (getter ? "get_" : "set_");
5579 sig.Append (Name);
5580 sig.Append (iparams.GetSignatureForError ());
5582 ec.Report.SymbolRelatedToPreviousError (mi);
5583 ec.Report.Error (1546, loc, "Property `{0}' is not supported by the C# language. Try to call the accessor method `{1}' directly",
5584 Name, sig.ToString ());
5587 public bool IsAccessibleFrom (Type invocation_type, bool lvalue)
5589 bool dummy;
5590 MethodInfo accessor = lvalue ? setter : getter;
5591 if (accessor == null && lvalue)
5592 accessor = getter;
5593 return accessor != null && IsAccessorAccessible (invocation_type, accessor, out dummy);
5596 bool IsSingleDimensionalArrayLength ()
5598 if (DeclaringType != TypeManager.array_type || getter == null || Name != "Length")
5599 return false;
5601 string t_name = InstanceExpression.Type.Name;
5602 int t_name_len = t_name.Length;
5603 return t_name_len > 2 && t_name [t_name_len - 2] == '[';
5606 protected override Expression DoResolve (ResolveContext ec)
5608 eclass = ExprClass.PropertyAccess;
5610 bool must_do_cs1540_check = false;
5611 ec.Report.DisableReporting ();
5612 bool res = ResolveGetter (ec, ref must_do_cs1540_check);
5613 ec.Report.EnableReporting ();
5615 if (!res) {
5616 if (InstanceExpression != null) {
5617 Type expr_type = InstanceExpression.Type;
5618 ExtensionMethodGroupExpr ex_method_lookup = ec.LookupExtensionMethod (expr_type, Name, loc);
5619 if (ex_method_lookup != null) {
5620 ex_method_lookup.ExtensionExpression = InstanceExpression;
5621 ex_method_lookup.SetTypeArguments (ec, targs);
5622 return ex_method_lookup.Resolve (ec);
5626 ResolveGetter (ec, ref must_do_cs1540_check);
5627 return null;
5630 if (!InstanceResolve (ec, false, must_do_cs1540_check))
5631 return null;
5634 // Only base will allow this invocation to happen.
5636 if (IsBase && getter.IsAbstract) {
5637 Error_CannotCallAbstractBase (ec, TypeManager.GetFullNameSignature (PropertyInfo));
5640 if (PropertyInfo.PropertyType.IsPointer && !ec.IsUnsafe){
5641 UnsafeError (ec, loc);
5644 if (!ec.IsObsolete) {
5645 PropertyBase pb = TypeManager.GetProperty (PropertyInfo);
5646 if (pb != null) {
5647 pb.CheckObsoleteness (loc);
5648 } else {
5649 ObsoleteAttribute oa = AttributeTester.GetMemberObsoleteAttribute (PropertyInfo);
5650 if (oa != null)
5651 AttributeTester.Report_ObsoleteMessage (oa, GetSignatureForError (), loc, ec.Report);
5655 return this;
5658 override public Expression DoResolveLValue (ResolveContext ec, Expression right_side)
5660 eclass = ExprClass.PropertyAccess;
5662 if (right_side == EmptyExpression.OutAccess.Instance) {
5663 if (ec.CurrentBlock.Toplevel.GetParameterReference (PropertyInfo.Name, loc) is MemberAccess) {
5664 ec.Report.Error (1939, loc, "A range variable `{0}' may not be passes as `ref' or `out' parameter",
5665 PropertyInfo.Name);
5666 } else {
5667 right_side.DoResolveLValue (ec, this);
5669 return null;
5672 if (right_side == EmptyExpression.LValueMemberAccess || right_side == EmptyExpression.LValueMemberOutAccess) {
5673 Error_CannotModifyIntermediateExpressionValue (ec);
5676 if (setter == null){
5678 // The following condition happens if the PropertyExpr was
5679 // created, but is invalid (ie, the property is inaccessible),
5680 // and we did not want to embed the knowledge about this in
5681 // the caller routine. This only avoids double error reporting.
5683 if (getter == null)
5684 return null;
5686 if (ec.CurrentBlock.Toplevel.GetParameterReference (PropertyInfo.Name, loc) is MemberAccess) {
5687 ec.Report.Error (1947, loc, "A range variable `{0}' cannot be assigned to. Consider using `let' clause to store the value",
5688 PropertyInfo.Name);
5689 } else {
5690 ec.Report.Error (200, loc, "Property or indexer `{0}' cannot be assigned to (it is read only)",
5691 GetSignatureForError ());
5693 return null;
5696 if (targs != null) {
5697 base.SetTypeArguments (ec, targs);
5698 return null;
5701 if (TypeManager.GetParameterData (setter).Count != 1){
5702 Error_PropertyNotFound (ec, setter, false);
5703 return null;
5706 bool must_do_cs1540_check;
5707 if (!IsAccessorAccessible (ec.CurrentType, setter, out must_do_cs1540_check)) {
5708 PropertyBase.PropertyMethod pm = TypeManager.GetMethod (setter) as PropertyBase.PropertyMethod;
5709 if (pm != null && pm.HasCustomAccessModifier) {
5710 ec.Report.SymbolRelatedToPreviousError (pm);
5711 ec.Report.Error (272, loc, "The property or indexer `{0}' cannot be used in this context because the set accessor is inaccessible",
5712 TypeManager.CSharpSignature (setter));
5714 else {
5715 ec.Report.SymbolRelatedToPreviousError (setter);
5716 ErrorIsInaccesible (loc, TypeManager.CSharpSignature (setter), ec.Report);
5718 return null;
5721 if (!InstanceResolve (ec, TypeManager.IsStruct (PropertyInfo.DeclaringType), must_do_cs1540_check))
5722 return null;
5725 // Only base will allow this invocation to happen.
5727 if (IsBase && setter.IsAbstract){
5728 Error_CannotCallAbstractBase (ec, TypeManager.GetFullNameSignature (PropertyInfo));
5731 if (PropertyInfo.PropertyType.IsPointer && !ec.IsUnsafe) {
5732 UnsafeError (ec, loc);
5735 if (!ec.IsObsolete) {
5736 PropertyBase pb = TypeManager.GetProperty (PropertyInfo);
5737 if (pb != null) {
5738 pb.CheckObsoleteness (loc);
5739 } else {
5740 ObsoleteAttribute oa = AttributeTester.GetMemberObsoleteAttribute (PropertyInfo);
5741 if (oa != null)
5742 AttributeTester.Report_ObsoleteMessage (oa, GetSignatureForError (), loc, ec.Report);
5746 return this;
5749 public override void Emit (EmitContext ec)
5751 Emit (ec, false);
5754 public void Emit (EmitContext ec, bool leave_copy)
5757 // Special case: length of single dimension array property is turned into ldlen
5759 if (IsSingleDimensionalArrayLength ()) {
5760 if (!prepared)
5761 EmitInstance (ec, false);
5762 ec.ig.Emit (OpCodes.Ldlen);
5763 ec.ig.Emit (OpCodes.Conv_I4);
5764 return;
5767 Invocation.EmitCall (ec, IsBase, InstanceExpression, getter, null, loc, prepared, false);
5769 if (leave_copy) {
5770 ec.ig.Emit (OpCodes.Dup);
5771 if (!is_static) {
5772 temp = new LocalTemporary (this.Type);
5773 temp.Store (ec);
5779 // Implements the IAssignMethod interface for assignments
5781 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
5783 Expression my_source = source;
5785 if (prepare_for_load) {
5786 prepared = true;
5787 source.Emit (ec);
5789 if (leave_copy) {
5790 ec.ig.Emit (OpCodes.Dup);
5791 if (!is_static) {
5792 temp = new LocalTemporary (this.Type);
5793 temp.Store (ec);
5796 } else if (leave_copy) {
5797 source.Emit (ec);
5798 temp = new LocalTemporary (this.Type);
5799 temp.Store (ec);
5800 my_source = temp;
5803 Arguments args = new Arguments (1);
5804 args.Add (new Argument (my_source));
5806 Invocation.EmitCall (ec, IsBase, InstanceExpression, setter, args, loc, false, prepared);
5808 if (temp != null) {
5809 temp.Emit (ec);
5810 temp.Release (ec);
5814 bool ResolveGetter (ResolveContext ec, ref bool must_do_cs1540_check)
5816 if (targs != null) {
5817 base.SetTypeArguments (ec, targs);
5818 return false;
5821 if (getter != null) {
5822 if (TypeManager.GetParameterData (getter).Count != 0) {
5823 Error_PropertyNotFound (ec, getter, true);
5824 return false;
5828 if (getter == null) {
5830 // The following condition happens if the PropertyExpr was
5831 // created, but is invalid (ie, the property is inaccessible),
5832 // and we did not want to embed the knowledge about this in
5833 // the caller routine. This only avoids double error reporting.
5835 if (setter == null)
5836 return false;
5838 if (InstanceExpression != EmptyExpression.Null) {
5839 ec.Report.Error (154, loc, "The property or indexer `{0}' cannot be used in this context because it lacks the `get' accessor",
5840 TypeManager.GetFullNameSignature (PropertyInfo));
5841 return false;
5845 if (getter != null &&
5846 !IsAccessorAccessible (ec.CurrentType, getter, out must_do_cs1540_check)) {
5847 PropertyBase.PropertyMethod pm = TypeManager.GetMethod (getter) as PropertyBase.PropertyMethod;
5848 if (pm != null && pm.HasCustomAccessModifier) {
5849 ec.Report.SymbolRelatedToPreviousError (pm);
5850 ec.Report.Error (271, loc, "The property or indexer `{0}' cannot be used in this context because the get accessor is inaccessible",
5851 TypeManager.CSharpSignature (getter));
5852 } else {
5853 ec.Report.SymbolRelatedToPreviousError (getter);
5854 ErrorIsInaccesible (loc, TypeManager.CSharpSignature (getter), ec.Report);
5857 return false;
5860 return true;
5863 public override void SetTypeArguments (ResolveContext ec, TypeArguments ta)
5865 targs = ta;
5869 /// <summary>
5870 /// Fully resolved expression that evaluates to an Event
5871 /// </summary>
5872 public class EventExpr : MemberExpr {
5873 public readonly EventInfo EventInfo;
5875 bool is_static;
5876 MethodInfo add_accessor, remove_accessor;
5878 public EventExpr (EventInfo ei, Location loc)
5880 EventInfo = ei;
5881 this.loc = loc;
5883 add_accessor = TypeManager.GetAddMethod (ei);
5884 remove_accessor = TypeManager.GetRemoveMethod (ei);
5885 if (add_accessor.IsStatic || remove_accessor.IsStatic)
5886 is_static = true;
5888 if (EventInfo is MyEventBuilder){
5889 MyEventBuilder eb = (MyEventBuilder) EventInfo;
5890 type = eb.EventType;
5891 eb.SetUsed ();
5892 } else
5893 type = EventInfo.EventHandlerType;
5896 public override string Name {
5897 get {
5898 return EventInfo.Name;
5902 public override bool IsInstance {
5903 get {
5904 return !is_static;
5908 public override bool IsStatic {
5909 get {
5910 return is_static;
5914 public override Type DeclaringType {
5915 get {
5916 return EventInfo.DeclaringType;
5920 public void Error_AssignmentEventOnly (ResolveContext ec)
5922 ec.Report.Error (79, loc, "The event `{0}' can only appear on the left hand side of `+=' or `-=' operator",
5923 GetSignatureForError ());
5926 public override MemberExpr ResolveMemberAccess (ResolveContext ec, Expression left, Location loc,
5927 SimpleName original)
5930 // If the event is local to this class, we transform ourselves into a FieldExpr
5933 if (EventInfo.DeclaringType == ec.CurrentType ||
5934 TypeManager.IsNestedChildOf(ec.CurrentType, EventInfo.DeclaringType)) {
5936 // TODO: Breaks dynamic binder as currect context fields are imported and not compiled
5937 EventField mi = TypeManager.GetEventField (EventInfo);
5939 if (mi != null) {
5940 if (!ec.IsObsolete)
5941 mi.CheckObsoleteness (loc);
5943 if ((mi.ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN)) != 0 && !ec.HasSet (ResolveContext.Options.CompoundAssignmentScope))
5944 Error_AssignmentEventOnly (ec);
5946 FieldExpr ml = new FieldExpr (mi.BackingField.FieldBuilder, loc);
5948 InstanceExpression = null;
5950 return ml.ResolveMemberAccess (ec, left, loc, original);
5954 if (left is This && !ec.HasSet (ResolveContext.Options.CompoundAssignmentScope))
5955 Error_AssignmentEventOnly (ec);
5957 return base.ResolveMemberAccess (ec, left, loc, original);
5960 bool InstanceResolve (ResolveContext ec, bool must_do_cs1540_check)
5962 if (is_static) {
5963 InstanceExpression = null;
5964 return true;
5967 if (InstanceExpression == null) {
5968 SimpleName.Error_ObjectRefRequired (ec, loc, GetSignatureForError ());
5969 return false;
5972 InstanceExpression = InstanceExpression.Resolve (ec);
5973 if (InstanceExpression == null)
5974 return false;
5976 if (IsBase && add_accessor.IsAbstract) {
5977 Error_CannotCallAbstractBase (ec, TypeManager.CSharpSignature(add_accessor));
5978 return false;
5982 // This is using the same mechanism as the CS1540 check in PropertyExpr.
5983 // However, in the Event case, we reported a CS0122 instead.
5985 // TODO: Exact copy from PropertyExpr
5987 if (must_do_cs1540_check && InstanceExpression != EmptyExpression.Null &&
5988 !TypeManager.IsInstantiationOfSameGenericType (InstanceExpression.Type, ec.CurrentType) &&
5989 !TypeManager.IsNestedChildOf (ec.CurrentType, InstanceExpression.Type) &&
5990 !TypeManager.IsSubclassOf (InstanceExpression.Type, ec.CurrentType)) {
5991 ec.Report.SymbolRelatedToPreviousError (EventInfo);
5992 ErrorIsInaccesible (loc, TypeManager.CSharpSignature (EventInfo), ec.Report);
5993 return false;
5996 return true;
5999 public bool IsAccessibleFrom (Type invocation_type)
6001 bool dummy;
6002 return IsAccessorAccessible (invocation_type, add_accessor, out dummy) &&
6003 IsAccessorAccessible (invocation_type, remove_accessor, out dummy);
6006 public override Expression CreateExpressionTree (ResolveContext ec)
6008 throw new NotSupportedException ("ET");
6011 public override Expression DoResolveLValue (ResolveContext ec, Expression right_side)
6013 // contexts where an LValue is valid have already devolved to FieldExprs
6014 Error_CannotAssign (ec);
6015 return null;
6018 protected override Expression DoResolve (ResolveContext ec)
6020 eclass = ExprClass.EventAccess;
6022 bool must_do_cs1540_check;
6023 if (!(IsAccessorAccessible (ec.CurrentType, add_accessor, out must_do_cs1540_check) &&
6024 IsAccessorAccessible (ec.CurrentType, remove_accessor, out must_do_cs1540_check))) {
6025 ec.Report.SymbolRelatedToPreviousError (EventInfo);
6026 ErrorIsInaccesible (loc, TypeManager.CSharpSignature (EventInfo), ec.Report);
6027 return null;
6030 if (!InstanceResolve (ec, must_do_cs1540_check))
6031 return null;
6033 if (!ec.HasSet (ResolveContext.Options.CompoundAssignmentScope)) {
6034 Error_CannotAssign (ec);
6035 return null;
6038 if (!ec.IsObsolete) {
6039 EventField ev = TypeManager.GetEventField (EventInfo);
6040 if (ev != null) {
6041 ev.CheckObsoleteness (loc);
6042 } else {
6043 ObsoleteAttribute oa = AttributeTester.GetMemberObsoleteAttribute (EventInfo);
6044 if (oa != null)
6045 AttributeTester.Report_ObsoleteMessage (oa, GetSignatureForError (), loc, ec.Report);
6049 return this;
6052 public override void Emit (EmitContext ec)
6054 throw new NotSupportedException ();
6055 //Error_CannotAssign ();
6058 public void Error_CannotAssign (ResolveContext ec)
6060 ec.Report.Error (70, loc,
6061 "The event `{0}' can only appear on the left hand side of += or -= when used outside of the type `{1}'",
6062 GetSignatureForError (), TypeManager.CSharpName (EventInfo.DeclaringType));
6065 public override string GetSignatureForError ()
6067 return TypeManager.CSharpSignature (EventInfo);
6070 public void EmitAddOrRemove (EmitContext ec, bool is_add, Expression source)
6072 Arguments args = new Arguments (1);
6073 args.Add (new Argument (source));
6074 Invocation.EmitCall (ec, IsBase, InstanceExpression, is_add ? add_accessor : remove_accessor, args, loc);
6078 public class TemporaryVariable : VariableReference
6080 LocalInfo li;
6082 public TemporaryVariable (Type type, Location loc)
6084 this.type = type;
6085 this.loc = loc;
6088 public override Expression CreateExpressionTree (ResolveContext ec)
6090 throw new NotSupportedException ("ET");
6093 protected override Expression DoResolve (ResolveContext ec)
6095 eclass = ExprClass.Variable;
6097 TypeExpr te = new TypeExpression (type, loc);
6098 li = ec.CurrentBlock.AddTemporaryVariable (te, loc);
6099 if (!li.Resolve (ec))
6100 return null;
6103 // Don't capture temporary variables except when using
6104 // iterator redirection
6106 if (ec.CurrentAnonymousMethod != null && ec.CurrentAnonymousMethod.IsIterator && ec.IsVariableCapturingRequired) {
6107 AnonymousMethodStorey storey = li.Block.Explicit.CreateAnonymousMethodStorey (ec);
6108 storey.CaptureLocalVariable (ec, li);
6111 return this;
6114 public override Expression DoResolveLValue (ResolveContext ec, Expression right_side)
6116 return Resolve (ec);
6119 public override void Emit (EmitContext ec)
6121 Emit (ec, false);
6124 public void EmitAssign (EmitContext ec, Expression source)
6126 EmitAssign (ec, source, false, false);
6129 public override HoistedVariable GetHoistedVariable (AnonymousExpression ae)
6131 return li.HoistedVariant;
6134 public override bool IsFixed {
6135 get { return true; }
6138 public override bool IsRef {
6139 get { return false; }
6142 public override string Name {
6143 get { throw new NotImplementedException (); }
6146 public override void SetHasAddressTaken ()
6148 throw new NotImplementedException ();
6151 protected override ILocalVariable Variable {
6152 get { return li; }
6155 public override VariableInfo VariableInfo {
6156 get { throw new NotImplementedException (); }
6160 ///
6161 /// Handles `var' contextual keyword; var becomes a keyword only
6162 /// if no type called var exists in a variable scope
6163 ///
6164 class VarExpr : SimpleName
6166 // Used for error reporting only
6167 ArrayList initializer;
6169 public VarExpr (Location loc)
6170 : base ("var", loc)
6174 public ArrayList VariableInitializer {
6175 set {
6176 this.initializer = value;
6180 public bool InferType (ResolveContext ec, Expression right_side)
6182 if (type != null)
6183 throw new InternalErrorException ("An implicitly typed local variable could not be redefined");
6185 type = right_side.Type;
6186 if (type == TypeManager.null_type || type == TypeManager.void_type || type == InternalType.AnonymousMethod || type == InternalType.MethodGroup) {
6187 ec.Report.Error (815, loc, "An implicitly typed local variable declaration cannot be initialized with `{0}'",
6188 right_side.GetSignatureForError ());
6189 return false;
6192 eclass = ExprClass.Variable;
6193 return true;
6196 protected override void Error_TypeOrNamespaceNotFound (IMemberContext ec)
6198 if (RootContext.Version < LanguageVersion.V_3)
6199 base.Error_TypeOrNamespaceNotFound (ec);
6200 else
6201 ec.Compiler.Report.Error (825, loc, "The contextual keyword `var' may only appear within a local variable declaration");
6204 public override TypeExpr ResolveAsContextualType (IMemberContext rc, bool silent)
6206 TypeExpr te = base.ResolveAsContextualType (rc, true);
6207 if (te != null)
6208 return te;
6210 if (RootContext.Version < LanguageVersion.V_3)
6211 rc.Compiler.Report.FeatureIsNotAvailable (loc, "implicitly typed local variable");
6213 if (initializer == null)
6214 return null;
6216 if (initializer.Count > 1) {
6217 Location loc_init = ((CSharpParser.VariableDeclaration) initializer[1]).Location;
6218 rc.Compiler.Report.Error (819, loc_init, "An implicitly typed local variable declaration cannot include multiple declarators");
6219 initializer = null;
6220 return null;
6223 Expression variable_initializer = ((CSharpParser.VariableDeclaration) initializer[0]).expression_or_array_initializer;
6224 if (variable_initializer == null) {
6225 rc.Compiler.Report.Error (818, loc, "An implicitly typed local variable declarator must include an initializer");
6226 return null;
6229 return null;