2 // ecore.cs: Core of the Expression representation for the intermediate tree.
5 // Miguel de Icaza (miguel@ximian.com)
6 // Marek Safar (marek.safar@seznam.cz)
8 // Copyright 2001, 2002, 2003 Ximian, Inc.
9 // Copyright 2003-2008 Novell, Inc.
13 namespace Mono
.CSharp
{
15 using System
.Collections
.Generic
;
16 using System
.Diagnostics
;
17 using System
.Reflection
;
18 using System
.Reflection
.Emit
;
20 using SLE
= System
.Linq
.Expressions
;
23 /// The ExprClass class contains the is used to pass the
24 /// classification of an expression (value, variable, namespace,
25 /// type, method group, property access, event access, indexer access,
28 public enum ExprClass
: byte {
44 /// This is used to tell Resolve in which types of expressions we're
48 public enum ResolveFlags
{
49 // Returns Value, Variable, PropertyAccess, EventAccess or IndexerAccess.
52 // Returns a type expression.
55 // Returns a method group.
58 TypeParameter
= 1 << 3,
60 // Mask of all the expression class flags.
61 MaskExprClass
= VariableOrValue
| Type
| MethodGroup
| TypeParameter
,
63 // Set if this is resolving the first part of a MemberAccess.
64 Intermediate
= 1 << 11,
68 // This is just as a hint to AddressOf of what will be done with the
71 public enum AddressOp
{
78 /// This interface is implemented by variables
80 public interface IMemoryLocation
{
82 /// The AddressOf method should generate code that loads
83 /// the address of the object and leaves it on the stack.
85 /// The `mode' argument is used to notify the expression
86 /// of whether this will be used to read from the address or
87 /// write to the address.
89 /// This is just a hint that can be used to provide good error
90 /// reporting, and should have no other side effects.
92 void AddressOf (EmitContext ec
, AddressOp mode
);
96 // An expressions resolved as a direct variable reference
98 public interface IVariableReference
: IFixedExpression
100 bool IsHoisted { get; }
102 VariableInfo VariableInfo { get; }
104 void SetHasAddressTaken ();
108 // Implemented by an expression which could be or is always
111 public interface IFixedExpression
113 bool IsFixed { get; }
117 /// Base class for expressions
119 public abstract class Expression
{
120 public ExprClass eclass
;
122 protected Location loc
;
126 set { type = value; }
129 public virtual Location Location
{
133 // Not nice but we have broken hierarchy.
134 public virtual void CheckMarshalByRefAccess (ResolveContext ec
)
138 public virtual bool GetAttributableValue (ResolveContext ec
, Type value_type
, out object value)
140 Attribute
.Error_AttributeArgumentNotValid (ec
, loc
);
145 public virtual string GetSignatureForError ()
147 return TypeManager
.CSharpName (type
);
150 public static bool IsAccessorAccessible (Type invocation_type
, MethodInfo mi
, out bool must_do_cs1540_check
)
152 MethodAttributes ma
= mi
.Attributes
& MethodAttributes
.MemberAccessMask
;
154 must_do_cs1540_check
= false; // by default we do not check for this
156 if (ma
== MethodAttributes
.Public
)
160 // If only accessible to the current class or children
162 if (ma
== MethodAttributes
.Private
)
163 return TypeManager
.IsPrivateAccessible (invocation_type
, mi
.DeclaringType
) ||
164 TypeManager
.IsNestedChildOf (invocation_type
, mi
.DeclaringType
);
166 if (TypeManager
.IsThisOrFriendAssembly (invocation_type
.Assembly
, mi
.DeclaringType
.Assembly
)) {
167 if (ma
== MethodAttributes
.Assembly
|| ma
== MethodAttributes
.FamORAssem
)
170 if (ma
== MethodAttributes
.Assembly
|| ma
== MethodAttributes
.FamANDAssem
)
174 // Family and FamANDAssem require that we derive.
175 // FamORAssem requires that we derive if in different assemblies.
176 if (!TypeManager
.IsNestedFamilyAccessible (invocation_type
, mi
.DeclaringType
))
179 if (!TypeManager
.IsNestedChildOf (invocation_type
, mi
.DeclaringType
))
180 must_do_cs1540_check
= true;
185 public virtual bool IsNull
{
192 /// Performs semantic analysis on the Expression
196 /// The Resolve method is invoked to perform the semantic analysis
199 /// The return value is an expression (it can be the
200 /// same expression in some cases) or a new
201 /// expression that better represents this node.
203 /// For example, optimizations of Unary (LiteralInt)
204 /// would return a new LiteralInt with a negated
207 /// If there is an error during semantic analysis,
208 /// then an error should be reported (using Report)
209 /// and a null value should be returned.
211 /// There are two side effects expected from calling
212 /// Resolve(): the the field variable "eclass" should
213 /// be set to any value of the enumeration
214 /// `ExprClass' and the type variable should be set
215 /// to a valid type (this is the type of the
218 protected abstract Expression
DoResolve (ResolveContext rc
);
220 public virtual Expression
DoResolveLValue (ResolveContext rc
, Expression right_side
)
226 // This is used if the expression should be resolved as a type or namespace name.
227 // the default implementation fails.
229 public virtual FullNamedExpression
ResolveAsTypeStep (IMemberContext rc
, bool silent
)
232 ResolveContext ec
= new ResolveContext (rc
);
233 Expression e
= Resolve (ec
);
235 e
.Error_UnexpectedKind (ec
, ResolveFlags
.Type
, loc
);
242 // C# 3.0 introduced contextual keywords (var) which behaves like a type if type with
243 // same name exists or as a keyword when no type was found
245 public virtual TypeExpr
ResolveAsContextualType (IMemberContext rc
, bool silent
)
247 return ResolveAsTypeTerminal (rc
, silent
);
251 // This is used to resolve the expression as a type, a null
252 // value will be returned if the expression is not a type
255 public virtual TypeExpr
ResolveAsTypeTerminal (IMemberContext ec
, bool silent
)
257 TypeExpr te
= ResolveAsBaseTerminal (ec
, silent
);
261 if (!silent
) { // && !(te is TypeParameterExpr)) {
262 ObsoleteAttribute obsolete_attr
= AttributeTester
.GetObsoleteAttribute (te
.Type
);
263 if (obsolete_attr
!= null && !ec
.IsObsolete
) {
264 AttributeTester
.Report_ObsoleteMessage (obsolete_attr
, te
.GetSignatureForError (), Location
, ec
.Compiler
.Report
);
268 GenericTypeExpr ct
= te
as GenericTypeExpr
;
271 // TODO: Constrained type parameters check for parameters of generic method overrides is broken
272 // There are 2 solutions.
273 // 1, Skip this check completely when we are in override/explicit impl scope
274 // 2, Copy type parameters constraints from base implementation and pass (they have to be emitted anyway)
276 MemberCore gm
= ec
as GenericMethod
;
279 if (gm
!= null && ((gm
.ModFlags
& Modifiers
.OVERRIDE
) != 0 || gm
.MemberName
.Left
!= null)) {
284 // TODO: silent flag is ignored
285 ct
.CheckConstraints (ec
);
291 public TypeExpr
ResolveAsBaseTerminal (IMemberContext ec
, bool silent
)
293 int errors
= ec
.Compiler
.Report
.Errors
;
295 FullNamedExpression fne
= ResolveAsTypeStep (ec
, silent
);
300 TypeExpr te
= fne
as TypeExpr
;
302 if (!silent
&& errors
== ec
.Compiler
.Report
.Errors
)
303 fne
.Error_UnexpectedKind (ec
.Compiler
.Report
, null, "type", loc
);
307 if (!te
.CheckAccessLevel (ec
)) {
308 ec
.Compiler
.Report
.SymbolRelatedToPreviousError (te
.Type
);
309 ErrorIsInaccesible (loc
, TypeManager
.CSharpName (te
.Type
), ec
.Compiler
.Report
);
317 public static void ErrorIsInaccesible (Location loc
, string name
, Report Report
)
319 Report
.Error (122, loc
, "`{0}' is inaccessible due to its protection level", name
);
322 protected static void Error_CannotAccessProtected (ResolveContext ec
, Location loc
, MemberInfo m
, Type qualifier
, Type container
)
324 ec
.Report
.Error (1540, loc
, "Cannot access protected member `{0}' via a qualifier of type `{1}'."
325 + " The qualifier must be of type `{2}' or derived from it",
326 TypeManager
.GetFullNameSignature (m
),
327 TypeManager
.CSharpName (qualifier
),
328 TypeManager
.CSharpName (container
));
332 public static void Error_InvalidExpressionStatement (Report Report
, Location loc
)
334 Report
.Error (201, loc
, "Only assignment, call, increment, decrement, and new object " +
335 "expressions can be used as a statement");
338 public void Error_InvalidExpressionStatement (BlockContext ec
)
340 Error_InvalidExpressionStatement (ec
.Report
, loc
);
343 public static void Error_VoidInvalidInTheContext (Location loc
, Report Report
)
345 Report
.Error (1547, loc
, "Keyword `void' cannot be used in this context");
348 public virtual void Error_ValueCannotBeConverted (ResolveContext ec
, Location loc
, Type target
, bool expl
)
350 Error_ValueCannotBeConvertedCore (ec
, loc
, target
, expl
);
353 protected void Error_ValueCannotBeConvertedCore (ResolveContext ec
, Location loc
, Type target
, bool expl
)
355 // The error was already reported as CS1660
356 if (type
== InternalType
.AnonymousMethod
)
359 if (TypeManager
.IsGenericParameter (Type
) && TypeManager
.IsGenericParameter (target
) && type
.Name
== target
.Name
) {
360 string sig1
= type
.DeclaringMethod
== null ?
361 TypeManager
.CSharpName (type
.DeclaringType
) :
362 TypeManager
.CSharpSignature (type
.DeclaringMethod
);
363 string sig2
= target
.DeclaringMethod
== null ?
364 TypeManager
.CSharpName (target
.DeclaringType
) :
365 TypeManager
.CSharpSignature (target
.DeclaringMethod
);
366 ec
.Report
.ExtraInformation (loc
,
368 "The generic parameter `{0}' of `{1}' cannot be converted to the generic parameter `{0}' of `{2}' (in the previous ",
369 Type
.Name
, sig1
, sig2
));
370 } else if (Type
.FullName
== target
.FullName
){
371 ec
.Report
.ExtraInformation (loc
,
373 "The type `{0}' has two conflicting definitions, one comes from `{1}' and the other from `{2}' (in the previous ",
374 Type
.FullName
, Type
.Assembly
.FullName
, target
.Assembly
.FullName
));
378 ec
.Report
.Error (30, loc
, "Cannot convert type `{0}' to `{1}'",
379 TypeManager
.CSharpName (type
), TypeManager
.CSharpName (target
));
383 ec
.Report
.DisableReporting ();
384 bool expl_exists
= Convert
.ExplicitConversion (ec
, this, target
, Location
.Null
) != null;
385 ec
.Report
.EnableReporting ();
388 ec
.Report
.Error (266, loc
, "Cannot implicitly convert type `{0}' to `{1}'. " +
389 "An explicit conversion exists (are you missing a cast?)",
390 TypeManager
.CSharpName (Type
), TypeManager
.CSharpName (target
));
394 ec
.Report
.Error (29, loc
, "Cannot implicitly convert type `{0}' to `{1}'",
395 TypeManager
.CSharpName (type
),
396 TypeManager
.CSharpName (target
));
399 public virtual void Error_VariableIsUsedBeforeItIsDeclared (Report Report
, string name
)
401 Report
.Error (841, loc
, "A local variable `{0}' cannot be used before it is declared", name
);
404 public void Error_TypeArgumentsCannotBeUsed (Report report
, Location loc
)
406 // Better message for possible generic expressions
407 if (eclass
== ExprClass
.MethodGroup
|| eclass
== ExprClass
.Type
) {
408 if (this is TypeExpr
)
409 report
.SymbolRelatedToPreviousError (type
);
411 string name
= eclass
== ExprClass
.Type
? ExprClassName
: "method";
412 report
.Error (308, loc
, "The non-generic {0} `{1}' cannot be used with the type arguments",
413 name
, GetSignatureForError ());
415 report
.Error (307, loc
, "The {0} `{1}' cannot be used with type arguments",
416 ExprClassName
, GetSignatureForError ());
420 protected virtual void Error_TypeDoesNotContainDefinition (ResolveContext ec
, Type type
, string name
)
422 Error_TypeDoesNotContainDefinition (ec
, loc
, type
, name
);
425 public static void Error_TypeDoesNotContainDefinition (ResolveContext ec
, Location loc
, Type type
, string name
)
427 ec
.Report
.SymbolRelatedToPreviousError (type
);
428 ec
.Report
.Error (117, loc
, "`{0}' does not contain a definition for `{1}'",
429 TypeManager
.CSharpName (type
), name
);
432 protected static void Error_ValueAssignment (ResolveContext ec
, Location loc
)
434 ec
.Report
.Error (131, loc
, "The left-hand side of an assignment must be a variable, a property or an indexer");
437 ResolveFlags ExprClassToResolveFlags
{
441 case ExprClass
.Namespace
:
442 return ResolveFlags
.Type
;
444 case ExprClass
.MethodGroup
:
445 return ResolveFlags
.MethodGroup
;
447 case ExprClass
.TypeParameter
:
448 return ResolveFlags
.TypeParameter
;
450 case ExprClass
.Value
:
451 case ExprClass
.Variable
:
452 case ExprClass
.PropertyAccess
:
453 case ExprClass
.EventAccess
:
454 case ExprClass
.IndexerAccess
:
455 return ResolveFlags
.VariableOrValue
;
458 throw new InternalErrorException (loc
.ToString () + " " + GetType () + " ExprClass is Invalid after resolve");
464 /// Resolves an expression and performs semantic analysis on it.
468 /// Currently Resolve wraps DoResolve to perform sanity
469 /// checking and assertion checking on what we expect from Resolve.
471 public Expression
Resolve (ResolveContext ec
, ResolveFlags flags
)
473 if (eclass
!= ExprClass
.Unresolved
)
477 if (this is SimpleName
) {
478 e
= ((SimpleName
) this).DoResolve (ec
, (flags
& ResolveFlags
.Intermediate
) != 0);
486 if ((flags
& e
.ExprClassToResolveFlags
) == 0) {
487 e
.Error_UnexpectedKind (ec
, flags
, loc
);
492 throw new InternalErrorException ("Expression `{0}' didn't set its type in DoResolve", e
.GetType ());
498 /// Resolves an expression and performs semantic analysis on it.
500 public Expression
Resolve (ResolveContext rc
)
502 return Resolve (rc
, ResolveFlags
.VariableOrValue
| ResolveFlags
.MethodGroup
);
505 public Constant
ResolveAsConstant (ResolveContext ec
, MemberCore mc
)
507 Expression e
= Resolve (ec
);
511 Constant c
= e
as Constant
;
515 if (type
!= null && TypeManager
.IsReferenceType (type
))
516 Const
.Error_ConstantCanBeInitializedWithNullOnly (type
, loc
, mc
.GetSignatureForError (), ec
.Report
);
518 Const
.Error_ExpressionMustBeConstant (loc
, mc
.GetSignatureForError (), ec
.Report
);
524 /// Resolves an expression for LValue assignment
528 /// Currently ResolveLValue wraps DoResolveLValue to perform sanity
529 /// checking and assertion checking on what we expect from Resolve
531 public Expression
ResolveLValue (ResolveContext ec
, Expression right_side
)
533 int errors
= ec
.Report
.Errors
;
534 bool out_access
= right_side
== EmptyExpression
.OutAccess
.Instance
;
536 Expression e
= DoResolveLValue (ec
, right_side
);
538 if (e
!= null && out_access
&& !(e
is IMemoryLocation
)) {
539 // FIXME: There's no problem with correctness, the 'Expr = null' handles that.
540 // Enabling this 'throw' will "only" result in deleting useless code elsewhere,
542 //throw new InternalErrorException ("ResolveLValue didn't return an IMemoryLocation: " +
543 // e.GetType () + " " + e.GetSignatureForError ());
548 if (errors
== ec
.Report
.Errors
) {
550 ec
.Report
.Error (1510, loc
, "A ref or out argument must be an assignable variable");
552 Error_ValueAssignment (ec
, loc
);
557 if (e
.eclass
== ExprClass
.Unresolved
)
558 throw new Exception ("Expression " + e
+ " ExprClass is Invalid after resolve");
560 if ((e
.type
== null) && !(e
is GenericTypeExpr
))
561 throw new Exception ("Expression " + e
+ " did not set its type after Resolve");
567 /// Emits the code for the expression
571 /// The Emit method is invoked to generate the code
572 /// for the expression.
574 public abstract void Emit (EmitContext ec
);
576 // Emit code to branch to @target if this expression is equivalent to @on_true.
577 // The default implementation is to emit the value, and then emit a brtrue or brfalse.
578 // Subclasses can provide more efficient implementations, but those MUST be equivalent,
579 // including the use of conditional branches. Note also that a branch MUST be emitted
580 public virtual void EmitBranchable (EmitContext ec
, Label target
, bool on_true
)
583 ec
.ig
.Emit (on_true
? OpCodes
.Brtrue
: OpCodes
.Brfalse
, target
);
586 // Emit this expression for its side effects, not for its value.
587 // The default implementation is to emit the value, and then throw it away.
588 // Subclasses can provide more efficient implementations, but those MUST be equivalent
589 public virtual void EmitSideEffect (EmitContext ec
)
592 ec
.ig
.Emit (OpCodes
.Pop
);
596 /// Protected constructor. Only derivate types should
597 /// be able to be created
600 protected Expression ()
605 /// Returns a fully formed expression after a MemberLookup
608 public static Expression
ExprClassFromMemberInfo (Type container_type
, MemberInfo mi
, Location loc
)
611 return new EventExpr ((EventInfo
) mi
, loc
);
612 else if (mi
is FieldInfo
) {
613 FieldInfo fi
= (FieldInfo
) mi
;
614 if (fi
.IsLiteral
|| (fi
.IsInitOnly
&& fi
.FieldType
== TypeManager
.decimal_type
))
615 return new ConstantExpr (fi
, loc
);
616 return new FieldExpr (fi
, loc
);
617 } else if (mi
is PropertyInfo
)
618 return new PropertyExpr (container_type
, (PropertyInfo
) mi
, loc
);
619 else if (mi
is Type
) {
620 return new TypeExpression ((System
.Type
) mi
, loc
);
626 // TODO: [Obsolete ("Can be removed")]
627 protected static IList
<MemberInfo
> almost_matched_members
= new List
<MemberInfo
> (4);
630 // FIXME: Probably implement a cache for (t,name,current_access_set)?
632 // This code could use some optimizations, but we need to do some
633 // measurements. For example, we could use a delegate to `flag' when
634 // something can not any longer be a method-group (because it is something
638 // If the return value is an Array, then it is an array of
641 // If the return value is an MemberInfo, it is anything, but a Method
645 // FIXME: When calling MemberLookup inside an `Invocation', we should pass
646 // the arguments here and have MemberLookup return only the methods that
647 // match the argument count/type, unlike we are doing now (we delay this
650 // This is so we can catch correctly attempts to invoke instance methods
651 // from a static body (scan for error 120 in ResolveSimpleName).
654 // FIXME: Potential optimization, have a static ArrayList
657 public static Expression
MemberLookup (CompilerContext ctx
, Type container_type
, Type queried_type
, string name
,
658 MemberTypes mt
, BindingFlags bf
, Location loc
)
660 return MemberLookup (ctx
, container_type
, null, queried_type
, name
, mt
, bf
, loc
);
664 // Lookup type `queried_type' for code in class `container_type' with a qualifier of
665 // `qualifier_type' or null to lookup members in the current class.
668 public static Expression
MemberLookup (CompilerContext ctx
, Type container_type
,
669 Type qualifier_type
, Type queried_type
,
670 string name
, MemberTypes mt
,
671 BindingFlags bf
, Location loc
)
673 almost_matched_members
.Clear ();
675 MemberInfo
[] mi
= TypeManager
.MemberLookup (container_type
, qualifier_type
,
676 queried_type
, mt
, bf
, name
, almost_matched_members
);
682 bool is_interface
= qualifier_type
!= null && qualifier_type
.IsInterface
;
683 var methods
= new List
<MethodBase
> (2);
684 List
<MemberInfo
> non_methods
= null;
686 foreach (MemberInfo m
in mi
) {
687 if (m
is MethodBase
) {
688 methods
.Add ((MethodBase
) m
);
692 if (non_methods
== null)
693 non_methods
= new List
<MemberInfo
> (2);
695 bool is_candidate
= true;
696 for (int i
= 0; i
< non_methods
.Count
; ++i
) {
697 MemberInfo n_m
= non_methods
[i
];
698 if (n_m
.DeclaringType
.IsInterface
&& TypeManager
.ImplementsInterface (m
.DeclaringType
, n_m
.DeclaringType
)) {
699 non_methods
.Remove (n_m
);
701 } else if (m
.DeclaringType
.IsInterface
&& TypeManager
.ImplementsInterface (n_m
.DeclaringType
, m
.DeclaringType
)) {
702 is_candidate
= false;
712 if (methods
.Count
== 0 && non_methods
!= null && non_methods
.Count
> 1) {
713 ctx
.Report
.SymbolRelatedToPreviousError (non_methods
[1]);
714 ctx
.Report
.SymbolRelatedToPreviousError (non_methods
[0]);
715 ctx
.Report
.Error (229, loc
, "Ambiguity between `{0}' and `{1}'",
716 TypeManager
.GetFullNameSignature (non_methods
[1]),
717 TypeManager
.GetFullNameSignature (non_methods
[0]));
721 if (methods
.Count
== 0)
722 return ExprClassFromMemberInfo (container_type
, (MemberInfo
)non_methods
[0], loc
);
724 if (non_methods
!= null && non_methods
.Count
> 0) {
725 MethodBase method
= (MethodBase
) methods
[0];
726 MemberInfo non_method
= (MemberInfo
) non_methods
[0];
727 if (method
.DeclaringType
== non_method
.DeclaringType
) {
728 // Cannot happen with C# code, but is valid in IL
729 ctx
.Report
.SymbolRelatedToPreviousError (method
);
730 ctx
.Report
.SymbolRelatedToPreviousError (non_method
);
731 ctx
.Report
.Error (229, loc
, "Ambiguity between `{0}' and `{1}'",
732 TypeManager
.GetFullNameSignature (non_method
),
733 TypeManager
.CSharpSignature (method
));
738 ctx
.Report
.SymbolRelatedToPreviousError (method
);
739 ctx
.Report
.SymbolRelatedToPreviousError (non_method
);
740 ctx
.Report
.Warning (467, 2, loc
, "Ambiguity between method `{0}' and non-method `{1}'. Using method `{0}'",
741 TypeManager
.CSharpSignature (method
), TypeManager
.GetFullNameSignature (non_method
));
745 return new MethodGroupExpr (methods
, queried_type
, loc
);
748 if (mi
[0] is MethodBase
)
749 return new MethodGroupExpr (mi
, queried_type
, loc
);
751 return ExprClassFromMemberInfo (container_type
, mi
[0], loc
);
754 public const MemberTypes AllMemberTypes
=
755 MemberTypes
.Constructor
|
759 MemberTypes
.NestedType
|
760 MemberTypes
.Property
;
762 public const BindingFlags AllBindingFlags
=
763 BindingFlags
.Public
|
764 BindingFlags
.Static
|
765 BindingFlags
.Instance
;
767 public static Expression
MemberLookup (CompilerContext ctx
, Type container_type
, Type queried_type
,
768 string name
, Location loc
)
770 return MemberLookup (ctx
, container_type
, null, queried_type
, name
,
771 AllMemberTypes
, AllBindingFlags
, loc
);
774 public static Expression
MemberLookup (CompilerContext ctx
, Type container_type
, Type qualifier_type
,
775 Type queried_type
, string name
, Location loc
)
777 return MemberLookup (ctx
, container_type
, qualifier_type
, queried_type
,
778 name
, AllMemberTypes
, AllBindingFlags
, loc
);
781 public static MethodGroupExpr
MethodLookup (CompilerContext ctx
, Type container_type
, Type queried_type
,
782 string name
, Location loc
)
784 return (MethodGroupExpr
)MemberLookup (ctx
, container_type
, null, queried_type
, name
,
785 MemberTypes
.Method
, AllBindingFlags
, loc
);
789 /// This is a wrapper for MemberLookup that is not used to "probe", but
790 /// to find a final definition. If the final definition is not found, we
791 /// look for private members and display a useful debugging message if we
794 protected Expression
MemberLookupFinal (ResolveContext ec
, Type qualifier_type
,
795 Type queried_type
, string name
,
796 MemberTypes mt
, BindingFlags bf
,
801 int errors
= ec
.Report
.Errors
;
802 e
= MemberLookup (ec
.Compiler
, ec
.CurrentType
, qualifier_type
, queried_type
, name
, mt
, bf
, loc
);
804 if (e
!= null || errors
!= ec
.Report
.Errors
)
807 // No errors were reported by MemberLookup, but there was an error.
808 return Error_MemberLookupFailed (ec
, ec
.CurrentType
, qualifier_type
, queried_type
,
812 protected virtual Expression
Error_MemberLookupFailed (ResolveContext ec
, Type container_type
, Type qualifier_type
,
813 Type queried_type
, string name
, string class_name
,
814 MemberTypes mt
, BindingFlags bf
)
816 MemberInfo
[] lookup
= null;
817 if (queried_type
== null) {
818 class_name
= "global::";
820 lookup
= TypeManager
.MemberLookup (queried_type
, null, queried_type
,
821 mt
, (bf
& ~BindingFlags
.Public
) | BindingFlags
.NonPublic
,
824 if (lookup
!= null) {
825 Expression e
= Error_MemberLookupFailed (ec
, queried_type
, lookup
);
828 // FIXME: This is still very wrong, it should be done inside
829 // OverloadResolve to do correct arguments matching.
830 // Requires MemberLookup accessiblity check removal
832 if (e
== null || (mt
& (MemberTypes
.Method
| MemberTypes
.Constructor
)) == 0) {
833 MemberInfo mi
= lookup
[0];
834 ec
.Report
.SymbolRelatedToPreviousError (mi
);
835 if (qualifier_type
!= null && container_type
!= null && qualifier_type
!= container_type
&&
836 TypeManager
.IsNestedFamilyAccessible (container_type
, mi
.DeclaringType
)) {
837 // Although a derived class can access protected members of
838 // its base class it cannot do so through an instance of the
839 // base class (CS1540). If the qualifier_type is a base of the
840 // ec.CurrentType and the lookup succeeds with the latter one,
841 // then we are in this situation.
842 Error_CannotAccessProtected (ec
, loc
, mi
, qualifier_type
, container_type
);
844 ErrorIsInaccesible (loc
, TypeManager
.GetFullNameSignature (mi
), ec
.Report
);
851 lookup
= TypeManager
.MemberLookup (queried_type
, null, queried_type
,
852 AllMemberTypes
, AllBindingFlags
| BindingFlags
.NonPublic
,
856 if (lookup
== null) {
857 if (class_name
!= null) {
858 ec
.Report
.Error (103, loc
, "The name `{0}' does not exist in the current context",
861 Error_TypeDoesNotContainDefinition (ec
, queried_type
, name
);
866 if (TypeManager
.MemberLookup (queried_type
, null, queried_type
,
867 AllMemberTypes
, AllBindingFlags
|
868 BindingFlags
.NonPublic
, name
, null) == null) {
869 if ((lookup
.Length
== 1) && (lookup
[0] is Type
)) {
870 Type t
= (Type
) lookup
[0];
872 ec
.Report
.Error (305, loc
,
873 "Using the generic type `{0}' " +
874 "requires {1} type arguments",
875 TypeManager
.CSharpName (t
),
876 TypeManager
.GetNumberOfTypeArguments (t
).ToString ());
881 return Error_MemberLookupFailed (ec
, queried_type
, lookup
);
884 protected virtual Expression
Error_MemberLookupFailed (ResolveContext ec
, Type type
, MemberInfo
[] members
)
886 for (int i
= 0; i
< members
.Length
; ++i
) {
887 if (!(members
[i
] is MethodBase
))
891 // By default propagate the closest candidates upwards
892 return new MethodGroupExpr (members
, type
, loc
, true);
895 protected virtual void Error_NegativeArrayIndex (ResolveContext ec
, Location loc
)
897 throw new NotImplementedException ();
900 protected void Error_PointerInsideExpressionTree (ResolveContext ec
)
902 ec
.Report
.Error (1944, loc
, "An expression tree cannot contain an unsafe pointer operation");
906 /// Returns an expression that can be used to invoke operator true
907 /// on the expression if it exists.
909 protected static Expression
GetOperatorTrue (ResolveContext ec
, Expression e
, Location loc
)
911 return GetOperatorTrueOrFalse (ec
, e
, true, loc
);
915 /// Returns an expression that can be used to invoke operator false
916 /// on the expression if it exists.
918 static public Expression
GetOperatorFalse (ResolveContext ec
, Expression e
, Location loc
)
920 return GetOperatorTrueOrFalse (ec
, e
, false, loc
);
923 static Expression
GetOperatorTrueOrFalse (ResolveContext ec
, Expression e
, bool is_true
, Location loc
)
925 MethodGroupExpr operator_group
;
926 string mname
= Operator
.GetMetadataName (is_true
? Operator
.OpType
.True
: Operator
.OpType
.False
);
927 operator_group
= MethodLookup (ec
.Compiler
, ec
.CurrentType
, e
.Type
, mname
, loc
) as MethodGroupExpr
;
928 if (operator_group
== null)
931 Arguments arguments
= new Arguments (1);
932 arguments
.Add (new Argument (e
));
933 operator_group
= operator_group
.OverloadResolve (
934 ec
, ref arguments
, false, loc
);
936 if (operator_group
== null)
939 return new UserOperatorCall (operator_group
, arguments
, null, loc
);
942 public virtual string ExprClassName
946 case ExprClass
.Unresolved
:
948 case ExprClass
.Value
:
950 case ExprClass
.Variable
:
952 case ExprClass
.Namespace
:
956 case ExprClass
.MethodGroup
:
957 return "method group";
958 case ExprClass
.PropertyAccess
:
959 return "property access";
960 case ExprClass
.EventAccess
:
961 return "event access";
962 case ExprClass
.IndexerAccess
:
963 return "indexer access";
964 case ExprClass
.Nothing
:
966 case ExprClass
.TypeParameter
:
967 return "type parameter";
969 throw new Exception ("Should not happen");
974 /// Reports that we were expecting `expr' to be of class `expected'
976 public void Error_UnexpectedKind (Report r
, MemberCore mc
, string expected
, Location loc
)
978 Error_UnexpectedKind (r
, mc
, expected
, ExprClassName
, loc
);
981 public void Error_UnexpectedKind (Report r
, MemberCore mc
, string expected
, string was
, Location loc
)
985 name
= mc
.GetSignatureForError ();
987 name
= GetSignatureForError ();
989 r
.Error (118, loc
, "`{0}' is a `{1}' but a `{2}' was expected",
990 name
, was
, expected
);
993 public void Error_UnexpectedKind (ResolveContext ec
, ResolveFlags flags
, Location loc
)
995 string [] valid
= new string [4];
998 if ((flags
& ResolveFlags
.VariableOrValue
) != 0) {
999 valid
[count
++] = "variable";
1000 valid
[count
++] = "value";
1003 if ((flags
& ResolveFlags
.Type
) != 0)
1004 valid
[count
++] = "type";
1006 if ((flags
& ResolveFlags
.MethodGroup
) != 0)
1007 valid
[count
++] = "method group";
1010 valid
[count
++] = "unknown";
1012 StringBuilder sb
= new StringBuilder (valid
[0]);
1013 for (int i
= 1; i
< count
- 1; i
++) {
1015 sb
.Append (valid
[i
]);
1018 sb
.Append ("' or `");
1019 sb
.Append (valid
[count
- 1]);
1022 ec
.Report
.Error (119, loc
,
1023 "Expression denotes a `{0}', where a `{1}' was expected", ExprClassName
, sb
.ToString ());
1026 public static void UnsafeError (ResolveContext ec
, Location loc
)
1028 UnsafeError (ec
.Report
, loc
);
1031 public static void UnsafeError (Report Report
, Location loc
)
1033 Report
.Error (214, loc
, "Pointers and fixed size buffers may only be used in an unsafe context");
1037 // Load the object from the pointer.
1039 public static void LoadFromPtr (ILGenerator ig
, Type t
)
1041 if (t
== TypeManager
.int32_type
)
1042 ig
.Emit (OpCodes
.Ldind_I4
);
1043 else if (t
== TypeManager
.uint32_type
)
1044 ig
.Emit (OpCodes
.Ldind_U4
);
1045 else if (t
== TypeManager
.short_type
)
1046 ig
.Emit (OpCodes
.Ldind_I2
);
1047 else if (t
== TypeManager
.ushort_type
)
1048 ig
.Emit (OpCodes
.Ldind_U2
);
1049 else if (t
== TypeManager
.char_type
)
1050 ig
.Emit (OpCodes
.Ldind_U2
);
1051 else if (t
== TypeManager
.byte_type
)
1052 ig
.Emit (OpCodes
.Ldind_U1
);
1053 else if (t
== TypeManager
.sbyte_type
)
1054 ig
.Emit (OpCodes
.Ldind_I1
);
1055 else if (t
== TypeManager
.uint64_type
)
1056 ig
.Emit (OpCodes
.Ldind_I8
);
1057 else if (t
== TypeManager
.int64_type
)
1058 ig
.Emit (OpCodes
.Ldind_I8
);
1059 else if (t
== TypeManager
.float_type
)
1060 ig
.Emit (OpCodes
.Ldind_R4
);
1061 else if (t
== TypeManager
.double_type
)
1062 ig
.Emit (OpCodes
.Ldind_R8
);
1063 else if (t
== TypeManager
.bool_type
)
1064 ig
.Emit (OpCodes
.Ldind_I1
);
1065 else if (t
== TypeManager
.intptr_type
)
1066 ig
.Emit (OpCodes
.Ldind_I
);
1067 else if (TypeManager
.IsEnumType (t
)) {
1068 if (t
== TypeManager
.enum_type
)
1069 ig
.Emit (OpCodes
.Ldind_Ref
);
1071 LoadFromPtr (ig
, TypeManager
.GetEnumUnderlyingType (t
));
1072 } else if (TypeManager
.IsStruct (t
) || TypeManager
.IsGenericParameter (t
))
1073 ig
.Emit (OpCodes
.Ldobj
, t
);
1074 else if (t
.IsPointer
)
1075 ig
.Emit (OpCodes
.Ldind_I
);
1077 ig
.Emit (OpCodes
.Ldind_Ref
);
1081 // The stack contains the pointer and the value of type `type'
1083 public static void StoreFromPtr (ILGenerator ig
, Type type
)
1085 if (TypeManager
.IsEnumType (type
))
1086 type
= TypeManager
.GetEnumUnderlyingType (type
);
1087 if (type
== TypeManager
.int32_type
|| type
== TypeManager
.uint32_type
)
1088 ig
.Emit (OpCodes
.Stind_I4
);
1089 else if (type
== TypeManager
.int64_type
|| type
== TypeManager
.uint64_type
)
1090 ig
.Emit (OpCodes
.Stind_I8
);
1091 else if (type
== TypeManager
.char_type
|| type
== TypeManager
.short_type
||
1092 type
== TypeManager
.ushort_type
)
1093 ig
.Emit (OpCodes
.Stind_I2
);
1094 else if (type
== TypeManager
.float_type
)
1095 ig
.Emit (OpCodes
.Stind_R4
);
1096 else if (type
== TypeManager
.double_type
)
1097 ig
.Emit (OpCodes
.Stind_R8
);
1098 else if (type
== TypeManager
.byte_type
|| type
== TypeManager
.sbyte_type
||
1099 type
== TypeManager
.bool_type
)
1100 ig
.Emit (OpCodes
.Stind_I1
);
1101 else if (type
== TypeManager
.intptr_type
)
1102 ig
.Emit (OpCodes
.Stind_I
);
1103 else if (TypeManager
.IsStruct (type
) || TypeManager
.IsGenericParameter (type
))
1104 ig
.Emit (OpCodes
.Stobj
, type
);
1106 ig
.Emit (OpCodes
.Stind_Ref
);
1110 // Returns the size of type `t' if known, otherwise, 0
1112 public static int GetTypeSize (Type t
)
1114 t
= TypeManager
.TypeToCoreType (t
);
1115 if (t
== TypeManager
.int32_type
||
1116 t
== TypeManager
.uint32_type
||
1117 t
== TypeManager
.float_type
)
1119 else if (t
== TypeManager
.int64_type
||
1120 t
== TypeManager
.uint64_type
||
1121 t
== TypeManager
.double_type
)
1123 else if (t
== TypeManager
.byte_type
||
1124 t
== TypeManager
.sbyte_type
||
1125 t
== TypeManager
.bool_type
)
1127 else if (t
== TypeManager
.short_type
||
1128 t
== TypeManager
.char_type
||
1129 t
== TypeManager
.ushort_type
)
1131 else if (t
== TypeManager
.decimal_type
)
1137 protected void Error_CannotCallAbstractBase (ResolveContext ec
, string name
)
1139 ec
.Report
.Error (205, loc
, "Cannot call an abstract base member `{0}'", name
);
1142 protected void Error_CannotModifyIntermediateExpressionValue (ResolveContext ec
)
1144 ec
.Report
.SymbolRelatedToPreviousError (type
);
1145 if (ec
.CurrentInitializerVariable
!= null) {
1146 ec
.Report
.Error (1918, loc
, "Members of value type `{0}' cannot be assigned using a property `{1}' object initializer",
1147 TypeManager
.CSharpName (type
), GetSignatureForError ());
1149 ec
.Report
.Error (1612, loc
, "Cannot modify a value type return value of `{0}'. Consider storing the value in a temporary variable",
1150 GetSignatureForError ());
1155 // Converts `source' to an int, uint, long or ulong.
1157 protected Expression
ConvertExpressionToArrayIndex (ResolveContext ec
, Expression source
)
1159 if (TypeManager
.IsDynamicType (source
.type
)) {
1160 Arguments args
= new Arguments (1);
1161 args
.Add (new Argument (source
));
1162 return new DynamicConversion (TypeManager
.int32_type
, CSharpBinderFlags
.ConvertArrayIndex
, args
, loc
).Resolve (ec
);
1165 Expression converted
;
1167 using (ec
.Set (ResolveContext
.Options
.CheckedScope
)) {
1168 converted
= Convert
.ImplicitConversion (ec
, source
, TypeManager
.int32_type
, source
.loc
);
1169 if (converted
== null)
1170 converted
= Convert
.ImplicitConversion (ec
, source
, TypeManager
.uint32_type
, source
.loc
);
1171 if (converted
== null)
1172 converted
= Convert
.ImplicitConversion (ec
, source
, TypeManager
.int64_type
, source
.loc
);
1173 if (converted
== null)
1174 converted
= Convert
.ImplicitConversion (ec
, source
, TypeManager
.uint64_type
, source
.loc
);
1176 if (converted
== null) {
1177 source
.Error_ValueCannotBeConverted (ec
, source
.loc
, TypeManager
.int32_type
, false);
1183 // Only positive constants are allowed at compile time
1185 Constant c
= converted
as Constant
;
1186 if (c
!= null && c
.IsNegative
)
1187 Error_NegativeArrayIndex (ec
, source
.loc
);
1189 // No conversion needed to array index
1190 if (converted
.Type
== TypeManager
.int32_type
)
1193 return new ArrayIndexCast (converted
).Resolve (ec
);
1197 // Derived classes implement this method by cloning the fields that
1198 // could become altered during the Resolve stage
1200 // Only expressions that are created for the parser need to implement
1203 protected virtual void CloneTo (CloneContext clonectx
, Expression target
)
1205 throw new NotImplementedException (
1207 "CloneTo not implemented for expression {0}", this.GetType ()));
1211 // Clones an expression created by the parser.
1213 // We only support expressions created by the parser so far, not
1214 // expressions that have been resolved (many more classes would need
1215 // to implement CloneTo).
1217 // This infrastructure is here merely for Lambda expressions which
1218 // compile the same code using different type values for the same
1219 // arguments to find the correct overload
1221 public Expression
Clone (CloneContext clonectx
)
1223 Expression cloned
= (Expression
) MemberwiseClone ();
1224 CloneTo (clonectx
, cloned
);
1230 // Implementation of expression to expression tree conversion
1232 public abstract Expression
CreateExpressionTree (ResolveContext ec
);
1234 protected Expression
CreateExpressionFactoryCall (ResolveContext ec
, string name
, Arguments args
)
1236 return CreateExpressionFactoryCall (ec
, name
, null, args
, loc
);
1239 protected Expression
CreateExpressionFactoryCall (ResolveContext ec
, string name
, TypeArguments typeArguments
, Arguments args
)
1241 return CreateExpressionFactoryCall (ec
, name
, typeArguments
, args
, loc
);
1244 public static Expression
CreateExpressionFactoryCall (ResolveContext ec
, string name
, TypeArguments typeArguments
, Arguments args
, Location loc
)
1246 return new Invocation (new MemberAccess (CreateExpressionTypeExpression (ec
, loc
), name
, typeArguments
, loc
), args
);
1249 protected static TypeExpr
CreateExpressionTypeExpression (ResolveContext ec
, Location loc
)
1251 TypeExpr texpr
= TypeManager
.expression_type_expr
;
1252 if (texpr
== null) {
1253 Type t
= TypeManager
.CoreLookupType (ec
.Compiler
, "System.Linq.Expressions", "Expression", Kind
.Class
, true);
1257 TypeManager
.expression_type_expr
= texpr
= new TypeExpression (t
, Location
.Null
);
1264 // Implemented by all expressions which support conversion from
1265 // compiler expression to invokable runtime expression. Used by
1266 // dynamic C# binder.
1268 public virtual SLE
.Expression
MakeExpression (BuilderContext ctx
)
1270 throw new NotImplementedException ("MakeExpression for " + GetType ());
1273 public virtual void MutateHoistedGenericType (AnonymousMethodStorey storey
)
1275 // TODO: It should probably be type = storey.MutateType (type);
1280 /// This is just a base class for expressions that can
1281 /// appear on statements (invocations, object creation,
1282 /// assignments, post/pre increment and decrement). The idea
1283 /// being that they would support an extra Emition interface that
1284 /// does not leave a result on the stack.
1286 public abstract class ExpressionStatement
: Expression
{
1288 public virtual ExpressionStatement
ResolveStatement (BlockContext ec
)
1290 Expression e
= Resolve (ec
);
1294 ExpressionStatement es
= e
as ExpressionStatement
;
1296 Error_InvalidExpressionStatement (ec
);
1302 /// Requests the expression to be emitted in a `statement'
1303 /// context. This means that no new value is left on the
1304 /// stack after invoking this method (constrasted with
1305 /// Emit that will always leave a value on the stack).
1307 public abstract void EmitStatement (EmitContext ec
);
1309 public override void EmitSideEffect (EmitContext ec
)
1316 /// This kind of cast is used to encapsulate the child
1317 /// whose type is child.Type into an expression that is
1318 /// reported to return "return_type". This is used to encapsulate
1319 /// expressions which have compatible types, but need to be dealt
1320 /// at higher levels with.
1322 /// For example, a "byte" expression could be encapsulated in one
1323 /// of these as an "unsigned int". The type for the expression
1324 /// would be "unsigned int".
1327 public abstract class TypeCast
: Expression
1329 protected readonly Expression child
;
1331 protected TypeCast (Expression child
, Type return_type
)
1333 eclass
= child
.eclass
;
1334 loc
= child
.Location
;
1339 public override Expression
CreateExpressionTree (ResolveContext ec
)
1341 Arguments args
= new Arguments (2);
1342 args
.Add (new Argument (child
.CreateExpressionTree (ec
)));
1343 args
.Add (new Argument (new TypeOf (new TypeExpression (type
, loc
), loc
)));
1345 if (type
.IsPointer
|| child
.Type
.IsPointer
)
1346 Error_PointerInsideExpressionTree (ec
);
1348 return CreateExpressionFactoryCall (ec
, ec
.HasSet (ResolveContext
.Options
.CheckedScope
) ? "ConvertChecked" : "Convert", args
);
1351 protected override Expression
DoResolve (ResolveContext ec
)
1353 // This should never be invoked, we are born in fully
1354 // initialized state.
1359 public override void Emit (EmitContext ec
)
1364 public override bool GetAttributableValue (ResolveContext ec
, Type value_type
, out object value)
1366 return child
.GetAttributableValue (ec
, value_type
, out value);
1369 public override SLE
.Expression
MakeExpression (BuilderContext ctx
)
1371 return ctx
.HasSet (BuilderContext
.Options
.CheckedScope
) ?
1372 SLE
.Expression
.ConvertChecked (child
.MakeExpression (ctx
), type
) :
1373 SLE
.Expression
.Convert (child
.MakeExpression (ctx
), type
);
1376 public override void MutateHoistedGenericType (AnonymousMethodStorey storey
)
1378 type
= storey
.MutateType (type
);
1379 child
.MutateHoistedGenericType (storey
);
1382 protected override void CloneTo (CloneContext clonectx
, Expression t
)
1387 public override bool IsNull
{
1388 get { return child.IsNull; }
1392 public class EmptyCast
: TypeCast
{
1393 EmptyCast (Expression child
, Type target_type
)
1394 : base (child
, target_type
)
1398 public static Expression
Create (Expression child
, Type type
)
1400 Constant c
= child
as Constant
;
1402 return new EmptyConstantCast (c
, type
);
1404 EmptyCast e
= child
as EmptyCast
;
1406 return new EmptyCast (e
.child
, type
);
1408 return new EmptyCast (child
, type
);
1411 public override void EmitBranchable (EmitContext ec
, Label label
, bool on_true
)
1413 child
.EmitBranchable (ec
, label
, on_true
);
1416 public override void EmitSideEffect (EmitContext ec
)
1418 child
.EmitSideEffect (ec
);
1423 // Used for predefined class library user casts (no obsolete check, etc.)
1425 public class OperatorCast
: TypeCast
{
1426 MethodInfo conversion_operator
;
1428 public OperatorCast (Expression child
, Type target_type
)
1429 : this (child
, target_type
, false)
1433 public OperatorCast (Expression child
, Type target_type
, bool find_explicit
)
1434 : base (child
, target_type
)
1436 conversion_operator
= GetConversionOperator (find_explicit
);
1437 if (conversion_operator
== null)
1438 throw new InternalErrorException ("Outer conversion routine is out of sync");
1441 // Returns the implicit operator that converts from
1442 // 'child.Type' to our target type (type)
1443 MethodInfo
GetConversionOperator (bool find_explicit
)
1445 string operator_name
= find_explicit
? "op_Explicit" : "op_Implicit";
1449 mi
= TypeManager
.MemberLookup (child
.Type
, child
.Type
, child
.Type
, MemberTypes
.Method
,
1450 BindingFlags
.Static
| BindingFlags
.Public
, operator_name
, null);
1453 mi
= TypeManager
.MemberLookup (type
, type
, type
, MemberTypes
.Method
,
1454 BindingFlags
.Static
| BindingFlags
.Public
, operator_name
, null);
1457 foreach (MethodInfo oper
in mi
) {
1458 AParametersCollection pd
= TypeManager
.GetParameterData (oper
);
1460 if (pd
.Types
[0] == child
.Type
&& TypeManager
.TypeToCoreType (oper
.ReturnType
) == type
)
1467 public override void Emit (EmitContext ec
)
1470 ec
.ig
.Emit (OpCodes
.Call
, conversion_operator
);
1475 /// This is a numeric cast to a Decimal
1477 public class CastToDecimal
: OperatorCast
{
1478 public CastToDecimal (Expression child
)
1479 : this (child
, false)
1483 public CastToDecimal (Expression child
, bool find_explicit
)
1484 : base (child
, TypeManager
.decimal_type
, find_explicit
)
1490 /// This is an explicit numeric cast from a Decimal
1492 public class CastFromDecimal
: TypeCast
1494 static Dictionary
<Type
, MethodInfo
> operators
;
1496 public CastFromDecimal (Expression child
, Type return_type
)
1497 : base (child
, return_type
)
1499 if (child
.Type
!= TypeManager
.decimal_type
)
1500 throw new InternalErrorException (
1501 "The expected type is Decimal, instead it is " + child
.Type
.FullName
);
1504 // Returns the explicit operator that converts from an
1505 // express of type System.Decimal to 'type'.
1506 public Expression
Resolve ()
1508 if (operators
== null) {
1509 MemberInfo
[] all_oper
= TypeManager
.MemberLookup (TypeManager
.decimal_type
,
1510 TypeManager
.decimal_type
, TypeManager
.decimal_type
, MemberTypes
.Method
,
1511 BindingFlags
.Static
| BindingFlags
.Public
, "op_Explicit", null);
1513 operators
= new Dictionary
<Type
, MethodInfo
> (ReferenceEquality
<Type
>.Default
);
1514 foreach (MethodInfo oper
in all_oper
) {
1515 AParametersCollection pd
= TypeManager
.GetParameterData (oper
);
1516 if (pd
.Types
[0] == TypeManager
.decimal_type
)
1517 operators
.Add (TypeManager
.TypeToCoreType (oper
.ReturnType
), oper
);
1521 return operators
.ContainsKey (type
) ? this : null;
1524 public override void Emit (EmitContext ec
)
1526 ILGenerator ig
= ec
.ig
;
1529 ig
.Emit (OpCodes
.Call
, operators
[type
]);
1535 // Constant specialization of EmptyCast.
1536 // We need to special case this since an empty cast of
1537 // a constant is still a constant.
1539 public class EmptyConstantCast
: Constant
1541 public Constant child
;
1543 public EmptyConstantCast (Constant child
, Type type
)
1544 : base (child
.Location
)
1547 throw new ArgumentNullException ("child");
1550 this.eclass
= child
.eclass
;
1554 public override string AsString ()
1556 return child
.AsString ();
1559 public override object GetValue ()
1561 return child
.GetValue ();
1564 public override Constant
ConvertExplicitly (bool in_checked_context
, Type target_type
)
1566 if (child
.Type
== target_type
)
1569 // FIXME: check that 'type' can be converted to 'target_type' first
1570 return child
.ConvertExplicitly (in_checked_context
, target_type
);
1573 public override Expression
CreateExpressionTree (ResolveContext ec
)
1575 Arguments args
= Arguments
.CreateForExpressionTree (ec
, null,
1576 child
.CreateExpressionTree (ec
),
1577 new TypeOf (new TypeExpression (type
, loc
), loc
));
1580 Error_PointerInsideExpressionTree (ec
);
1582 return CreateExpressionFactoryCall (ec
, "Convert", args
);
1585 public override bool IsDefaultValue
{
1586 get { return child.IsDefaultValue; }
1589 public override bool IsNegative
{
1590 get { return child.IsNegative; }
1593 public override bool IsNull
{
1594 get { return child.IsNull; }
1597 public override bool IsZeroInteger
{
1598 get { return child.IsZeroInteger; }
1601 protected override Expression
DoResolve (ResolveContext rc
)
1606 public override void Emit (EmitContext ec
)
1611 public override void EmitBranchable (EmitContext ec
, Label label
, bool on_true
)
1613 child
.EmitBranchable (ec
, label
, on_true
);
1615 // Only to make verifier happy
1616 if (TypeManager
.IsGenericParameter (type
) && child
.IsNull
)
1617 ec
.ig
.Emit (OpCodes
.Unbox_Any
, type
);
1620 public override void EmitSideEffect (EmitContext ec
)
1622 child
.EmitSideEffect (ec
);
1625 public override Constant
ConvertImplicitly (ResolveContext rc
, Type target_type
)
1627 // FIXME: Do we need to check user conversions?
1628 if (!Convert
.ImplicitStandardConversionExists (this, target_type
))
1630 return child
.ConvertImplicitly (rc
, target_type
);
1633 public override void MutateHoistedGenericType (AnonymousMethodStorey storey
)
1635 child
.MutateHoistedGenericType (storey
);
1640 /// This class is used to wrap literals which belong inside Enums
1642 public class EnumConstant
: Constant
1644 public Constant Child
;
1646 public EnumConstant (Constant child
, Type enum_type
)
1647 : base (child
.Location
)
1650 this.type
= enum_type
;
1653 protected EnumConstant (Location loc
)
1658 protected override Expression
DoResolve (ResolveContext rc
)
1660 Child
= Child
.Resolve (rc
);
1661 this.eclass
= ExprClass
.Value
;
1665 public override void Emit (EmitContext ec
)
1670 public override void EmitBranchable (EmitContext ec
, Label label
, bool on_true
)
1672 Child
.EmitBranchable (ec
, label
, on_true
);
1675 public override void EmitSideEffect (EmitContext ec
)
1677 Child
.EmitSideEffect (ec
);
1680 public override bool GetAttributableValue (ResolveContext ec
, Type value_type
, out object value)
1682 value = GetTypedValue ();
1686 public override string GetSignatureForError()
1688 return TypeManager
.CSharpName (Type
);
1691 public override object GetValue ()
1693 return Child
.GetValue ();
1696 public override object GetTypedValue ()
1698 // FIXME: runtime is not ready to work with just emited enums
1699 if (!RootContext
.StdLib
) {
1700 return Child
.GetValue ();
1704 // Small workaround for big problem
1705 // System.Enum.ToObject cannot be called on dynamic types
1706 // EnumBuilder has to be used, but we cannot use EnumBuilder
1707 // because it does not properly support generics
1709 // This works only sometimes
1711 if (TypeManager
.IsBeingCompiled (type
))
1712 return Child
.GetValue ();
1715 return System
.Enum
.ToObject (type
, Child
.GetValue ());
1718 public override string AsString ()
1720 return Child
.AsString ();
1723 public EnumConstant
Increment()
1725 return new EnumConstant (((IntegralConstant
) Child
).Increment (), type
);
1728 public override bool IsDefaultValue
{
1730 return Child
.IsDefaultValue
;
1734 public override bool IsZeroInteger
{
1735 get { return Child.IsZeroInteger; }
1738 public override bool IsNegative
{
1740 return Child
.IsNegative
;
1744 public override Constant
ConvertExplicitly(bool in_checked_context
, Type target_type
)
1746 if (Child
.Type
== target_type
)
1749 return Child
.ConvertExplicitly (in_checked_context
, target_type
);
1752 public override Constant
ConvertImplicitly (ResolveContext rc
, Type type
)
1754 Type this_type
= TypeManager
.DropGenericTypeArguments (Type
);
1755 type
= TypeManager
.DropGenericTypeArguments (type
);
1757 if (this_type
== type
) {
1758 // This is workaround of mono bug. It can be removed when the latest corlib spreads enough
1759 if (TypeManager
.IsEnumType (type
.UnderlyingSystemType
))
1762 Type child_type
= TypeManager
.DropGenericTypeArguments (Child
.Type
);
1763 if (type
.UnderlyingSystemType
!= child_type
)
1764 Child
= Child
.ConvertImplicitly (rc
, type
.UnderlyingSystemType
);
1768 if (!Convert
.ImplicitStandardConversionExists (this, type
)){
1772 return Child
.ConvertImplicitly (rc
, type
);
1777 /// This kind of cast is used to encapsulate Value Types in objects.
1779 /// The effect of it is to box the value type emitted by the previous
1782 public class BoxedCast
: TypeCast
{
1784 public BoxedCast (Expression expr
, Type target_type
)
1785 : base (expr
, target_type
)
1787 eclass
= ExprClass
.Value
;
1790 protected override Expression
DoResolve (ResolveContext ec
)
1792 // This should never be invoked, we are born in fully
1793 // initialized state.
1798 public override void Emit (EmitContext ec
)
1802 ec
.ig
.Emit (OpCodes
.Box
, child
.Type
);
1805 public override void EmitSideEffect (EmitContext ec
)
1807 // boxing is side-effectful, since it involves runtime checks, except when boxing to Object or ValueType
1808 // so, we need to emit the box+pop instructions in most cases
1809 if (TypeManager
.IsStruct (child
.Type
) &&
1810 (type
== TypeManager
.object_type
|| type
== TypeManager
.value_type
))
1811 child
.EmitSideEffect (ec
);
1813 base.EmitSideEffect (ec
);
1817 public class UnboxCast
: TypeCast
{
1818 public UnboxCast (Expression expr
, Type return_type
)
1819 : base (expr
, return_type
)
1823 protected override Expression
DoResolve (ResolveContext ec
)
1825 // This should never be invoked, we are born in fully
1826 // initialized state.
1831 public override Expression
DoResolveLValue (ResolveContext ec
, Expression right_side
)
1833 if (right_side
== EmptyExpression
.LValueMemberAccess
|| right_side
== EmptyExpression
.LValueMemberOutAccess
)
1834 ec
.Report
.Error (445, loc
, "Cannot modify the result of an unboxing conversion");
1835 return base.DoResolveLValue (ec
, right_side
);
1838 public override void Emit (EmitContext ec
)
1842 ILGenerator ig
= ec
.ig
;
1843 ig
.Emit (OpCodes
.Unbox_Any
, type
);
1846 public override void MutateHoistedGenericType (AnonymousMethodStorey storey
)
1848 type
= storey
.MutateType (type
);
1849 base.MutateHoistedGenericType (storey
);
1854 /// This is used to perform explicit numeric conversions.
1856 /// Explicit numeric conversions might trigger exceptions in a checked
1857 /// context, so they should generate the conv.ovf opcodes instead of
1860 public class ConvCast
: TypeCast
{
1861 public enum Mode
: byte {
1862 I1_U1
, I1_U2
, I1_U4
, I1_U8
, I1_CH
,
1864 I2_I1
, I2_U1
, I2_U2
, I2_U4
, I2_U8
, I2_CH
,
1865 U2_I1
, U2_U1
, U2_I2
, U2_CH
,
1866 I4_I1
, I4_U1
, I4_I2
, I4_U2
, I4_U4
, I4_U8
, I4_CH
,
1867 U4_I1
, U4_U1
, U4_I2
, U4_U2
, U4_I4
, U4_CH
,
1868 I8_I1
, I8_U1
, I8_I2
, I8_U2
, I8_I4
, I8_U4
, I8_U8
, I8_CH
, I8_I
,
1869 U8_I1
, U8_U1
, U8_I2
, U8_U2
, U8_I4
, U8_U4
, U8_I8
, U8_CH
, U8_I
,
1870 CH_I1
, CH_U1
, CH_I2
,
1871 R4_I1
, R4_U1
, R4_I2
, R4_U2
, R4_I4
, R4_U4
, R4_I8
, R4_U8
, R4_CH
,
1872 R8_I1
, R8_U1
, R8_I2
, R8_U2
, R8_I4
, R8_U4
, R8_I8
, R8_U8
, R8_CH
, R8_R4
,
1878 public ConvCast (Expression child
, Type return_type
, Mode m
)
1879 : base (child
, return_type
)
1884 protected override Expression
DoResolve (ResolveContext ec
)
1886 // This should never be invoked, we are born in fully
1887 // initialized state.
1892 public override string ToString ()
1894 return String
.Format ("ConvCast ({0}, {1})", mode
, child
);
1897 public override void Emit (EmitContext ec
)
1899 ILGenerator ig
= ec
.ig
;
1903 if (ec
.HasSet (EmitContext
.Options
.CheckedScope
)) {
1905 case Mode
.I1_U1
: ig
.Emit (OpCodes
.Conv_Ovf_U1
); break;
1906 case Mode
.I1_U2
: ig
.Emit (OpCodes
.Conv_Ovf_U2
); break;
1907 case Mode
.I1_U4
: ig
.Emit (OpCodes
.Conv_Ovf_U4
); break;
1908 case Mode
.I1_U8
: ig
.Emit (OpCodes
.Conv_Ovf_U8
); break;
1909 case Mode
.I1_CH
: ig
.Emit (OpCodes
.Conv_Ovf_U2
); break;
1911 case Mode
.U1_I1
: ig
.Emit (OpCodes
.Conv_Ovf_I1_Un
); break;
1912 case Mode
.U1_CH
: /* nothing */ break;
1914 case Mode
.I2_I1
: ig
.Emit (OpCodes
.Conv_Ovf_I1
); break;
1915 case Mode
.I2_U1
: ig
.Emit (OpCodes
.Conv_Ovf_U1
); break;
1916 case Mode
.I2_U2
: ig
.Emit (OpCodes
.Conv_Ovf_U2
); break;
1917 case Mode
.I2_U4
: ig
.Emit (OpCodes
.Conv_Ovf_U4
); break;
1918 case Mode
.I2_U8
: ig
.Emit (OpCodes
.Conv_Ovf_U8
); break;
1919 case Mode
.I2_CH
: ig
.Emit (OpCodes
.Conv_Ovf_U2
); break;
1921 case Mode
.U2_I1
: ig
.Emit (OpCodes
.Conv_Ovf_I1_Un
); break;
1922 case Mode
.U2_U1
: ig
.Emit (OpCodes
.Conv_Ovf_U1_Un
); break;
1923 case Mode
.U2_I2
: ig
.Emit (OpCodes
.Conv_Ovf_I2_Un
); break;
1924 case Mode
.U2_CH
: /* nothing */ break;
1926 case Mode
.I4_I1
: ig
.Emit (OpCodes
.Conv_Ovf_I1
); break;
1927 case Mode
.I4_U1
: ig
.Emit (OpCodes
.Conv_Ovf_U1
); break;
1928 case Mode
.I4_I2
: ig
.Emit (OpCodes
.Conv_Ovf_I2
); break;
1929 case Mode
.I4_U4
: ig
.Emit (OpCodes
.Conv_Ovf_U4
); break;
1930 case Mode
.I4_U2
: ig
.Emit (OpCodes
.Conv_Ovf_U2
); break;
1931 case Mode
.I4_U8
: ig
.Emit (OpCodes
.Conv_Ovf_U8
); break;
1932 case Mode
.I4_CH
: ig
.Emit (OpCodes
.Conv_Ovf_U2
); break;
1934 case Mode
.U4_I1
: ig
.Emit (OpCodes
.Conv_Ovf_I1_Un
); break;
1935 case Mode
.U4_U1
: ig
.Emit (OpCodes
.Conv_Ovf_U1_Un
); break;
1936 case Mode
.U4_I2
: ig
.Emit (OpCodes
.Conv_Ovf_I2_Un
); break;
1937 case Mode
.U4_U2
: ig
.Emit (OpCodes
.Conv_Ovf_U2_Un
); break;
1938 case Mode
.U4_I4
: ig
.Emit (OpCodes
.Conv_Ovf_I4_Un
); break;
1939 case Mode
.U4_CH
: ig
.Emit (OpCodes
.Conv_Ovf_U2_Un
); break;
1941 case Mode
.I8_I1
: ig
.Emit (OpCodes
.Conv_Ovf_I1
); break;
1942 case Mode
.I8_U1
: ig
.Emit (OpCodes
.Conv_Ovf_U1
); break;
1943 case Mode
.I8_I2
: ig
.Emit (OpCodes
.Conv_Ovf_I2
); break;
1944 case Mode
.I8_U2
: ig
.Emit (OpCodes
.Conv_Ovf_U2
); break;
1945 case Mode
.I8_I4
: ig
.Emit (OpCodes
.Conv_Ovf_I4
); break;
1946 case Mode
.I8_U4
: ig
.Emit (OpCodes
.Conv_Ovf_U4
); break;
1947 case Mode
.I8_U8
: ig
.Emit (OpCodes
.Conv_Ovf_U8
); break;
1948 case Mode
.I8_CH
: ig
.Emit (OpCodes
.Conv_Ovf_U2
); break;
1949 case Mode
.I8_I
: ig
.Emit (OpCodes
.Conv_Ovf_U
); break;
1951 case Mode
.U8_I1
: ig
.Emit (OpCodes
.Conv_Ovf_I1_Un
); break;
1952 case Mode
.U8_U1
: ig
.Emit (OpCodes
.Conv_Ovf_U1_Un
); break;
1953 case Mode
.U8_I2
: ig
.Emit (OpCodes
.Conv_Ovf_I2_Un
); break;
1954 case Mode
.U8_U2
: ig
.Emit (OpCodes
.Conv_Ovf_U2_Un
); break;
1955 case Mode
.U8_I4
: ig
.Emit (OpCodes
.Conv_Ovf_I4_Un
); break;
1956 case Mode
.U8_U4
: ig
.Emit (OpCodes
.Conv_Ovf_U4_Un
); break;
1957 case Mode
.U8_I8
: ig
.Emit (OpCodes
.Conv_Ovf_I8_Un
); break;
1958 case Mode
.U8_CH
: ig
.Emit (OpCodes
.Conv_Ovf_U2_Un
); break;
1959 case Mode
.U8_I
: ig
.Emit (OpCodes
.Conv_Ovf_U_Un
); break;
1961 case Mode
.CH_I1
: ig
.Emit (OpCodes
.Conv_Ovf_I1_Un
); break;
1962 case Mode
.CH_U1
: ig
.Emit (OpCodes
.Conv_Ovf_U1_Un
); break;
1963 case Mode
.CH_I2
: ig
.Emit (OpCodes
.Conv_Ovf_I2_Un
); break;
1965 case Mode
.R4_I1
: ig
.Emit (OpCodes
.Conv_Ovf_I1
); break;
1966 case Mode
.R4_U1
: ig
.Emit (OpCodes
.Conv_Ovf_U1
); break;
1967 case Mode
.R4_I2
: ig
.Emit (OpCodes
.Conv_Ovf_I2
); break;
1968 case Mode
.R4_U2
: ig
.Emit (OpCodes
.Conv_Ovf_U2
); break;
1969 case Mode
.R4_I4
: ig
.Emit (OpCodes
.Conv_Ovf_I4
); break;
1970 case Mode
.R4_U4
: ig
.Emit (OpCodes
.Conv_Ovf_U4
); break;
1971 case Mode
.R4_I8
: ig
.Emit (OpCodes
.Conv_Ovf_I8
); break;
1972 case Mode
.R4_U8
: ig
.Emit (OpCodes
.Conv_Ovf_U8
); break;
1973 case Mode
.R4_CH
: ig
.Emit (OpCodes
.Conv_Ovf_U2
); break;
1975 case Mode
.R8_I1
: ig
.Emit (OpCodes
.Conv_Ovf_I1
); break;
1976 case Mode
.R8_U1
: ig
.Emit (OpCodes
.Conv_Ovf_U1
); break;
1977 case Mode
.R8_I2
: ig
.Emit (OpCodes
.Conv_Ovf_I2
); break;
1978 case Mode
.R8_U2
: ig
.Emit (OpCodes
.Conv_Ovf_U2
); break;
1979 case Mode
.R8_I4
: ig
.Emit (OpCodes
.Conv_Ovf_I4
); break;
1980 case Mode
.R8_U4
: ig
.Emit (OpCodes
.Conv_Ovf_U4
); break;
1981 case Mode
.R8_I8
: ig
.Emit (OpCodes
.Conv_Ovf_I8
); break;
1982 case Mode
.R8_U8
: ig
.Emit (OpCodes
.Conv_Ovf_U8
); break;
1983 case Mode
.R8_CH
: ig
.Emit (OpCodes
.Conv_Ovf_U2
); break;
1984 case Mode
.R8_R4
: ig
.Emit (OpCodes
.Conv_R4
); break;
1986 case Mode
.I_I8
: ig
.Emit (OpCodes
.Conv_Ovf_I8_Un
); break;
1990 case Mode
.I1_U1
: ig
.Emit (OpCodes
.Conv_U1
); break;
1991 case Mode
.I1_U2
: ig
.Emit (OpCodes
.Conv_U2
); break;
1992 case Mode
.I1_U4
: ig
.Emit (OpCodes
.Conv_U4
); break;
1993 case Mode
.I1_U8
: ig
.Emit (OpCodes
.Conv_I8
); break;
1994 case Mode
.I1_CH
: ig
.Emit (OpCodes
.Conv_U2
); break;
1996 case Mode
.U1_I1
: ig
.Emit (OpCodes
.Conv_I1
); break;
1997 case Mode
.U1_CH
: ig
.Emit (OpCodes
.Conv_U2
); break;
1999 case Mode
.I2_I1
: ig
.Emit (OpCodes
.Conv_I1
); break;
2000 case Mode
.I2_U1
: ig
.Emit (OpCodes
.Conv_U1
); break;
2001 case Mode
.I2_U2
: ig
.Emit (OpCodes
.Conv_U2
); break;
2002 case Mode
.I2_U4
: ig
.Emit (OpCodes
.Conv_U4
); break;
2003 case Mode
.I2_U8
: ig
.Emit (OpCodes
.Conv_I8
); break;
2004 case Mode
.I2_CH
: ig
.Emit (OpCodes
.Conv_U2
); break;
2006 case Mode
.U2_I1
: ig
.Emit (OpCodes
.Conv_I1
); break;
2007 case Mode
.U2_U1
: ig
.Emit (OpCodes
.Conv_U1
); break;
2008 case Mode
.U2_I2
: ig
.Emit (OpCodes
.Conv_I2
); break;
2009 case Mode
.U2_CH
: /* nothing */ break;
2011 case Mode
.I4_I1
: ig
.Emit (OpCodes
.Conv_I1
); break;
2012 case Mode
.I4_U1
: ig
.Emit (OpCodes
.Conv_U1
); break;
2013 case Mode
.I4_I2
: ig
.Emit (OpCodes
.Conv_I2
); break;
2014 case Mode
.I4_U4
: /* nothing */ break;
2015 case Mode
.I4_U2
: ig
.Emit (OpCodes
.Conv_U2
); break;
2016 case Mode
.I4_U8
: ig
.Emit (OpCodes
.Conv_I8
); break;
2017 case Mode
.I4_CH
: ig
.Emit (OpCodes
.Conv_U2
); break;
2019 case Mode
.U4_I1
: ig
.Emit (OpCodes
.Conv_I1
); break;
2020 case Mode
.U4_U1
: ig
.Emit (OpCodes
.Conv_U1
); break;
2021 case Mode
.U4_I2
: ig
.Emit (OpCodes
.Conv_I2
); break;
2022 case Mode
.U4_U2
: ig
.Emit (OpCodes
.Conv_U2
); break;
2023 case Mode
.U4_I4
: /* nothing */ break;
2024 case Mode
.U4_CH
: ig
.Emit (OpCodes
.Conv_U2
); break;
2026 case Mode
.I8_I1
: ig
.Emit (OpCodes
.Conv_I1
); break;
2027 case Mode
.I8_U1
: ig
.Emit (OpCodes
.Conv_U1
); break;
2028 case Mode
.I8_I2
: ig
.Emit (OpCodes
.Conv_I2
); break;
2029 case Mode
.I8_U2
: ig
.Emit (OpCodes
.Conv_U2
); break;
2030 case Mode
.I8_I4
: ig
.Emit (OpCodes
.Conv_I4
); break;
2031 case Mode
.I8_U4
: ig
.Emit (OpCodes
.Conv_U4
); break;
2032 case Mode
.I8_U8
: /* nothing */ break;
2033 case Mode
.I8_CH
: ig
.Emit (OpCodes
.Conv_U2
); break;
2034 case Mode
.I8_I
: ig
.Emit (OpCodes
.Conv_U
); break;
2036 case Mode
.U8_I1
: ig
.Emit (OpCodes
.Conv_I1
); break;
2037 case Mode
.U8_U1
: ig
.Emit (OpCodes
.Conv_U1
); break;
2038 case Mode
.U8_I2
: ig
.Emit (OpCodes
.Conv_I2
); break;
2039 case Mode
.U8_U2
: ig
.Emit (OpCodes
.Conv_U2
); break;
2040 case Mode
.U8_I4
: ig
.Emit (OpCodes
.Conv_I4
); break;
2041 case Mode
.U8_U4
: ig
.Emit (OpCodes
.Conv_U4
); break;
2042 case Mode
.U8_I8
: /* nothing */ break;
2043 case Mode
.U8_CH
: ig
.Emit (OpCodes
.Conv_U2
); break;
2044 case Mode
.U8_I
: ig
.Emit (OpCodes
.Conv_U
); break;
2046 case Mode
.CH_I1
: ig
.Emit (OpCodes
.Conv_I1
); break;
2047 case Mode
.CH_U1
: ig
.Emit (OpCodes
.Conv_U1
); break;
2048 case Mode
.CH_I2
: ig
.Emit (OpCodes
.Conv_I2
); break;
2050 case Mode
.R4_I1
: ig
.Emit (OpCodes
.Conv_I1
); break;
2051 case Mode
.R4_U1
: ig
.Emit (OpCodes
.Conv_U1
); break;
2052 case Mode
.R4_I2
: ig
.Emit (OpCodes
.Conv_I2
); break;
2053 case Mode
.R4_U2
: ig
.Emit (OpCodes
.Conv_U2
); break;
2054 case Mode
.R4_I4
: ig
.Emit (OpCodes
.Conv_I4
); break;
2055 case Mode
.R4_U4
: ig
.Emit (OpCodes
.Conv_U4
); break;
2056 case Mode
.R4_I8
: ig
.Emit (OpCodes
.Conv_I8
); break;
2057 case Mode
.R4_U8
: ig
.Emit (OpCodes
.Conv_U8
); break;
2058 case Mode
.R4_CH
: ig
.Emit (OpCodes
.Conv_U2
); break;
2060 case Mode
.R8_I1
: ig
.Emit (OpCodes
.Conv_I1
); break;
2061 case Mode
.R8_U1
: ig
.Emit (OpCodes
.Conv_U1
); break;
2062 case Mode
.R8_I2
: ig
.Emit (OpCodes
.Conv_I2
); break;
2063 case Mode
.R8_U2
: ig
.Emit (OpCodes
.Conv_U2
); break;
2064 case Mode
.R8_I4
: ig
.Emit (OpCodes
.Conv_I4
); break;
2065 case Mode
.R8_U4
: ig
.Emit (OpCodes
.Conv_U4
); break;
2066 case Mode
.R8_I8
: ig
.Emit (OpCodes
.Conv_I8
); break;
2067 case Mode
.R8_U8
: ig
.Emit (OpCodes
.Conv_U8
); break;
2068 case Mode
.R8_CH
: ig
.Emit (OpCodes
.Conv_U2
); break;
2069 case Mode
.R8_R4
: ig
.Emit (OpCodes
.Conv_R4
); break;
2071 case Mode
.I_I8
: ig
.Emit (OpCodes
.Conv_U8
); break;
2077 public class OpcodeCast
: TypeCast
{
2080 public OpcodeCast (Expression child
, Type return_type
, OpCode op
)
2081 : base (child
, return_type
)
2086 protected override Expression
DoResolve (ResolveContext ec
)
2088 // This should never be invoked, we are born in fully
2089 // initialized state.
2094 public override void Emit (EmitContext ec
)
2100 public Type UnderlyingType
{
2101 get { return child.Type; }
2106 /// This kind of cast is used to encapsulate a child and cast it
2107 /// to the class requested
2109 public sealed class ClassCast
: TypeCast
{
2110 readonly bool forced
;
2112 public ClassCast (Expression child
, Type return_type
)
2113 : base (child
, return_type
)
2117 public ClassCast (Expression child
, Type return_type
, bool forced
)
2118 : base (child
, return_type
)
2120 this.forced
= forced
;
2123 public override void Emit (EmitContext ec
)
2127 bool gen
= TypeManager
.IsGenericParameter (child
.Type
);
2129 ec
.ig
.Emit (OpCodes
.Box
, child
.Type
);
2131 if (type
.IsGenericParameter
) {
2132 ec
.ig
.Emit (OpCodes
.Unbox_Any
, type
);
2139 ec
.ig
.Emit (OpCodes
.Castclass
, type
);
2144 // Created during resolving pahse when an expression is wrapped or constantified
2145 // and original expression can be used later (e.g. for expression trees)
2147 public class ReducedExpression
: Expression
2149 sealed class ReducedConstantExpression
: EmptyConstantCast
2151 readonly Expression orig_expr
;
2153 public ReducedConstantExpression (Constant expr
, Expression orig_expr
)
2154 : base (expr
, expr
.Type
)
2156 this.orig_expr
= orig_expr
;
2159 public override Constant
ConvertImplicitly (ResolveContext rc
, Type target_type
)
2161 Constant c
= base.ConvertImplicitly (rc
, target_type
);
2163 c
= new ReducedConstantExpression (c
, orig_expr
);
2168 public override Expression
CreateExpressionTree (ResolveContext ec
)
2170 return orig_expr
.CreateExpressionTree (ec
);
2173 public override bool GetAttributableValue (ResolveContext ec
, Type value_type
, out object value)
2176 // Even if resolved result is a constant original expression was not
2177 // and attribute accepts constants only
2179 Attribute
.Error_AttributeArgumentNotValid (ec
, orig_expr
.Location
);
2184 public override Constant
ConvertExplicitly (bool in_checked_context
, Type target_type
)
2186 Constant c
= base.ConvertExplicitly (in_checked_context
, target_type
);
2188 c
= new ReducedConstantExpression (c
, orig_expr
);
2193 sealed class ReducedExpressionStatement
: ExpressionStatement
2195 readonly Expression orig_expr
;
2196 readonly ExpressionStatement stm
;
2198 public ReducedExpressionStatement (ExpressionStatement stm
, Expression orig
)
2200 this.orig_expr
= orig
;
2202 this.loc
= orig
.Location
;
2205 public override Expression
CreateExpressionTree (ResolveContext ec
)
2207 return orig_expr
.CreateExpressionTree (ec
);
2210 protected override Expression
DoResolve (ResolveContext ec
)
2212 eclass
= stm
.eclass
;
2217 public override void Emit (EmitContext ec
)
2222 public override void EmitStatement (EmitContext ec
)
2224 stm
.EmitStatement (ec
);
2227 public override void MutateHoistedGenericType (AnonymousMethodStorey storey
)
2229 stm
.MutateHoistedGenericType (storey
);
2233 readonly Expression expr
, orig_expr
;
2235 private ReducedExpression (Expression expr
, Expression orig_expr
)
2238 this.eclass
= expr
.eclass
;
2239 this.type
= expr
.Type
;
2240 this.orig_expr
= orig_expr
;
2241 this.loc
= orig_expr
.Location
;
2245 // Creates fully resolved expression switcher
2247 public static Constant
Create (Constant expr
, Expression original_expr
)
2249 if (expr
.eclass
== ExprClass
.Unresolved
)
2250 throw new ArgumentException ("Unresolved expression");
2252 return new ReducedConstantExpression (expr
, original_expr
);
2255 public static ExpressionStatement
Create (ExpressionStatement s
, Expression orig
)
2257 return new ReducedExpressionStatement (s
, orig
);
2261 // Creates unresolved reduce expression. The original expression has to be
2264 public static Expression
Create (Expression expr
, Expression original_expr
)
2266 Constant c
= expr
as Constant
;
2268 return Create (c
, original_expr
);
2270 ExpressionStatement s
= expr
as ExpressionStatement
;
2272 return Create (s
, original_expr
);
2274 if (expr
.eclass
== ExprClass
.Unresolved
)
2275 throw new ArgumentException ("Unresolved expression");
2277 return new ReducedExpression (expr
, original_expr
);
2280 public override Expression
CreateExpressionTree (ResolveContext ec
)
2282 return orig_expr
.CreateExpressionTree (ec
);
2285 protected override Expression
DoResolve (ResolveContext ec
)
2290 public override void Emit (EmitContext ec
)
2295 public override void EmitBranchable (EmitContext ec
, Label target
, bool on_true
)
2297 expr
.EmitBranchable (ec
, target
, on_true
);
2300 public override SLE
.Expression
MakeExpression (BuilderContext ctx
)
2302 return orig_expr
.MakeExpression (ctx
);
2305 public override void MutateHoistedGenericType (AnonymousMethodStorey storey
)
2307 expr
.MutateHoistedGenericType (storey
);
2312 // Standard composite pattern
2314 public abstract class CompositeExpression
: Expression
2318 protected CompositeExpression (Expression expr
)
2321 this.loc
= expr
.Location
;
2324 public override Expression
CreateExpressionTree (ResolveContext ec
)
2326 return expr
.CreateExpressionTree (ec
);
2329 public Expression Child
{
2330 get { return expr; }
2333 protected override Expression
DoResolve (ResolveContext ec
)
2335 expr
= expr
.Resolve (ec
);
2338 eclass
= expr
.eclass
;
2344 public override void Emit (EmitContext ec
)
2349 public override bool IsNull
{
2350 get { return expr.IsNull; }
2355 // Base of expressions used only to narrow resolve flow
2357 public abstract class ShimExpression
: Expression
2359 protected Expression expr
;
2361 protected ShimExpression (Expression expr
)
2366 protected override void CloneTo (CloneContext clonectx
, Expression t
)
2371 ShimExpression target
= (ShimExpression
) t
;
2372 target
.expr
= expr
.Clone (clonectx
);
2375 public override Expression
CreateExpressionTree (ResolveContext ec
)
2377 throw new NotSupportedException ("ET");
2380 public override void Emit (EmitContext ec
)
2382 throw new InternalErrorException ("Missing Resolve call");
2385 public Expression Expr
{
2386 get { return expr; }
2389 public override void MutateHoistedGenericType (AnonymousMethodStorey storey
)
2391 throw new InternalErrorException ("Missing Resolve call");
2396 // Unresolved type name expressions
2398 public abstract class ATypeNameExpression
: FullNamedExpression
2401 protected TypeArguments targs
;
2403 protected ATypeNameExpression (string name
, Location l
)
2409 protected ATypeNameExpression (string name
, TypeArguments targs
, Location l
)
2416 public bool HasTypeArguments
{
2418 return targs
!= null;
2422 public override bool Equals (object obj
)
2424 ATypeNameExpression atne
= obj
as ATypeNameExpression
;
2425 return atne
!= null && atne
.Name
== Name
&&
2426 (targs
== null || targs
.Equals (atne
.targs
));
2429 public override int GetHashCode ()
2431 return Name
.GetHashCode ();
2434 public override string GetSignatureForError ()
2436 if (targs
!= null) {
2437 return TypeManager
.RemoveGenericArity (Name
) + "<" +
2438 targs
.GetSignatureForError () + ">";
2444 public string Name
{
2453 public TypeArguments TypeArguments
{
2461 /// SimpleName expressions are formed of a single word and only happen at the beginning
2462 /// of a dotted-name.
2464 public class SimpleName
: ATypeNameExpression
2466 public SimpleName (string name
, Location l
)
2471 public SimpleName (string name
, TypeArguments args
, Location l
)
2472 : base (name
, args
, l
)
2476 public SimpleName (string name
, TypeParameter
[] type_params
, Location l
)
2479 targs
= new TypeArguments ();
2480 foreach (TypeParameter type_param
in type_params
)
2481 targs
.Add (new TypeParameterExpr (type_param
, l
));
2484 public static string RemoveGenericArity (string name
)
2487 StringBuilder sb
= null;
2489 int pos
= name
.IndexOf ('`', start
);
2494 sb
.Append (name
.Substring (start
));
2499 sb
= new StringBuilder ();
2500 sb
.Append (name
.Substring (start
, pos
-start
));
2503 while ((pos
< name
.Length
) && Char
.IsNumber (name
[pos
]))
2507 } while (start
< name
.Length
);
2509 return sb
.ToString ();
2512 public SimpleName
GetMethodGroup ()
2514 return new SimpleName (RemoveGenericArity (Name
), targs
, loc
);
2517 public static void Error_ObjectRefRequired (ResolveContext ec
, Location l
, string name
)
2519 if (ec
.HasSet (ResolveContext
.Options
.FieldInitializerScope
))
2520 ec
.Report
.Error (236, l
,
2521 "A field initializer cannot reference the nonstatic field, method, or property `{0}'",
2524 ec
.Report
.Error (120, l
,
2525 "An object reference is required to access non-static member `{0}'",
2529 public bool IdenticalNameAndTypeName (IMemberContext mc
, Expression resolved_to
, Location loc
)
2531 return resolved_to
!= null && resolved_to
.Type
!= null &&
2532 resolved_to
.Type
.Name
== Name
&&
2533 (mc
.LookupNamespaceOrType (Name
, loc
, /* ignore_cs0104 = */ true) != null);
2536 protected override Expression
DoResolve (ResolveContext ec
)
2538 return SimpleNameResolve (ec
, null, false);
2541 public override Expression
DoResolveLValue (ResolveContext ec
, Expression right_side
)
2543 return SimpleNameResolve (ec
, right_side
, false);
2546 public Expression
DoResolve (ResolveContext ec
, bool intermediate
)
2548 return SimpleNameResolve (ec
, null, intermediate
);
2551 static bool IsNestedChild (Type t
, Type parent
)
2553 while (parent
!= null) {
2554 if (TypeManager
.IsNestedChildOf (t
, TypeManager
.DropGenericTypeArguments (parent
)))
2557 parent
= parent
.BaseType
;
2563 FullNamedExpression
ResolveNested (Type t
)
2565 if (!TypeManager
.IsGenericTypeDefinition (t
) && !TypeManager
.IsGenericType (t
))
2569 while (ds
!= null && !IsNestedChild (t
, ds
))
2570 ds
= ds
.DeclaringType
;
2575 Type
[] gen_params
= TypeManager
.GetTypeArguments (t
);
2577 int arg_count
= targs
!= null ? targs
.Count
: 0;
2579 for (; (ds
!= null) && TypeManager
.IsGenericType (ds
); ds
= ds
.DeclaringType
) {
2580 Type
[] gargs
= TypeManager
.GetTypeArguments (ds
);
2581 if (arg_count
+ gargs
.Length
== gen_params
.Length
) {
2582 TypeArguments new_args
= new TypeArguments ();
2583 foreach (Type param
in gargs
)
2584 new_args
.Add (new TypeExpression (param
, loc
));
2587 new_args
.Add (targs
);
2589 return new GenericTypeExpr (t
, new_args
, loc
);
2596 public override FullNamedExpression
ResolveAsTypeStep (IMemberContext ec
, bool silent
)
2598 int errors
= ec
.Compiler
.Report
.Errors
;
2599 FullNamedExpression fne
= ec
.LookupNamespaceOrType (Name
, loc
, /*ignore_cs0104=*/ false);
2602 if (fne
.Type
== null)
2605 FullNamedExpression nested
= ResolveNested (fne
.Type
);
2607 return nested
.ResolveAsTypeStep (ec
, false);
2609 if (targs
!= null) {
2610 if (TypeManager
.IsGenericType (fne
.Type
)) {
2611 GenericTypeExpr ct
= new GenericTypeExpr (fne
.Type
, targs
, loc
);
2612 return ct
.ResolveAsTypeStep (ec
, false);
2615 fne
.Error_TypeArgumentsCannotBeUsed (ec
.Compiler
.Report
, loc
);
2621 if (!HasTypeArguments
&& Name
== "dynamic" &&
2622 RootContext
.Version
> LanguageVersion
.V_3
&&
2623 RootContext
.MetadataCompatibilityVersion
> MetadataVersion
.v2
) {
2625 if (!PredefinedAttributes
.Get
.Dynamic
.IsDefined
) {
2626 ec
.Compiler
.Report
.Error (1980, Location
,
2627 "Dynamic keyword requires `{0}' to be defined. Are you missing System.Core.dll assembly reference?",
2628 PredefinedAttributes
.Get
.Dynamic
.GetSignatureForError ());
2631 return new DynamicTypeExpr (loc
);
2634 if (silent
|| errors
!= ec
.Compiler
.Report
.Errors
)
2637 Error_TypeOrNamespaceNotFound (ec
);
2641 protected virtual void Error_TypeOrNamespaceNotFound (IMemberContext ec
)
2643 if (ec
.CurrentType
!= null) {
2644 if (ec
.CurrentTypeDefinition
!= null) {
2645 MemberCore mc
= ec
.CurrentTypeDefinition
.GetDefinition (Name
);
2647 Error_UnexpectedKind (ec
.Compiler
.Report
, mc
, "type", GetMemberType (mc
), loc
);
2652 string ns
= ec
.CurrentType
.Namespace
;
2653 string fullname
= (ns
.Length
> 0) ? ns
+ "." + Name
: Name
;
2654 foreach (Assembly a
in GlobalRootNamespace
.Instance
.Assemblies
) {
2655 Type type
= a
.GetType (fullname
);
2657 ec
.Compiler
.Report
.SymbolRelatedToPreviousError (type
);
2658 Expression
.ErrorIsInaccesible (loc
, TypeManager
.CSharpName (type
), ec
.Compiler
.Report
);
2663 if (ec
.CurrentTypeDefinition
!= null) {
2664 Type t
= ec
.CurrentTypeDefinition
.LookupAnyGeneric (Name
);
2666 Namespace
.Error_InvalidNumberOfTypeArguments (ec
.Compiler
.Report
, t
, loc
);
2672 if (targs
!= null) {
2673 FullNamedExpression retval
= ec
.LookupNamespaceOrType (SimpleName
.RemoveGenericArity (Name
), loc
, true);
2674 if (retval
!= null) {
2675 retval
.Error_TypeArgumentsCannotBeUsed (ec
.Compiler
.Report
, loc
);
2680 NamespaceEntry
.Error_NamespaceNotFound (loc
, Name
, ec
.Compiler
.Report
);
2683 // TODO: I am still not convinced about this. If someone else will need it
2684 // implement this as virtual property in MemberCore hierarchy
2685 public static string GetMemberType (MemberCore mc
)
2691 if (mc
is FieldBase
)
2693 if (mc
is MethodCore
)
2695 if (mc
is EnumMember
)
2703 Expression
SimpleNameResolve (ResolveContext ec
, Expression right_side
, bool intermediate
)
2705 Expression e
= DoSimpleNameResolve (ec
, right_side
, intermediate
);
2710 if (ec
.CurrentBlock
== null || ec
.CurrentBlock
.CheckInvariantMeaningInBlock (Name
, e
, Location
))
2717 /// 7.5.2: Simple Names.
2719 /// Local Variables and Parameters are handled at
2720 /// parse time, so they never occur as SimpleNames.
2722 /// The `intermediate' flag is used by MemberAccess only
2723 /// and it is used to inform us that it is ok for us to
2724 /// avoid the static check, because MemberAccess might end
2725 /// up resolving the Name as a Type name and the access as
2726 /// a static type access.
2728 /// ie: Type Type; .... { Type.GetType (""); }
2730 /// Type is both an instance variable and a Type; Type.GetType
2731 /// is the static method not an instance method of type.
2733 Expression
DoSimpleNameResolve (ResolveContext ec
, Expression right_side
, bool intermediate
)
2735 Expression e
= null;
2738 // Stage 1: Performed by the parser (binding to locals or parameters).
2740 Block current_block
= ec
.CurrentBlock
;
2741 if (current_block
!= null){
2742 LocalInfo vi
= current_block
.GetLocalInfo (Name
);
2744 e
= new LocalVariableReference (ec
.CurrentBlock
, Name
, loc
);
2746 if (right_side
!= null) {
2747 e
= e
.ResolveLValue (ec
, right_side
);
2750 using (ec
.With (ResolveContext
.Options
.DoFlowAnalysis
, false)) {
2751 e
= e
.Resolve (ec
, ResolveFlags
.VariableOrValue
);
2754 e
= e
.Resolve (ec
, ResolveFlags
.VariableOrValue
);
2758 if (targs
!= null && e
!= null)
2759 e
.Error_TypeArgumentsCannotBeUsed (ec
.Report
, loc
);
2764 e
= current_block
.Toplevel
.GetParameterReference (Name
, loc
);
2766 if (right_side
!= null)
2767 e
= e
.ResolveLValue (ec
, right_side
);
2771 if (targs
!= null && e
!= null)
2772 e
.Error_TypeArgumentsCannotBeUsed (ec
.Report
, loc
);
2779 // Stage 2: Lookup members
2782 Type almost_matched_type
= null;
2783 IList
<MemberInfo
> almost_matched
= null;
2784 for (Type lookup_ds
= ec
.CurrentType
; lookup_ds
!= null; lookup_ds
= lookup_ds
.DeclaringType
) {
2785 e
= MemberLookup (ec
.Compiler
, ec
.CurrentType
, lookup_ds
, Name
, loc
);
2787 PropertyExpr pe
= e
as PropertyExpr
;
2789 AParametersCollection param
= TypeManager
.GetParameterData (pe
.PropertyInfo
);
2791 // since TypeManager.MemberLookup doesn't know if we're doing a lvalue access or not,
2792 // it doesn't know which accessor to check permissions against
2793 if (param
.IsEmpty
&& pe
.IsAccessibleFrom (ec
.CurrentType
, right_side
!= null))
2795 } else if (e
is EventExpr
) {
2796 if (((EventExpr
) e
).IsAccessibleFrom (ec
.CurrentType
))
2798 } else if (targs
!= null && e
is TypeExpression
) {
2799 e
= new GenericTypeExpr (e
.Type
, targs
, loc
).ResolveAsTypeStep (ec
, false);
2807 if (almost_matched
== null && almost_matched_members
.Count
> 0) {
2808 almost_matched_type
= lookup_ds
;
2809 almost_matched
= new List
<MemberInfo
>(almost_matched_members
);
2814 if (almost_matched
== null && almost_matched_members
.Count
> 0) {
2815 almost_matched_type
= ec
.CurrentType
;
2816 almost_matched
= new List
<MemberInfo
> (almost_matched_members
);
2818 e
= ResolveAsTypeStep (ec
, true);
2822 if (current_block
!= null) {
2823 IKnownVariable ikv
= current_block
.Explicit
.GetKnownVariable (Name
);
2825 LocalInfo li
= ikv
as LocalInfo
;
2826 // Supress CS0219 warning
2830 Error_VariableIsUsedBeforeItIsDeclared (ec
.Report
, Name
);
2835 if (RootContext
.EvalMode
){
2836 FieldInfo fi
= Evaluator
.LookupField (Name
);
2838 return new FieldExpr (fi
, loc
).Resolve (ec
);
2841 if (almost_matched
!= null)
2842 almost_matched_members
= almost_matched
;
2843 if (almost_matched_type
== null)
2844 almost_matched_type
= ec
.CurrentType
;
2846 string type_name
= ec
.MemberContext
.CurrentType
== null ? null : ec
.MemberContext
.CurrentType
.Name
;
2847 return Error_MemberLookupFailed (ec
, ec
.CurrentType
, null, almost_matched_type
, Name
,
2848 type_name
, AllMemberTypes
, AllBindingFlags
);
2851 if (e
is MemberExpr
) {
2852 MemberExpr me
= (MemberExpr
) e
;
2855 if (me
.IsInstance
) {
2856 if (ec
.IsStatic
|| ec
.HasAny (ResolveContext
.Options
.FieldInitializerScope
| ResolveContext
.Options
.BaseInitializer
| ResolveContext
.Options
.ConstantScope
)) {
2858 // Note that an MemberExpr can be both IsInstance and IsStatic.
2859 // An unresolved MethodGroupExpr can contain both kinds of methods
2860 // and each predicate is true if the MethodGroupExpr contains
2861 // at least one of that kind of method.
2865 (!intermediate
|| !IdenticalNameAndTypeName (ec
, me
, loc
))) {
2866 Error_ObjectRefRequired (ec
, loc
, me
.GetSignatureForError ());
2871 // Pass the buck to MemberAccess and Invocation.
2873 left
= EmptyExpression
.Null
;
2875 left
= ec
.GetThis (loc
);
2878 left
= new TypeExpression (ec
.CurrentType
, loc
);
2881 me
= me
.ResolveMemberAccess (ec
, left
, loc
, null);
2885 if (targs
!= null) {
2886 if (!targs
.Resolve (ec
))
2889 me
.SetTypeArguments (ec
, targs
);
2892 if (!me
.IsStatic
&& (me
.InstanceExpression
!= null && me
.InstanceExpression
!= EmptyExpression
.Null
) &&
2893 TypeManager
.IsNestedFamilyAccessible (me
.InstanceExpression
.Type
, me
.DeclaringType
) &&
2894 me
.InstanceExpression
.Type
!= me
.DeclaringType
&&
2895 !TypeManager
.IsFamilyAccessible (me
.InstanceExpression
.Type
, me
.DeclaringType
) &&
2896 (!intermediate
|| !IdenticalNameAndTypeName (ec
, e
, loc
))) {
2897 ec
.Report
.Error (38, loc
, "Cannot access a nonstatic member of outer type `{0}' via nested type `{1}'",
2898 TypeManager
.CSharpName (me
.DeclaringType
), TypeManager
.CSharpName (me
.InstanceExpression
.Type
));
2902 return (right_side
!= null)
2903 ? me
.DoResolveLValue (ec
, right_side
)
2912 /// Represents a namespace or a type. The name of the class was inspired by
2913 /// section 10.8.1 (Fully Qualified Names).
2915 public abstract class FullNamedExpression
: Expression
2917 protected override void CloneTo (CloneContext clonectx
, Expression target
)
2919 // Do nothing, most unresolved type expressions cannot be
2920 // resolved to different type
2923 public override Expression
CreateExpressionTree (ResolveContext ec
)
2925 throw new NotSupportedException ("ET");
2928 public override void MutateHoistedGenericType (AnonymousMethodStorey storey
)
2930 throw new NotSupportedException ();
2933 public override FullNamedExpression
ResolveAsTypeStep (IMemberContext ec
, bool silent
)
2938 public override void Emit (EmitContext ec
)
2940 throw new InternalErrorException ("FullNamedExpression `{0}' found in resolved tree",
2941 GetSignatureForError ());
2946 /// Expression that evaluates to a type
2948 public abstract class TypeExpr
: FullNamedExpression
{
2949 public override FullNamedExpression
ResolveAsTypeStep (IMemberContext ec
, bool silent
)
2951 TypeExpr t
= DoResolveAsTypeStep (ec
);
2955 eclass
= ExprClass
.Type
;
2959 protected override Expression
DoResolve (ResolveContext ec
)
2961 return ResolveAsTypeTerminal (ec
, false);
2964 public virtual bool CheckAccessLevel (IMemberContext mc
)
2966 return mc
.CurrentTypeDefinition
.CheckAccessLevel (Type
);
2969 public virtual bool IsClass
{
2970 get { return Type.IsClass; }
2973 public virtual bool IsValueType
{
2974 get { return TypeManager.IsStruct (Type); }
2977 public virtual bool IsInterface
{
2978 get { return Type.IsInterface; }
2981 public virtual bool IsSealed
{
2982 get { return Type.IsSealed; }
2985 public virtual bool CanInheritFrom ()
2987 if (Type
== TypeManager
.enum_type
||
2988 (Type
== TypeManager
.value_type
&& RootContext
.StdLib
) ||
2989 Type
== TypeManager
.multicast_delegate_type
||
2990 Type
== TypeManager
.delegate_type
||
2991 Type
== TypeManager
.array_type
)
2997 protected abstract TypeExpr
DoResolveAsTypeStep (IMemberContext ec
);
2999 public override bool Equals (object obj
)
3001 TypeExpr tobj
= obj
as TypeExpr
;
3005 return Type
== tobj
.Type
;
3008 public override int GetHashCode ()
3010 return Type
.GetHashCode ();
3013 public override void MutateHoistedGenericType (AnonymousMethodStorey storey
)
3015 type
= storey
.MutateType (type
);
3020 /// Fully resolved Expression that already evaluated to a type
3022 public class TypeExpression
: TypeExpr
{
3023 public TypeExpression (Type t
, Location l
)
3026 eclass
= ExprClass
.Type
;
3030 protected override TypeExpr
DoResolveAsTypeStep (IMemberContext ec
)
3035 public override TypeExpr
ResolveAsTypeTerminal (IMemberContext ec
, bool silent
)
3042 // Used to create types from a fully qualified name. These are just used
3043 // by the parser to setup the core types.
3045 public sealed class TypeLookupExpression
: TypeExpr
{
3046 readonly string ns_name
;
3047 readonly string name
;
3049 public TypeLookupExpression (string ns
, string name
)
3053 eclass
= ExprClass
.Type
;
3056 public override TypeExpr
ResolveAsTypeTerminal (IMemberContext ec
, bool silent
)
3059 // It's null only during mscorlib bootstrap when DefineType
3060 // nees to resolve base type of same type
3062 // For instance struct Char : IComparable<char>
3064 // TODO: it could be removed when Resolve starts to use
3065 // DeclSpace instead of Type
3068 Namespace ns
= GlobalRootNamespace
.Instance
.GetNamespace (ns_name
, false);
3069 FullNamedExpression fne
= ns
.Lookup (ec
.Compiler
, name
, loc
);
3077 protected override TypeExpr
DoResolveAsTypeStep (IMemberContext ec
)
3082 public override string GetSignatureForError ()
3085 return TypeManager
.CSharpName (ns_name
+ "." + name
, null);
3087 return base.GetSignatureForError ();
3092 /// This class denotes an expression which evaluates to a member
3093 /// of a struct or a class.
3095 public abstract class MemberExpr
: Expression
3097 protected bool is_base
;
3100 /// The name of this member.
3102 public abstract string Name
{
3107 // When base.member is used
3109 public bool IsBase
{
3110 get { return is_base; }
3111 set { is_base = value; }
3115 /// Whether this is an instance member.
3117 public abstract bool IsInstance
{
3122 /// Whether this is a static member.
3124 public abstract bool IsStatic
{
3129 /// The type which declares this member.
3131 public abstract Type DeclaringType
{
3136 /// The instance expression associated with this member, if it's a
3137 /// non-static member.
3139 public Expression InstanceExpression
;
3141 public static void error176 (ResolveContext ec
, Location loc
, string name
)
3143 ec
.Report
.Error (176, loc
, "Static member `{0}' cannot be accessed " +
3144 "with an instance reference, qualify it with a type name instead", name
);
3147 public static void Error_BaseAccessInExpressionTree (ResolveContext ec
, Location loc
)
3149 ec
.Report
.Error (831, loc
, "An expression tree may not contain a base access");
3152 public override void MutateHoistedGenericType (AnonymousMethodStorey storey
)
3154 if (InstanceExpression
!= null)
3155 InstanceExpression
.MutateHoistedGenericType (storey
);
3158 // TODO: possible optimalization
3159 // Cache resolved constant result in FieldBuilder <-> expression map
3160 public virtual MemberExpr
ResolveMemberAccess (ResolveContext ec
, Expression left
, Location loc
,
3161 SimpleName original
)
3165 // original == null || original.Resolve (...) ==> left
3168 if (left
is TypeExpr
) {
3169 left
= left
.ResolveAsBaseTerminal (ec
, false);
3173 // TODO: Same problem as in class.cs, TypeTerminal does not
3174 // always do all necessary checks
3175 ObsoleteAttribute oa
= AttributeTester
.GetObsoleteAttribute (left
.Type
);
3176 if (oa
!= null && !ec
.IsObsolete
) {
3177 AttributeTester
.Report_ObsoleteMessage (oa
, left
.GetSignatureForError (), loc
, ec
.Report
);
3180 GenericTypeExpr ct
= left
as GenericTypeExpr
;
3181 if (ct
!= null && !ct
.CheckConstraints (ec
))
3186 SimpleName
.Error_ObjectRefRequired (ec
, loc
, GetSignatureForError ());
3194 if (original
!= null && original
.IdenticalNameAndTypeName (ec
, left
, loc
))
3197 return ResolveExtensionMemberAccess (ec
, left
);
3200 InstanceExpression
= left
;
3204 protected virtual MemberExpr
ResolveExtensionMemberAccess (ResolveContext ec
, Expression left
)
3206 error176 (ec
, loc
, GetSignatureForError ());
3210 protected void EmitInstance (EmitContext ec
, bool prepare_for_load
)
3215 if (InstanceExpression
== EmptyExpression
.Null
) {
3216 // FIXME: This should not be here at all
3217 SimpleName
.Error_ObjectRefRequired (new ResolveContext (ec
.MemberContext
), loc
, GetSignatureForError ());
3221 if (TypeManager
.IsValueType (InstanceExpression
.Type
)) {
3222 if (InstanceExpression
is IMemoryLocation
) {
3223 ((IMemoryLocation
) InstanceExpression
).AddressOf (ec
, AddressOp
.LoadStore
);
3225 LocalTemporary t
= new LocalTemporary (InstanceExpression
.Type
);
3226 InstanceExpression
.Emit (ec
);
3228 t
.AddressOf (ec
, AddressOp
.Store
);
3231 InstanceExpression
.Emit (ec
);
3233 if (prepare_for_load
)
3234 ec
.ig
.Emit (OpCodes
.Dup
);
3237 public virtual void SetTypeArguments (ResolveContext ec
, TypeArguments ta
)
3239 // TODO: need to get correct member type
3240 ec
.Report
.Error (307, loc
, "The property `{0}' cannot be used with type arguments",
3241 GetSignatureForError ());
3246 /// Represents group of extension methods
3248 public class ExtensionMethodGroupExpr
: MethodGroupExpr
3250 readonly NamespaceEntry namespace_entry
;
3251 public Expression ExtensionExpression
;
3252 Argument extension_argument
;
3254 public ExtensionMethodGroupExpr (List
<MethodBase
> list
, NamespaceEntry n
, Type extensionType
, Location l
)
3255 : base (list
, extensionType
, l
)
3257 this.namespace_entry
= n
;
3260 public override bool IsStatic
{
3261 get { return true; }
3264 public bool IsTopLevel
{
3265 get { return namespace_entry == null; }
3268 public override void MutateHoistedGenericType (AnonymousMethodStorey storey
)
3270 extension_argument
.Expr
.MutateHoistedGenericType (storey
);
3271 base.MutateHoistedGenericType (storey
);
3274 public override MethodGroupExpr
OverloadResolve (ResolveContext ec
, ref Arguments arguments
, bool may_fail
, Location loc
)
3276 if (arguments
== null)
3277 arguments
= new Arguments (1);
3279 arguments
.Insert (0, new Argument (ExtensionExpression
));
3280 MethodGroupExpr mg
= ResolveOverloadExtensions (ec
, ref arguments
, namespace_entry
, loc
);
3282 // Store resolved argument and restore original arguments
3284 ((ExtensionMethodGroupExpr
)mg
).extension_argument
= arguments
[0];
3286 arguments
.RemoveAt (0); // Clean-up modified arguments for error reporting
3291 MethodGroupExpr
ResolveOverloadExtensions (ResolveContext ec
, ref Arguments arguments
, NamespaceEntry ns
, Location loc
)
3293 // Use normal resolve rules
3294 MethodGroupExpr mg
= base.OverloadResolve (ec
, ref arguments
, ns
!= null, loc
);
3302 ExtensionMethodGroupExpr e
= ns
.LookupExtensionMethod (type
, Name
, loc
);
3304 return base.OverloadResolve (ec
, ref arguments
, false, loc
);
3306 e
.ExtensionExpression
= ExtensionExpression
;
3307 e
.SetTypeArguments (ec
, type_arguments
);
3308 return e
.ResolveOverloadExtensions (ec
, ref arguments
, e
.namespace_entry
, loc
);
3313 /// MethodGroupExpr represents a group of method candidates which
3314 /// can be resolved to the best method overload
3316 public class MethodGroupExpr
: MemberExpr
3318 public interface IErrorHandler
3320 bool AmbiguousCall (ResolveContext ec
, MethodBase ambiguous
);
3321 bool NoExactMatch (ResolveContext ec
, MethodBase method
);
3324 public IErrorHandler CustomErrorHandler
;
3325 public MethodBase
[] Methods
;
3326 MethodBase best_candidate
;
3327 // TODO: make private
3328 public TypeArguments type_arguments
;
3329 bool identical_type_name
;
3330 bool has_inaccessible_candidates_only
;
3334 public MethodGroupExpr (MemberInfo
[] mi
, Type type
, Location l
)
3337 Methods
= new MethodBase
[mi
.Length
];
3338 mi
.CopyTo (Methods
, 0);
3341 public MethodGroupExpr (MemberInfo
[] mi
, Type type
, Location l
, bool inacessibleCandidatesOnly
)
3342 : this (mi
, type
, l
)
3344 has_inaccessible_candidates_only
= inacessibleCandidatesOnly
;
3347 public MethodGroupExpr (List
<MethodBase
> list
, Type type
, Location l
)
3351 Methods
= list
.ToArray ();
3353 foreach (MemberInfo m
in list
){
3354 if (!(m
is MethodBase
)){
3355 Console
.WriteLine ("Name " + m
.Name
);
3356 Console
.WriteLine ("Found a: " + m
.GetType ().FullName
);
3365 protected MethodGroupExpr (Type type
, Location loc
)
3368 eclass
= ExprClass
.MethodGroup
;
3369 this.type
= InternalType
.MethodGroup
;
3370 queried_type
= type
;
3373 public override Type DeclaringType
{
3375 return queried_type
;
3379 public Type DelegateType
{
3381 delegate_type
= value;
3385 public bool IdenticalTypeName
{
3387 return identical_type_name
;
3391 public override string GetSignatureForError ()
3393 if (best_candidate
!= null)
3394 return TypeManager
.CSharpSignature (best_candidate
);
3396 return TypeManager
.CSharpSignature (Methods
[0]);
3399 public override string Name
{
3401 return Methods
[0].Name
;
3405 public override bool IsInstance
{
3407 if (best_candidate
!= null)
3408 return !best_candidate
.IsStatic
;
3410 foreach (MethodBase mb
in Methods
)
3418 public override bool IsStatic
{
3420 if (best_candidate
!= null)
3421 return best_candidate
.IsStatic
;
3423 foreach (MethodBase mb
in Methods
)
3431 public static explicit operator ConstructorInfo (MethodGroupExpr mg
)
3433 return (ConstructorInfo
)mg
.best_candidate
;
3436 public static explicit operator MethodInfo (MethodGroupExpr mg
)
3438 return (MethodInfo
)mg
.best_candidate
;
3442 // 7.4.3.3 Better conversion from expression
3443 // Returns : 1 if a->p is better,
3444 // 2 if a->q is better,
3445 // 0 if neither is better
3447 static int BetterExpressionConversion (ResolveContext ec
, Argument a
, Type p
, Type q
)
3449 Type argument_type
= TypeManager
.TypeToCoreType (a
.Type
);
3450 if (argument_type
== InternalType
.AnonymousMethod
&& RootContext
.Version
> LanguageVersion
.ISO_2
) {
3452 // Uwrap delegate from Expression<T>
3454 if (TypeManager
.DropGenericTypeArguments (p
) == TypeManager
.expression_type
) {
3455 p
= TypeManager
.GetTypeArguments (p
) [0];
3457 if (TypeManager
.DropGenericTypeArguments (q
) == TypeManager
.expression_type
) {
3458 q
= TypeManager
.GetTypeArguments (q
) [0];
3461 p
= Delegate
.GetInvokeMethod (ec
.Compiler
, null, p
).ReturnType
;
3462 q
= Delegate
.GetInvokeMethod (ec
.Compiler
, null, q
).ReturnType
;
3463 if (p
== TypeManager
.void_type
&& q
!= TypeManager
.void_type
)
3465 if (q
== TypeManager
.void_type
&& p
!= TypeManager
.void_type
)
3468 if (argument_type
== p
)
3471 if (argument_type
== q
)
3475 return BetterTypeConversion (ec
, p
, q
);
3479 // 7.4.3.4 Better conversion from type
3481 public static int BetterTypeConversion (ResolveContext ec
, Type p
, Type q
)
3483 if (p
== null || q
== null)
3484 throw new InternalErrorException ("BetterTypeConversion got a null conversion");
3486 if (p
== TypeManager
.int32_type
) {
3487 if (q
== TypeManager
.uint32_type
|| q
== TypeManager
.uint64_type
)
3489 } else if (p
== TypeManager
.int64_type
) {
3490 if (q
== TypeManager
.uint64_type
)
3492 } else if (p
== TypeManager
.sbyte_type
) {
3493 if (q
== TypeManager
.byte_type
|| q
== TypeManager
.ushort_type
||
3494 q
== TypeManager
.uint32_type
|| q
== TypeManager
.uint64_type
)
3496 } else if (p
== TypeManager
.short_type
) {
3497 if (q
== TypeManager
.ushort_type
|| q
== TypeManager
.uint32_type
||
3498 q
== TypeManager
.uint64_type
)
3500 } else if (p
== InternalType
.Dynamic
) {
3501 if (q
== TypeManager
.object_type
)
3505 if (q
== TypeManager
.int32_type
) {
3506 if (p
== TypeManager
.uint32_type
|| p
== TypeManager
.uint64_type
)
3508 } if (q
== TypeManager
.int64_type
) {
3509 if (p
== TypeManager
.uint64_type
)
3511 } else if (q
== TypeManager
.sbyte_type
) {
3512 if (p
== TypeManager
.byte_type
|| p
== TypeManager
.ushort_type
||
3513 p
== TypeManager
.uint32_type
|| p
== TypeManager
.uint64_type
)
3515 } if (q
== TypeManager
.short_type
) {
3516 if (p
== TypeManager
.ushort_type
|| p
== TypeManager
.uint32_type
||
3517 p
== TypeManager
.uint64_type
)
3519 } else if (q
== InternalType
.Dynamic
) {
3520 if (p
== TypeManager
.object_type
)
3524 // TODO: this is expensive
3525 Expression p_tmp
= new EmptyExpression (p
);
3526 Expression q_tmp
= new EmptyExpression (q
);
3528 bool p_to_q
= Convert
.ImplicitConversionExists (ec
, p_tmp
, q
);
3529 bool q_to_p
= Convert
.ImplicitConversionExists (ec
, q_tmp
, p
);
3531 if (p_to_q
&& !q_to_p
)
3534 if (q_to_p
&& !p_to_q
)
3541 /// Determines "Better function" between candidate
3542 /// and the current best match
3545 /// Returns a boolean indicating :
3546 /// false if candidate ain't better
3547 /// true if candidate is better than the current best match
3549 static bool BetterFunction (ResolveContext ec
, Arguments args
, int argument_count
,
3550 MethodBase candidate
, bool candidate_params
,
3551 MethodBase best
, bool best_params
)
3553 AParametersCollection candidate_pd
= TypeManager
.GetParameterData (candidate
);
3554 AParametersCollection best_pd
= TypeManager
.GetParameterData (best
);
3556 bool better_at_least_one
= false;
3558 for (int j
= 0, c_idx
= 0, b_idx
= 0; j
< argument_count
; ++j
, ++c_idx
, ++b_idx
)
3560 Argument a
= args
[j
];
3562 // Provided default argument value is never better
3563 if (a
.IsDefaultArgument
&& candidate_params
== best_params
)
3566 Type ct
= candidate_pd
.Types
[c_idx
];
3567 Type bt
= best_pd
.Types
[b_idx
];
3569 if (candidate_params
&& candidate_pd
.FixedParameters
[c_idx
].ModFlags
== Parameter
.Modifier
.PARAMS
)
3571 ct
= TypeManager
.GetElementType (ct
);
3575 if (best_params
&& best_pd
.FixedParameters
[b_idx
].ModFlags
== Parameter
.Modifier
.PARAMS
)
3577 bt
= TypeManager
.GetElementType (bt
);
3585 int result
= BetterExpressionConversion (ec
, a
, ct
, bt
);
3587 // for each argument, the conversion to 'ct' should be no worse than
3588 // the conversion to 'bt'.
3592 // for at least one argument, the conversion to 'ct' should be better than
3593 // the conversion to 'bt'.
3595 better_at_least_one
= true;
3598 if (better_at_least_one
)
3602 // This handles the case
3604 // Add (float f1, float f2, float f3);
3605 // Add (params decimal [] foo);
3607 // The call Add (3, 4, 5) should be ambiguous. Without this check, the
3608 // first candidate would've chosen as better.
3614 // The two methods have equal parameter types. Now apply tie-breaking rules
3616 if (TypeManager
.IsGenericMethod (best
)) {
3617 if (!TypeManager
.IsGenericMethod (candidate
))
3619 } else if (TypeManager
.IsGenericMethod (candidate
)) {
3624 // This handles the following cases:
3626 // Trim () is better than Trim (params char[] chars)
3627 // Concat (string s1, string s2, string s3) is better than
3628 // Concat (string s1, params string [] srest)
3629 // Foo (int, params int [] rest) is better than Foo (params int [] rest)
3631 if (!candidate_params
&& best_params
)
3633 if (candidate_params
&& !best_params
)
3636 int candidate_param_count
= candidate_pd
.Count
;
3637 int best_param_count
= best_pd
.Count
;
3639 if (candidate_param_count
!= best_param_count
)
3640 // can only happen if (candidate_params && best_params)
3641 return candidate_param_count
> best_param_count
&& best_pd
.HasParams
;
3644 // now, both methods have the same number of parameters, and the parameters have the same types
3645 // Pick the "more specific" signature
3648 MethodBase orig_candidate
= TypeManager
.DropGenericMethodArguments (candidate
);
3649 MethodBase orig_best
= TypeManager
.DropGenericMethodArguments (best
);
3651 AParametersCollection orig_candidate_pd
= TypeManager
.GetParameterData (orig_candidate
);
3652 AParametersCollection orig_best_pd
= TypeManager
.GetParameterData (orig_best
);
3654 bool specific_at_least_once
= false;
3655 for (int j
= 0; j
< candidate_param_count
; ++j
)
3657 Type ct
= orig_candidate_pd
.Types
[j
];
3658 Type bt
= orig_best_pd
.Types
[j
];
3661 Type specific
= MoreSpecific (ct
, bt
);
3665 specific_at_least_once
= true;
3668 if (specific_at_least_once
)
3671 // FIXME: handle lifted operators
3677 protected override MemberExpr
ResolveExtensionMemberAccess (ResolveContext ec
, Expression left
)
3680 return base.ResolveExtensionMemberAccess (ec
, left
);
3683 // When left side is an expression and at least one candidate method is
3684 // static, it can be extension method
3686 InstanceExpression
= left
;
3690 public override MemberExpr
ResolveMemberAccess (ResolveContext ec
, Expression left
, Location loc
,
3691 SimpleName original
)
3693 if (!(left
is TypeExpr
) &&
3694 original
!= null && original
.IdenticalNameAndTypeName (ec
, left
, loc
))
3695 identical_type_name
= true;
3697 return base.ResolveMemberAccess (ec
, left
, loc
, original
);
3700 public override Expression
CreateExpressionTree (ResolveContext ec
)
3702 if (best_candidate
== null) {
3703 ec
.Report
.Error (1953, loc
, "An expression tree cannot contain an expression with method group");
3707 IMethodData md
= TypeManager
.GetMethod (best_candidate
);
3708 if (md
!= null && md
.IsExcluded ())
3709 ec
.Report
.Error (765, loc
,
3710 "Partial methods with only a defining declaration or removed conditional methods cannot be used in an expression tree");
3712 return new TypeOfMethod (best_candidate
, loc
);
3715 protected override Expression
DoResolve (ResolveContext ec
)
3717 this.eclass
= ExprClass
.MethodGroup
;
3719 if (InstanceExpression
!= null) {
3720 InstanceExpression
= InstanceExpression
.Resolve (ec
);
3721 if (InstanceExpression
== null)
3728 public void ReportUsageError (ResolveContext ec
)
3730 ec
.Report
.Error (654, loc
, "Method `" + DeclaringType
+ "." +
3731 Name
+ "()' is referenced without parentheses");
3734 override public void Emit (EmitContext ec
)
3736 throw new NotSupportedException ();
3737 // ReportUsageError ();
3740 public void EmitCall (EmitContext ec
, Arguments arguments
)
3742 Invocation
.EmitCall (ec
, IsBase
, InstanceExpression
, best_candidate
, arguments
, loc
);
3745 void Error_AmbiguousCall (ResolveContext ec
, MethodBase ambiguous
)
3747 if (CustomErrorHandler
!= null && CustomErrorHandler
.AmbiguousCall (ec
, ambiguous
))
3750 ec
.Report
.SymbolRelatedToPreviousError (best_candidate
);
3751 ec
.Report
.Error (121, loc
, "The call is ambiguous between the following methods or properties: `{0}' and `{1}'",
3752 TypeManager
.CSharpSignature (ambiguous
), TypeManager
.CSharpSignature (best_candidate
));
3755 protected virtual void Error_InvalidArguments (ResolveContext ec
, Location loc
, int idx
, MethodBase method
,
3756 Argument a
, AParametersCollection expected_par
, Type paramType
)
3758 ExtensionMethodGroupExpr emg
= this as ExtensionMethodGroupExpr
;
3760 if (a
is CollectionElementInitializer
.ElementInitializerArgument
) {
3761 ec
.Report
.SymbolRelatedToPreviousError (method
);
3762 if ((expected_par
.FixedParameters
[idx
].ModFlags
& Parameter
.Modifier
.ISBYREF
) != 0) {
3763 ec
.Report
.Error (1954, loc
, "The best overloaded collection initalizer method `{0}' cannot have 'ref', or `out' modifier",
3764 TypeManager
.CSharpSignature (method
));
3767 ec
.Report
.Error (1950, loc
, "The best overloaded collection initalizer method `{0}' has some invalid arguments",
3768 TypeManager
.CSharpSignature (method
));
3769 } else if (TypeManager
.IsDelegateType (method
.DeclaringType
)) {
3770 ec
.Report
.Error (1594, loc
, "Delegate `{0}' has some invalid arguments",
3771 TypeManager
.CSharpName (method
.DeclaringType
));
3773 ec
.Report
.SymbolRelatedToPreviousError (method
);
3775 ec
.Report
.Error (1928, loc
,
3776 "Type `{0}' does not contain a member `{1}' and the best extension method overload `{2}' has some invalid arguments",
3777 emg
.ExtensionExpression
.GetSignatureForError (),
3778 emg
.Name
, TypeManager
.CSharpSignature (method
));
3780 ec
.Report
.Error (1502, loc
, "The best overloaded method match for `{0}' has some invalid arguments",
3781 TypeManager
.CSharpSignature (method
));
3785 Parameter
.Modifier mod
= idx
>= expected_par
.Count
? 0 : expected_par
.FixedParameters
[idx
].ModFlags
;
3787 string index
= (idx
+ 1).ToString ();
3788 if (((mod
& (Parameter
.Modifier
.REF
| Parameter
.Modifier
.OUT
)) ^
3789 (a
.Modifier
& (Parameter
.Modifier
.REF
| Parameter
.Modifier
.OUT
))) != 0) {
3790 if ((mod
& Parameter
.Modifier
.ISBYREF
) == 0)
3791 ec
.Report
.Error (1615, loc
, "Argument `#{0}' does not require `{1}' modifier. Consider removing `{1}' modifier",
3792 index
, Parameter
.GetModifierSignature (a
.Modifier
));
3794 ec
.Report
.Error (1620, loc
, "Argument `#{0}' is missing `{1}' modifier",
3795 index
, Parameter
.GetModifierSignature (mod
));
3797 string p1
= a
.GetSignatureForError ();
3798 string p2
= TypeManager
.CSharpName (paramType
);
3801 ec
.Report
.ExtraInformation (loc
, "(equally named types possibly from different assemblies in previous ");
3802 ec
.Report
.SymbolRelatedToPreviousError (a
.Expr
.Type
);
3803 ec
.Report
.SymbolRelatedToPreviousError (paramType
);
3806 if (idx
== 0 && emg
!= null) {
3807 ec
.Report
.Error (1929, loc
,
3808 "Extension method instance type `{0}' cannot be converted to `{1}'", p1
, p2
);
3810 ec
.Report
.Error (1503, loc
,
3811 "Argument `#{0}' cannot convert `{1}' expression to type `{2}'", index
, p1
, p2
);
3816 public override void Error_ValueCannotBeConverted (ResolveContext ec
, Location loc
, Type target
, bool expl
)
3818 ec
.Report
.Error (428, loc
, "Cannot convert method group `{0}' to non-delegate type `{1}'. Consider using parentheses to invoke the method",
3819 Name
, TypeManager
.CSharpName (target
));
3822 void Error_ArgumentCountWrong (ResolveContext ec
, int arg_count
)
3824 ec
.Report
.Error (1501, loc
, "No overload for method `{0}' takes `{1}' arguments",
3825 Name
, arg_count
.ToString ());
3828 protected virtual int GetApplicableParametersCount (MethodBase method
, AParametersCollection parameters
)
3830 return parameters
.Count
;
3833 public static bool IsAncestralType (Type first_type
, Type second_type
)
3835 return first_type
!= second_type
&&
3836 (TypeManager
.IsSubclassOf (second_type
, first_type
) ||
3837 TypeManager
.ImplementsInterface (second_type
, first_type
));
3841 /// Determines if the candidate method is applicable (section 14.4.2.1)
3842 /// to the given set of arguments
3843 /// A return value rates candidate method compatibility,
3844 /// 0 = the best, int.MaxValue = the worst
3846 public int IsApplicable (ResolveContext ec
,
3847 ref Arguments arguments
, int arg_count
, ref MethodBase method
, ref bool params_expanded_form
)
3849 MethodBase candidate
= method
;
3851 AParametersCollection pd
= TypeManager
.GetParameterData (candidate
);
3852 int param_count
= GetApplicableParametersCount (candidate
, pd
);
3853 int optional_count
= 0;
3855 if (arg_count
!= param_count
) {
3856 for (int i
= 0; i
< pd
.Count
; ++i
) {
3857 if (pd
.FixedParameters
[i
].HasDefaultValue
) {
3858 optional_count
= pd
.Count
- i
;
3863 int args_gap
= Math
.Abs (arg_count
- param_count
);
3864 if (optional_count
!= 0) {
3865 if (args_gap
> optional_count
)
3866 return int.MaxValue
- 10000 + args_gap
- optional_count
;
3868 // Readjust expected number when params used
3871 if (arg_count
< param_count
)
3873 } else if (arg_count
> param_count
) {
3874 return int.MaxValue
- 10000 + args_gap
;
3876 } else if (arg_count
!= param_count
) {
3878 return int.MaxValue
- 10000 + args_gap
;
3879 if (arg_count
< param_count
- 1)
3880 return int.MaxValue
- 10000 + args_gap
;
3883 // Initialize expanded form of a method with 1 params parameter
3884 params_expanded_form
= param_count
== 1 && pd
.HasParams
;
3886 // Resize to fit optional arguments
3887 if (optional_count
!= 0) {
3889 if (arguments
== null) {
3890 resized
= new Arguments (optional_count
);
3892 resized
= new Arguments (param_count
);
3893 resized
.AddRange (arguments
);
3896 for (int i
= arg_count
; i
< param_count
; ++i
)
3898 arguments
= resized
;
3902 if (arg_count
> 0) {
3904 // Shuffle named arguments to the right positions if there are any
3906 if (arguments
[arg_count
- 1] is NamedArgument
) {
3907 arg_count
= arguments
.Count
;
3909 for (int i
= 0; i
< arg_count
; ++i
) {
3910 bool arg_moved
= false;
3912 NamedArgument na
= arguments
[i
] as NamedArgument
;
3916 int index
= pd
.GetParameterIndexByName (na
.Name
);
3918 // Named parameter not found or already reordered
3922 // When using parameters which should not be available to the user
3923 if (index
>= param_count
)
3927 arguments
.MarkReorderedArgument (na
);
3931 Argument temp
= arguments
[index
];
3932 arguments
[index
] = arguments
[i
];
3933 arguments
[i
] = temp
;
3940 arg_count
= arguments
.Count
;
3942 } else if (arguments
!= null) {
3943 arg_count
= arguments
.Count
;
3947 // 1. Handle generic method using type arguments when specified or type inference
3949 if (TypeManager
.IsGenericMethod (candidate
)) {
3950 if (type_arguments
!= null) {
3951 Type
[] g_args
= candidate
.GetGenericArguments ();
3952 if (g_args
.Length
!= type_arguments
.Count
)
3953 return int.MaxValue
- 20000 + Math
.Abs (type_arguments
.Count
- g_args
.Length
);
3955 // TODO: Don't create new method, create Parameters only
3956 method
= TypeManager
.MakeGenericMethod ((MethodInfo
) candidate
, type_arguments
.Arguments
);
3958 pd
= TypeManager
.GetParameterData (candidate
);
3960 int score
= TypeManager
.InferTypeArguments (ec
, arguments
, ref candidate
);
3962 return score
- 20000;
3964 if (TypeManager
.IsGenericMethodDefinition (candidate
))
3965 throw new InternalErrorException ("A generic method `{0}' definition took part in overload resolution",
3966 TypeManager
.CSharpSignature (candidate
));
3968 pd
= TypeManager
.GetParameterData (candidate
);
3971 if (type_arguments
!= null)
3972 return int.MaxValue
- 15000;
3976 // 2. Each argument has to be implicitly convertible to method parameter
3979 Parameter
.Modifier p_mod
= 0;
3981 for (int i
= 0; i
< arg_count
; i
++) {
3982 Argument a
= arguments
[i
];
3984 if (!pd
.FixedParameters
[i
].HasDefaultValue
)
3985 throw new InternalErrorException ();
3987 Expression e
= pd
.FixedParameters
[i
].DefaultValue
as Constant
;
3989 e
= new DefaultValueExpression (new TypeExpression (pd
.Types
[i
], loc
), loc
).Resolve (ec
);
3991 arguments
[i
] = new Argument (e
, Argument
.AType
.Default
);
3995 if (p_mod
!= Parameter
.Modifier
.PARAMS
) {
3996 p_mod
= pd
.FixedParameters
[i
].ModFlags
& ~
(Parameter
.Modifier
.OUTMASK
| Parameter
.Modifier
.REFMASK
);
3999 params_expanded_form
= true;
4002 Parameter
.Modifier a_mod
= a
.Modifier
& ~
(Parameter
.Modifier
.OUTMASK
| Parameter
.Modifier
.REFMASK
);
4004 if (!params_expanded_form
)
4005 score
= IsArgumentCompatible (ec
, a_mod
, a
, p_mod
& ~Parameter
.Modifier
.PARAMS
, pt
);
4007 if (score
!= 0 && (p_mod
& Parameter
.Modifier
.PARAMS
) != 0 && delegate_type
== null) {
4008 // It can be applicable in expanded form
4009 score
= IsArgumentCompatible (ec
, a_mod
, a
, 0, TypeManager
.GetElementType (pt
));
4011 params_expanded_form
= true;
4015 if (params_expanded_form
)
4017 return (arg_count
- i
) * 2 + score
;
4021 if (arg_count
!= param_count
)
4022 params_expanded_form
= true;
4027 int IsArgumentCompatible (ResolveContext ec
, Parameter
.Modifier arg_mod
, Argument argument
, Parameter
.Modifier param_mod
, Type parameter
)
4030 // Types have to be identical when ref or out modifer is used
4032 if (arg_mod
!= 0 || param_mod
!= 0) {
4033 if (TypeManager
.HasElementType (parameter
))
4034 parameter
= TypeManager
.GetElementType (parameter
);
4036 Type a_type
= argument
.Type
;
4037 if (TypeManager
.HasElementType (a_type
))
4038 a_type
= TypeManager
.GetElementType (a_type
);
4040 if (a_type
!= parameter
) {
4041 if (TypeManager
.IsDynamicType (a_type
))
4047 if (!Convert
.ImplicitConversionExists (ec
, argument
.Expr
, parameter
)) {
4048 if (TypeManager
.IsDynamicType (argument
.Type
))
4055 if (arg_mod
!= param_mod
)
4061 public static bool IsOverride (MethodBase cand_method
, MethodBase base_method
)
4063 if (!IsAncestralType (base_method
.DeclaringType
, cand_method
.DeclaringType
))
4066 AParametersCollection cand_pd
= TypeManager
.GetParameterData (cand_method
);
4067 AParametersCollection base_pd
= TypeManager
.GetParameterData (base_method
);
4069 if (cand_pd
.Count
!= base_pd
.Count
)
4072 for (int j
= 0; j
< cand_pd
.Count
; ++j
)
4074 Parameter
.Modifier cm
= cand_pd
.FixedParameters
[j
].ModFlags
;
4075 Parameter
.Modifier bm
= base_pd
.FixedParameters
[j
].ModFlags
;
4076 Type ct
= cand_pd
.Types
[j
];
4077 Type bt
= base_pd
.Types
[j
];
4079 if (cm
!= bm
|| ct
!= bt
)
4086 public static MethodGroupExpr
MakeUnionSet (MethodGroupExpr mg1
, MethodGroupExpr mg2
, Location loc
)
4097 var all
= new List
<MethodBase
> (mg1
.Methods
);
4098 foreach (MethodBase m
in mg2
.Methods
){
4099 if (!TypeManager
.ArrayContainsMethod (mg1
.Methods
, m
, false))
4103 return new MethodGroupExpr (all
, null, loc
);
4106 static Type
MoreSpecific (Type p
, Type q
)
4108 if (TypeManager
.IsGenericParameter (p
) && !TypeManager
.IsGenericParameter (q
))
4110 if (!TypeManager
.IsGenericParameter (p
) && TypeManager
.IsGenericParameter (q
))
4113 if (TypeManager
.HasElementType (p
))
4115 Type pe
= TypeManager
.GetElementType (p
);
4116 Type qe
= TypeManager
.GetElementType (q
);
4117 Type specific
= MoreSpecific (pe
, qe
);
4123 else if (TypeManager
.IsGenericType (p
))
4125 Type
[] pargs
= TypeManager
.GetTypeArguments (p
);
4126 Type
[] qargs
= TypeManager
.GetTypeArguments (q
);
4128 bool p_specific_at_least_once
= false;
4129 bool q_specific_at_least_once
= false;
4131 for (int i
= 0; i
< pargs
.Length
; i
++)
4133 Type specific
= MoreSpecific (TypeManager
.TypeToCoreType (pargs
[i
]), TypeManager
.TypeToCoreType (qargs
[i
]));
4134 if (specific
== pargs
[i
])
4135 p_specific_at_least_once
= true;
4136 if (specific
== qargs
[i
])
4137 q_specific_at_least_once
= true;
4140 if (p_specific_at_least_once
&& !q_specific_at_least_once
)
4142 if (!p_specific_at_least_once
&& q_specific_at_least_once
)
4149 public override void MutateHoistedGenericType (AnonymousMethodStorey storey
)
4151 base.MutateHoistedGenericType (storey
);
4153 MethodInfo mi
= best_candidate
as MethodInfo
;
4155 best_candidate
= storey
.MutateGenericMethod (mi
);
4159 best_candidate
= storey
.MutateConstructor ((ConstructorInfo
) this);
4163 /// Find the Applicable Function Members (7.4.2.1)
4165 /// me: Method Group expression with the members to select.
4166 /// it might contain constructors or methods (or anything
4167 /// that maps to a method).
4169 /// Arguments: ArrayList containing resolved Argument objects.
4171 /// loc: The location if we want an error to be reported, or a Null
4172 /// location for "probing" purposes.
4174 /// Returns: The MethodBase (either a ConstructorInfo or a MethodInfo)
4175 /// that is the best match of me on Arguments.
4178 public virtual MethodGroupExpr
OverloadResolve (ResolveContext ec
, ref Arguments Arguments
,
4179 bool may_fail
, Location loc
)
4181 bool method_params
= false;
4182 Type applicable_type
= null;
4183 var candidates
= new List
<MethodBase
> (2);
4184 List
<MethodBase
> candidate_overrides
= null;
4187 // Used to keep a map between the candidate
4188 // and whether it is being considered in its
4189 // normal or expanded form
4191 // false is normal form, true is expanded form
4193 Dictionary
<MethodBase
, MethodBase
> candidate_to_form
= null;
4194 Dictionary
<MethodBase
, Arguments
> candidates_expanded
= null;
4195 Arguments candidate_args
= Arguments
;
4197 int arg_count
= Arguments
!= null ? Arguments
.Count
: 0;
4199 if (RootContext
.Version
== LanguageVersion
.ISO_1
&& Name
== "Invoke" && TypeManager
.IsDelegateType (DeclaringType
)) {
4201 ec
.Report
.Error (1533, loc
, "Invoke cannot be called directly on a delegate");
4205 int nmethods
= Methods
.Length
;
4209 // Methods marked 'override' don't take part in 'applicable_type'
4210 // computation, nor in the actual overload resolution.
4211 // However, they still need to be emitted instead of a base virtual method.
4212 // So, we salt them away into the 'candidate_overrides' array.
4214 // In case of reflected methods, we replace each overriding method with
4215 // its corresponding base virtual method. This is to improve compatibility
4216 // with non-C# libraries which change the visibility of overrides (#75636)
4219 for (int i
= 0; i
< Methods
.Length
; ++i
) {
4220 MethodBase m
= Methods
[i
];
4221 if (TypeManager
.IsOverride (m
)) {
4222 if (candidate_overrides
== null)
4223 candidate_overrides
= new List
<MethodBase
> ();
4224 candidate_overrides
.Add (m
);
4225 m
= TypeManager
.TryGetBaseDefinition (m
);
4226 if (m
!= null && Array
.Exists (Methods
, l
=> l
== m
))
4236 // Enable message recording, it's used mainly by lambda expressions
4238 SessionReportPrinter msg_recorder
= new SessionReportPrinter ();
4239 ReportPrinter prev_recorder
= ec
.Report
.SetPrinter (msg_recorder
);
4242 // First we construct the set of applicable methods
4244 bool is_sorted
= true;
4245 int best_candidate_rate
= int.MaxValue
;
4246 for (int i
= 0; i
< nmethods
; i
++) {
4247 Type decl_type
= Methods
[i
].DeclaringType
;
4250 // If we have already found an applicable method
4251 // we eliminate all base types (Section 14.5.5.1)
4253 if (applicable_type
!= null && IsAncestralType (decl_type
, applicable_type
))
4257 // Check if candidate is applicable (section 14.4.2.1)
4259 bool params_expanded_form
= false;
4260 int candidate_rate
= IsApplicable (ec
, ref candidate_args
, arg_count
, ref Methods
[i
], ref params_expanded_form
);
4262 if (candidate_rate
< best_candidate_rate
) {
4263 best_candidate_rate
= candidate_rate
;
4264 best_candidate
= Methods
[i
];
4267 if (params_expanded_form
) {
4268 if (candidate_to_form
== null)
4269 candidate_to_form
= new Dictionary
<MethodBase
, MethodBase
> (4, ReferenceEquality
<MethodBase
>.Default
);
4270 MethodBase candidate
= Methods
[i
];
4271 candidate_to_form
[candidate
] = candidate
;
4274 if (candidate_args
!= Arguments
) {
4275 if (candidates_expanded
== null)
4276 candidates_expanded
= new Dictionary
<MethodBase
, Arguments
> (4, ReferenceEquality
<MethodBase
>.Default
);
4278 candidates_expanded
.Add (Methods
[i
], candidate_args
);
4279 candidate_args
= Arguments
;
4282 if (candidate_rate
!= 0 || has_inaccessible_candidates_only
) {
4283 if (msg_recorder
!= null)
4284 msg_recorder
.EndSession ();
4288 msg_recorder
= null;
4289 candidates
.Add (Methods
[i
]);
4291 if (applicable_type
== null)
4292 applicable_type
= decl_type
;
4293 else if (applicable_type
!= decl_type
) {
4295 if (IsAncestralType (applicable_type
, decl_type
))
4296 applicable_type
= decl_type
;
4300 ec
.Report
.SetPrinter (prev_recorder
);
4301 if (msg_recorder
!= null && !msg_recorder
.IsEmpty
) {
4303 msg_recorder
.Merge (prev_recorder
);
4308 int candidate_top
= candidates
.Count
;
4310 if (applicable_type
== null) {
4312 // When we found a top level method which does not match and it's
4313 // not an extension method. We start extension methods lookup from here
4315 if (InstanceExpression
!= null) {
4316 ExtensionMethodGroupExpr ex_method_lookup
= ec
.LookupExtensionMethod (type
, Name
, loc
);
4317 if (ex_method_lookup
!= null) {
4318 ex_method_lookup
.ExtensionExpression
= InstanceExpression
;
4319 ex_method_lookup
.SetTypeArguments (ec
, type_arguments
);
4320 return ex_method_lookup
.OverloadResolve (ec
, ref Arguments
, may_fail
, loc
);
4328 // Okay so we have failed to find exact match so we
4329 // return error info about the closest match
4331 if (best_candidate
!= null) {
4332 if (CustomErrorHandler
!= null && !has_inaccessible_candidates_only
&& CustomErrorHandler
.NoExactMatch (ec
, best_candidate
))
4335 if (NoExactMatch (ec
, ref Arguments
, candidate_to_form
))
4340 // We failed to find any method with correct argument count
4342 if (Name
== ConstructorInfo
.ConstructorName
) {
4343 ec
.Report
.SymbolRelatedToPreviousError (queried_type
);
4344 ec
.Report
.Error (1729, loc
,
4345 "The type `{0}' does not contain a constructor that takes `{1}' arguments",
4346 TypeManager
.CSharpName (queried_type
), arg_count
);
4348 Error_ArgumentCountWrong (ec
, arg_count
);
4354 if (arg_count
!= 0 && Arguments
.HasDynamic
) {
4355 best_candidate
= null;
4361 // At this point, applicable_type is _one_ of the most derived types
4362 // in the set of types containing the methods in this MethodGroup.
4363 // Filter the candidates so that they only contain methods from the
4364 // most derived types.
4367 int finalized
= 0; // Number of finalized candidates
4370 // Invariant: applicable_type is a most derived type
4372 // We'll try to complete Section 14.5.5.1 for 'applicable_type' by
4373 // eliminating all it's base types. At the same time, we'll also move
4374 // every unrelated type to the end of the array, and pick the next
4375 // 'applicable_type'.
4377 Type next_applicable_type
= null;
4378 int j
= finalized
; // where to put the next finalized candidate
4379 int k
= finalized
; // where to put the next undiscarded candidate
4380 for (int i
= finalized
; i
< candidate_top
; ++i
) {
4381 MethodBase candidate
= candidates
[i
];
4382 Type decl_type
= candidate
.DeclaringType
;
4384 if (decl_type
== applicable_type
) {
4385 candidates
[k
++] = candidates
[j
];
4386 candidates
[j
++] = candidates
[i
];
4390 if (IsAncestralType (decl_type
, applicable_type
))
4393 if (next_applicable_type
!= null &&
4394 IsAncestralType (decl_type
, next_applicable_type
))
4397 candidates
[k
++] = candidates
[i
];
4399 if (next_applicable_type
== null ||
4400 IsAncestralType (next_applicable_type
, decl_type
))
4401 next_applicable_type
= decl_type
;
4404 applicable_type
= next_applicable_type
;
4407 } while (applicable_type
!= null);
4411 // Now we actually find the best method
4414 best_candidate
= candidates
[0];
4415 method_params
= candidate_to_form
!= null && candidate_to_form
.ContainsKey (best_candidate
);
4418 // TODO: Broken inverse order of candidates logic does not work with optional
4419 // parameters used for method overrides and I am not going to fix it for SRE
4421 if (candidates_expanded
!= null && candidates_expanded
.ContainsKey (best_candidate
)) {
4422 candidate_args
= candidates_expanded
[best_candidate
];
4423 arg_count
= candidate_args
.Count
;
4426 for (int ix
= 1; ix
< candidate_top
; ix
++) {
4427 MethodBase candidate
= (MethodBase
) candidates
[ix
];
4429 if (candidate
== best_candidate
)
4432 bool cand_params
= candidate_to_form
!= null && candidate_to_form
.ContainsKey (candidate
);
4434 if (BetterFunction (ec
, candidate_args
, arg_count
,
4435 candidate
, cand_params
,
4436 best_candidate
, method_params
)) {
4437 best_candidate
= candidate
;
4438 method_params
= cand_params
;
4442 // Now check that there are no ambiguities i.e the selected method
4443 // should be better than all the others
4445 MethodBase ambiguous
= null;
4446 for (int ix
= 1; ix
< candidate_top
; ix
++) {
4447 MethodBase candidate
= candidates
[ix
];
4449 if (candidate
== best_candidate
)
4452 bool cand_params
= candidate_to_form
!= null && candidate_to_form
.ContainsKey (candidate
);
4453 if (!BetterFunction (ec
, candidate_args
, arg_count
,
4454 best_candidate
, method_params
,
4455 candidate
, cand_params
))
4458 ec
.Report
.SymbolRelatedToPreviousError (candidate
);
4459 ambiguous
= candidate
;
4463 if (ambiguous
!= null) {
4464 Error_AmbiguousCall (ec
, ambiguous
);
4469 // If the method is a virtual function, pick an override closer to the LHS type.
4471 if (!IsBase
&& best_candidate
.IsVirtual
) {
4472 if (TypeManager
.IsOverride (best_candidate
))
4473 throw new InternalErrorException (
4474 "Should not happen. An 'override' method took part in overload resolution: " + best_candidate
);
4476 if (candidate_overrides
!= null) {
4477 Type
[] gen_args
= null;
4478 bool gen_override
= false;
4479 if (TypeManager
.IsGenericMethod (best_candidate
))
4480 gen_args
= TypeManager
.GetGenericArguments (best_candidate
);
4482 foreach (MethodBase candidate
in candidate_overrides
) {
4483 if (TypeManager
.IsGenericMethod (candidate
)) {
4484 if (gen_args
== null)
4487 if (gen_args
.Length
!= TypeManager
.GetGenericArguments (candidate
).Length
)
4490 if (gen_args
!= null)
4494 if (IsOverride (candidate
, best_candidate
)) {
4495 gen_override
= true;
4496 best_candidate
= candidate
;
4500 if (gen_override
&& gen_args
!= null) {
4501 best_candidate
= ((MethodInfo
) best_candidate
).MakeGenericMethod (gen_args
);
4507 // And now check if the arguments are all
4508 // compatible, perform conversions if
4509 // necessary etc. and return if everything is
4512 if (!VerifyArgumentsCompat (ec
, ref candidate_args
, arg_count
, best_candidate
,
4513 method_params
, may_fail
, loc
))
4516 if (best_candidate
== null)
4519 MethodBase the_method
= TypeManager
.DropGenericMethodArguments (best_candidate
);
4520 if (TypeManager
.IsGenericMethodDefinition (the_method
) &&
4521 !ConstraintChecker
.CheckConstraints (ec
, the_method
, best_candidate
, loc
))
4525 // Check ObsoleteAttribute on the best method
4527 ObsoleteAttribute oa
= AttributeTester
.GetMethodObsoleteAttribute (the_method
);
4528 if (oa
!= null && !ec
.IsObsolete
)
4529 AttributeTester
.Report_ObsoleteMessage (oa
, GetSignatureForError (), loc
, ec
.Report
);
4531 IMethodData data
= TypeManager
.GetMethod (the_method
);
4533 data
.SetMemberIsUsed ();
4535 Arguments
= candidate_args
;
4539 bool NoExactMatch (ResolveContext ec
, ref Arguments Arguments
, IDictionary
<MethodBase
, MethodBase
> candidate_to_form
)
4541 AParametersCollection pd
= TypeManager
.GetParameterData (best_candidate
);
4542 int arg_count
= Arguments
== null ? 0 : Arguments
.Count
;
4544 if (arg_count
== pd
.Count
|| pd
.HasParams
) {
4545 if (TypeManager
.IsGenericMethodDefinition (best_candidate
)) {
4546 if (type_arguments
== null) {
4547 ec
.Report
.Error (411, loc
,
4548 "The type arguments for method `{0}' cannot be inferred from " +
4549 "the usage. Try specifying the type arguments explicitly",
4550 TypeManager
.CSharpSignature (best_candidate
));
4554 Type
[] g_args
= TypeManager
.GetGenericArguments (best_candidate
);
4555 if (type_arguments
.Count
!= g_args
.Length
) {
4556 ec
.Report
.SymbolRelatedToPreviousError (best_candidate
);
4557 ec
.Report
.Error (305, loc
, "Using the generic method `{0}' requires `{1}' type argument(s)",
4558 TypeManager
.CSharpSignature (best_candidate
),
4559 g_args
.Length
.ToString ());
4563 if (type_arguments
!= null && !TypeManager
.IsGenericMethod (best_candidate
)) {
4564 Error_TypeArgumentsCannotBeUsed (ec
.Report
, loc
);
4569 if (has_inaccessible_candidates_only
) {
4570 if (InstanceExpression
!= null && type
!= ec
.CurrentType
&& TypeManager
.IsNestedFamilyAccessible (ec
.CurrentType
, best_candidate
.DeclaringType
)) {
4571 // Although a derived class can access protected members of
4572 // its base class it cannot do so through an instance of the
4573 // base class (CS1540). If the qualifier_type is a base of the
4574 // ec.CurrentType and the lookup succeeds with the latter one,
4575 // then we are in this situation.
4576 Error_CannotAccessProtected (ec
, loc
, best_candidate
, queried_type
, ec
.CurrentType
);
4578 ec
.Report
.SymbolRelatedToPreviousError (best_candidate
);
4579 ErrorIsInaccesible (loc
, GetSignatureForError (), ec
.Report
);
4583 bool cand_params
= candidate_to_form
!= null && candidate_to_form
.ContainsKey (best_candidate
);
4584 if (!VerifyArgumentsCompat (ec
, ref Arguments
, arg_count
, best_candidate
, cand_params
, false, loc
))
4587 if (has_inaccessible_candidates_only
)
4594 public override void SetTypeArguments (ResolveContext ec
, TypeArguments ta
)
4596 type_arguments
= ta
;
4599 public bool VerifyArgumentsCompat (ResolveContext ec
, ref Arguments arguments
,
4600 int arg_count
, MethodBase method
,
4601 bool chose_params_expanded
,
4602 bool may_fail
, Location loc
)
4604 AParametersCollection pd
= TypeManager
.GetParameterData (method
);
4605 int param_count
= GetApplicableParametersCount (method
, pd
);
4607 int errors
= ec
.Report
.Errors
;
4608 Parameter
.Modifier p_mod
= 0;
4610 int a_idx
= 0, a_pos
= 0;
4612 ArrayInitializer params_initializers
= null;
4613 bool has_unsafe_arg
= method
is MethodInfo
? ((MethodInfo
) method
).ReturnType
.IsPointer
: false;
4615 for (; a_idx
< arg_count
; a_idx
++, ++a_pos
) {
4616 a
= arguments
[a_idx
];
4617 if (p_mod
!= Parameter
.Modifier
.PARAMS
) {
4618 p_mod
= pd
.FixedParameters
[a_idx
].ModFlags
;
4619 pt
= pd
.Types
[a_idx
];
4620 has_unsafe_arg
|= pt
.IsPointer
;
4622 if (p_mod
== Parameter
.Modifier
.PARAMS
) {
4623 if (chose_params_expanded
) {
4624 params_initializers
= new ArrayInitializer (arg_count
- a_idx
, a
.Expr
.Location
);
4625 pt
= TypeManager
.GetElementType (pt
);
4631 // Types have to be identical when ref or out modifer is used
4633 if (a
.Modifier
!= 0 || (p_mod
& ~Parameter
.Modifier
.PARAMS
) != 0) {
4634 if ((p_mod
& ~Parameter
.Modifier
.PARAMS
) != a
.Modifier
)
4637 if (!TypeManager
.IsEqual (a
.Expr
.Type
, pt
))
4642 NamedArgument na
= a
as NamedArgument
;
4644 int name_index
= pd
.GetParameterIndexByName (na
.Name
);
4645 if (name_index
< 0 || name_index
>= param_count
) {
4646 if (DeclaringType
!= null && TypeManager
.IsDelegateType (DeclaringType
)) {
4647 ec
.Report
.SymbolRelatedToPreviousError (DeclaringType
);
4648 ec
.Report
.Error (1746, na
.Location
,
4649 "The delegate `{0}' does not contain a parameter named `{1}'",
4650 TypeManager
.CSharpName (DeclaringType
), na
.Name
);
4652 ec
.Report
.SymbolRelatedToPreviousError (best_candidate
);
4653 ec
.Report
.Error (1739, na
.Location
,
4654 "The best overloaded method match for `{0}' does not contain a parameter named `{1}'",
4655 TypeManager
.CSharpSignature (method
), na
.Name
);
4657 } else if (arguments
[name_index
] != a
) {
4658 if (DeclaringType
!= null && TypeManager
.IsDelegateType (DeclaringType
))
4659 ec
.Report
.SymbolRelatedToPreviousError (DeclaringType
);
4661 ec
.Report
.SymbolRelatedToPreviousError (best_candidate
);
4663 ec
.Report
.Error (1744, na
.Location
,
4664 "Named argument `{0}' cannot be used for a parameter which has positional argument specified",
4670 if (TypeManager
.IsDynamicType (a
.Expr
.Type
))
4673 if (delegate_type
!= null && !Delegate
.IsTypeCovariant (a
.Expr
, pt
))
4676 Expression conv
= Convert
.ImplicitConversion (ec
, a
.Expr
, pt
, loc
);
4681 // Convert params arguments to an array initializer
4683 if (params_initializers
!= null) {
4684 // we choose to use 'a.Expr' rather than 'conv' so that
4685 // we don't hide the kind of expression we have (esp. CompoundAssign.Helper)
4686 params_initializers
.Add (a
.Expr
);
4687 arguments
.RemoveAt (a_idx
--);
4692 // Update the argument with the implicit conversion
4696 if (a_idx
!= arg_count
) {
4697 if (!may_fail
&& ec
.Report
.Errors
== errors
) {
4698 if (CustomErrorHandler
!= null)
4699 CustomErrorHandler
.NoExactMatch (ec
, best_candidate
);
4701 Error_InvalidArguments (ec
, loc
, a_pos
, method
, a
, pd
, pt
);
4707 // Fill not provided arguments required by params modifier
4709 if (params_initializers
== null && pd
.HasParams
&& arg_count
+ 1 == param_count
) {
4710 if (arguments
== null)
4711 arguments
= new Arguments (1);
4713 pt
= pd
.Types
[param_count
- 1];
4714 pt
= TypeManager
.GetElementType (pt
);
4715 has_unsafe_arg
|= pt
.IsPointer
;
4716 params_initializers
= new ArrayInitializer (0, loc
);
4720 // Append an array argument with all params arguments
4722 if (params_initializers
!= null) {
4723 arguments
.Add (new Argument (
4724 new ArrayCreation (new TypeExpression (pt
, loc
), "[]", params_initializers
, loc
).Resolve (ec
)));
4728 if (arg_count
< param_count
) {
4730 Error_ArgumentCountWrong (ec
, arg_count
);
4734 if (has_unsafe_arg
&& !ec
.IsUnsafe
) {
4736 UnsafeError (ec
, loc
);
4744 public class ConstantExpr
: MemberExpr
4748 public ConstantExpr (FieldInfo constant
, Location loc
)
4750 this.constant
= constant
;
4754 public override string Name
{
4755 get { throw new NotImplementedException (); }
4758 public override bool IsInstance
{
4759 get { return !IsStatic; }
4762 public override bool IsStatic
{
4763 get { return constant.IsStatic; }
4766 public override Type DeclaringType
{
4767 get { return constant.DeclaringType; }
4770 public override MemberExpr
ResolveMemberAccess (ResolveContext ec
, Expression left
, Location loc
, SimpleName original
)
4772 constant
= TypeManager
.GetGenericFieldDefinition (constant
);
4774 IConstant ic
= TypeManager
.GetConstant (constant
);
4776 if (constant
.IsLiteral
) {
4777 ic
= new ExternalConstant (constant
, ec
.Compiler
);
4779 ic
= ExternalConstant
.CreateDecimal (constant
, ec
);
4780 // HACK: decimal field was not resolved as constant
4782 return new FieldExpr (constant
, loc
).ResolveMemberAccess (ec
, left
, loc
, original
);
4784 TypeManager
.RegisterConstant (constant
, ic
);
4787 return base.ResolveMemberAccess (ec
, left
, loc
, original
);
4790 public override Expression
CreateExpressionTree (ResolveContext ec
)
4792 throw new NotSupportedException ("ET");
4795 protected override Expression
DoResolve (ResolveContext rc
)
4797 IConstant ic
= TypeManager
.GetConstant (constant
);
4798 if (ic
.ResolveValue ()) {
4800 ic
.CheckObsoleteness (loc
);
4803 return ic
.CreateConstantReference (rc
, loc
);
4806 public override void Emit (EmitContext ec
)
4808 throw new NotSupportedException ();
4811 public override string GetSignatureForError ()
4813 return TypeManager
.GetFullNameSignature (constant
);
4818 /// Fully resolved expression that evaluates to a Field
4820 public class FieldExpr
: MemberExpr
, IDynamicAssign
, IMemoryLocation
, IVariableReference
{
4821 public FieldInfo FieldInfo
;
4822 readonly Type constructed_generic_type
;
4823 VariableInfo variable_info
;
4825 LocalTemporary temp
;
4828 protected FieldExpr (Location l
)
4833 public FieldExpr (FieldInfo fi
, Location l
)
4836 type
= TypeManager
.TypeToCoreType (fi
.FieldType
);
4840 public FieldExpr (FieldInfo fi
, Type genericType
, Location l
)
4843 if (TypeManager
.IsGenericTypeDefinition (genericType
))
4845 this.constructed_generic_type
= genericType
;
4848 public override string Name
{
4850 return FieldInfo
.Name
;
4854 public override bool IsInstance
{
4856 return !FieldInfo
.IsStatic
;
4860 public override bool IsStatic
{
4862 return FieldInfo
.IsStatic
;
4866 public override Type DeclaringType
{
4868 return FieldInfo
.DeclaringType
;
4872 public override string GetSignatureForError ()
4874 return TypeManager
.GetFullNameSignature (FieldInfo
);
4877 public VariableInfo VariableInfo
{
4879 return variable_info
;
4883 public override MemberExpr
ResolveMemberAccess (ResolveContext ec
, Expression left
, Location loc
,
4884 SimpleName original
)
4886 FieldInfo fi
= TypeManager
.GetGenericFieldDefinition (FieldInfo
);
4887 Type t
= fi
.FieldType
;
4889 if (t
.IsPointer
&& !ec
.IsUnsafe
) {
4890 UnsafeError (ec
, loc
);
4893 return base.ResolveMemberAccess (ec
, left
, loc
, original
);
4896 public void SetHasAddressTaken ()
4898 IVariableReference vr
= InstanceExpression
as IVariableReference
;
4900 vr
.SetHasAddressTaken ();
4903 public override Expression
CreateExpressionTree (ResolveContext ec
)
4905 Expression instance
;
4906 if (InstanceExpression
== null) {
4907 instance
= new NullLiteral (loc
);
4909 instance
= InstanceExpression
.CreateExpressionTree (ec
);
4912 Arguments args
= Arguments
.CreateForExpressionTree (ec
, null,
4914 CreateTypeOfExpression ());
4916 return CreateExpressionFactoryCall (ec
, "Field", args
);
4919 public Expression
CreateTypeOfExpression ()
4921 return new TypeOfField (GetConstructedFieldInfo (), loc
);
4924 protected override Expression
DoResolve (ResolveContext ec
)
4926 return DoResolve (ec
, false, false);
4929 Expression
DoResolve (ResolveContext ec
, bool lvalue_instance
, bool out_access
)
4931 if (!FieldInfo
.IsStatic
){
4932 if (InstanceExpression
== null){
4934 // This can happen when referencing an instance field using
4935 // a fully qualified type expression: TypeName.InstanceField = xxx
4937 SimpleName
.Error_ObjectRefRequired (ec
, loc
, GetSignatureForError ());
4941 // Resolve the field's instance expression while flow analysis is turned
4942 // off: when accessing a field "a.b", we must check whether the field
4943 // "a.b" is initialized, not whether the whole struct "a" is initialized.
4945 if (lvalue_instance
) {
4946 using (ec
.With (ResolveContext
.Options
.DoFlowAnalysis
, false)) {
4947 Expression right_side
=
4948 out_access
? EmptyExpression
.LValueMemberOutAccess
: EmptyExpression
.LValueMemberAccess
;
4950 if (InstanceExpression
!= EmptyExpression
.Null
)
4951 InstanceExpression
= InstanceExpression
.ResolveLValue (ec
, right_side
);
4954 if (InstanceExpression
!= EmptyExpression
.Null
) {
4955 using (ec
.With (ResolveContext
.Options
.DoFlowAnalysis
, false)) {
4956 InstanceExpression
= InstanceExpression
.Resolve (ec
, ResolveFlags
.VariableOrValue
);
4961 if (InstanceExpression
== null)
4964 using (ec
.Set (ResolveContext
.Options
.OmitStructFlowAnalysis
)) {
4965 InstanceExpression
.CheckMarshalByRefAccess (ec
);
4969 if (!ec
.IsObsolete
) {
4970 FieldBase f
= TypeManager
.GetField (FieldInfo
);
4972 f
.CheckObsoleteness (loc
);
4974 ObsoleteAttribute oa
= AttributeTester
.GetMemberObsoleteAttribute (FieldInfo
);
4976 AttributeTester
.Report_ObsoleteMessage (oa
, TypeManager
.GetFullNameSignature (FieldInfo
), loc
, ec
.Report
);
4980 IFixedBuffer fb
= AttributeTester
.GetFixedBuffer (FieldInfo
);
4981 IVariableReference
var = InstanceExpression
as IVariableReference
;
4984 IFixedExpression fe
= InstanceExpression
as IFixedExpression
;
4985 if (!ec
.HasSet (ResolveContext
.Options
.FixedInitializerScope
) && (fe
== null || !fe
.IsFixed
)) {
4986 ec
.Report
.Error (1666, loc
, "You cannot use fixed size buffers contained in unfixed expressions. Try using the fixed statement");
4989 if (InstanceExpression
.eclass
!= ExprClass
.Variable
) {
4990 ec
.Report
.SymbolRelatedToPreviousError (FieldInfo
);
4991 ec
.Report
.Error (1708, loc
, "`{0}': Fixed size buffers can only be accessed through locals or fields",
4992 TypeManager
.GetFullNameSignature (FieldInfo
));
4993 } else if (var != null && var.IsHoisted
) {
4994 AnonymousMethodExpression
.Error_AddressOfCapturedVar (ec
, var, loc
);
4997 return new FixedBufferPtr (this, fb
.ElementType
, loc
).Resolve (ec
);
5000 eclass
= ExprClass
.Variable
;
5002 // If the instance expression is a local variable or parameter.
5003 if (var == null || var.VariableInfo
== null)
5006 VariableInfo vi
= var.VariableInfo
;
5007 if (!vi
.IsFieldAssigned (ec
, FieldInfo
.Name
, loc
))
5010 variable_info
= vi
.GetSubStruct (FieldInfo
.Name
);
5014 static readonly int [] codes
= {
5015 191, // instance, write access
5016 192, // instance, out access
5017 198, // static, write access
5018 199, // static, out access
5019 1648, // member of value instance, write access
5020 1649, // member of value instance, out access
5021 1650, // member of value static, write access
5022 1651 // member of value static, out access
5025 static readonly string [] msgs
= {
5026 /*0191*/ "A readonly field `{0}' cannot be assigned to (except in a constructor or a variable initializer)",
5027 /*0192*/ "A readonly field `{0}' cannot be passed ref or out (except in a constructor)",
5028 /*0198*/ "A static readonly field `{0}' cannot be assigned to (except in a static constructor or a variable initializer)",
5029 /*0199*/ "A static readonly field `{0}' cannot be passed ref or out (except in a static constructor)",
5030 /*1648*/ "Members of readonly field `{0}' cannot be modified (except in a constructor or a variable initializer)",
5031 /*1649*/ "Members of readonly field `{0}' cannot be passed ref or out (except in a constructor)",
5032 /*1650*/ "Fields of static readonly field `{0}' cannot be assigned to (except in a static constructor or a variable initializer)",
5033 /*1651*/ "Fields of static readonly field `{0}' cannot be passed ref or out (except in a static constructor)"
5036 // The return value is always null. Returning a value simplifies calling code.
5037 Expression
Report_AssignToReadonly (ResolveContext ec
, Expression right_side
)
5040 if (right_side
== EmptyExpression
.OutAccess
.Instance
|| right_side
== EmptyExpression
.LValueMemberOutAccess
)
5044 if (right_side
== EmptyExpression
.LValueMemberAccess
|| right_side
== EmptyExpression
.LValueMemberOutAccess
)
5046 ec
.Report
.Error (codes
[i
], loc
, msgs
[i
], GetSignatureForError ());
5051 override public Expression
DoResolveLValue (ResolveContext ec
, Expression right_side
)
5053 IVariableReference
var = InstanceExpression
as IVariableReference
;
5054 if (var != null && var.VariableInfo
!= null)
5055 var.VariableInfo
.SetFieldAssigned (ec
, FieldInfo
.Name
);
5057 bool lvalue_instance
= !FieldInfo
.IsStatic
&& TypeManager
.IsValueType (FieldInfo
.DeclaringType
);
5058 bool out_access
= right_side
== EmptyExpression
.OutAccess
.Instance
|| right_side
== EmptyExpression
.LValueMemberOutAccess
;
5060 Expression e
= DoResolve (ec
, lvalue_instance
, out_access
);
5065 FieldBase fb
= TypeManager
.GetField (FieldInfo
);
5069 if ((right_side
== EmptyExpression
.UnaryAddress
|| right_side
== EmptyExpression
.OutAccess
.Instance
) &&
5070 (fb
.ModFlags
& Modifiers
.VOLATILE
) != 0) {
5071 ec
.Report
.Warning (420, 1, loc
,
5072 "`{0}': A volatile field references will not be treated as volatile",
5073 fb
.GetSignatureForError ());
5077 if (FieldInfo
.IsInitOnly
) {
5078 // InitOnly fields can only be assigned in constructors or initializers
5079 if (!ec
.HasAny (ResolveContext
.Options
.FieldInitializerScope
| ResolveContext
.Options
.ConstructorScope
))
5080 return Report_AssignToReadonly (ec
, right_side
);
5082 if (ec
.HasSet (ResolveContext
.Options
.ConstructorScope
)) {
5083 Type ctype
= ec
.CurrentType
;
5085 // InitOnly fields cannot be assigned-to in a different constructor from their declaring type
5086 if (!TypeManager
.IsEqual (ctype
, FieldInfo
.DeclaringType
))
5087 return Report_AssignToReadonly (ec
, right_side
);
5088 // static InitOnly fields cannot be assigned-to in an instance constructor
5089 if (IsStatic
&& !ec
.IsStatic
)
5090 return Report_AssignToReadonly (ec
, right_side
);
5091 // instance constructors can't modify InitOnly fields of other instances of the same type
5092 if (!IsStatic
&& !(InstanceExpression
is This
))
5093 return Report_AssignToReadonly (ec
, right_side
);
5097 if (right_side
== EmptyExpression
.OutAccess
.Instance
&&
5098 !IsStatic
&& !(InstanceExpression
is This
) && TypeManager
.mbr_type
!= null && TypeManager
.IsSubclassOf (DeclaringType
, TypeManager
.mbr_type
)) {
5099 ec
.Report
.SymbolRelatedToPreviousError (DeclaringType
);
5100 ec
.Report
.Warning (197, 1, loc
,
5101 "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",
5102 GetSignatureForError ());
5105 eclass
= ExprClass
.Variable
;
5109 bool is_marshal_by_ref ()
5111 return !IsStatic
&& TypeManager
.IsStruct (Type
) && TypeManager
.mbr_type
!= null && TypeManager
.IsSubclassOf (DeclaringType
, TypeManager
.mbr_type
);
5114 public override void CheckMarshalByRefAccess (ResolveContext ec
)
5116 if (is_marshal_by_ref () && !(InstanceExpression
is This
)) {
5117 ec
.Report
.SymbolRelatedToPreviousError (DeclaringType
);
5118 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",
5119 GetSignatureForError ());
5123 public override int GetHashCode ()
5125 return FieldInfo
.GetHashCode ();
5128 public bool IsFixed
{
5131 // A variable of the form V.I is fixed when V is a fixed variable of a struct type
5133 IVariableReference variable
= InstanceExpression
as IVariableReference
;
5134 if (variable
!= null)
5135 return TypeManager
.IsStruct (InstanceExpression
.Type
) && variable
.IsFixed
;
5137 IFixedExpression fe
= InstanceExpression
as IFixedExpression
;
5138 return fe
!= null && fe
.IsFixed
;
5142 public bool IsHoisted
{
5144 IVariableReference hv
= InstanceExpression
as IVariableReference
;
5145 return hv
!= null && hv
.IsHoisted
;
5149 public override bool Equals (object obj
)
5151 FieldExpr fe
= obj
as FieldExpr
;
5155 if (FieldInfo
!= fe
.FieldInfo
)
5158 if (InstanceExpression
== null || fe
.InstanceExpression
== null)
5161 return InstanceExpression
.Equals (fe
.InstanceExpression
);
5164 public void Emit (EmitContext ec
, bool leave_copy
)
5166 ILGenerator ig
= ec
.ig
;
5167 bool is_volatile
= false;
5169 FieldBase f
= TypeManager
.GetField (FieldInfo
);
5171 if ((f
.ModFlags
& Modifiers
.VOLATILE
) != 0)
5174 f
.SetMemberIsUsed ();
5177 if (FieldInfo
.IsStatic
){
5179 ig
.Emit (OpCodes
.Volatile
);
5181 ig
.Emit (OpCodes
.Ldsfld
, GetConstructedFieldInfo ());
5184 EmitInstance (ec
, false);
5186 // Optimization for build-in types
5187 if (TypeManager
.IsStruct (type
) && TypeManager
.IsEqual (type
, ec
.MemberContext
.CurrentType
)) {
5188 LoadFromPtr (ig
, type
);
5190 IFixedBuffer ff
= AttributeTester
.GetFixedBuffer (FieldInfo
);
5192 ig
.Emit (OpCodes
.Ldflda
, GetConstructedFieldInfo ());
5193 ig
.Emit (OpCodes
.Ldflda
, ff
.Element
);
5196 ig
.Emit (OpCodes
.Volatile
);
5198 ig
.Emit (OpCodes
.Ldfld
, GetConstructedFieldInfo ());
5204 ec
.ig
.Emit (OpCodes
.Dup
);
5205 if (!FieldInfo
.IsStatic
) {
5206 temp
= new LocalTemporary (this.Type
);
5212 public void EmitAssign (EmitContext ec
, Expression source
, bool leave_copy
, bool prepare_for_load
)
5214 FieldAttributes fa
= FieldInfo
.Attributes
;
5215 bool is_static
= (fa
& FieldAttributes
.Static
) != 0;
5216 ILGenerator ig
= ec
.ig
;
5218 prepared
= prepare_for_load
;
5219 EmitInstance (ec
, prepared
);
5223 ec
.ig
.Emit (OpCodes
.Dup
);
5224 if (!FieldInfo
.IsStatic
) {
5225 temp
= new LocalTemporary (this.Type
);
5230 FieldBase f
= TypeManager
.GetField (FieldInfo
);
5232 if ((f
.ModFlags
& Modifiers
.VOLATILE
) != 0)
5233 ig
.Emit (OpCodes
.Volatile
);
5239 ig
.Emit (OpCodes
.Stsfld
, GetConstructedFieldInfo ());
5241 ig
.Emit (OpCodes
.Stfld
, GetConstructedFieldInfo ());
5250 public override void Emit (EmitContext ec
)
5255 public override void EmitSideEffect (EmitContext ec
)
5257 FieldBase f
= TypeManager
.GetField (FieldInfo
);
5258 bool is_volatile
= f
!= null && (f
.ModFlags
& Modifiers
.VOLATILE
) != 0;
5260 if (is_volatile
|| is_marshal_by_ref ())
5261 base.EmitSideEffect (ec
);
5264 public override void Error_VariableIsUsedBeforeItIsDeclared (Report r
, string name
)
5267 "A local variable `{0}' cannot be used before it is declared. Consider renaming the local variable when it hides the field `{1}'",
5268 name
, GetSignatureForError ());
5271 public void AddressOf (EmitContext ec
, AddressOp mode
)
5273 ILGenerator ig
= ec
.ig
;
5275 FieldBase f
= TypeManager
.GetField (FieldInfo
);
5277 if ((mode
& AddressOp
.Store
) != 0)
5279 if ((mode
& AddressOp
.Load
) != 0)
5280 f
.SetMemberIsUsed ();
5284 // Handle initonly fields specially: make a copy and then
5285 // get the address of the copy.
5288 if (FieldInfo
.IsInitOnly
){
5290 if (ec
.HasSet (EmitContext
.Options
.ConstructorScope
)){
5291 if (FieldInfo
.IsStatic
){
5303 local
= ig
.DeclareLocal (type
);
5304 ig
.Emit (OpCodes
.Stloc
, local
);
5305 ig
.Emit (OpCodes
.Ldloca
, local
);
5310 if (FieldInfo
.IsStatic
){
5311 ig
.Emit (OpCodes
.Ldsflda
, GetConstructedFieldInfo ());
5314 EmitInstance (ec
, false);
5315 ig
.Emit (OpCodes
.Ldflda
, GetConstructedFieldInfo ());
5319 FieldInfo
GetConstructedFieldInfo ()
5321 if (constructed_generic_type
== null)
5324 return TypeBuilder
.GetField (constructed_generic_type
, FieldInfo
);
5327 public SLE
.Expression
MakeAssignExpression (BuilderContext ctx
)
5329 return MakeExpression (ctx
);
5332 public override SLE
.Expression
MakeExpression (BuilderContext ctx
)
5334 return SLE
.Expression
.Field (InstanceExpression
.MakeExpression (ctx
), FieldInfo
);
5337 public override void MutateHoistedGenericType (AnonymousMethodStorey storey
)
5339 FieldInfo
= storey
.MutateField (FieldInfo
);
5340 base.MutateHoistedGenericType (storey
);
5346 /// Expression that evaluates to a Property. The Assign class
5347 /// might set the `Value' expression if we are in an assignment.
5349 /// This is not an LValue because we need to re-write the expression, we
5350 /// can not take data from the stack and store it.
5352 public class PropertyExpr
: MemberExpr
, IDynamicAssign
5354 public readonly PropertyInfo PropertyInfo
;
5355 MethodInfo getter
, setter
;
5358 TypeArguments targs
;
5360 LocalTemporary temp
;
5363 public PropertyExpr (Type container_type
, PropertyInfo pi
, Location l
)
5369 type
= TypeManager
.TypeToCoreType (pi
.PropertyType
);
5371 ResolveAccessors (container_type
);
5374 public override string Name
{
5376 return PropertyInfo
.Name
;
5380 public override bool IsInstance
{
5386 public override bool IsStatic
{
5392 public override Expression
CreateExpressionTree (ResolveContext ec
)
5395 if (IsSingleDimensionalArrayLength ()) {
5396 args
= new Arguments (1);
5397 args
.Add (new Argument (InstanceExpression
.CreateExpressionTree (ec
)));
5398 return CreateExpressionFactoryCall (ec
, "ArrayLength", args
);
5402 Error_BaseAccessInExpressionTree (ec
, loc
);
5406 args
= new Arguments (2);
5407 if (InstanceExpression
== null)
5408 args
.Add (new Argument (new NullLiteral (loc
)));
5410 args
.Add (new Argument (InstanceExpression
.CreateExpressionTree (ec
)));
5411 args
.Add (new Argument (new TypeOfMethod (getter
, loc
)));
5412 return CreateExpressionFactoryCall (ec
, "Property", args
);
5415 public Expression
CreateSetterTypeOfExpression ()
5417 return new TypeOfMethod (setter
, loc
);
5420 public override Type DeclaringType
{
5422 return PropertyInfo
.DeclaringType
;
5426 public override string GetSignatureForError ()
5428 return TypeManager
.GetFullNameSignature (PropertyInfo
);
5431 void FindAccessors (Type invocation_type
)
5433 const BindingFlags flags
= BindingFlags
.Public
| BindingFlags
.NonPublic
|
5434 BindingFlags
.Static
| BindingFlags
.Instance
|
5435 BindingFlags
.DeclaredOnly
;
5437 Type current
= PropertyInfo
.DeclaringType
;
5438 for (; current
!= null; current
= current
.BaseType
) {
5439 MemberInfo
[] group = TypeManager
.MemberLookup (
5440 invocation_type
, invocation_type
, current
,
5441 MemberTypes
.Property
, flags
, PropertyInfo
.Name
, null);
5446 if (group.Length
!= 1)
5447 // Oooops, can this ever happen ?
5450 PropertyInfo pi
= (PropertyInfo
) group [0];
5453 getter
= pi
.GetGetMethod (true);
5456 setter
= pi
.GetSetMethod (true);
5458 MethodInfo accessor
= getter
!= null ? getter
: setter
;
5460 if (!accessor
.IsVirtual
)
5466 // We also perform the permission checking here, as the PropertyInfo does not
5467 // hold the information for the accessibility of its setter/getter
5469 // TODO: Refactor to use some kind of cache together with GetPropertyFromAccessor
5470 void ResolveAccessors (Type container_type
)
5472 FindAccessors (container_type
);
5474 if (getter
!= null) {
5475 MethodBase the_getter
= TypeManager
.DropGenericMethodArguments (getter
);
5476 IMethodData md
= TypeManager
.GetMethod (the_getter
);
5478 md
.SetMemberIsUsed ();
5480 is_static
= getter
.IsStatic
;
5483 if (setter
!= null) {
5484 MethodBase the_setter
= TypeManager
.DropGenericMethodArguments (setter
);
5485 IMethodData md
= TypeManager
.GetMethod (the_setter
);
5487 md
.SetMemberIsUsed ();
5489 is_static
= setter
.IsStatic
;
5493 public SLE
.Expression
MakeAssignExpression (BuilderContext ctx
)
5495 return SLE
.Expression
.Property (InstanceExpression
.MakeExpression (ctx
), setter
);
5498 public override SLE
.Expression
MakeExpression (BuilderContext ctx
)
5500 return SLE
.Expression
.Property (InstanceExpression
.MakeExpression (ctx
), getter
);
5503 public override void MutateHoistedGenericType (AnonymousMethodStorey storey
)
5505 if (InstanceExpression
!= null)
5506 InstanceExpression
.MutateHoistedGenericType (storey
);
5508 type
= storey
.MutateType (type
);
5510 getter
= storey
.MutateGenericMethod (getter
);
5512 setter
= storey
.MutateGenericMethod (setter
);
5515 bool InstanceResolve (ResolveContext ec
, bool lvalue_instance
, bool must_do_cs1540_check
)
5518 InstanceExpression
= null;
5522 if (InstanceExpression
== null) {
5523 SimpleName
.Error_ObjectRefRequired (ec
, loc
, GetSignatureForError ());
5527 InstanceExpression
= InstanceExpression
.Resolve (ec
);
5528 if (lvalue_instance
&& InstanceExpression
!= null)
5529 InstanceExpression
= InstanceExpression
.ResolveLValue (ec
, EmptyExpression
.LValueMemberAccess
);
5531 if (InstanceExpression
== null)
5534 InstanceExpression
.CheckMarshalByRefAccess (ec
);
5536 if (must_do_cs1540_check
&& (InstanceExpression
!= EmptyExpression
.Null
) &&
5537 !TypeManager
.IsInstantiationOfSameGenericType (InstanceExpression
.Type
, ec
.CurrentType
) &&
5538 !TypeManager
.IsNestedChildOf (ec
.CurrentType
, InstanceExpression
.Type
) &&
5539 !TypeManager
.IsSubclassOf (InstanceExpression
.Type
, ec
.CurrentType
)) {
5540 ec
.Report
.SymbolRelatedToPreviousError (PropertyInfo
);
5541 Error_CannotAccessProtected (ec
, loc
, PropertyInfo
, InstanceExpression
.Type
, ec
.CurrentType
);
5548 void Error_PropertyNotFound (ResolveContext ec
, MethodInfo mi
, bool getter
)
5550 // TODO: correctly we should compare arguments but it will lead to bigger changes
5551 if (mi
is MethodBuilder
) {
5552 Error_TypeDoesNotContainDefinition (ec
, loc
, PropertyInfo
.DeclaringType
, Name
);
5556 StringBuilder sig
= new StringBuilder (TypeManager
.CSharpName (mi
.DeclaringType
));
5558 AParametersCollection iparams
= TypeManager
.GetParameterData (mi
);
5559 sig
.Append (getter
? "get_" : "set_");
5561 sig
.Append (iparams
.GetSignatureForError ());
5563 ec
.Report
.SymbolRelatedToPreviousError (mi
);
5564 ec
.Report
.Error (1546, loc
, "Property `{0}' is not supported by the C# language. Try to call the accessor method `{1}' directly",
5565 Name
, sig
.ToString ());
5568 public bool IsAccessibleFrom (Type invocation_type
, bool lvalue
)
5571 MethodInfo accessor
= lvalue
? setter
: getter
;
5572 if (accessor
== null && lvalue
)
5574 return accessor
!= null && IsAccessorAccessible (invocation_type
, accessor
, out dummy
);
5577 bool IsSingleDimensionalArrayLength ()
5579 if (DeclaringType
!= TypeManager
.array_type
|| getter
== null || Name
!= "Length")
5582 string t_name
= InstanceExpression
.Type
.Name
;
5583 int t_name_len
= t_name
.Length
;
5584 return t_name_len
> 2 && t_name
[t_name_len
- 2] == '[';
5587 protected override Expression
DoResolve (ResolveContext ec
)
5589 eclass
= ExprClass
.PropertyAccess
;
5591 bool must_do_cs1540_check
= false;
5592 ec
.Report
.DisableReporting ();
5593 bool res
= ResolveGetter (ec
, ref must_do_cs1540_check
);
5594 ec
.Report
.EnableReporting ();
5597 if (InstanceExpression
!= null) {
5598 Type expr_type
= InstanceExpression
.Type
;
5599 ExtensionMethodGroupExpr ex_method_lookup
= ec
.LookupExtensionMethod (expr_type
, Name
, loc
);
5600 if (ex_method_lookup
!= null) {
5601 ex_method_lookup
.ExtensionExpression
= InstanceExpression
;
5602 ex_method_lookup
.SetTypeArguments (ec
, targs
);
5603 return ex_method_lookup
.Resolve (ec
);
5607 ResolveGetter (ec
, ref must_do_cs1540_check
);
5611 if (!InstanceResolve (ec
, false, must_do_cs1540_check
))
5615 // Only base will allow this invocation to happen.
5617 if (IsBase
&& getter
.IsAbstract
) {
5618 Error_CannotCallAbstractBase (ec
, TypeManager
.GetFullNameSignature (PropertyInfo
));
5621 if (PropertyInfo
.PropertyType
.IsPointer
&& !ec
.IsUnsafe
){
5622 UnsafeError (ec
, loc
);
5625 if (!ec
.IsObsolete
) {
5626 PropertyBase pb
= TypeManager
.GetProperty (PropertyInfo
);
5628 pb
.CheckObsoleteness (loc
);
5630 ObsoleteAttribute oa
= AttributeTester
.GetMemberObsoleteAttribute (PropertyInfo
);
5632 AttributeTester
.Report_ObsoleteMessage (oa
, GetSignatureForError (), loc
, ec
.Report
);
5639 override public Expression
DoResolveLValue (ResolveContext ec
, Expression right_side
)
5641 eclass
= ExprClass
.PropertyAccess
;
5643 if (right_side
== EmptyExpression
.OutAccess
.Instance
) {
5644 if (ec
.CurrentBlock
.Toplevel
.GetParameterReference (PropertyInfo
.Name
, loc
) is MemberAccess
) {
5645 ec
.Report
.Error (1939, loc
, "A range variable `{0}' may not be passes as `ref' or `out' parameter",
5648 right_side
.DoResolveLValue (ec
, this);
5653 if (right_side
== EmptyExpression
.LValueMemberAccess
|| right_side
== EmptyExpression
.LValueMemberOutAccess
) {
5654 Error_CannotModifyIntermediateExpressionValue (ec
);
5657 if (setter
== null){
5659 // The following condition happens if the PropertyExpr was
5660 // created, but is invalid (ie, the property is inaccessible),
5661 // and we did not want to embed the knowledge about this in
5662 // the caller routine. This only avoids double error reporting.
5667 if (ec
.CurrentBlock
.Toplevel
.GetParameterReference (PropertyInfo
.Name
, loc
) is MemberAccess
) {
5668 ec
.Report
.Error (1947, loc
, "A range variable `{0}' cannot be assigned to. Consider using `let' clause to store the value",
5671 ec
.Report
.Error (200, loc
, "Property or indexer `{0}' cannot be assigned to (it is read only)",
5672 GetSignatureForError ());
5677 if (targs
!= null) {
5678 base.SetTypeArguments (ec
, targs
);
5682 if (TypeManager
.GetParameterData (setter
).Count
!= 1){
5683 Error_PropertyNotFound (ec
, setter
, false);
5687 bool must_do_cs1540_check
;
5688 if (!IsAccessorAccessible (ec
.CurrentType
, setter
, out must_do_cs1540_check
)) {
5689 PropertyBase
.PropertyMethod pm
= TypeManager
.GetMethod (setter
) as PropertyBase
.PropertyMethod
;
5690 if (pm
!= null && pm
.HasCustomAccessModifier
) {
5691 ec
.Report
.SymbolRelatedToPreviousError (pm
);
5692 ec
.Report
.Error (272, loc
, "The property or indexer `{0}' cannot be used in this context because the set accessor is inaccessible",
5693 TypeManager
.CSharpSignature (setter
));
5696 ec
.Report
.SymbolRelatedToPreviousError (setter
);
5697 ErrorIsInaccesible (loc
, TypeManager
.CSharpSignature (setter
), ec
.Report
);
5702 if (!InstanceResolve (ec
, TypeManager
.IsStruct (PropertyInfo
.DeclaringType
), must_do_cs1540_check
))
5706 // Only base will allow this invocation to happen.
5708 if (IsBase
&& setter
.IsAbstract
){
5709 Error_CannotCallAbstractBase (ec
, TypeManager
.GetFullNameSignature (PropertyInfo
));
5712 if (PropertyInfo
.PropertyType
.IsPointer
&& !ec
.IsUnsafe
) {
5713 UnsafeError (ec
, loc
);
5716 if (!ec
.IsObsolete
) {
5717 PropertyBase pb
= TypeManager
.GetProperty (PropertyInfo
);
5719 pb
.CheckObsoleteness (loc
);
5721 ObsoleteAttribute oa
= AttributeTester
.GetMemberObsoleteAttribute (PropertyInfo
);
5723 AttributeTester
.Report_ObsoleteMessage (oa
, GetSignatureForError (), loc
, ec
.Report
);
5730 public override void Emit (EmitContext ec
)
5735 public void Emit (EmitContext ec
, bool leave_copy
)
5738 // Special case: length of single dimension array property is turned into ldlen
5740 if (IsSingleDimensionalArrayLength ()) {
5742 EmitInstance (ec
, false);
5743 ec
.ig
.Emit (OpCodes
.Ldlen
);
5744 ec
.ig
.Emit (OpCodes
.Conv_I4
);
5748 Invocation
.EmitCall (ec
, IsBase
, InstanceExpression
, getter
, null, loc
, prepared
, false);
5751 ec
.ig
.Emit (OpCodes
.Dup
);
5753 temp
= new LocalTemporary (this.Type
);
5760 // Implements the IAssignMethod interface for assignments
5762 public void EmitAssign (EmitContext ec
, Expression source
, bool leave_copy
, bool prepare_for_load
)
5764 Expression my_source
= source
;
5766 if (prepare_for_load
) {
5771 ec
.ig
.Emit (OpCodes
.Dup
);
5773 temp
= new LocalTemporary (this.Type
);
5777 } else if (leave_copy
) {
5779 temp
= new LocalTemporary (this.Type
);
5784 Arguments args
= new Arguments (1);
5785 args
.Add (new Argument (my_source
));
5787 Invocation
.EmitCall (ec
, IsBase
, InstanceExpression
, setter
, args
, loc
, false, prepared
);
5795 bool ResolveGetter (ResolveContext ec
, ref bool must_do_cs1540_check
)
5797 if (targs
!= null) {
5798 base.SetTypeArguments (ec
, targs
);
5802 if (getter
!= null) {
5803 if (TypeManager
.GetParameterData (getter
).Count
!= 0) {
5804 Error_PropertyNotFound (ec
, getter
, true);
5809 if (getter
== null) {
5811 // The following condition happens if the PropertyExpr was
5812 // created, but is invalid (ie, the property is inaccessible),
5813 // and we did not want to embed the knowledge about this in
5814 // the caller routine. This only avoids double error reporting.
5819 if (InstanceExpression
!= EmptyExpression
.Null
) {
5820 ec
.Report
.Error (154, loc
, "The property or indexer `{0}' cannot be used in this context because it lacks the `get' accessor",
5821 TypeManager
.GetFullNameSignature (PropertyInfo
));
5826 if (getter
!= null &&
5827 !IsAccessorAccessible (ec
.CurrentType
, getter
, out must_do_cs1540_check
)) {
5828 PropertyBase
.PropertyMethod pm
= TypeManager
.GetMethod (getter
) as PropertyBase
.PropertyMethod
;
5829 if (pm
!= null && pm
.HasCustomAccessModifier
) {
5830 ec
.Report
.SymbolRelatedToPreviousError (pm
);
5831 ec
.Report
.Error (271, loc
, "The property or indexer `{0}' cannot be used in this context because the get accessor is inaccessible",
5832 TypeManager
.CSharpSignature (getter
));
5834 ec
.Report
.SymbolRelatedToPreviousError (getter
);
5835 ErrorIsInaccesible (loc
, TypeManager
.CSharpSignature (getter
), ec
.Report
);
5844 public override void SetTypeArguments (ResolveContext ec
, TypeArguments ta
)
5851 /// Fully resolved expression that evaluates to an Event
5853 public class EventExpr
: MemberExpr
{
5854 public readonly EventInfo EventInfo
;
5857 MethodInfo add_accessor
, remove_accessor
;
5859 public EventExpr (EventInfo ei
, Location loc
)
5864 add_accessor
= TypeManager
.GetAddMethod (ei
);
5865 remove_accessor
= TypeManager
.GetRemoveMethod (ei
);
5866 if (add_accessor
.IsStatic
|| remove_accessor
.IsStatic
)
5869 if (EventInfo
is MyEventBuilder
){
5870 MyEventBuilder eb
= (MyEventBuilder
) EventInfo
;
5871 type
= eb
.EventType
;
5874 type
= EventInfo
.EventHandlerType
;
5877 public override string Name
{
5879 return EventInfo
.Name
;
5883 public override bool IsInstance
{
5889 public override bool IsStatic
{
5895 public override Type DeclaringType
{
5897 return EventInfo
.DeclaringType
;
5901 public void Error_AssignmentEventOnly (ResolveContext ec
)
5903 ec
.Report
.Error (79, loc
, "The event `{0}' can only appear on the left hand side of `+=' or `-=' operator",
5904 GetSignatureForError ());
5907 public override MemberExpr
ResolveMemberAccess (ResolveContext ec
, Expression left
, Location loc
,
5908 SimpleName original
)
5911 // If the event is local to this class, we transform ourselves into a FieldExpr
5914 if (EventInfo
.DeclaringType
== ec
.CurrentType
||
5915 TypeManager
.IsNestedChildOf(ec
.CurrentType
, EventInfo
.DeclaringType
)) {
5917 // TODO: Breaks dynamic binder as currect context fields are imported and not compiled
5918 EventField mi
= TypeManager
.GetEventField (EventInfo
);
5922 mi
.CheckObsoleteness (loc
);
5924 if ((mi
.ModFlags
& (Modifiers
.ABSTRACT
| Modifiers
.EXTERN
)) != 0 && !ec
.HasSet (ResolveContext
.Options
.CompoundAssignmentScope
))
5925 Error_AssignmentEventOnly (ec
);
5927 FieldExpr ml
= new FieldExpr (mi
.BackingField
.FieldBuilder
, loc
);
5929 InstanceExpression
= null;
5931 return ml
.ResolveMemberAccess (ec
, left
, loc
, original
);
5935 if (left
is This
&& !ec
.HasSet (ResolveContext
.Options
.CompoundAssignmentScope
))
5936 Error_AssignmentEventOnly (ec
);
5938 return base.ResolveMemberAccess (ec
, left
, loc
, original
);
5941 bool InstanceResolve (ResolveContext ec
, bool must_do_cs1540_check
)
5944 InstanceExpression
= null;
5948 if (InstanceExpression
== null) {
5949 SimpleName
.Error_ObjectRefRequired (ec
, loc
, GetSignatureForError ());
5953 InstanceExpression
= InstanceExpression
.Resolve (ec
);
5954 if (InstanceExpression
== null)
5957 if (IsBase
&& add_accessor
.IsAbstract
) {
5958 Error_CannotCallAbstractBase (ec
, TypeManager
.CSharpSignature(add_accessor
));
5963 // This is using the same mechanism as the CS1540 check in PropertyExpr.
5964 // However, in the Event case, we reported a CS0122 instead.
5966 // TODO: Exact copy from PropertyExpr
5968 if (must_do_cs1540_check
&& InstanceExpression
!= EmptyExpression
.Null
&&
5969 !TypeManager
.IsInstantiationOfSameGenericType (InstanceExpression
.Type
, ec
.CurrentType
) &&
5970 !TypeManager
.IsNestedChildOf (ec
.CurrentType
, InstanceExpression
.Type
) &&
5971 !TypeManager
.IsSubclassOf (InstanceExpression
.Type
, ec
.CurrentType
)) {
5972 ec
.Report
.SymbolRelatedToPreviousError (EventInfo
);
5973 ErrorIsInaccesible (loc
, TypeManager
.CSharpSignature (EventInfo
), ec
.Report
);
5980 public bool IsAccessibleFrom (Type invocation_type
)
5983 return IsAccessorAccessible (invocation_type
, add_accessor
, out dummy
) &&
5984 IsAccessorAccessible (invocation_type
, remove_accessor
, out dummy
);
5987 public override Expression
CreateExpressionTree (ResolveContext ec
)
5989 throw new NotSupportedException ("ET");
5992 public override Expression
DoResolveLValue (ResolveContext ec
, Expression right_side
)
5994 // contexts where an LValue is valid have already devolved to FieldExprs
5995 Error_CannotAssign (ec
);
5999 protected override Expression
DoResolve (ResolveContext ec
)
6001 eclass
= ExprClass
.EventAccess
;
6003 bool must_do_cs1540_check
;
6004 if (!(IsAccessorAccessible (ec
.CurrentType
, add_accessor
, out must_do_cs1540_check
) &&
6005 IsAccessorAccessible (ec
.CurrentType
, remove_accessor
, out must_do_cs1540_check
))) {
6006 ec
.Report
.SymbolRelatedToPreviousError (EventInfo
);
6007 ErrorIsInaccesible (loc
, TypeManager
.CSharpSignature (EventInfo
), ec
.Report
);
6011 if (!InstanceResolve (ec
, must_do_cs1540_check
))
6014 if (!ec
.HasSet (ResolveContext
.Options
.CompoundAssignmentScope
)) {
6015 Error_CannotAssign (ec
);
6019 if (!ec
.IsObsolete
) {
6020 EventField ev
= TypeManager
.GetEventField (EventInfo
);
6022 ev
.CheckObsoleteness (loc
);
6024 ObsoleteAttribute oa
= AttributeTester
.GetMemberObsoleteAttribute (EventInfo
);
6026 AttributeTester
.Report_ObsoleteMessage (oa
, GetSignatureForError (), loc
, ec
.Report
);
6033 public override void Emit (EmitContext ec
)
6035 throw new NotSupportedException ();
6036 //Error_CannotAssign ();
6039 public void Error_CannotAssign (ResolveContext ec
)
6041 ec
.Report
.Error (70, loc
,
6042 "The event `{0}' can only appear on the left hand side of += or -= when used outside of the type `{1}'",
6043 GetSignatureForError (), TypeManager
.CSharpName (EventInfo
.DeclaringType
));
6046 public override string GetSignatureForError ()
6048 return TypeManager
.CSharpSignature (EventInfo
);
6051 public void EmitAddOrRemove (EmitContext ec
, bool is_add
, Expression source
)
6053 Arguments args
= new Arguments (1);
6054 args
.Add (new Argument (source
));
6055 Invocation
.EmitCall (ec
, IsBase
, InstanceExpression
, is_add
? add_accessor
: remove_accessor
, args
, loc
);
6059 public class TemporaryVariable
: VariableReference
6063 public TemporaryVariable (Type type
, Location loc
)
6069 public override Expression
CreateExpressionTree (ResolveContext ec
)
6071 throw new NotSupportedException ("ET");
6074 protected override Expression
DoResolve (ResolveContext ec
)
6076 eclass
= ExprClass
.Variable
;
6078 TypeExpr te
= new TypeExpression (type
, loc
);
6079 li
= ec
.CurrentBlock
.AddTemporaryVariable (te
, loc
);
6080 if (!li
.Resolve (ec
))
6084 // Don't capture temporary variables except when using
6085 // iterator redirection
6087 if (ec
.CurrentAnonymousMethod
!= null && ec
.CurrentAnonymousMethod
.IsIterator
&& ec
.IsVariableCapturingRequired
) {
6088 AnonymousMethodStorey storey
= li
.Block
.Explicit
.CreateAnonymousMethodStorey (ec
);
6089 storey
.CaptureLocalVariable (ec
, li
);
6095 public override Expression
DoResolveLValue (ResolveContext ec
, Expression right_side
)
6097 return Resolve (ec
);
6100 public override void Emit (EmitContext ec
)
6105 public void EmitAssign (EmitContext ec
, Expression source
)
6107 EmitAssign (ec
, source
, false, false);
6110 public override HoistedVariable
GetHoistedVariable (AnonymousExpression ae
)
6112 return li
.HoistedVariant
;
6115 public override bool IsFixed
{
6116 get { return true; }
6119 public override bool IsRef
{
6120 get { return false; }
6123 public override string Name
{
6124 get { throw new NotImplementedException (); }
6127 public override void SetHasAddressTaken ()
6129 throw new NotImplementedException ();
6132 protected override ILocalVariable Variable
{
6136 public override VariableInfo VariableInfo
{
6137 get { throw new NotImplementedException (); }
6142 /// Handles `var' contextual keyword; var becomes a keyword only
6143 /// if no type called var exists in a variable scope
6145 class VarExpr
: SimpleName
6147 // Used for error reporting only
6148 int initializers_count
;
6150 public VarExpr (Location loc
)
6153 initializers_count
= 1;
6156 public int VariableInitializersCount
{
6158 this.initializers_count
= value;
6162 public bool InferType (ResolveContext ec
, Expression right_side
)
6165 throw new InternalErrorException ("An implicitly typed local variable could not be redefined");
6167 type
= right_side
.Type
;
6168 if (type
== TypeManager
.null_type
|| type
== TypeManager
.void_type
|| type
== InternalType
.AnonymousMethod
|| type
== InternalType
.MethodGroup
) {
6169 ec
.Report
.Error (815, loc
, "An implicitly typed local variable declaration cannot be initialized with `{0}'",
6170 right_side
.GetSignatureForError ());
6174 eclass
= ExprClass
.Variable
;
6178 protected override void Error_TypeOrNamespaceNotFound (IMemberContext ec
)
6180 if (RootContext
.Version
< LanguageVersion
.V_3
)
6181 base.Error_TypeOrNamespaceNotFound (ec
);
6183 ec
.Compiler
.Report
.Error (825, loc
, "The contextual keyword `var' may only appear within a local variable declaration");
6186 public override TypeExpr
ResolveAsContextualType (IMemberContext rc
, bool silent
)
6188 TypeExpr te
= base.ResolveAsContextualType (rc
, true);
6192 if (RootContext
.Version
< LanguageVersion
.V_3
)
6193 rc
.Compiler
.Report
.FeatureIsNotAvailable (loc
, "implicitly typed local variable");
6195 if (initializers_count
== 1)
6198 if (initializers_count
> 1) {
6199 rc
.Compiler
.Report
.Error (819, loc
, "An implicitly typed local variable declaration cannot include multiple declarators");
6200 initializers_count
= 1;
6204 if (initializers_count
== 0) {
6205 initializers_count
= 1;
6206 rc
.Compiler
.Report
.Error (818, loc
, "An implicitly typed local variable declarator must include an initializer");