2009-12-02 Jb Evain <jbevain@novell.com>
[mcs.git] / mcs / ecore.cs
blob1a22933ada16068418a188165924b832f73821ac
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
2475 public SimpleName (string name, Location l)
2476 : base (name, l)
2480 public SimpleName (string name, TypeArguments args, Location l)
2481 : base (name, args, l)
2485 public SimpleName (string name, TypeParameter[] type_params, Location l)
2486 : base (name, l)
2488 targs = new TypeArguments ();
2489 foreach (TypeParameter type_param in type_params)
2490 targs.Add (new TypeParameterExpr (type_param, l));
2493 public static string RemoveGenericArity (string name)
2495 int start = 0;
2496 StringBuilder sb = null;
2497 do {
2498 int pos = name.IndexOf ('`', start);
2499 if (pos < 0) {
2500 if (start == 0)
2501 return name;
2503 sb.Append (name.Substring (start));
2504 break;
2507 if (sb == null)
2508 sb = new StringBuilder ();
2509 sb.Append (name.Substring (start, pos-start));
2511 pos++;
2512 while ((pos < name.Length) && Char.IsNumber (name [pos]))
2513 pos++;
2515 start = pos;
2516 } while (start < name.Length);
2518 return sb.ToString ();
2521 public SimpleName GetMethodGroup ()
2523 return new SimpleName (RemoveGenericArity (Name), targs, loc);
2526 public static void Error_ObjectRefRequired (ResolveContext ec, Location l, string name)
2528 if (ec.HasSet (ResolveContext.Options.FieldInitializerScope))
2529 ec.Report.Error (236, l,
2530 "A field initializer cannot reference the nonstatic field, method, or property `{0}'",
2531 name);
2532 else
2533 ec.Report.Error (120, l,
2534 "An object reference is required to access non-static member `{0}'",
2535 name);
2538 public bool IdenticalNameAndTypeName (IMemberContext mc, Expression resolved_to, Location loc)
2540 return resolved_to != null && resolved_to.Type != null &&
2541 resolved_to.Type.Name == Name &&
2542 (mc.LookupNamespaceOrType (Name, loc, /* ignore_cs0104 = */ true) != null);
2545 protected override Expression DoResolve (ResolveContext ec)
2547 return SimpleNameResolve (ec, null, false);
2550 public override Expression DoResolveLValue (ResolveContext ec, Expression right_side)
2552 return SimpleNameResolve (ec, right_side, false);
2555 public Expression DoResolve (ResolveContext ec, bool intermediate)
2557 return SimpleNameResolve (ec, null, intermediate);
2560 static bool IsNestedChild (Type t, Type parent)
2562 while (parent != null) {
2563 if (TypeManager.IsNestedChildOf (t, TypeManager.DropGenericTypeArguments (parent)))
2564 return true;
2566 parent = parent.BaseType;
2569 return false;
2572 FullNamedExpression ResolveNested (Type t)
2574 if (!TypeManager.IsGenericTypeDefinition (t) && !TypeManager.IsGenericType (t))
2575 return null;
2577 Type ds = t;
2578 while (ds != null && !IsNestedChild (t, ds))
2579 ds = ds.DeclaringType;
2581 if (ds == null)
2582 return null;
2584 Type[] gen_params = TypeManager.GetTypeArguments (t);
2586 int arg_count = targs != null ? targs.Count : 0;
2588 for (; (ds != null) && TypeManager.IsGenericType (ds); ds = ds.DeclaringType) {
2589 Type[] gargs = TypeManager.GetTypeArguments (ds);
2590 if (arg_count + gargs.Length == gen_params.Length) {
2591 TypeArguments new_args = new TypeArguments ();
2592 foreach (Type param in gargs)
2593 new_args.Add (new TypeExpression (param, loc));
2595 if (targs != null)
2596 new_args.Add (targs);
2598 return new GenericTypeExpr (t, new_args, loc);
2602 return null;
2605 public override FullNamedExpression ResolveAsTypeStep (IMemberContext ec, bool silent)
2607 int errors = ec.Compiler.Report.Errors;
2608 FullNamedExpression fne = ec.LookupNamespaceOrType (Name, loc, /*ignore_cs0104=*/ false);
2610 if (fne != null) {
2611 if (fne.Type == null)
2612 return fne;
2614 FullNamedExpression nested = ResolveNested (fne.Type);
2615 if (nested != null)
2616 return nested.ResolveAsTypeStep (ec, false);
2618 if (targs != null) {
2619 if (TypeManager.IsGenericType (fne.Type)) {
2620 GenericTypeExpr ct = new GenericTypeExpr (fne.Type, targs, loc);
2621 return ct.ResolveAsTypeStep (ec, false);
2624 fne.Error_TypeArgumentsCannotBeUsed (ec.Compiler.Report, loc);
2627 return fne;
2630 if (!HasTypeArguments && Name == "dynamic" &&
2631 RootContext.Version > LanguageVersion.V_3 &&
2632 RootContext.MetadataCompatibilityVersion > MetadataVersion.v2) {
2634 if (!PredefinedAttributes.Get.Dynamic.IsDefined) {
2635 ec.Compiler.Report.Error (1980, Location,
2636 "Dynamic keyword requires `{0}' to be defined. Are you missing System.Core.dll assembly reference?",
2637 PredefinedAttributes.Get.Dynamic.GetSignatureForError ());
2640 return new DynamicTypeExpr (loc);
2643 if (silent || errors != ec.Compiler.Report.Errors)
2644 return null;
2646 Error_TypeOrNamespaceNotFound (ec);
2647 return null;
2650 protected virtual void Error_TypeOrNamespaceNotFound (IMemberContext ec)
2652 if (ec.CurrentType != null) {
2653 if (ec.CurrentTypeDefinition != null) {
2654 MemberCore mc = ec.CurrentTypeDefinition.GetDefinition (Name);
2655 if (mc != null) {
2656 Error_UnexpectedKind (ec.Compiler.Report, mc, "type", GetMemberType (mc), loc);
2657 return;
2661 string ns = ec.CurrentType.Namespace;
2662 string fullname = (ns.Length > 0) ? ns + "." + Name : Name;
2663 foreach (Assembly a in GlobalRootNamespace.Instance.Assemblies) {
2664 Type type = a.GetType (fullname);
2665 if (type != null) {
2666 ec.Compiler.Report.SymbolRelatedToPreviousError (type);
2667 Expression.ErrorIsInaccesible (loc, TypeManager.CSharpName (type), ec.Compiler.Report);
2668 return;
2672 if (ec.CurrentTypeDefinition != null) {
2673 Type t = ec.CurrentTypeDefinition.LookupAnyGeneric (Name);
2674 if (t != null) {
2675 Namespace.Error_InvalidNumberOfTypeArguments (ec.Compiler.Report, t, loc);
2676 return;
2681 if (targs != null) {
2682 FullNamedExpression retval = ec.LookupNamespaceOrType (SimpleName.RemoveGenericArity (Name), loc, true);
2683 if (retval != null) {
2684 retval.Error_TypeArgumentsCannotBeUsed (ec.Compiler.Report, loc);
2685 return;
2689 NamespaceEntry.Error_NamespaceNotFound (loc, Name, ec.Compiler.Report);
2692 // TODO: I am still not convinced about this. If someone else will need it
2693 // implement this as virtual property in MemberCore hierarchy
2694 public static string GetMemberType (MemberCore mc)
2696 if (mc is Property)
2697 return "property";
2698 if (mc is Indexer)
2699 return "indexer";
2700 if (mc is FieldBase)
2701 return "field";
2702 if (mc is MethodCore)
2703 return "method";
2704 if (mc is EnumMember)
2705 return "enum";
2706 if (mc is Event)
2707 return "event";
2709 return "type";
2712 Expression SimpleNameResolve (ResolveContext ec, Expression right_side, bool intermediate)
2714 Expression e = DoSimpleNameResolve (ec, right_side, intermediate);
2716 if (e == null)
2717 return null;
2719 if (ec.CurrentBlock == null || ec.CurrentBlock.CheckInvariantMeaningInBlock (Name, e, Location))
2720 return e;
2722 return null;
2725 /// <remarks>
2726 /// 7.5.2: Simple Names.
2728 /// Local Variables and Parameters are handled at
2729 /// parse time, so they never occur as SimpleNames.
2731 /// The `intermediate' flag is used by MemberAccess only
2732 /// and it is used to inform us that it is ok for us to
2733 /// avoid the static check, because MemberAccess might end
2734 /// up resolving the Name as a Type name and the access as
2735 /// a static type access.
2737 /// ie: Type Type; .... { Type.GetType (""); }
2739 /// Type is both an instance variable and a Type; Type.GetType
2740 /// is the static method not an instance method of type.
2741 /// </remarks>
2742 Expression DoSimpleNameResolve (ResolveContext ec, Expression right_side, bool intermediate)
2744 Expression e = null;
2747 // Stage 1: Performed by the parser (binding to locals or parameters).
2749 Block current_block = ec.CurrentBlock;
2750 if (current_block != null){
2751 LocalInfo vi = current_block.GetLocalInfo (Name);
2752 if (vi != null){
2753 e = new LocalVariableReference (ec.CurrentBlock, Name, loc);
2755 if (right_side != null) {
2756 e = e.ResolveLValue (ec, right_side);
2757 } else {
2758 if (intermediate) {
2759 using (ec.With (ResolveContext.Options.DoFlowAnalysis, false)) {
2760 e = e.Resolve (ec, ResolveFlags.VariableOrValue);
2762 } else {
2763 e = e.Resolve (ec, ResolveFlags.VariableOrValue);
2767 if (targs != null && e != null)
2768 e.Error_TypeArgumentsCannotBeUsed (ec.Report, loc);
2770 return e;
2773 e = current_block.Toplevel.GetParameterReference (Name, loc);
2774 if (e != null) {
2775 if (right_side != null)
2776 e = e.ResolveLValue (ec, right_side);
2777 else
2778 e = e.Resolve (ec);
2780 if (targs != null && e != null)
2781 e.Error_TypeArgumentsCannotBeUsed (ec.Report, loc);
2783 return e;
2788 // Stage 2: Lookup members
2791 Type almost_matched_type = null;
2792 ArrayList almost_matched = null;
2793 for (Type lookup_ds = ec.CurrentType; lookup_ds != null; lookup_ds = lookup_ds.DeclaringType) {
2794 e = MemberLookup (ec.Compiler, ec.CurrentType, lookup_ds, Name, loc);
2795 if (e != null) {
2796 PropertyExpr pe = e as PropertyExpr;
2797 if (pe != null) {
2798 AParametersCollection param = TypeManager.GetParameterData (pe.PropertyInfo);
2800 // since TypeManager.MemberLookup doesn't know if we're doing a lvalue access or not,
2801 // it doesn't know which accessor to check permissions against
2802 if (param.IsEmpty && pe.IsAccessibleFrom (ec.CurrentType, right_side != null))
2803 break;
2804 } else if (e is EventExpr) {
2805 if (((EventExpr) e).IsAccessibleFrom (ec.CurrentType))
2806 break;
2807 } else if (targs != null && e is TypeExpression) {
2808 e = new GenericTypeExpr (e.Type, targs, loc).ResolveAsTypeStep (ec, false);
2809 break;
2810 } else {
2811 break;
2813 e = null;
2816 if (almost_matched == null && almost_matched_members.Count > 0) {
2817 almost_matched_type = lookup_ds;
2818 almost_matched = (ArrayList) almost_matched_members.Clone ();
2822 if (e == null) {
2823 if (almost_matched == null && almost_matched_members.Count > 0) {
2824 almost_matched_type = ec.CurrentType;
2825 almost_matched = (ArrayList) almost_matched_members.Clone ();
2827 e = ResolveAsTypeStep (ec, true);
2830 if (e == null) {
2831 if (current_block != null) {
2832 IKnownVariable ikv = current_block.Explicit.GetKnownVariable (Name);
2833 if (ikv != null) {
2834 LocalInfo li = ikv as LocalInfo;
2835 // Supress CS0219 warning
2836 if (li != null)
2837 li.Used = true;
2839 Error_VariableIsUsedBeforeItIsDeclared (ec.Report, Name);
2840 return null;
2844 if (RootContext.EvalMode){
2845 FieldInfo fi = Evaluator.LookupField (Name);
2846 if (fi != null)
2847 return new FieldExpr (fi, loc).Resolve (ec);
2850 if (almost_matched != null)
2851 almost_matched_members = almost_matched;
2852 if (almost_matched_type == null)
2853 almost_matched_type = ec.CurrentType;
2855 string type_name = ec.MemberContext.CurrentType == null ? null : ec.MemberContext.CurrentType.Name;
2856 return Error_MemberLookupFailed (ec, ec.CurrentType, null, almost_matched_type, Name,
2857 type_name, AllMemberTypes, AllBindingFlags);
2860 if (e is MemberExpr) {
2861 MemberExpr me = (MemberExpr) e;
2863 Expression left;
2864 if (me.IsInstance) {
2865 if (ec.IsStatic || ec.HasAny (ResolveContext.Options.FieldInitializerScope | ResolveContext.Options.BaseInitializer | ResolveContext.Options.ConstantScope)) {
2867 // Note that an MemberExpr can be both IsInstance and IsStatic.
2868 // An unresolved MethodGroupExpr can contain both kinds of methods
2869 // and each predicate is true if the MethodGroupExpr contains
2870 // at least one of that kind of method.
2873 if (!me.IsStatic &&
2874 (!intermediate || !IdenticalNameAndTypeName (ec, me, loc))) {
2875 Error_ObjectRefRequired (ec, loc, me.GetSignatureForError ());
2876 return null;
2880 // Pass the buck to MemberAccess and Invocation.
2882 left = EmptyExpression.Null;
2883 } else {
2884 left = ec.GetThis (loc);
2886 } else {
2887 left = new TypeExpression (ec.CurrentType, loc);
2890 me = me.ResolveMemberAccess (ec, left, loc, null);
2891 if (me == null)
2892 return null;
2894 if (targs != null) {
2895 if (!targs.Resolve (ec))
2896 return null;
2898 me.SetTypeArguments (ec, targs);
2901 if (!me.IsStatic && (me.InstanceExpression != null && me.InstanceExpression != EmptyExpression.Null) &&
2902 TypeManager.IsNestedFamilyAccessible (me.InstanceExpression.Type, me.DeclaringType) &&
2903 me.InstanceExpression.Type != me.DeclaringType &&
2904 !TypeManager.IsFamilyAccessible (me.InstanceExpression.Type, me.DeclaringType) &&
2905 (!intermediate || !IdenticalNameAndTypeName (ec, e, loc))) {
2906 ec.Report.Error (38, loc, "Cannot access a nonstatic member of outer type `{0}' via nested type `{1}'",
2907 TypeManager.CSharpName (me.DeclaringType), TypeManager.CSharpName (me.InstanceExpression.Type));
2908 return null;
2911 return (right_side != null)
2912 ? me.DoResolveLValue (ec, right_side)
2913 : me.Resolve (ec);
2916 return e;
2920 /// <summary>
2921 /// Represents a namespace or a type. The name of the class was inspired by
2922 /// section 10.8.1 (Fully Qualified Names).
2923 /// </summary>
2924 public abstract class FullNamedExpression : Expression
2926 protected override void CloneTo (CloneContext clonectx, Expression target)
2928 // Do nothing, most unresolved type expressions cannot be
2929 // resolved to different type
2932 public override Expression CreateExpressionTree (ResolveContext ec)
2934 throw new NotSupportedException ("ET");
2937 public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
2939 throw new NotSupportedException ();
2942 public override FullNamedExpression ResolveAsTypeStep (IMemberContext ec, bool silent)
2944 return this;
2947 public override void Emit (EmitContext ec)
2949 throw new InternalErrorException ("FullNamedExpression `{0}' found in resolved tree",
2950 GetSignatureForError ());
2954 /// <summary>
2955 /// Expression that evaluates to a type
2956 /// </summary>
2957 public abstract class TypeExpr : FullNamedExpression {
2958 public override FullNamedExpression ResolveAsTypeStep (IMemberContext ec, bool silent)
2960 TypeExpr t = DoResolveAsTypeStep (ec);
2961 if (t == null)
2962 return null;
2964 eclass = ExprClass.Type;
2965 return t;
2968 protected override Expression DoResolve (ResolveContext ec)
2970 return ResolveAsTypeTerminal (ec, false);
2973 public virtual bool CheckAccessLevel (IMemberContext mc)
2975 return mc.CurrentTypeDefinition.CheckAccessLevel (Type);
2978 public virtual bool IsClass {
2979 get { return Type.IsClass; }
2982 public virtual bool IsValueType {
2983 get { return TypeManager.IsStruct (Type); }
2986 public virtual bool IsInterface {
2987 get { return Type.IsInterface; }
2990 public virtual bool IsSealed {
2991 get { return Type.IsSealed; }
2994 public virtual bool CanInheritFrom ()
2996 if (Type == TypeManager.enum_type ||
2997 (Type == TypeManager.value_type && RootContext.StdLib) ||
2998 Type == TypeManager.multicast_delegate_type ||
2999 Type == TypeManager.delegate_type ||
3000 Type == TypeManager.array_type)
3001 return false;
3003 return true;
3006 protected abstract TypeExpr DoResolveAsTypeStep (IMemberContext ec);
3008 public override bool Equals (object obj)
3010 TypeExpr tobj = obj as TypeExpr;
3011 if (tobj == null)
3012 return false;
3014 return Type == tobj.Type;
3017 public override int GetHashCode ()
3019 return Type.GetHashCode ();
3022 public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
3024 type = storey.MutateType (type);
3028 /// <summary>
3029 /// Fully resolved Expression that already evaluated to a type
3030 /// </summary>
3031 public class TypeExpression : TypeExpr {
3032 public TypeExpression (Type t, Location l)
3034 Type = t;
3035 eclass = ExprClass.Type;
3036 loc = l;
3039 protected override TypeExpr DoResolveAsTypeStep (IMemberContext ec)
3041 return this;
3044 public override TypeExpr ResolveAsTypeTerminal (IMemberContext ec, bool silent)
3046 return this;
3051 // Used to create types from a fully qualified name. These are just used
3052 // by the parser to setup the core types.
3054 public sealed class TypeLookupExpression : TypeExpr {
3055 readonly string ns_name;
3056 readonly string name;
3058 public TypeLookupExpression (string ns, string name)
3060 this.name = name;
3061 this.ns_name = ns;
3062 eclass = ExprClass.Type;
3065 public override TypeExpr ResolveAsTypeTerminal (IMemberContext ec, bool silent)
3068 // It's null only during mscorlib bootstrap when DefineType
3069 // nees to resolve base type of same type
3071 // For instance struct Char : IComparable<char>
3073 // TODO: it could be removed when Resolve starts to use
3074 // DeclSpace instead of Type
3076 if (type == null) {
3077 Namespace ns = GlobalRootNamespace.Instance.GetNamespace (ns_name, false);
3078 FullNamedExpression fne = ns.Lookup (ec.Compiler, name, loc);
3079 if (fne != null)
3080 type = fne.Type;
3083 return this;
3086 protected override TypeExpr DoResolveAsTypeStep (IMemberContext ec)
3088 return this;
3091 public override string GetSignatureForError ()
3093 if (type == null)
3094 return TypeManager.CSharpName (ns_name + "." + name, null);
3096 return base.GetSignatureForError ();
3100 /// <summary>
3101 /// This class denotes an expression which evaluates to a member
3102 /// of a struct or a class.
3103 /// </summary>
3104 public abstract class MemberExpr : Expression
3106 protected bool is_base;
3108 /// <summary>
3109 /// The name of this member.
3110 /// </summary>
3111 public abstract string Name {
3112 get;
3116 // When base.member is used
3118 public bool IsBase {
3119 get { return is_base; }
3120 set { is_base = value; }
3123 /// <summary>
3124 /// Whether this is an instance member.
3125 /// </summary>
3126 public abstract bool IsInstance {
3127 get;
3130 /// <summary>
3131 /// Whether this is a static member.
3132 /// </summary>
3133 public abstract bool IsStatic {
3134 get;
3137 /// <summary>
3138 /// The type which declares this member.
3139 /// </summary>
3140 public abstract Type DeclaringType {
3141 get;
3144 /// <summary>
3145 /// The instance expression associated with this member, if it's a
3146 /// non-static member.
3147 /// </summary>
3148 public Expression InstanceExpression;
3150 public static void error176 (ResolveContext ec, Location loc, string name)
3152 ec.Report.Error (176, loc, "Static member `{0}' cannot be accessed " +
3153 "with an instance reference, qualify it with a type name instead", name);
3156 public static void Error_BaseAccessInExpressionTree (ResolveContext ec, Location loc)
3158 ec.Report.Error (831, loc, "An expression tree may not contain a base access");
3161 public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
3163 if (InstanceExpression != null)
3164 InstanceExpression.MutateHoistedGenericType (storey);
3167 // TODO: possible optimalization
3168 // Cache resolved constant result in FieldBuilder <-> expression map
3169 public virtual MemberExpr ResolveMemberAccess (ResolveContext ec, Expression left, Location loc,
3170 SimpleName original)
3173 // Precondition:
3174 // original == null || original.Resolve (...) ==> left
3177 if (left is TypeExpr) {
3178 left = left.ResolveAsBaseTerminal (ec, false);
3179 if (left == null)
3180 return null;
3182 // TODO: Same problem as in class.cs, TypeTerminal does not
3183 // always do all necessary checks
3184 ObsoleteAttribute oa = AttributeTester.GetObsoleteAttribute (left.Type);
3185 if (oa != null && !ec.IsObsolete) {
3186 AttributeTester.Report_ObsoleteMessage (oa, left.GetSignatureForError (), loc, ec.Report);
3189 GenericTypeExpr ct = left as GenericTypeExpr;
3190 if (ct != null && !ct.CheckConstraints (ec))
3191 return null;
3194 if (!IsStatic) {
3195 SimpleName.Error_ObjectRefRequired (ec, loc, GetSignatureForError ());
3196 return null;
3199 return this;
3202 if (!IsInstance) {
3203 if (original != null && original.IdenticalNameAndTypeName (ec, left, loc))
3204 return this;
3206 return ResolveExtensionMemberAccess (ec, left);
3209 InstanceExpression = left;
3210 return this;
3213 protected virtual MemberExpr ResolveExtensionMemberAccess (ResolveContext ec, Expression left)
3215 error176 (ec, loc, GetSignatureForError ());
3216 return this;
3219 protected void EmitInstance (EmitContext ec, bool prepare_for_load)
3221 if (IsStatic)
3222 return;
3224 if (InstanceExpression == EmptyExpression.Null) {
3225 // FIXME: This should not be here at all
3226 SimpleName.Error_ObjectRefRequired (new ResolveContext (ec.MemberContext), loc, GetSignatureForError ());
3227 return;
3230 if (TypeManager.IsValueType (InstanceExpression.Type)) {
3231 if (InstanceExpression is IMemoryLocation) {
3232 ((IMemoryLocation) InstanceExpression).AddressOf (ec, AddressOp.LoadStore);
3233 } else {
3234 LocalTemporary t = new LocalTemporary (InstanceExpression.Type);
3235 InstanceExpression.Emit (ec);
3236 t.Store (ec);
3237 t.AddressOf (ec, AddressOp.Store);
3239 } else
3240 InstanceExpression.Emit (ec);
3242 if (prepare_for_load)
3243 ec.ig.Emit (OpCodes.Dup);
3246 public virtual void SetTypeArguments (ResolveContext ec, TypeArguments ta)
3248 // TODO: need to get correct member type
3249 ec.Report.Error (307, loc, "The property `{0}' cannot be used with type arguments",
3250 GetSignatureForError ());
3254 ///
3255 /// Represents group of extension methods
3256 ///
3257 public class ExtensionMethodGroupExpr : MethodGroupExpr
3259 readonly NamespaceEntry namespace_entry;
3260 public Expression ExtensionExpression;
3261 Argument extension_argument;
3263 public ExtensionMethodGroupExpr (ArrayList list, NamespaceEntry n, Type extensionType, Location l)
3264 : base (list, extensionType, l)
3266 this.namespace_entry = n;
3269 public override bool IsStatic {
3270 get { return true; }
3273 public bool IsTopLevel {
3274 get { return namespace_entry == null; }
3277 public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
3279 extension_argument.Expr.MutateHoistedGenericType (storey);
3280 base.MutateHoistedGenericType (storey);
3283 public override MethodGroupExpr OverloadResolve (ResolveContext ec, ref Arguments arguments, bool may_fail, Location loc)
3285 if (arguments == null)
3286 arguments = new Arguments (1);
3288 arguments.Insert (0, new Argument (ExtensionExpression));
3289 MethodGroupExpr mg = ResolveOverloadExtensions (ec, ref arguments, namespace_entry, loc);
3291 // Store resolved argument and restore original arguments
3292 if (mg != null)
3293 ((ExtensionMethodGroupExpr)mg).extension_argument = arguments [0];
3294 else
3295 arguments.RemoveAt (0); // Clean-up modified arguments for error reporting
3297 return mg;
3300 MethodGroupExpr ResolveOverloadExtensions (ResolveContext ec, ref Arguments arguments, NamespaceEntry ns, Location loc)
3302 // Use normal resolve rules
3303 MethodGroupExpr mg = base.OverloadResolve (ec, ref arguments, ns != null, loc);
3304 if (mg != null)
3305 return mg;
3307 if (ns == null)
3308 return null;
3310 // Search continues
3311 ExtensionMethodGroupExpr e = ns.LookupExtensionMethod (type, Name, loc);
3312 if (e == null)
3313 return base.OverloadResolve (ec, ref arguments, false, loc);
3315 e.ExtensionExpression = ExtensionExpression;
3316 e.SetTypeArguments (ec, type_arguments);
3317 return e.ResolveOverloadExtensions (ec, ref arguments, e.namespace_entry, loc);
3321 /// <summary>
3322 /// MethodGroupExpr represents a group of method candidates which
3323 /// can be resolved to the best method overload
3324 /// </summary>
3325 public class MethodGroupExpr : MemberExpr
3327 public interface IErrorHandler
3329 bool AmbiguousCall (ResolveContext ec, MethodBase ambiguous);
3330 bool NoExactMatch (ResolveContext ec, MethodBase method);
3333 public IErrorHandler CustomErrorHandler;
3334 public MethodBase [] Methods;
3335 MethodBase best_candidate;
3336 // TODO: make private
3337 public TypeArguments type_arguments;
3338 bool identical_type_name;
3339 bool has_inaccessible_candidates_only;
3340 Type delegate_type;
3341 Type queried_type;
3343 public MethodGroupExpr (MemberInfo [] mi, Type type, Location l)
3344 : this (type, l)
3346 Methods = new MethodBase [mi.Length];
3347 mi.CopyTo (Methods, 0);
3350 public MethodGroupExpr (MemberInfo[] mi, Type type, Location l, bool inacessibleCandidatesOnly)
3351 : this (mi, type, l)
3353 has_inaccessible_candidates_only = inacessibleCandidatesOnly;
3356 public MethodGroupExpr (ArrayList list, Type type, Location l)
3357 : this (type, l)
3359 try {
3360 Methods = (MethodBase[])list.ToArray (typeof (MethodBase));
3361 } catch {
3362 foreach (MemberInfo m in list){
3363 if (!(m is MethodBase)){
3364 Console.WriteLine ("Name " + m.Name);
3365 Console.WriteLine ("Found a: " + m.GetType ().FullName);
3368 throw;
3374 protected MethodGroupExpr (Type type, Location loc)
3376 this.loc = loc;
3377 eclass = ExprClass.MethodGroup;
3378 this.type = InternalType.MethodGroup;
3379 queried_type = type;
3382 public override Type DeclaringType {
3383 get {
3384 return queried_type;
3388 public Type DelegateType {
3389 set {
3390 delegate_type = value;
3394 public bool IdenticalTypeName {
3395 get {
3396 return identical_type_name;
3400 public override string GetSignatureForError ()
3402 if (best_candidate != null)
3403 return TypeManager.CSharpSignature (best_candidate);
3405 return TypeManager.CSharpSignature (Methods [0]);
3408 public override string Name {
3409 get {
3410 return Methods [0].Name;
3414 public override bool IsInstance {
3415 get {
3416 if (best_candidate != null)
3417 return !best_candidate.IsStatic;
3419 foreach (MethodBase mb in Methods)
3420 if (!mb.IsStatic)
3421 return true;
3423 return false;
3427 public override bool IsStatic {
3428 get {
3429 if (best_candidate != null)
3430 return best_candidate.IsStatic;
3432 foreach (MethodBase mb in Methods)
3433 if (mb.IsStatic)
3434 return true;
3436 return false;
3440 public static explicit operator ConstructorInfo (MethodGroupExpr mg)
3442 return (ConstructorInfo)mg.best_candidate;
3445 public static explicit operator MethodInfo (MethodGroupExpr mg)
3447 return (MethodInfo)mg.best_candidate;
3451 // 7.4.3.3 Better conversion from expression
3452 // Returns : 1 if a->p is better,
3453 // 2 if a->q is better,
3454 // 0 if neither is better
3456 static int BetterExpressionConversion (ResolveContext ec, Argument a, Type p, Type q)
3458 Type argument_type = TypeManager.TypeToCoreType (a.Type);
3459 if (argument_type == InternalType.AnonymousMethod && RootContext.Version > LanguageVersion.ISO_2) {
3461 // Uwrap delegate from Expression<T>
3463 if (TypeManager.DropGenericTypeArguments (p) == TypeManager.expression_type) {
3464 p = TypeManager.GetTypeArguments (p) [0];
3466 if (TypeManager.DropGenericTypeArguments (q) == TypeManager.expression_type) {
3467 q = TypeManager.GetTypeArguments (q) [0];
3470 p = Delegate.GetInvokeMethod (ec.Compiler, null, p).ReturnType;
3471 q = Delegate.GetInvokeMethod (ec.Compiler, null, q).ReturnType;
3472 if (p == TypeManager.void_type && q != TypeManager.void_type)
3473 return 2;
3474 if (q == TypeManager.void_type && p != TypeManager.void_type)
3475 return 1;
3476 } else {
3477 if (argument_type == p)
3478 return 1;
3480 if (argument_type == q)
3481 return 2;
3484 return BetterTypeConversion (ec, p, q);
3488 // 7.4.3.4 Better conversion from type
3490 public static int BetterTypeConversion (ResolveContext ec, Type p, Type q)
3492 if (p == null || q == null)
3493 throw new InternalErrorException ("BetterTypeConversion got a null conversion");
3495 if (p == TypeManager.int32_type) {
3496 if (q == TypeManager.uint32_type || q == TypeManager.uint64_type)
3497 return 1;
3498 } else if (p == TypeManager.int64_type) {
3499 if (q == TypeManager.uint64_type)
3500 return 1;
3501 } else if (p == TypeManager.sbyte_type) {
3502 if (q == TypeManager.byte_type || q == TypeManager.ushort_type ||
3503 q == TypeManager.uint32_type || q == TypeManager.uint64_type)
3504 return 1;
3505 } else if (p == TypeManager.short_type) {
3506 if (q == TypeManager.ushort_type || q == TypeManager.uint32_type ||
3507 q == TypeManager.uint64_type)
3508 return 1;
3509 } else if (p == InternalType.Dynamic) {
3510 if (q == TypeManager.object_type)
3511 return 2;
3514 if (q == TypeManager.int32_type) {
3515 if (p == TypeManager.uint32_type || p == TypeManager.uint64_type)
3516 return 2;
3517 } if (q == TypeManager.int64_type) {
3518 if (p == TypeManager.uint64_type)
3519 return 2;
3520 } else if (q == TypeManager.sbyte_type) {
3521 if (p == TypeManager.byte_type || p == TypeManager.ushort_type ||
3522 p == TypeManager.uint32_type || p == TypeManager.uint64_type)
3523 return 2;
3524 } if (q == TypeManager.short_type) {
3525 if (p == TypeManager.ushort_type || p == TypeManager.uint32_type ||
3526 p == TypeManager.uint64_type)
3527 return 2;
3528 } else if (q == InternalType.Dynamic) {
3529 if (p == TypeManager.object_type)
3530 return 1;
3533 // TODO: this is expensive
3534 Expression p_tmp = new EmptyExpression (p);
3535 Expression q_tmp = new EmptyExpression (q);
3537 bool p_to_q = Convert.ImplicitConversionExists (ec, p_tmp, q);
3538 bool q_to_p = Convert.ImplicitConversionExists (ec, q_tmp, p);
3540 if (p_to_q && !q_to_p)
3541 return 1;
3543 if (q_to_p && !p_to_q)
3544 return 2;
3546 return 0;
3549 /// <summary>
3550 /// Determines "Better function" between candidate
3551 /// and the current best match
3552 /// </summary>
3553 /// <remarks>
3554 /// Returns a boolean indicating :
3555 /// false if candidate ain't better
3556 /// true if candidate is better than the current best match
3557 /// </remarks>
3558 static bool BetterFunction (ResolveContext ec, Arguments args, int argument_count,
3559 MethodBase candidate, bool candidate_params,
3560 MethodBase best, bool best_params)
3562 AParametersCollection candidate_pd = TypeManager.GetParameterData (candidate);
3563 AParametersCollection best_pd = TypeManager.GetParameterData (best);
3565 bool better_at_least_one = false;
3566 bool same = true;
3567 for (int j = 0, c_idx = 0, b_idx = 0; j < argument_count; ++j, ++c_idx, ++b_idx)
3569 Argument a = args [j];
3571 // Provided default argument value is never better
3572 if (a.IsDefaultArgument && candidate_params == best_params)
3573 return false;
3575 Type ct = candidate_pd.Types [c_idx];
3576 Type bt = best_pd.Types [b_idx];
3578 if (candidate_params && candidate_pd.FixedParameters [c_idx].ModFlags == Parameter.Modifier.PARAMS)
3580 ct = TypeManager.GetElementType (ct);
3581 --c_idx;
3584 if (best_params && best_pd.FixedParameters [b_idx].ModFlags == Parameter.Modifier.PARAMS)
3586 bt = TypeManager.GetElementType (bt);
3587 --b_idx;
3590 if (ct == bt)
3591 continue;
3593 same = false;
3594 int result = BetterExpressionConversion (ec, a, ct, bt);
3596 // for each argument, the conversion to 'ct' should be no worse than
3597 // the conversion to 'bt'.
3598 if (result == 2)
3599 return false;
3601 // for at least one argument, the conversion to 'ct' should be better than
3602 // the conversion to 'bt'.
3603 if (result != 0)
3604 better_at_least_one = true;
3607 if (better_at_least_one)
3608 return true;
3611 // This handles the case
3613 // Add (float f1, float f2, float f3);
3614 // Add (params decimal [] foo);
3616 // The call Add (3, 4, 5) should be ambiguous. Without this check, the
3617 // first candidate would've chosen as better.
3619 if (!same)
3620 return false;
3623 // The two methods have equal parameter types. Now apply tie-breaking rules
3625 if (TypeManager.IsGenericMethod (best)) {
3626 if (!TypeManager.IsGenericMethod (candidate))
3627 return true;
3628 } else if (TypeManager.IsGenericMethod (candidate)) {
3629 return false;
3633 // This handles the following cases:
3635 // Trim () is better than Trim (params char[] chars)
3636 // Concat (string s1, string s2, string s3) is better than
3637 // Concat (string s1, params string [] srest)
3638 // Foo (int, params int [] rest) is better than Foo (params int [] rest)
3640 if (!candidate_params && best_params)
3641 return true;
3642 if (candidate_params && !best_params)
3643 return false;
3645 int candidate_param_count = candidate_pd.Count;
3646 int best_param_count = best_pd.Count;
3648 if (candidate_param_count != best_param_count)
3649 // can only happen if (candidate_params && best_params)
3650 return candidate_param_count > best_param_count && best_pd.HasParams;
3653 // now, both methods have the same number of parameters, and the parameters have the same types
3654 // Pick the "more specific" signature
3657 MethodBase orig_candidate = TypeManager.DropGenericMethodArguments (candidate);
3658 MethodBase orig_best = TypeManager.DropGenericMethodArguments (best);
3660 AParametersCollection orig_candidate_pd = TypeManager.GetParameterData (orig_candidate);
3661 AParametersCollection orig_best_pd = TypeManager.GetParameterData (orig_best);
3663 bool specific_at_least_once = false;
3664 for (int j = 0; j < candidate_param_count; ++j)
3666 Type ct = orig_candidate_pd.Types [j];
3667 Type bt = orig_best_pd.Types [j];
3668 if (ct.Equals (bt))
3669 continue;
3670 Type specific = MoreSpecific (ct, bt);
3671 if (specific == bt)
3672 return false;
3673 if (specific == ct)
3674 specific_at_least_once = true;
3677 if (specific_at_least_once)
3678 return true;
3680 // FIXME: handle lifted operators
3681 // ...
3683 return false;
3686 protected override MemberExpr ResolveExtensionMemberAccess (ResolveContext ec, Expression left)
3688 if (!IsStatic)
3689 return base.ResolveExtensionMemberAccess (ec, left);
3692 // When left side is an expression and at least one candidate method is
3693 // static, it can be extension method
3695 InstanceExpression = left;
3696 return this;
3699 public override MemberExpr ResolveMemberAccess (ResolveContext ec, Expression left, Location loc,
3700 SimpleName original)
3702 if (!(left is TypeExpr) &&
3703 original != null && original.IdenticalNameAndTypeName (ec, left, loc))
3704 identical_type_name = true;
3706 return base.ResolveMemberAccess (ec, left, loc, original);
3709 public override Expression CreateExpressionTree (ResolveContext ec)
3711 if (best_candidate == null) {
3712 ec.Report.Error (1953, loc, "An expression tree cannot contain an expression with method group");
3713 return null;
3716 IMethodData md = TypeManager.GetMethod (best_candidate);
3717 if (md != null && md.IsExcluded ())
3718 ec.Report.Error (765, loc,
3719 "Partial methods with only a defining declaration or removed conditional methods cannot be used in an expression tree");
3721 return new TypeOfMethod (best_candidate, loc);
3724 protected override Expression DoResolve (ResolveContext ec)
3726 this.eclass = ExprClass.MethodGroup;
3728 if (InstanceExpression != null) {
3729 InstanceExpression = InstanceExpression.Resolve (ec);
3730 if (InstanceExpression == null)
3731 return null;
3734 return this;
3737 public void ReportUsageError (ResolveContext ec)
3739 ec.Report.Error (654, loc, "Method `" + DeclaringType + "." +
3740 Name + "()' is referenced without parentheses");
3743 override public void Emit (EmitContext ec)
3745 throw new NotSupportedException ();
3746 // ReportUsageError ();
3749 public void EmitCall (EmitContext ec, Arguments arguments)
3751 Invocation.EmitCall (ec, IsBase, InstanceExpression, best_candidate, arguments, loc);
3754 void Error_AmbiguousCall (ResolveContext ec, MethodBase ambiguous)
3756 if (CustomErrorHandler != null && CustomErrorHandler.AmbiguousCall (ec, ambiguous))
3757 return;
3759 ec.Report.SymbolRelatedToPreviousError (best_candidate);
3760 ec.Report.Error (121, loc, "The call is ambiguous between the following methods or properties: `{0}' and `{1}'",
3761 TypeManager.CSharpSignature (ambiguous), TypeManager.CSharpSignature (best_candidate));
3764 protected virtual void Error_InvalidArguments (ResolveContext ec, Location loc, int idx, MethodBase method,
3765 Argument a, AParametersCollection expected_par, Type paramType)
3767 ExtensionMethodGroupExpr emg = this as ExtensionMethodGroupExpr;
3769 if (a is CollectionElementInitializer.ElementInitializerArgument) {
3770 ec.Report.SymbolRelatedToPreviousError (method);
3771 if ((expected_par.FixedParameters [idx].ModFlags & Parameter.Modifier.ISBYREF) != 0) {
3772 ec.Report.Error (1954, loc, "The best overloaded collection initalizer method `{0}' cannot have 'ref', or `out' modifier",
3773 TypeManager.CSharpSignature (method));
3774 return;
3776 ec.Report.Error (1950, loc, "The best overloaded collection initalizer method `{0}' has some invalid arguments",
3777 TypeManager.CSharpSignature (method));
3778 } else if (TypeManager.IsDelegateType (method.DeclaringType)) {
3779 ec.Report.Error (1594, loc, "Delegate `{0}' has some invalid arguments",
3780 TypeManager.CSharpName (method.DeclaringType));
3781 } else {
3782 ec.Report.SymbolRelatedToPreviousError (method);
3783 if (emg != null) {
3784 ec.Report.Error (1928, loc,
3785 "Type `{0}' does not contain a member `{1}' and the best extension method overload `{2}' has some invalid arguments",
3786 emg.ExtensionExpression.GetSignatureForError (),
3787 emg.Name, TypeManager.CSharpSignature (method));
3788 } else {
3789 ec.Report.Error (1502, loc, "The best overloaded method match for `{0}' has some invalid arguments",
3790 TypeManager.CSharpSignature (method));
3794 Parameter.Modifier mod = idx >= expected_par.Count ? 0 : expected_par.FixedParameters [idx].ModFlags;
3796 string index = (idx + 1).ToString ();
3797 if (((mod & (Parameter.Modifier.REF | Parameter.Modifier.OUT)) ^
3798 (a.Modifier & (Parameter.Modifier.REF | Parameter.Modifier.OUT))) != 0) {
3799 if ((mod & Parameter.Modifier.ISBYREF) == 0)
3800 ec.Report.Error (1615, loc, "Argument `#{0}' does not require `{1}' modifier. Consider removing `{1}' modifier",
3801 index, Parameter.GetModifierSignature (a.Modifier));
3802 else
3803 ec.Report.Error (1620, loc, "Argument `#{0}' is missing `{1}' modifier",
3804 index, Parameter.GetModifierSignature (mod));
3805 } else {
3806 string p1 = a.GetSignatureForError ();
3807 string p2 = TypeManager.CSharpName (paramType);
3809 if (p1 == p2) {
3810 ec.Report.ExtraInformation (loc, "(equally named types possibly from different assemblies in previous ");
3811 ec.Report.SymbolRelatedToPreviousError (a.Expr.Type);
3812 ec.Report.SymbolRelatedToPreviousError (paramType);
3815 if (idx == 0 && emg != null) {
3816 ec.Report.Error (1929, loc,
3817 "Extension method instance type `{0}' cannot be converted to `{1}'", p1, p2);
3818 } else {
3819 ec.Report.Error (1503, loc,
3820 "Argument `#{0}' cannot convert `{1}' expression to type `{2}'", index, p1, p2);
3825 public override void Error_ValueCannotBeConverted (ResolveContext ec, Location loc, Type target, bool expl)
3827 ec.Report.Error (428, loc, "Cannot convert method group `{0}' to non-delegate type `{1}'. Consider using parentheses to invoke the method",
3828 Name, TypeManager.CSharpName (target));
3831 void Error_ArgumentCountWrong (ResolveContext ec, int arg_count)
3833 ec.Report.Error (1501, loc, "No overload for method `{0}' takes `{1}' arguments",
3834 Name, arg_count.ToString ());
3837 protected virtual int GetApplicableParametersCount (MethodBase method, AParametersCollection parameters)
3839 return parameters.Count;
3842 public static bool IsAncestralType (Type first_type, Type second_type)
3844 return first_type != second_type &&
3845 (TypeManager.IsSubclassOf (second_type, first_type) ||
3846 TypeManager.ImplementsInterface (second_type, first_type));
3850 /// Determines if the candidate method is applicable (section 14.4.2.1)
3851 /// to the given set of arguments
3852 /// A return value rates candidate method compatibility,
3853 /// 0 = the best, int.MaxValue = the worst
3855 public int IsApplicable (ResolveContext ec,
3856 ref Arguments arguments, int arg_count, ref MethodBase method, ref bool params_expanded_form)
3858 MethodBase candidate = method;
3860 AParametersCollection pd = TypeManager.GetParameterData (candidate);
3861 int param_count = GetApplicableParametersCount (candidate, pd);
3862 int optional_count = 0;
3864 if (arg_count != param_count) {
3865 for (int i = 0; i < pd.Count; ++i) {
3866 if (pd.FixedParameters [i].HasDefaultValue) {
3867 optional_count = pd.Count - i;
3868 break;
3872 int args_gap = Math.Abs (arg_count - param_count);
3873 if (optional_count != 0) {
3874 if (args_gap > optional_count)
3875 return int.MaxValue - 10000 + args_gap - optional_count;
3877 // Readjust expected number when params used
3878 if (pd.HasParams) {
3879 optional_count--;
3880 if (arg_count < param_count)
3881 param_count--;
3882 } else if (arg_count > param_count) {
3883 return int.MaxValue - 10000 + args_gap;
3885 } else if (arg_count != param_count) {
3886 if (!pd.HasParams)
3887 return int.MaxValue - 10000 + args_gap;
3888 if (arg_count < param_count - 1)
3889 return int.MaxValue - 10000 + args_gap;
3892 // Initialize expanded form of a method with 1 params parameter
3893 params_expanded_form = param_count == 1 && pd.HasParams;
3895 // Resize to fit optional arguments
3896 if (optional_count != 0) {
3897 Arguments resized;
3898 if (arguments == null) {
3899 resized = new Arguments (optional_count);
3900 } else {
3901 resized = new Arguments (param_count);
3902 resized.AddRange (arguments);
3905 for (int i = arg_count; i < param_count; ++i)
3906 resized.Add (null);
3907 arguments = resized;
3911 if (arg_count > 0) {
3913 // Shuffle named arguments to the right positions if there are any
3915 if (arguments [arg_count - 1] is NamedArgument) {
3916 arg_count = arguments.Count;
3918 for (int i = 0; i < arg_count; ++i) {
3919 bool arg_moved = false;
3920 while (true) {
3921 NamedArgument na = arguments[i] as NamedArgument;
3922 if (na == null)
3923 break;
3925 int index = pd.GetParameterIndexByName (na.Name);
3927 // Named parameter not found or already reordered
3928 if (index <= i)
3929 break;
3931 // When using parameters which should not be available to the user
3932 if (index >= param_count)
3933 break;
3935 if (!arg_moved) {
3936 arguments.MarkReorderedArgument (na);
3937 arg_moved = true;
3940 Argument temp = arguments[index];
3941 arguments[index] = arguments[i];
3942 arguments[i] = temp;
3944 if (temp == null)
3945 break;
3948 } else {
3949 arg_count = arguments.Count;
3951 } else if (arguments != null) {
3952 arg_count = arguments.Count;
3956 // 1. Handle generic method using type arguments when specified or type inference
3958 if (TypeManager.IsGenericMethod (candidate)) {
3959 if (type_arguments != null) {
3960 Type [] g_args = candidate.GetGenericArguments ();
3961 if (g_args.Length != type_arguments.Count)
3962 return int.MaxValue - 20000 + Math.Abs (type_arguments.Count - g_args.Length);
3964 // TODO: Don't create new method, create Parameters only
3965 method = ((MethodInfo) candidate).MakeGenericMethod (type_arguments.Arguments);
3966 candidate = method;
3967 pd = TypeManager.GetParameterData (candidate);
3968 } else {
3969 int score = TypeManager.InferTypeArguments (ec, arguments, ref candidate);
3970 if (score != 0)
3971 return score - 20000;
3973 if (TypeManager.IsGenericMethodDefinition (candidate))
3974 throw new InternalErrorException ("A generic method `{0}' definition took part in overload resolution",
3975 TypeManager.CSharpSignature (candidate));
3977 pd = TypeManager.GetParameterData (candidate);
3979 } else {
3980 if (type_arguments != null)
3981 return int.MaxValue - 15000;
3985 // 2. Each argument has to be implicitly convertible to method parameter
3987 method = candidate;
3988 Parameter.Modifier p_mod = 0;
3989 Type pt = null;
3990 for (int i = 0; i < arg_count; i++) {
3991 Argument a = arguments [i];
3992 if (a == null) {
3993 if (!pd.FixedParameters [i].HasDefaultValue)
3994 throw new InternalErrorException ();
3996 Expression e = pd.FixedParameters [i].DefaultValue as Constant;
3997 if (e == null)
3998 e = new DefaultValueExpression (new TypeExpression (pd.Types [i], loc), loc).Resolve (ec);
4000 arguments [i] = new Argument (e, Argument.AType.Default);
4001 continue;
4004 if (p_mod != Parameter.Modifier.PARAMS) {
4005 p_mod = pd.FixedParameters [i].ModFlags & ~(Parameter.Modifier.OUTMASK | Parameter.Modifier.REFMASK);
4006 pt = pd.Types [i];
4007 } else {
4008 params_expanded_form = true;
4011 Parameter.Modifier a_mod = a.Modifier & ~(Parameter.Modifier.OUTMASK | Parameter.Modifier.REFMASK);
4012 int score = 1;
4013 if (!params_expanded_form)
4014 score = IsArgumentCompatible (ec, a_mod, a, p_mod & ~Parameter.Modifier.PARAMS, pt);
4016 if (score != 0 && (p_mod & Parameter.Modifier.PARAMS) != 0 && delegate_type == null) {
4017 // It can be applicable in expanded form
4018 score = IsArgumentCompatible (ec, a_mod, a, 0, TypeManager.GetElementType (pt));
4019 if (score == 0)
4020 params_expanded_form = true;
4023 if (score != 0) {
4024 if (params_expanded_form)
4025 ++score;
4026 return (arg_count - i) * 2 + score;
4030 if (arg_count != param_count)
4031 params_expanded_form = true;
4033 return 0;
4036 int IsArgumentCompatible (ResolveContext ec, Parameter.Modifier arg_mod, Argument argument, Parameter.Modifier param_mod, Type parameter)
4039 // Types have to be identical when ref or out modifer is used
4041 if (arg_mod != 0 || param_mod != 0) {
4042 if (TypeManager.HasElementType (parameter))
4043 parameter = TypeManager.GetElementType (parameter);
4045 Type a_type = argument.Type;
4046 if (TypeManager.HasElementType (a_type))
4047 a_type = TypeManager.GetElementType (a_type);
4049 if (a_type != parameter) {
4050 if (TypeManager.IsDynamicType (a_type))
4051 return 0;
4053 return 2;
4055 } else {
4056 if (!Convert.ImplicitConversionExists (ec, argument.Expr, parameter)) {
4057 if (TypeManager.IsDynamicType (argument.Type))
4058 return 0;
4060 return 2;
4064 if (arg_mod != param_mod)
4065 return 1;
4067 return 0;
4070 public static bool IsOverride (MethodBase cand_method, MethodBase base_method)
4072 if (!IsAncestralType (base_method.DeclaringType, cand_method.DeclaringType))
4073 return false;
4075 AParametersCollection cand_pd = TypeManager.GetParameterData (cand_method);
4076 AParametersCollection base_pd = TypeManager.GetParameterData (base_method);
4078 if (cand_pd.Count != base_pd.Count)
4079 return false;
4081 for (int j = 0; j < cand_pd.Count; ++j)
4083 Parameter.Modifier cm = cand_pd.FixedParameters [j].ModFlags;
4084 Parameter.Modifier bm = base_pd.FixedParameters [j].ModFlags;
4085 Type ct = cand_pd.Types [j];
4086 Type bt = base_pd.Types [j];
4088 if (cm != bm || ct != bt)
4089 return false;
4092 return true;
4095 public static MethodGroupExpr MakeUnionSet (MethodGroupExpr mg1, MethodGroupExpr mg2, Location loc)
4097 if (mg1 == null) {
4098 if (mg2 == null)
4099 return null;
4100 return mg2;
4103 if (mg2 == null)
4104 return mg1;
4106 ArrayList all = new ArrayList (mg1.Methods);
4107 foreach (MethodBase m in mg2.Methods){
4108 if (!TypeManager.ArrayContainsMethod (mg1.Methods, m, false))
4109 all.Add (m);
4112 return new MethodGroupExpr (all, null, loc);
4115 static Type MoreSpecific (Type p, Type q)
4117 if (TypeManager.IsGenericParameter (p) && !TypeManager.IsGenericParameter (q))
4118 return q;
4119 if (!TypeManager.IsGenericParameter (p) && TypeManager.IsGenericParameter (q))
4120 return p;
4122 if (TypeManager.HasElementType (p))
4124 Type pe = TypeManager.GetElementType (p);
4125 Type qe = TypeManager.GetElementType (q);
4126 Type specific = MoreSpecific (pe, qe);
4127 if (specific == pe)
4128 return p;
4129 if (specific == qe)
4130 return q;
4132 else if (TypeManager.IsGenericType (p))
4134 Type[] pargs = TypeManager.GetTypeArguments (p);
4135 Type[] qargs = TypeManager.GetTypeArguments (q);
4137 bool p_specific_at_least_once = false;
4138 bool q_specific_at_least_once = false;
4140 for (int i = 0; i < pargs.Length; i++)
4142 Type specific = MoreSpecific (TypeManager.TypeToCoreType (pargs [i]), TypeManager.TypeToCoreType (qargs [i]));
4143 if (specific == pargs [i])
4144 p_specific_at_least_once = true;
4145 if (specific == qargs [i])
4146 q_specific_at_least_once = true;
4149 if (p_specific_at_least_once && !q_specific_at_least_once)
4150 return p;
4151 if (!p_specific_at_least_once && q_specific_at_least_once)
4152 return q;
4155 return null;
4158 public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
4160 base.MutateHoistedGenericType (storey);
4162 MethodInfo mi = best_candidate as MethodInfo;
4163 if (mi != null) {
4164 best_candidate = storey.MutateGenericMethod (mi);
4165 return;
4168 best_candidate = storey.MutateConstructor ((ConstructorInfo) this);
4171 /// <summary>
4172 /// Find the Applicable Function Members (7.4.2.1)
4174 /// me: Method Group expression with the members to select.
4175 /// it might contain constructors or methods (or anything
4176 /// that maps to a method).
4178 /// Arguments: ArrayList containing resolved Argument objects.
4180 /// loc: The location if we want an error to be reported, or a Null
4181 /// location for "probing" purposes.
4183 /// Returns: The MethodBase (either a ConstructorInfo or a MethodInfo)
4184 /// that is the best match of me on Arguments.
4186 /// </summary>
4187 public virtual MethodGroupExpr OverloadResolve (ResolveContext ec, ref Arguments Arguments,
4188 bool may_fail, Location loc)
4190 bool method_params = false;
4191 Type applicable_type = null;
4192 ArrayList candidates = new ArrayList (2);
4193 ArrayList candidate_overrides = null;
4196 // Used to keep a map between the candidate
4197 // and whether it is being considered in its
4198 // normal or expanded form
4200 // false is normal form, true is expanded form
4202 Hashtable candidate_to_form = null;
4203 Hashtable candidates_expanded = null;
4204 Arguments candidate_args = Arguments;
4206 int arg_count = Arguments != null ? Arguments.Count : 0;
4208 if (RootContext.Version == LanguageVersion.ISO_1 && Name == "Invoke" && TypeManager.IsDelegateType (DeclaringType)) {
4209 if (!may_fail)
4210 ec.Report.Error (1533, loc, "Invoke cannot be called directly on a delegate");
4211 return null;
4214 int nmethods = Methods.Length;
4216 if (!IsBase) {
4218 // Methods marked 'override' don't take part in 'applicable_type'
4219 // computation, nor in the actual overload resolution.
4220 // However, they still need to be emitted instead of a base virtual method.
4221 // So, we salt them away into the 'candidate_overrides' array.
4223 // In case of reflected methods, we replace each overriding method with
4224 // its corresponding base virtual method. This is to improve compatibility
4225 // with non-C# libraries which change the visibility of overrides (#75636)
4227 int j = 0;
4228 for (int i = 0; i < Methods.Length; ++i) {
4229 MethodBase m = Methods [i];
4230 if (TypeManager.IsOverride (m)) {
4231 if (candidate_overrides == null)
4232 candidate_overrides = new ArrayList ();
4233 candidate_overrides.Add (m);
4234 m = TypeManager.TryGetBaseDefinition (m);
4236 if (m != null)
4237 Methods [j++] = m;
4239 nmethods = j;
4243 // Enable message recording, it's used mainly by lambda expressions
4245 SessionReportPrinter msg_recorder = new SessionReportPrinter ();
4246 ReportPrinter prev_recorder = ec.Report.SetPrinter (msg_recorder);
4249 // First we construct the set of applicable methods
4251 bool is_sorted = true;
4252 int best_candidate_rate = int.MaxValue;
4253 for (int i = 0; i < nmethods; i++) {
4254 Type decl_type = Methods [i].DeclaringType;
4257 // If we have already found an applicable method
4258 // we eliminate all base types (Section 14.5.5.1)
4260 if (applicable_type != null && IsAncestralType (decl_type, applicable_type))
4261 continue;
4264 // Check if candidate is applicable (section 14.4.2.1)
4266 bool params_expanded_form = false;
4267 int candidate_rate = IsApplicable (ec, ref candidate_args, arg_count, ref Methods [i], ref params_expanded_form);
4269 if (candidate_rate < best_candidate_rate) {
4270 best_candidate_rate = candidate_rate;
4271 best_candidate = Methods [i];
4274 if (params_expanded_form) {
4275 if (candidate_to_form == null)
4276 candidate_to_form = new PtrHashtable ();
4277 MethodBase candidate = Methods [i];
4278 candidate_to_form [candidate] = candidate;
4281 if (candidate_args != Arguments) {
4282 if (candidates_expanded == null)
4283 candidates_expanded = new Hashtable (2);
4285 candidates_expanded.Add (Methods [i], candidate_args);
4286 candidate_args = Arguments;
4289 if (candidate_rate != 0 || has_inaccessible_candidates_only) {
4290 if (msg_recorder != null)
4291 msg_recorder.EndSession ();
4292 continue;
4295 msg_recorder = null;
4296 candidates.Add (Methods [i]);
4298 if (applicable_type == null)
4299 applicable_type = decl_type;
4300 else if (applicable_type != decl_type) {
4301 is_sorted = false;
4302 if (IsAncestralType (applicable_type, decl_type))
4303 applicable_type = decl_type;
4307 ec.Report.SetPrinter (prev_recorder);
4308 if (msg_recorder != null && !msg_recorder.IsEmpty) {
4309 if (!may_fail)
4310 msg_recorder.Merge (prev_recorder);
4312 return null;
4315 int candidate_top = candidates.Count;
4317 if (applicable_type == null) {
4319 // When we found a top level method which does not match and it's
4320 // not an extension method. We start extension methods lookup from here
4322 if (InstanceExpression != null) {
4323 ExtensionMethodGroupExpr ex_method_lookup = ec.LookupExtensionMethod (type, Name, loc);
4324 if (ex_method_lookup != null) {
4325 ex_method_lookup.ExtensionExpression = InstanceExpression;
4326 ex_method_lookup.SetTypeArguments (ec, type_arguments);
4327 return ex_method_lookup.OverloadResolve (ec, ref Arguments, may_fail, loc);
4331 if (may_fail)
4332 return null;
4335 // Okay so we have failed to find exact match so we
4336 // return error info about the closest match
4338 if (best_candidate != null) {
4339 if (CustomErrorHandler != null && !has_inaccessible_candidates_only && CustomErrorHandler.NoExactMatch (ec, best_candidate))
4340 return null;
4342 if (NoExactMatch (ec, ref Arguments, candidate_to_form))
4343 return null;
4347 // We failed to find any method with correct argument count
4349 if (Name == ConstructorInfo.ConstructorName) {
4350 ec.Report.SymbolRelatedToPreviousError (queried_type);
4351 ec.Report.Error (1729, loc,
4352 "The type `{0}' does not contain a constructor that takes `{1}' arguments",
4353 TypeManager.CSharpName (queried_type), arg_count);
4354 } else {
4355 Error_ArgumentCountWrong (ec, arg_count);
4358 return null;
4361 if (arg_count != 0 && Arguments.HasDynamic) {
4362 best_candidate = null;
4363 return this;
4366 if (!is_sorted) {
4368 // At this point, applicable_type is _one_ of the most derived types
4369 // in the set of types containing the methods in this MethodGroup.
4370 // Filter the candidates so that they only contain methods from the
4371 // most derived types.
4374 int finalized = 0; // Number of finalized candidates
4376 do {
4377 // Invariant: applicable_type is a most derived type
4379 // We'll try to complete Section 14.5.5.1 for 'applicable_type' by
4380 // eliminating all it's base types. At the same time, we'll also move
4381 // every unrelated type to the end of the array, and pick the next
4382 // 'applicable_type'.
4384 Type next_applicable_type = null;
4385 int j = finalized; // where to put the next finalized candidate
4386 int k = finalized; // where to put the next undiscarded candidate
4387 for (int i = finalized; i < candidate_top; ++i) {
4388 MethodBase candidate = (MethodBase) candidates [i];
4389 Type decl_type = candidate.DeclaringType;
4391 if (decl_type == applicable_type) {
4392 candidates [k++] = candidates [j];
4393 candidates [j++] = candidates [i];
4394 continue;
4397 if (IsAncestralType (decl_type, applicable_type))
4398 continue;
4400 if (next_applicable_type != null &&
4401 IsAncestralType (decl_type, next_applicable_type))
4402 continue;
4404 candidates [k++] = candidates [i];
4406 if (next_applicable_type == null ||
4407 IsAncestralType (next_applicable_type, decl_type))
4408 next_applicable_type = decl_type;
4411 applicable_type = next_applicable_type;
4412 finalized = j;
4413 candidate_top = k;
4414 } while (applicable_type != null);
4418 // Now we actually find the best method
4421 best_candidate = (MethodBase) candidates [0];
4422 method_params = candidate_to_form != null && candidate_to_form.Contains (best_candidate);
4425 // TODO: Broken inverse order of candidates logic does not work with optional
4426 // parameters used for method overrides and I am not going to fix it for SRE
4428 if (candidates_expanded != null && candidates_expanded.Contains (best_candidate)) {
4429 candidate_args = (Arguments) candidates_expanded [best_candidate];
4430 arg_count = candidate_args.Count;
4433 for (int ix = 1; ix < candidate_top; ix++) {
4434 MethodBase candidate = (MethodBase) candidates [ix];
4436 if (candidate == best_candidate)
4437 continue;
4439 bool cand_params = candidate_to_form != null && candidate_to_form.Contains (candidate);
4441 if (BetterFunction (ec, candidate_args, arg_count,
4442 candidate, cand_params,
4443 best_candidate, method_params)) {
4444 best_candidate = candidate;
4445 method_params = cand_params;
4449 // Now check that there are no ambiguities i.e the selected method
4450 // should be better than all the others
4452 MethodBase ambiguous = null;
4453 for (int ix = 1; ix < candidate_top; ix++) {
4454 MethodBase candidate = (MethodBase) candidates [ix];
4456 if (candidate == best_candidate)
4457 continue;
4459 bool cand_params = candidate_to_form != null && candidate_to_form.Contains (candidate);
4460 if (!BetterFunction (ec, candidate_args, arg_count,
4461 best_candidate, method_params,
4462 candidate, cand_params))
4464 if (!may_fail)
4465 ec.Report.SymbolRelatedToPreviousError (candidate);
4466 ambiguous = candidate;
4470 if (ambiguous != null) {
4471 Error_AmbiguousCall (ec, ambiguous);
4472 return this;
4476 // If the method is a virtual function, pick an override closer to the LHS type.
4478 if (!IsBase && best_candidate.IsVirtual) {
4479 if (TypeManager.IsOverride (best_candidate))
4480 throw new InternalErrorException (
4481 "Should not happen. An 'override' method took part in overload resolution: " + best_candidate);
4483 if (candidate_overrides != null) {
4484 Type[] gen_args = null;
4485 bool gen_override = false;
4486 if (TypeManager.IsGenericMethod (best_candidate))
4487 gen_args = TypeManager.GetGenericArguments (best_candidate);
4489 foreach (MethodBase candidate in candidate_overrides) {
4490 if (TypeManager.IsGenericMethod (candidate)) {
4491 if (gen_args == null)
4492 continue;
4494 if (gen_args.Length != TypeManager.GetGenericArguments (candidate).Length)
4495 continue;
4496 } else {
4497 if (gen_args != null)
4498 continue;
4501 if (IsOverride (candidate, best_candidate)) {
4502 gen_override = true;
4503 best_candidate = candidate;
4507 if (gen_override && gen_args != null) {
4508 best_candidate = ((MethodInfo) best_candidate).MakeGenericMethod (gen_args);
4514 // And now check if the arguments are all
4515 // compatible, perform conversions if
4516 // necessary etc. and return if everything is
4517 // all right
4519 if (!VerifyArgumentsCompat (ec, ref candidate_args, arg_count, best_candidate,
4520 method_params, may_fail, loc))
4521 return null;
4523 if (best_candidate == null)
4524 return null;
4526 MethodBase the_method = TypeManager.DropGenericMethodArguments (best_candidate);
4527 if (TypeManager.IsGenericMethodDefinition (the_method) &&
4528 !ConstraintChecker.CheckConstraints (ec, the_method, best_candidate, loc))
4529 return null;
4532 // Check ObsoleteAttribute on the best method
4534 ObsoleteAttribute oa = AttributeTester.GetMethodObsoleteAttribute (the_method);
4535 if (oa != null && !ec.IsObsolete)
4536 AttributeTester.Report_ObsoleteMessage (oa, GetSignatureForError (), loc, ec.Report);
4538 IMethodData data = TypeManager.GetMethod (the_method);
4539 if (data != null)
4540 data.SetMemberIsUsed ();
4542 Arguments = candidate_args;
4543 return this;
4546 bool NoExactMatch (ResolveContext ec, ref Arguments Arguments, Hashtable candidate_to_form)
4548 AParametersCollection pd = TypeManager.GetParameterData (best_candidate);
4549 int arg_count = Arguments == null ? 0 : Arguments.Count;
4551 if (arg_count == pd.Count || pd.HasParams) {
4552 if (TypeManager.IsGenericMethodDefinition (best_candidate)) {
4553 if (type_arguments == null) {
4554 ec.Report.Error (411, loc,
4555 "The type arguments for method `{0}' cannot be inferred from " +
4556 "the usage. Try specifying the type arguments explicitly",
4557 TypeManager.CSharpSignature (best_candidate));
4558 return true;
4561 Type[] g_args = TypeManager.GetGenericArguments (best_candidate);
4562 if (type_arguments.Count != g_args.Length) {
4563 ec.Report.SymbolRelatedToPreviousError (best_candidate);
4564 ec.Report.Error (305, loc, "Using the generic method `{0}' requires `{1}' type argument(s)",
4565 TypeManager.CSharpSignature (best_candidate),
4566 g_args.Length.ToString ());
4567 return true;
4569 } else {
4570 if (type_arguments != null && !TypeManager.IsGenericMethod (best_candidate)) {
4571 Error_TypeArgumentsCannotBeUsed (ec.Report, loc);
4572 return true;
4576 if (has_inaccessible_candidates_only) {
4577 if (InstanceExpression != null && type != ec.CurrentType && TypeManager.IsNestedFamilyAccessible (ec.CurrentType, best_candidate.DeclaringType)) {
4578 // Although a derived class can access protected members of
4579 // its base class it cannot do so through an instance of the
4580 // base class (CS1540). If the qualifier_type is a base of the
4581 // ec.CurrentType and the lookup succeeds with the latter one,
4582 // then we are in this situation.
4583 Error_CannotAccessProtected (ec, loc, best_candidate, queried_type, ec.CurrentType);
4584 } else {
4585 ec.Report.SymbolRelatedToPreviousError (best_candidate);
4586 ErrorIsInaccesible (loc, GetSignatureForError (), ec.Report);
4590 bool cand_params = candidate_to_form != null && candidate_to_form.Contains (best_candidate);
4591 if (!VerifyArgumentsCompat (ec, ref Arguments, arg_count, best_candidate, cand_params, false, loc))
4592 return true;
4594 if (has_inaccessible_candidates_only)
4595 return true;
4598 return false;
4601 public override void SetTypeArguments (ResolveContext ec, TypeArguments ta)
4603 type_arguments = ta;
4606 public bool VerifyArgumentsCompat (ResolveContext ec, ref Arguments arguments,
4607 int arg_count, MethodBase method,
4608 bool chose_params_expanded,
4609 bool may_fail, Location loc)
4611 AParametersCollection pd = TypeManager.GetParameterData (method);
4612 int param_count = GetApplicableParametersCount (method, pd);
4614 int errors = ec.Report.Errors;
4615 Parameter.Modifier p_mod = 0;
4616 Type pt = null;
4617 int a_idx = 0, a_pos = 0;
4618 Argument a = null;
4619 ArrayList params_initializers = null;
4620 bool has_unsafe_arg = method is MethodInfo ? ((MethodInfo) method).ReturnType.IsPointer : false;
4622 for (; a_idx < arg_count; a_idx++, ++a_pos) {
4623 a = arguments [a_idx];
4624 if (p_mod != Parameter.Modifier.PARAMS) {
4625 p_mod = pd.FixedParameters [a_idx].ModFlags;
4626 pt = pd.Types [a_idx];
4627 has_unsafe_arg |= pt.IsPointer;
4629 if (p_mod == Parameter.Modifier.PARAMS) {
4630 if (chose_params_expanded) {
4631 params_initializers = new ArrayList (arg_count - a_idx);
4632 pt = TypeManager.GetElementType (pt);
4638 // Types have to be identical when ref or out modifer is used
4640 if (a.Modifier != 0 || (p_mod & ~Parameter.Modifier.PARAMS) != 0) {
4641 if ((p_mod & ~Parameter.Modifier.PARAMS) != a.Modifier)
4642 break;
4644 if (!TypeManager.IsEqual (a.Expr.Type, pt))
4645 break;
4647 continue;
4648 } else {
4649 NamedArgument na = a as NamedArgument;
4650 if (na != null) {
4651 int name_index = pd.GetParameterIndexByName (na.Name);
4652 if (name_index < 0 || name_index >= param_count) {
4653 if (DeclaringType != null && TypeManager.IsDelegateType (DeclaringType)) {
4654 ec.Report.SymbolRelatedToPreviousError (DeclaringType);
4655 ec.Report.Error (1746, na.Location,
4656 "The delegate `{0}' does not contain a parameter named `{1}'",
4657 TypeManager.CSharpName (DeclaringType), na.Name);
4658 } else {
4659 ec.Report.SymbolRelatedToPreviousError (best_candidate);
4660 ec.Report.Error (1739, na.Location,
4661 "The best overloaded method match for `{0}' does not contain a parameter named `{1}'",
4662 TypeManager.CSharpSignature (method), na.Name);
4664 } else if (arguments[name_index] != a) {
4665 if (DeclaringType != null && TypeManager.IsDelegateType (DeclaringType))
4666 ec.Report.SymbolRelatedToPreviousError (DeclaringType);
4667 else
4668 ec.Report.SymbolRelatedToPreviousError (best_candidate);
4670 ec.Report.Error (1744, na.Location,
4671 "Named argument `{0}' cannot be used for a parameter which has positional argument specified",
4672 na.Name);
4677 if (TypeManager.IsDynamicType (a.Expr.Type))
4678 continue;
4680 if (delegate_type != null && !Delegate.IsTypeCovariant (a.Expr, pt))
4681 break;
4683 Expression conv = Convert.ImplicitConversion (ec, a.Expr, pt, loc);
4684 if (conv == null)
4685 break;
4688 // Convert params arguments to an array initializer
4690 if (params_initializers != null) {
4691 // we choose to use 'a.Expr' rather than 'conv' so that
4692 // we don't hide the kind of expression we have (esp. CompoundAssign.Helper)
4693 params_initializers.Add (a.Expr);
4694 arguments.RemoveAt (a_idx--);
4695 --arg_count;
4696 continue;
4699 // Update the argument with the implicit conversion
4700 a.Expr = conv;
4703 if (a_idx != arg_count) {
4704 if (!may_fail && ec.Report.Errors == errors) {
4705 if (CustomErrorHandler != null)
4706 CustomErrorHandler.NoExactMatch (ec, best_candidate);
4707 else
4708 Error_InvalidArguments (ec, loc, a_pos, method, a, pd, pt);
4710 return false;
4714 // Fill not provided arguments required by params modifier
4716 if (params_initializers == null && pd.HasParams && arg_count + 1 == param_count) {
4717 if (arguments == null)
4718 arguments = new Arguments (1);
4720 pt = pd.Types [param_count - 1];
4721 pt = TypeManager.GetElementType (pt);
4722 has_unsafe_arg |= pt.IsPointer;
4723 params_initializers = new ArrayList (0);
4727 // Append an array argument with all params arguments
4729 if (params_initializers != null) {
4730 arguments.Add (new Argument (
4731 new ArrayCreation (new TypeExpression (pt, loc), "[]",
4732 params_initializers, loc).Resolve (ec)));
4733 arg_count++;
4736 if (arg_count < param_count) {
4737 if (!may_fail)
4738 Error_ArgumentCountWrong (ec, arg_count);
4739 return false;
4742 if (has_unsafe_arg && !ec.IsUnsafe) {
4743 if (!may_fail)
4744 UnsafeError (ec, loc);
4745 return false;
4748 return true;
4752 public class ConstantExpr : MemberExpr
4754 FieldInfo constant;
4756 public ConstantExpr (FieldInfo constant, Location loc)
4758 this.constant = constant;
4759 this.loc = loc;
4762 public override string Name {
4763 get { throw new NotImplementedException (); }
4766 public override bool IsInstance {
4767 get { return !IsStatic; }
4770 public override bool IsStatic {
4771 get { return constant.IsStatic; }
4774 public override Type DeclaringType {
4775 get { return constant.DeclaringType; }
4778 public override MemberExpr ResolveMemberAccess (ResolveContext ec, Expression left, Location loc, SimpleName original)
4780 constant = TypeManager.GetGenericFieldDefinition (constant);
4782 IConstant ic = TypeManager.GetConstant (constant);
4783 if (ic == null) {
4784 if (constant.IsLiteral) {
4785 ic = new ExternalConstant (constant, ec.Compiler);
4786 } else {
4787 ic = ExternalConstant.CreateDecimal (constant, ec);
4788 // HACK: decimal field was not resolved as constant
4789 if (ic == null)
4790 return new FieldExpr (constant, loc).ResolveMemberAccess (ec, left, loc, original);
4792 TypeManager.RegisterConstant (constant, ic);
4795 return base.ResolveMemberAccess (ec, left, loc, original);
4798 public override Expression CreateExpressionTree (ResolveContext ec)
4800 throw new NotSupportedException ("ET");
4803 protected override Expression DoResolve (ResolveContext rc)
4805 IConstant ic = TypeManager.GetConstant (constant);
4806 if (ic.ResolveValue ()) {
4807 if (!rc.IsObsolete)
4808 ic.CheckObsoleteness (loc);
4811 return ic.CreateConstantReference (rc, loc);
4814 public override void Emit (EmitContext ec)
4816 throw new NotSupportedException ();
4819 public override string GetSignatureForError ()
4821 return TypeManager.GetFullNameSignature (constant);
4825 /// <summary>
4826 /// Fully resolved expression that evaluates to a Field
4827 /// </summary>
4828 public class FieldExpr : MemberExpr, IDynamicAssign, IMemoryLocation, IVariableReference {
4829 public FieldInfo FieldInfo;
4830 readonly Type constructed_generic_type;
4831 VariableInfo variable_info;
4833 LocalTemporary temp;
4834 bool prepared;
4836 protected FieldExpr (Location l)
4838 loc = l;
4841 public FieldExpr (FieldInfo fi, Location l)
4843 FieldInfo = fi;
4844 type = TypeManager.TypeToCoreType (fi.FieldType);
4845 loc = l;
4848 public FieldExpr (FieldInfo fi, Type genericType, Location l)
4849 : this (fi, l)
4851 if (TypeManager.IsGenericTypeDefinition (genericType))
4852 return;
4853 this.constructed_generic_type = genericType;
4856 public override string Name {
4857 get {
4858 return FieldInfo.Name;
4862 public override bool IsInstance {
4863 get {
4864 return !FieldInfo.IsStatic;
4868 public override bool IsStatic {
4869 get {
4870 return FieldInfo.IsStatic;
4874 public override Type DeclaringType {
4875 get {
4876 return FieldInfo.DeclaringType;
4880 public override string GetSignatureForError ()
4882 return TypeManager.GetFullNameSignature (FieldInfo);
4885 public VariableInfo VariableInfo {
4886 get {
4887 return variable_info;
4891 public override MemberExpr ResolveMemberAccess (ResolveContext ec, Expression left, Location loc,
4892 SimpleName original)
4894 FieldInfo fi = TypeManager.GetGenericFieldDefinition (FieldInfo);
4895 Type t = fi.FieldType;
4897 if (t.IsPointer && !ec.IsUnsafe) {
4898 UnsafeError (ec, loc);
4901 return base.ResolveMemberAccess (ec, left, loc, original);
4904 public void SetHasAddressTaken ()
4906 IVariableReference vr = InstanceExpression as IVariableReference;
4907 if (vr != null)
4908 vr.SetHasAddressTaken ();
4911 public override Expression CreateExpressionTree (ResolveContext ec)
4913 Expression instance;
4914 if (InstanceExpression == null) {
4915 instance = new NullLiteral (loc);
4916 } else {
4917 instance = InstanceExpression.CreateExpressionTree (ec);
4920 Arguments args = Arguments.CreateForExpressionTree (ec, null,
4921 instance,
4922 CreateTypeOfExpression ());
4924 return CreateExpressionFactoryCall (ec, "Field", args);
4927 public Expression CreateTypeOfExpression ()
4929 return new TypeOfField (GetConstructedFieldInfo (), loc);
4932 protected override Expression DoResolve (ResolveContext ec)
4934 return DoResolve (ec, false, false);
4937 Expression DoResolve (ResolveContext ec, bool lvalue_instance, bool out_access)
4939 if (!FieldInfo.IsStatic){
4940 if (InstanceExpression == null){
4942 // This can happen when referencing an instance field using
4943 // a fully qualified type expression: TypeName.InstanceField = xxx
4945 SimpleName.Error_ObjectRefRequired (ec, loc, GetSignatureForError ());
4946 return null;
4949 // Resolve the field's instance expression while flow analysis is turned
4950 // off: when accessing a field "a.b", we must check whether the field
4951 // "a.b" is initialized, not whether the whole struct "a" is initialized.
4953 if (lvalue_instance) {
4954 using (ec.With (ResolveContext.Options.DoFlowAnalysis, false)) {
4955 Expression right_side =
4956 out_access ? EmptyExpression.LValueMemberOutAccess : EmptyExpression.LValueMemberAccess;
4958 if (InstanceExpression != EmptyExpression.Null)
4959 InstanceExpression = InstanceExpression.ResolveLValue (ec, right_side);
4961 } else {
4962 if (InstanceExpression != EmptyExpression.Null) {
4963 using (ec.With (ResolveContext.Options.DoFlowAnalysis, false)) {
4964 InstanceExpression = InstanceExpression.Resolve (ec, ResolveFlags.VariableOrValue);
4969 if (InstanceExpression == null)
4970 return null;
4972 using (ec.Set (ResolveContext.Options.OmitStructFlowAnalysis)) {
4973 InstanceExpression.CheckMarshalByRefAccess (ec);
4977 if (!ec.IsObsolete) {
4978 FieldBase f = TypeManager.GetField (FieldInfo);
4979 if (f != null) {
4980 f.CheckObsoleteness (loc);
4981 } else {
4982 ObsoleteAttribute oa = AttributeTester.GetMemberObsoleteAttribute (FieldInfo);
4983 if (oa != null)
4984 AttributeTester.Report_ObsoleteMessage (oa, TypeManager.GetFullNameSignature (FieldInfo), loc, ec.Report);
4988 IFixedBuffer fb = AttributeTester.GetFixedBuffer (FieldInfo);
4989 IVariableReference var = InstanceExpression as IVariableReference;
4991 if (fb != null) {
4992 IFixedExpression fe = InstanceExpression as IFixedExpression;
4993 if (!ec.HasSet (ResolveContext.Options.FixedInitializerScope) && (fe == null || !fe.IsFixed)) {
4994 ec.Report.Error (1666, loc, "You cannot use fixed size buffers contained in unfixed expressions. Try using the fixed statement");
4997 if (InstanceExpression.eclass != ExprClass.Variable) {
4998 ec.Report.SymbolRelatedToPreviousError (FieldInfo);
4999 ec.Report.Error (1708, loc, "`{0}': Fixed size buffers can only be accessed through locals or fields",
5000 TypeManager.GetFullNameSignature (FieldInfo));
5001 } else if (var != null && var.IsHoisted) {
5002 AnonymousMethodExpression.Error_AddressOfCapturedVar (ec, var, loc);
5005 return new FixedBufferPtr (this, fb.ElementType, loc).Resolve (ec);
5008 eclass = ExprClass.Variable;
5010 // If the instance expression is a local variable or parameter.
5011 if (var == null || var.VariableInfo == null)
5012 return this;
5014 VariableInfo vi = var.VariableInfo;
5015 if (!vi.IsFieldAssigned (ec, FieldInfo.Name, loc))
5016 return null;
5018 variable_info = vi.GetSubStruct (FieldInfo.Name);
5019 return this;
5022 static readonly int [] codes = {
5023 191, // instance, write access
5024 192, // instance, out access
5025 198, // static, write access
5026 199, // static, out access
5027 1648, // member of value instance, write access
5028 1649, // member of value instance, out access
5029 1650, // member of value static, write access
5030 1651 // member of value static, out access
5033 static readonly string [] msgs = {
5034 /*0191*/ "A readonly field `{0}' cannot be assigned to (except in a constructor or a variable initializer)",
5035 /*0192*/ "A readonly field `{0}' cannot be passed ref or out (except in a constructor)",
5036 /*0198*/ "A static readonly field `{0}' cannot be assigned to (except in a static constructor or a variable initializer)",
5037 /*0199*/ "A static readonly field `{0}' cannot be passed ref or out (except in a static constructor)",
5038 /*1648*/ "Members of readonly field `{0}' cannot be modified (except in a constructor or a variable initializer)",
5039 /*1649*/ "Members of readonly field `{0}' cannot be passed ref or out (except in a constructor)",
5040 /*1650*/ "Fields of static readonly field `{0}' cannot be assigned to (except in a static constructor or a variable initializer)",
5041 /*1651*/ "Fields of static readonly field `{0}' cannot be passed ref or out (except in a static constructor)"
5044 // The return value is always null. Returning a value simplifies calling code.
5045 Expression Report_AssignToReadonly (ResolveContext ec, Expression right_side)
5047 int i = 0;
5048 if (right_side == EmptyExpression.OutAccess.Instance || right_side == EmptyExpression.LValueMemberOutAccess)
5049 i += 1;
5050 if (IsStatic)
5051 i += 2;
5052 if (right_side == EmptyExpression.LValueMemberAccess || right_side == EmptyExpression.LValueMemberOutAccess)
5053 i += 4;
5054 ec.Report.Error (codes [i], loc, msgs [i], GetSignatureForError ());
5056 return null;
5059 override public Expression DoResolveLValue (ResolveContext ec, Expression right_side)
5061 IVariableReference var = InstanceExpression as IVariableReference;
5062 if (var != null && var.VariableInfo != null)
5063 var.VariableInfo.SetFieldAssigned (ec, FieldInfo.Name);
5065 bool lvalue_instance = !FieldInfo.IsStatic && TypeManager.IsValueType (FieldInfo.DeclaringType);
5066 bool out_access = right_side == EmptyExpression.OutAccess.Instance || right_side == EmptyExpression.LValueMemberOutAccess;
5068 Expression e = DoResolve (ec, lvalue_instance, out_access);
5070 if (e == null)
5071 return null;
5073 FieldBase fb = TypeManager.GetField (FieldInfo);
5074 if (fb != null) {
5075 fb.SetAssigned ();
5077 if ((right_side == EmptyExpression.UnaryAddress || right_side == EmptyExpression.OutAccess.Instance) &&
5078 (fb.ModFlags & Modifiers.VOLATILE) != 0) {
5079 ec.Report.Warning (420, 1, loc,
5080 "`{0}': A volatile field references will not be treated as volatile",
5081 fb.GetSignatureForError ());
5085 if (FieldInfo.IsInitOnly) {
5086 // InitOnly fields can only be assigned in constructors or initializers
5087 if (!ec.HasAny (ResolveContext.Options.FieldInitializerScope | ResolveContext.Options.ConstructorScope))
5088 return Report_AssignToReadonly (ec, right_side);
5090 if (ec.HasSet (ResolveContext.Options.ConstructorScope)) {
5091 Type ctype = ec.CurrentType;
5093 // InitOnly fields cannot be assigned-to in a different constructor from their declaring type
5094 if (!TypeManager.IsEqual (ctype, FieldInfo.DeclaringType))
5095 return Report_AssignToReadonly (ec, right_side);
5096 // static InitOnly fields cannot be assigned-to in an instance constructor
5097 if (IsStatic && !ec.IsStatic)
5098 return Report_AssignToReadonly (ec, right_side);
5099 // instance constructors can't modify InitOnly fields of other instances of the same type
5100 if (!IsStatic && !(InstanceExpression is This))
5101 return Report_AssignToReadonly (ec, right_side);
5105 if (right_side == EmptyExpression.OutAccess.Instance &&
5106 !IsStatic && !(InstanceExpression is This) && TypeManager.mbr_type != null && TypeManager.IsSubclassOf (DeclaringType, TypeManager.mbr_type)) {
5107 ec.Report.SymbolRelatedToPreviousError (DeclaringType);
5108 ec.Report.Warning (197, 1, loc,
5109 "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",
5110 GetSignatureForError ());
5113 eclass = ExprClass.Variable;
5114 return this;
5117 bool is_marshal_by_ref ()
5119 return !IsStatic && TypeManager.IsStruct (Type) && TypeManager.mbr_type != null && TypeManager.IsSubclassOf (DeclaringType, TypeManager.mbr_type);
5122 public override void CheckMarshalByRefAccess (ResolveContext ec)
5124 if (is_marshal_by_ref () && !(InstanceExpression is This)) {
5125 ec.Report.SymbolRelatedToPreviousError (DeclaringType);
5126 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",
5127 GetSignatureForError ());
5131 public override int GetHashCode ()
5133 return FieldInfo.GetHashCode ();
5136 public bool IsFixed {
5137 get {
5139 // A variable of the form V.I is fixed when V is a fixed variable of a struct type
5141 IVariableReference variable = InstanceExpression as IVariableReference;
5142 if (variable != null)
5143 return TypeManager.IsStruct (InstanceExpression.Type) && variable.IsFixed;
5145 IFixedExpression fe = InstanceExpression as IFixedExpression;
5146 return fe != null && fe.IsFixed;
5150 public bool IsHoisted {
5151 get {
5152 IVariableReference hv = InstanceExpression as IVariableReference;
5153 return hv != null && hv.IsHoisted;
5157 public override bool Equals (object obj)
5159 FieldExpr fe = obj as FieldExpr;
5160 if (fe == null)
5161 return false;
5163 if (FieldInfo != fe.FieldInfo)
5164 return false;
5166 if (InstanceExpression == null || fe.InstanceExpression == null)
5167 return true;
5169 return InstanceExpression.Equals (fe.InstanceExpression);
5172 public void Emit (EmitContext ec, bool leave_copy)
5174 ILGenerator ig = ec.ig;
5175 bool is_volatile = false;
5177 FieldBase f = TypeManager.GetField (FieldInfo);
5178 if (f != null){
5179 if ((f.ModFlags & Modifiers.VOLATILE) != 0)
5180 is_volatile = true;
5182 f.SetMemberIsUsed ();
5185 if (FieldInfo.IsStatic){
5186 if (is_volatile)
5187 ig.Emit (OpCodes.Volatile);
5189 ig.Emit (OpCodes.Ldsfld, GetConstructedFieldInfo ());
5190 } else {
5191 if (!prepared)
5192 EmitInstance (ec, false);
5194 // Optimization for build-in types
5195 if (TypeManager.IsStruct (type) && TypeManager.IsEqual (type, ec.MemberContext.CurrentType)) {
5196 LoadFromPtr (ig, type);
5197 } else {
5198 IFixedBuffer ff = AttributeTester.GetFixedBuffer (FieldInfo);
5199 if (ff != null) {
5200 ig.Emit (OpCodes.Ldflda, GetConstructedFieldInfo ());
5201 ig.Emit (OpCodes.Ldflda, ff.Element);
5202 } else {
5203 if (is_volatile)
5204 ig.Emit (OpCodes.Volatile);
5206 ig.Emit (OpCodes.Ldfld, GetConstructedFieldInfo ());
5211 if (leave_copy) {
5212 ec.ig.Emit (OpCodes.Dup);
5213 if (!FieldInfo.IsStatic) {
5214 temp = new LocalTemporary (this.Type);
5215 temp.Store (ec);
5220 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
5222 FieldAttributes fa = FieldInfo.Attributes;
5223 bool is_static = (fa & FieldAttributes.Static) != 0;
5224 ILGenerator ig = ec.ig;
5226 prepared = prepare_for_load;
5227 EmitInstance (ec, prepared);
5229 source.Emit (ec);
5230 if (leave_copy) {
5231 ec.ig.Emit (OpCodes.Dup);
5232 if (!FieldInfo.IsStatic) {
5233 temp = new LocalTemporary (this.Type);
5234 temp.Store (ec);
5238 FieldBase f = TypeManager.GetField (FieldInfo);
5239 if (f != null){
5240 if ((f.ModFlags & Modifiers.VOLATILE) != 0)
5241 ig.Emit (OpCodes.Volatile);
5243 f.SetAssigned ();
5246 if (is_static)
5247 ig.Emit (OpCodes.Stsfld, GetConstructedFieldInfo ());
5248 else
5249 ig.Emit (OpCodes.Stfld, GetConstructedFieldInfo ());
5251 if (temp != null) {
5252 temp.Emit (ec);
5253 temp.Release (ec);
5254 temp = null;
5258 public override void Emit (EmitContext ec)
5260 Emit (ec, false);
5263 public override void EmitSideEffect (EmitContext ec)
5265 FieldBase f = TypeManager.GetField (FieldInfo);
5266 bool is_volatile = f != null && (f.ModFlags & Modifiers.VOLATILE) != 0;
5268 if (is_volatile || is_marshal_by_ref ())
5269 base.EmitSideEffect (ec);
5272 public override void Error_VariableIsUsedBeforeItIsDeclared (Report r, string name)
5274 r.Error (844, loc,
5275 "A local variable `{0}' cannot be used before it is declared. Consider renaming the local variable when it hides the field `{1}'",
5276 name, GetSignatureForError ());
5279 public void AddressOf (EmitContext ec, AddressOp mode)
5281 ILGenerator ig = ec.ig;
5283 FieldBase f = TypeManager.GetField (FieldInfo);
5284 if (f != null){
5285 if ((mode & AddressOp.Store) != 0)
5286 f.SetAssigned ();
5287 if ((mode & AddressOp.Load) != 0)
5288 f.SetMemberIsUsed ();
5292 // Handle initonly fields specially: make a copy and then
5293 // get the address of the copy.
5295 bool need_copy;
5296 if (FieldInfo.IsInitOnly){
5297 need_copy = true;
5298 if (ec.HasSet (EmitContext.Options.ConstructorScope)){
5299 if (FieldInfo.IsStatic){
5300 if (ec.IsStatic)
5301 need_copy = false;
5302 } else
5303 need_copy = false;
5305 } else
5306 need_copy = false;
5308 if (need_copy){
5309 LocalBuilder local;
5310 Emit (ec);
5311 local = ig.DeclareLocal (type);
5312 ig.Emit (OpCodes.Stloc, local);
5313 ig.Emit (OpCodes.Ldloca, local);
5314 return;
5318 if (FieldInfo.IsStatic){
5319 ig.Emit (OpCodes.Ldsflda, GetConstructedFieldInfo ());
5320 } else {
5321 if (!prepared)
5322 EmitInstance (ec, false);
5323 ig.Emit (OpCodes.Ldflda, GetConstructedFieldInfo ());
5327 FieldInfo GetConstructedFieldInfo ()
5329 if (constructed_generic_type == null)
5330 return FieldInfo;
5332 return TypeBuilder.GetField (constructed_generic_type, FieldInfo);
5335 #if NET_4_0
5336 public SLE.Expression MakeAssignExpression (BuilderContext ctx)
5338 return MakeExpression (ctx);
5341 public override SLE.Expression MakeExpression (BuilderContext ctx)
5343 return SLE.Expression.Field (InstanceExpression.MakeExpression (ctx), FieldInfo);
5345 #endif
5347 public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
5349 FieldInfo = storey.MutateField (FieldInfo);
5350 base.MutateHoistedGenericType (storey);
5355 /// <summary>
5356 /// Expression that evaluates to a Property. The Assign class
5357 /// might set the `Value' expression if we are in an assignment.
5359 /// This is not an LValue because we need to re-write the expression, we
5360 /// can not take data from the stack and store it.
5361 /// </summary>
5362 public class PropertyExpr : MemberExpr, IDynamicAssign
5364 public readonly PropertyInfo PropertyInfo;
5365 MethodInfo getter, setter;
5366 bool is_static;
5368 TypeArguments targs;
5370 LocalTemporary temp;
5371 bool prepared;
5373 public PropertyExpr (Type container_type, PropertyInfo pi, Location l)
5375 PropertyInfo = pi;
5376 is_static = false;
5377 loc = l;
5379 type = TypeManager.TypeToCoreType (pi.PropertyType);
5381 ResolveAccessors (container_type);
5384 public override string Name {
5385 get {
5386 return PropertyInfo.Name;
5390 public override bool IsInstance {
5391 get {
5392 return !is_static;
5396 public override bool IsStatic {
5397 get {
5398 return is_static;
5402 public override Expression CreateExpressionTree (ResolveContext ec)
5404 Arguments args;
5405 if (IsSingleDimensionalArrayLength ()) {
5406 args = new Arguments (1);
5407 args.Add (new Argument (InstanceExpression.CreateExpressionTree (ec)));
5408 return CreateExpressionFactoryCall (ec, "ArrayLength", args);
5411 if (is_base) {
5412 Error_BaseAccessInExpressionTree (ec, loc);
5413 return null;
5416 args = new Arguments (2);
5417 if (InstanceExpression == null)
5418 args.Add (new Argument (new NullLiteral (loc)));
5419 else
5420 args.Add (new Argument (InstanceExpression.CreateExpressionTree (ec)));
5421 args.Add (new Argument (new TypeOfMethod (getter, loc)));
5422 return CreateExpressionFactoryCall (ec, "Property", args);
5425 public Expression CreateSetterTypeOfExpression ()
5427 return new TypeOfMethod (setter, loc);
5430 public override Type DeclaringType {
5431 get {
5432 return PropertyInfo.DeclaringType;
5436 public override string GetSignatureForError ()
5438 return TypeManager.GetFullNameSignature (PropertyInfo);
5441 void FindAccessors (Type invocation_type)
5443 const BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic |
5444 BindingFlags.Static | BindingFlags.Instance |
5445 BindingFlags.DeclaredOnly;
5447 Type current = PropertyInfo.DeclaringType;
5448 for (; current != null; current = current.BaseType) {
5449 MemberInfo[] group = TypeManager.MemberLookup (
5450 invocation_type, invocation_type, current,
5451 MemberTypes.Property, flags, PropertyInfo.Name, null);
5453 if (group == null)
5454 continue;
5456 if (group.Length != 1)
5457 // Oooops, can this ever happen ?
5458 return;
5460 PropertyInfo pi = (PropertyInfo) group [0];
5462 if (getter == null)
5463 getter = pi.GetGetMethod (true);
5465 if (setter == null)
5466 setter = pi.GetSetMethod (true);
5468 MethodInfo accessor = getter != null ? getter : setter;
5470 if (!accessor.IsVirtual)
5471 return;
5476 // We also perform the permission checking here, as the PropertyInfo does not
5477 // hold the information for the accessibility of its setter/getter
5479 // TODO: Refactor to use some kind of cache together with GetPropertyFromAccessor
5480 void ResolveAccessors (Type container_type)
5482 FindAccessors (container_type);
5484 if (getter != null) {
5485 MethodBase the_getter = TypeManager.DropGenericMethodArguments (getter);
5486 IMethodData md = TypeManager.GetMethod (the_getter);
5487 if (md != null)
5488 md.SetMemberIsUsed ();
5490 is_static = getter.IsStatic;
5493 if (setter != null) {
5494 MethodBase the_setter = TypeManager.DropGenericMethodArguments (setter);
5495 IMethodData md = TypeManager.GetMethod (the_setter);
5496 if (md != null)
5497 md.SetMemberIsUsed ();
5499 is_static = setter.IsStatic;
5503 #if NET_4_0
5504 public SLE.Expression MakeAssignExpression (BuilderContext ctx)
5506 return SLE.Expression.Property (InstanceExpression.MakeExpression (ctx), setter);
5509 public override SLE.Expression MakeExpression (BuilderContext ctx)
5511 return SLE.Expression.Property (InstanceExpression.MakeExpression (ctx), getter);
5513 #endif
5515 public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
5517 if (InstanceExpression != null)
5518 InstanceExpression.MutateHoistedGenericType (storey);
5520 type = storey.MutateType (type);
5521 if (getter != null)
5522 getter = storey.MutateGenericMethod (getter);
5523 if (setter != null)
5524 setter = storey.MutateGenericMethod (setter);
5527 bool InstanceResolve (ResolveContext ec, bool lvalue_instance, bool must_do_cs1540_check)
5529 if (is_static) {
5530 InstanceExpression = null;
5531 return true;
5534 if (InstanceExpression == null) {
5535 SimpleName.Error_ObjectRefRequired (ec, loc, GetSignatureForError ());
5536 return false;
5539 InstanceExpression = InstanceExpression.Resolve (ec);
5540 if (lvalue_instance && InstanceExpression != null)
5541 InstanceExpression = InstanceExpression.ResolveLValue (ec, EmptyExpression.LValueMemberAccess);
5543 if (InstanceExpression == null)
5544 return false;
5546 InstanceExpression.CheckMarshalByRefAccess (ec);
5548 if (must_do_cs1540_check && (InstanceExpression != EmptyExpression.Null) &&
5549 !TypeManager.IsInstantiationOfSameGenericType (InstanceExpression.Type, ec.CurrentType) &&
5550 !TypeManager.IsNestedChildOf (ec.CurrentType, InstanceExpression.Type) &&
5551 !TypeManager.IsSubclassOf (InstanceExpression.Type, ec.CurrentType)) {
5552 ec.Report.SymbolRelatedToPreviousError (PropertyInfo);
5553 Error_CannotAccessProtected (ec, loc, PropertyInfo, InstanceExpression.Type, ec.CurrentType);
5554 return false;
5557 return true;
5560 void Error_PropertyNotFound (ResolveContext ec, MethodInfo mi, bool getter)
5562 // TODO: correctly we should compare arguments but it will lead to bigger changes
5563 if (mi is MethodBuilder) {
5564 Error_TypeDoesNotContainDefinition (ec, loc, PropertyInfo.DeclaringType, Name);
5565 return;
5568 StringBuilder sig = new StringBuilder (TypeManager.CSharpName (mi.DeclaringType));
5569 sig.Append ('.');
5570 AParametersCollection iparams = TypeManager.GetParameterData (mi);
5571 sig.Append (getter ? "get_" : "set_");
5572 sig.Append (Name);
5573 sig.Append (iparams.GetSignatureForError ());
5575 ec.Report.SymbolRelatedToPreviousError (mi);
5576 ec.Report.Error (1546, loc, "Property `{0}' is not supported by the C# language. Try to call the accessor method `{1}' directly",
5577 Name, sig.ToString ());
5580 public bool IsAccessibleFrom (Type invocation_type, bool lvalue)
5582 bool dummy;
5583 MethodInfo accessor = lvalue ? setter : getter;
5584 if (accessor == null && lvalue)
5585 accessor = getter;
5586 return accessor != null && IsAccessorAccessible (invocation_type, accessor, out dummy);
5589 bool IsSingleDimensionalArrayLength ()
5591 if (DeclaringType != TypeManager.array_type || getter == null || Name != "Length")
5592 return false;
5594 string t_name = InstanceExpression.Type.Name;
5595 int t_name_len = t_name.Length;
5596 return t_name_len > 2 && t_name [t_name_len - 2] == '[';
5599 protected override Expression DoResolve (ResolveContext ec)
5601 eclass = ExprClass.PropertyAccess;
5603 bool must_do_cs1540_check = false;
5604 ec.Report.DisableReporting ();
5605 bool res = ResolveGetter (ec, ref must_do_cs1540_check);
5606 ec.Report.EnableReporting ();
5608 if (!res) {
5609 if (InstanceExpression != null) {
5610 Type expr_type = InstanceExpression.Type;
5611 ExtensionMethodGroupExpr ex_method_lookup = ec.LookupExtensionMethod (expr_type, Name, loc);
5612 if (ex_method_lookup != null) {
5613 ex_method_lookup.ExtensionExpression = InstanceExpression;
5614 ex_method_lookup.SetTypeArguments (ec, targs);
5615 return ex_method_lookup.Resolve (ec);
5619 ResolveGetter (ec, ref must_do_cs1540_check);
5620 return null;
5623 if (!InstanceResolve (ec, false, must_do_cs1540_check))
5624 return null;
5627 // Only base will allow this invocation to happen.
5629 if (IsBase && getter.IsAbstract) {
5630 Error_CannotCallAbstractBase (ec, TypeManager.GetFullNameSignature (PropertyInfo));
5633 if (PropertyInfo.PropertyType.IsPointer && !ec.IsUnsafe){
5634 UnsafeError (ec, loc);
5637 if (!ec.IsObsolete) {
5638 PropertyBase pb = TypeManager.GetProperty (PropertyInfo);
5639 if (pb != null) {
5640 pb.CheckObsoleteness (loc);
5641 } else {
5642 ObsoleteAttribute oa = AttributeTester.GetMemberObsoleteAttribute (PropertyInfo);
5643 if (oa != null)
5644 AttributeTester.Report_ObsoleteMessage (oa, GetSignatureForError (), loc, ec.Report);
5648 return this;
5651 override public Expression DoResolveLValue (ResolveContext ec, Expression right_side)
5653 eclass = ExprClass.PropertyAccess;
5655 if (right_side == EmptyExpression.OutAccess.Instance) {
5656 if (ec.CurrentBlock.Toplevel.GetParameterReference (PropertyInfo.Name, loc) is MemberAccess) {
5657 ec.Report.Error (1939, loc, "A range variable `{0}' may not be passes as `ref' or `out' parameter",
5658 PropertyInfo.Name);
5659 } else {
5660 right_side.DoResolveLValue (ec, this);
5662 return null;
5665 if (right_side == EmptyExpression.LValueMemberAccess || right_side == EmptyExpression.LValueMemberOutAccess) {
5666 Error_CannotModifyIntermediateExpressionValue (ec);
5669 if (setter == null){
5671 // The following condition happens if the PropertyExpr was
5672 // created, but is invalid (ie, the property is inaccessible),
5673 // and we did not want to embed the knowledge about this in
5674 // the caller routine. This only avoids double error reporting.
5676 if (getter == null)
5677 return null;
5679 if (ec.CurrentBlock.Toplevel.GetParameterReference (PropertyInfo.Name, loc) is MemberAccess) {
5680 ec.Report.Error (1947, loc, "A range variable `{0}' cannot be assigned to. Consider using `let' clause to store the value",
5681 PropertyInfo.Name);
5682 } else {
5683 ec.Report.Error (200, loc, "Property or indexer `{0}' cannot be assigned to (it is read only)",
5684 GetSignatureForError ());
5686 return null;
5689 if (targs != null) {
5690 base.SetTypeArguments (ec, targs);
5691 return null;
5694 if (TypeManager.GetParameterData (setter).Count != 1){
5695 Error_PropertyNotFound (ec, setter, false);
5696 return null;
5699 bool must_do_cs1540_check;
5700 if (!IsAccessorAccessible (ec.CurrentType, setter, out must_do_cs1540_check)) {
5701 PropertyBase.PropertyMethod pm = TypeManager.GetMethod (setter) as PropertyBase.PropertyMethod;
5702 if (pm != null && pm.HasCustomAccessModifier) {
5703 ec.Report.SymbolRelatedToPreviousError (pm);
5704 ec.Report.Error (272, loc, "The property or indexer `{0}' cannot be used in this context because the set accessor is inaccessible",
5705 TypeManager.CSharpSignature (setter));
5707 else {
5708 ec.Report.SymbolRelatedToPreviousError (setter);
5709 ErrorIsInaccesible (loc, TypeManager.CSharpSignature (setter), ec.Report);
5711 return null;
5714 if (!InstanceResolve (ec, TypeManager.IsStruct (PropertyInfo.DeclaringType), must_do_cs1540_check))
5715 return null;
5718 // Only base will allow this invocation to happen.
5720 if (IsBase && setter.IsAbstract){
5721 Error_CannotCallAbstractBase (ec, TypeManager.GetFullNameSignature (PropertyInfo));
5724 if (PropertyInfo.PropertyType.IsPointer && !ec.IsUnsafe) {
5725 UnsafeError (ec, loc);
5728 if (!ec.IsObsolete) {
5729 PropertyBase pb = TypeManager.GetProperty (PropertyInfo);
5730 if (pb != null) {
5731 pb.CheckObsoleteness (loc);
5732 } else {
5733 ObsoleteAttribute oa = AttributeTester.GetMemberObsoleteAttribute (PropertyInfo);
5734 if (oa != null)
5735 AttributeTester.Report_ObsoleteMessage (oa, GetSignatureForError (), loc, ec.Report);
5739 return this;
5742 public override void Emit (EmitContext ec)
5744 Emit (ec, false);
5747 public void Emit (EmitContext ec, bool leave_copy)
5750 // Special case: length of single dimension array property is turned into ldlen
5752 if (IsSingleDimensionalArrayLength ()) {
5753 if (!prepared)
5754 EmitInstance (ec, false);
5755 ec.ig.Emit (OpCodes.Ldlen);
5756 ec.ig.Emit (OpCodes.Conv_I4);
5757 return;
5760 Invocation.EmitCall (ec, IsBase, InstanceExpression, getter, null, loc, prepared, false);
5762 if (leave_copy) {
5763 ec.ig.Emit (OpCodes.Dup);
5764 if (!is_static) {
5765 temp = new LocalTemporary (this.Type);
5766 temp.Store (ec);
5772 // Implements the IAssignMethod interface for assignments
5774 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
5776 Expression my_source = source;
5778 if (prepare_for_load) {
5779 prepared = true;
5780 source.Emit (ec);
5782 if (leave_copy) {
5783 ec.ig.Emit (OpCodes.Dup);
5784 if (!is_static) {
5785 temp = new LocalTemporary (this.Type);
5786 temp.Store (ec);
5789 } else if (leave_copy) {
5790 source.Emit (ec);
5791 temp = new LocalTemporary (this.Type);
5792 temp.Store (ec);
5793 my_source = temp;
5796 Arguments args = new Arguments (1);
5797 args.Add (new Argument (my_source));
5799 Invocation.EmitCall (ec, IsBase, InstanceExpression, setter, args, loc, false, prepared);
5801 if (temp != null) {
5802 temp.Emit (ec);
5803 temp.Release (ec);
5807 bool ResolveGetter (ResolveContext ec, ref bool must_do_cs1540_check)
5809 if (targs != null) {
5810 base.SetTypeArguments (ec, targs);
5811 return false;
5814 if (getter != null) {
5815 if (TypeManager.GetParameterData (getter).Count != 0) {
5816 Error_PropertyNotFound (ec, getter, true);
5817 return false;
5821 if (getter == null) {
5823 // The following condition happens if the PropertyExpr was
5824 // created, but is invalid (ie, the property is inaccessible),
5825 // and we did not want to embed the knowledge about this in
5826 // the caller routine. This only avoids double error reporting.
5828 if (setter == null)
5829 return false;
5831 if (InstanceExpression != EmptyExpression.Null) {
5832 ec.Report.Error (154, loc, "The property or indexer `{0}' cannot be used in this context because it lacks the `get' accessor",
5833 TypeManager.GetFullNameSignature (PropertyInfo));
5834 return false;
5838 if (getter != null &&
5839 !IsAccessorAccessible (ec.CurrentType, getter, out must_do_cs1540_check)) {
5840 PropertyBase.PropertyMethod pm = TypeManager.GetMethod (getter) as PropertyBase.PropertyMethod;
5841 if (pm != null && pm.HasCustomAccessModifier) {
5842 ec.Report.SymbolRelatedToPreviousError (pm);
5843 ec.Report.Error (271, loc, "The property or indexer `{0}' cannot be used in this context because the get accessor is inaccessible",
5844 TypeManager.CSharpSignature (getter));
5845 } else {
5846 ec.Report.SymbolRelatedToPreviousError (getter);
5847 ErrorIsInaccesible (loc, TypeManager.CSharpSignature (getter), ec.Report);
5850 return false;
5853 return true;
5856 public override void SetTypeArguments (ResolveContext ec, TypeArguments ta)
5858 targs = ta;
5862 /// <summary>
5863 /// Fully resolved expression that evaluates to an Event
5864 /// </summary>
5865 public class EventExpr : MemberExpr {
5866 public readonly EventInfo EventInfo;
5868 bool is_static;
5869 MethodInfo add_accessor, remove_accessor;
5871 public EventExpr (EventInfo ei, Location loc)
5873 EventInfo = ei;
5874 this.loc = loc;
5876 add_accessor = TypeManager.GetAddMethod (ei);
5877 remove_accessor = TypeManager.GetRemoveMethod (ei);
5878 if (add_accessor.IsStatic || remove_accessor.IsStatic)
5879 is_static = true;
5881 if (EventInfo is MyEventBuilder){
5882 MyEventBuilder eb = (MyEventBuilder) EventInfo;
5883 type = eb.EventType;
5884 eb.SetUsed ();
5885 } else
5886 type = EventInfo.EventHandlerType;
5889 public override string Name {
5890 get {
5891 return EventInfo.Name;
5895 public override bool IsInstance {
5896 get {
5897 return !is_static;
5901 public override bool IsStatic {
5902 get {
5903 return is_static;
5907 public override Type DeclaringType {
5908 get {
5909 return EventInfo.DeclaringType;
5913 public void Error_AssignmentEventOnly (ResolveContext ec)
5915 ec.Report.Error (79, loc, "The event `{0}' can only appear on the left hand side of `+=' or `-=' operator",
5916 GetSignatureForError ());
5919 public override MemberExpr ResolveMemberAccess (ResolveContext ec, Expression left, Location loc,
5920 SimpleName original)
5923 // If the event is local to this class, we transform ourselves into a FieldExpr
5926 if (EventInfo.DeclaringType == ec.CurrentType ||
5927 TypeManager.IsNestedChildOf(ec.CurrentType, EventInfo.DeclaringType)) {
5929 // TODO: Breaks dynamic binder as currect context fields are imported and not compiled
5930 EventField mi = TypeManager.GetEventField (EventInfo);
5932 if (mi != null) {
5933 if (!ec.IsObsolete)
5934 mi.CheckObsoleteness (loc);
5936 if ((mi.ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN)) != 0 && !ec.HasSet (ResolveContext.Options.CompoundAssignmentScope))
5937 Error_AssignmentEventOnly (ec);
5939 FieldExpr ml = new FieldExpr (mi.BackingField.FieldBuilder, loc);
5941 InstanceExpression = null;
5943 return ml.ResolveMemberAccess (ec, left, loc, original);
5947 if (left is This && !ec.HasSet (ResolveContext.Options.CompoundAssignmentScope))
5948 Error_AssignmentEventOnly (ec);
5950 return base.ResolveMemberAccess (ec, left, loc, original);
5953 bool InstanceResolve (ResolveContext ec, bool must_do_cs1540_check)
5955 if (is_static) {
5956 InstanceExpression = null;
5957 return true;
5960 if (InstanceExpression == null) {
5961 SimpleName.Error_ObjectRefRequired (ec, loc, GetSignatureForError ());
5962 return false;
5965 InstanceExpression = InstanceExpression.Resolve (ec);
5966 if (InstanceExpression == null)
5967 return false;
5969 if (IsBase && add_accessor.IsAbstract) {
5970 Error_CannotCallAbstractBase (ec, TypeManager.CSharpSignature(add_accessor));
5971 return false;
5975 // This is using the same mechanism as the CS1540 check in PropertyExpr.
5976 // However, in the Event case, we reported a CS0122 instead.
5978 // TODO: Exact copy from PropertyExpr
5980 if (must_do_cs1540_check && InstanceExpression != EmptyExpression.Null &&
5981 !TypeManager.IsInstantiationOfSameGenericType (InstanceExpression.Type, ec.CurrentType) &&
5982 !TypeManager.IsNestedChildOf (ec.CurrentType, InstanceExpression.Type) &&
5983 !TypeManager.IsSubclassOf (InstanceExpression.Type, ec.CurrentType)) {
5984 ec.Report.SymbolRelatedToPreviousError (EventInfo);
5985 ErrorIsInaccesible (loc, TypeManager.CSharpSignature (EventInfo), ec.Report);
5986 return false;
5989 return true;
5992 public bool IsAccessibleFrom (Type invocation_type)
5994 bool dummy;
5995 return IsAccessorAccessible (invocation_type, add_accessor, out dummy) &&
5996 IsAccessorAccessible (invocation_type, remove_accessor, out dummy);
5999 public override Expression CreateExpressionTree (ResolveContext ec)
6001 throw new NotSupportedException ("ET");
6004 public override Expression DoResolveLValue (ResolveContext ec, Expression right_side)
6006 // contexts where an LValue is valid have already devolved to FieldExprs
6007 Error_CannotAssign (ec);
6008 return null;
6011 protected override Expression DoResolve (ResolveContext ec)
6013 eclass = ExprClass.EventAccess;
6015 bool must_do_cs1540_check;
6016 if (!(IsAccessorAccessible (ec.CurrentType, add_accessor, out must_do_cs1540_check) &&
6017 IsAccessorAccessible (ec.CurrentType, remove_accessor, out must_do_cs1540_check))) {
6018 ec.Report.SymbolRelatedToPreviousError (EventInfo);
6019 ErrorIsInaccesible (loc, TypeManager.CSharpSignature (EventInfo), ec.Report);
6020 return null;
6023 if (!InstanceResolve (ec, must_do_cs1540_check))
6024 return null;
6026 if (!ec.HasSet (ResolveContext.Options.CompoundAssignmentScope)) {
6027 Error_CannotAssign (ec);
6028 return null;
6031 if (!ec.IsObsolete) {
6032 EventField ev = TypeManager.GetEventField (EventInfo);
6033 if (ev != null) {
6034 ev.CheckObsoleteness (loc);
6035 } else {
6036 ObsoleteAttribute oa = AttributeTester.GetMemberObsoleteAttribute (EventInfo);
6037 if (oa != null)
6038 AttributeTester.Report_ObsoleteMessage (oa, GetSignatureForError (), loc, ec.Report);
6042 return this;
6045 public override void Emit (EmitContext ec)
6047 throw new NotSupportedException ();
6048 //Error_CannotAssign ();
6051 public void Error_CannotAssign (ResolveContext ec)
6053 ec.Report.Error (70, loc,
6054 "The event `{0}' can only appear on the left hand side of += or -= when used outside of the type `{1}'",
6055 GetSignatureForError (), TypeManager.CSharpName (EventInfo.DeclaringType));
6058 public override string GetSignatureForError ()
6060 return TypeManager.CSharpSignature (EventInfo);
6063 public void EmitAddOrRemove (EmitContext ec, bool is_add, Expression source)
6065 Arguments args = new Arguments (1);
6066 args.Add (new Argument (source));
6067 Invocation.EmitCall (ec, IsBase, InstanceExpression, is_add ? add_accessor : remove_accessor, args, loc);
6071 public class TemporaryVariable : VariableReference
6073 LocalInfo li;
6075 public TemporaryVariable (Type type, Location loc)
6077 this.type = type;
6078 this.loc = loc;
6081 public override Expression CreateExpressionTree (ResolveContext ec)
6083 throw new NotSupportedException ("ET");
6086 protected override Expression DoResolve (ResolveContext ec)
6088 eclass = ExprClass.Variable;
6090 TypeExpr te = new TypeExpression (type, loc);
6091 li = ec.CurrentBlock.AddTemporaryVariable (te, loc);
6092 if (!li.Resolve (ec))
6093 return null;
6096 // Don't capture temporary variables except when using
6097 // iterator redirection
6099 if (ec.CurrentAnonymousMethod != null && ec.CurrentAnonymousMethod.IsIterator && ec.IsVariableCapturingRequired) {
6100 AnonymousMethodStorey storey = li.Block.Explicit.CreateAnonymousMethodStorey (ec);
6101 storey.CaptureLocalVariable (ec, li);
6104 return this;
6107 public override Expression DoResolveLValue (ResolveContext ec, Expression right_side)
6109 return Resolve (ec);
6112 public override void Emit (EmitContext ec)
6114 Emit (ec, false);
6117 public void EmitAssign (EmitContext ec, Expression source)
6119 EmitAssign (ec, source, false, false);
6122 public override HoistedVariable GetHoistedVariable (AnonymousExpression ae)
6124 return li.HoistedVariant;
6127 public override bool IsFixed {
6128 get { return true; }
6131 public override bool IsRef {
6132 get { return false; }
6135 public override string Name {
6136 get { throw new NotImplementedException (); }
6139 public override void SetHasAddressTaken ()
6141 throw new NotImplementedException ();
6144 protected override ILocalVariable Variable {
6145 get { return li; }
6148 public override VariableInfo VariableInfo {
6149 get { throw new NotImplementedException (); }
6153 ///
6154 /// Handles `var' contextual keyword; var becomes a keyword only
6155 /// if no type called var exists in a variable scope
6156 ///
6157 class VarExpr : SimpleName
6159 // Used for error reporting only
6160 int initializers_count;
6162 public VarExpr (Location loc)
6163 : base ("var", loc)
6165 initializers_count = 1;
6168 public int VariableInitializersCount {
6169 set {
6170 this.initializers_count = value;
6174 public bool InferType (ResolveContext ec, Expression right_side)
6176 if (type != null)
6177 throw new InternalErrorException ("An implicitly typed local variable could not be redefined");
6179 type = right_side.Type;
6180 if (type == TypeManager.null_type || type == TypeManager.void_type || type == InternalType.AnonymousMethod || type == InternalType.MethodGroup) {
6181 ec.Report.Error (815, loc, "An implicitly typed local variable declaration cannot be initialized with `{0}'",
6182 right_side.GetSignatureForError ());
6183 return false;
6186 eclass = ExprClass.Variable;
6187 return true;
6190 protected override void Error_TypeOrNamespaceNotFound (IMemberContext ec)
6192 if (RootContext.Version < LanguageVersion.V_3)
6193 base.Error_TypeOrNamespaceNotFound (ec);
6194 else
6195 ec.Compiler.Report.Error (825, loc, "The contextual keyword `var' may only appear within a local variable declaration");
6198 public override TypeExpr ResolveAsContextualType (IMemberContext rc, bool silent)
6200 TypeExpr te = base.ResolveAsContextualType (rc, true);
6201 if (te != null)
6202 return te;
6204 if (RootContext.Version < LanguageVersion.V_3)
6205 rc.Compiler.Report.FeatureIsNotAvailable (loc, "implicitly typed local variable");
6207 if (initializers_count == 1)
6208 return null;
6210 if (initializers_count > 1) {
6211 rc.Compiler.Report.Error (819, loc, "An implicitly typed local variable declaration cannot include multiple declarators");
6212 initializers_count = 1;
6213 return null;
6216 if (initializers_count == 0) {
6217 initializers_count = 1;
6218 rc.Compiler.Report.Error (818, loc, "An implicitly typed local variable declarator must include an initializer");
6219 return null;
6222 return null;