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