2 // anonymous.cs: Support for anonymous methods and types
5 // Miguel de Icaza (miguel@ximain.com)
6 // Marek Safar (marek.safar@gmail.com)
8 // Dual licensed under the terms of the MIT X11 or GNU GPL
9 // Copyright 2003-2008 Novell, Inc.
14 using System
.Collections
;
15 using System
.Collections
.Specialized
;
16 using System
.Reflection
;
17 using System
.Reflection
.Emit
;
19 namespace Mono
.CSharp
{
21 public abstract class CompilerGeneratedClass
: Class
23 public static string MakeName (string host
, string typePrefix
, string name
, int id
)
25 return "<" + host
+ ">" + typePrefix
+ "__" + name
+ id
.ToString ("X");
28 protected CompilerGeneratedClass (DeclSpace parent
, MemberName name
, int mod
)
29 : base (parent
.NamespaceEntry
, parent
, name
, mod
| Modifiers
.COMPILER_GENERATED
| Modifiers
.SEALED
, null)
33 protected CompilerGeneratedClass (DeclSpace parent
, GenericMethod generic
, MemberName name
, int mod
)
34 : this (parent
, name
, mod
)
36 if (generic
!= null) {
37 ArrayList list
= new ArrayList ();
38 foreach (TypeParameter tparam
in generic
.TypeParameters
) {
39 if (tparam
.Constraints
!= null)
40 list
.Add (tparam
.Constraints
.Clone ());
42 SetParameterInfo (list
);
46 protected void CheckMembersDefined ()
49 throw new InternalErrorException ("Helper class already defined!");
54 // Anonymous method storey is created when an anonymous method uses
55 // variable or parameter from outer scope. They are then hoisted to
56 // anonymous method storey (captured)
58 public class AnonymousMethodStorey
: CompilerGeneratedClass
60 class StoreyFieldPair
{
61 public readonly AnonymousMethodStorey Storey
;
62 public readonly Field Field
;
64 public StoreyFieldPair (AnonymousMethodStorey storey
, Field field
)
70 public override int GetHashCode ()
72 return Storey
.ID
.GetHashCode ();
75 public override bool Equals (object obj
)
77 return (AnonymousMethodStorey
)obj
== Storey
;
81 sealed class HoistedGenericField
: Field
83 public HoistedGenericField (DeclSpace parent
, FullNamedExpression type
, int mod
, string name
,
84 Attributes attrs
, Location loc
)
85 : base (parent
, type
, mod
, new MemberName (name
, loc
), attrs
)
89 protected override bool ResolveMemberType ()
91 if (!base.ResolveMemberType ())
94 AnonymousMethodStorey parent
= ((AnonymousMethodStorey
) Parent
).GetGenericStorey ();
96 member_type
= parent
.MutateType (member_type
);
103 // Needed to delay hoisted _this_ initialization. When an anonymous
104 // method is used inside ctor and _this_ is hoisted, base ctor has to
105 // be called first, otherwise _this_ will be initialized with
106 // uninitialized value.
108 sealed class ThisInitializer
: Statement
110 readonly HoistedThis hoisted_this
;
112 public ThisInitializer (HoistedThis hoisted_this
)
114 this.hoisted_this
= hoisted_this
;
117 protected override void DoEmit (EmitContext ec
)
119 hoisted_this
.EmitHoistingAssignment (ec
);
122 protected override void CloneTo (CloneContext clonectx
, Statement target
)
127 public override void MutateHoistedGenericType (AnonymousMethodStorey storey
)
134 public readonly int ID
;
135 static int unique_id
;
137 public readonly Block OriginalSourceBlock
;
139 // A list of StoreyFieldPair with local field keeping parent storey instance
140 ArrayList used_parent_storeys
;
141 ArrayList children_references
;
143 // A list of hoisted parameters
144 protected ArrayList hoisted_params
;
145 protected ArrayList hoisted_locals
;
148 protected HoistedThis hoisted_this
;
150 // Local variable which holds this storey instance
151 public LocalTemporary Instance
;
153 public AnonymousMethodStorey (Block block
, TypeContainer parent
, MemberBase host
, GenericMethod generic
, string name
)
154 : base (parent
, generic
, MakeMemberName (host
, name
, generic
, block
.StartLocation
), Modifiers
.PRIVATE
)
157 OriginalSourceBlock
= block
;
161 static MemberName
MakeMemberName (MemberBase host
, string name
, GenericMethod generic
, Location loc
)
163 string host_name
= host
== null ? null : host
.Name
;
164 string tname
= MakeName (host_name
, "c", name
, unique_id
);
165 TypeArguments args
= null;
166 if (generic
!= null) {
167 args
= new TypeArguments ();
168 foreach (TypeParameter tparam
in generic
.CurrentTypeParameters
)
169 args
.Add (new TypeParameterName (tparam
.Name
, null, loc
));
172 return new MemberName (tname
, args
, loc
);
175 public void AddCapturedThisField (EmitContext ec
)
177 TypeExpr type_expr
= new TypeExpression (ec
.CurrentType
, Location
);
178 Field f
= AddCompilerGeneratedField ("<>f__this", type_expr
);
180 hoisted_this
= new HoistedThis (this, f
);
183 public Field
AddCapturedVariable (string name
, Type type
)
185 CheckMembersDefined ();
187 FullNamedExpression field_type
= new TypeExpression (type
, Location
);
189 return AddCompilerGeneratedField (name
, field_type
);
191 const int mod
= Modifiers
.INTERNAL
| Modifiers
.COMPILER_GENERATED
;
192 Field f
= new HoistedGenericField (this, field_type
, mod
, name
, null, Location
);
197 protected Field
AddCompilerGeneratedField (string name
, FullNamedExpression type
)
199 const int mod
= Modifiers
.INTERNAL
| Modifiers
.COMPILER_GENERATED
;
200 Field f
= new Field (this, type
, mod
, new MemberName (name
, Location
), null);
206 // Creates a link between block and the anonymous method storey
208 // An anonymous method can reference variables from any outer block, but they are
209 // hoisted in their own ExplicitBlock. When more than one block is referenced we
210 // need to create another link between those variable storeys
212 public void AddReferenceFromChildrenBlock (ExplicitBlock block
)
214 if (children_references
== null)
215 children_references
= new ArrayList ();
217 if (!children_references
.Contains (block
))
218 children_references
.Add (block
);
221 public void AddParentStoreyReference (AnonymousMethodStorey storey
)
223 CheckMembersDefined ();
225 if (used_parent_storeys
== null)
226 used_parent_storeys
= new ArrayList ();
227 else if (used_parent_storeys
.IndexOf (storey
) != -1)
230 TypeExpr type_expr
= new TypeExpression (storey
.TypeBuilder
, Location
);
231 Field f
= AddCompilerGeneratedField ("<>f__ref$" + storey
.ID
, type_expr
);
232 used_parent_storeys
.Add (new StoreyFieldPair (storey
, f
));
235 public void CaptureLocalVariable (ResolveContext ec
, LocalInfo local_info
)
237 ec
.CurrentBlock
.Explicit
.HasCapturedVariable
= true;
238 if (ec
.CurrentBlock
.Explicit
!= local_info
.Block
.Explicit
)
239 AddReferenceFromChildrenBlock (ec
.CurrentBlock
.Explicit
);
241 if (local_info
.HoistedVariableReference
!= null)
244 HoistedVariable
var = new HoistedLocalVariable (this, local_info
, GetVariableMangledName (local_info
));
245 local_info
.HoistedVariableReference
= var;
247 if (hoisted_locals
== null)
248 hoisted_locals
= new ArrayList ();
250 hoisted_locals
.Add (var);
253 public void CaptureParameter (ResolveContext ec
, ParameterReference param_ref
)
255 ec
.CurrentBlock
.Explicit
.HasCapturedVariable
= true;
256 AddReferenceFromChildrenBlock (ec
.CurrentBlock
.Explicit
);
258 if (param_ref
.GetHoistedVariable (ec
) != null)
261 if (hoisted_params
== null)
262 hoisted_params
= new ArrayList (2);
264 HoistedVariable expr
= new HoistedParameter (this, param_ref
);
265 param_ref
.Parameter
.HoistedVariableReference
= expr
;
266 hoisted_params
.Add (expr
);
269 public void ChangeParentStorey (AnonymousMethodStorey parentStorey
)
271 Parent
= parentStorey
;
276 // Initializes all hoisted variables
278 public void EmitStoreyInstantiation (EmitContext ec
)
280 // There can be only one instance variable for each storey type
281 if (Instance
!= null)
282 throw new InternalErrorException ();
284 SymbolWriter
.OpenCompilerGeneratedBlock (ec
.ig
);
287 // Create an instance of storey type
289 Expression storey_type_expr
;
292 // Use current method type parameter (MVAR) for top level storey only. All
293 // nested storeys use class type parameter (VAR)
295 TypeParameter
[] tparams
= ec
.CurrentAnonymousMethod
!= null && ec
.CurrentAnonymousMethod
.Storey
!= null ?
296 ec
.CurrentAnonymousMethod
.Storey
.TypeParameters
:
297 ec
.CurrentTypeParameters
;
299 TypeArguments targs
= new TypeArguments ();
301 if (tparams
.Length
< CountTypeParameters
) {
302 TypeParameter
[] parent_tparams
= ec
.MemberContext
.CurrentTypeDefinition
.TypeParameters
;
303 for (int i
= 0; i
< parent_tparams
.Length
; ++i
)
304 targs
.Add (new TypeParameterExpr (parent_tparams
[i
], Location
));
307 for (int i
= 0; i
< tparams
.Length
; ++i
)
308 targs
.Add (new TypeParameterExpr (tparams
[i
], Location
));
310 storey_type_expr
= new GenericTypeExpr (TypeBuilder
, targs
, Location
);
312 storey_type_expr
= new TypeExpression (TypeBuilder
, Location
);
315 ResolveContext rc
= new ResolveContext (this);
316 Expression e
= new New (storey_type_expr
, null, Location
).Resolve (rc
);
319 Instance
= new LocalTemporary (storey_type_expr
.Type
);
322 EmitHoistedFieldsInitialization (ec
);
324 SymbolWriter
.DefineScopeVariable (ID
, Instance
.Builder
);
325 SymbolWriter
.CloseCompilerGeneratedBlock (ec
.ig
);
328 void EmitHoistedFieldsInitialization (EmitContext ec
)
331 // Initialize all storey reference fields by using local or hoisted variables
333 if (used_parent_storeys
!= null) {
334 foreach (StoreyFieldPair sf
in used_parent_storeys
) {
336 // Setting local field
338 Expression instace_expr
= GetStoreyInstanceExpression (ec
);
339 FieldExpr f_set_expr
= TypeManager
.IsGenericType (instace_expr
.Type
) ?
340 new FieldExpr (sf
.Field
.FieldBuilder
, instace_expr
.Type
, Location
) :
341 new FieldExpr (sf
.Field
.FieldBuilder
, Location
);
342 f_set_expr
.InstanceExpression
= instace_expr
;
344 SimpleAssign a
= new SimpleAssign (f_set_expr
, sf
.Storey
.GetStoreyInstanceExpression (ec
));
345 if (a
.Resolve (new ResolveContext (ec
.MemberContext
)) != null)
346 a
.EmitStatement (ec
);
351 // Define hoisted `this' in top-level storey only
353 if (OriginalSourceBlock
.Explicit
.HasCapturedThis
&& !(Parent
is AnonymousMethodStorey
)) {
354 AddCapturedThisField (ec
);
355 OriginalSourceBlock
.AddScopeStatement (new ThisInitializer (hoisted_this
));
359 // Setting currect anonymous method to null blocks any further variable hoisting
361 AnonymousExpression ae
= ec
.CurrentAnonymousMethod
;
362 ec
.CurrentAnonymousMethod
= null;
364 if (hoisted_params
!= null) {
365 EmitHoistedParameters (ec
, hoisted_params
);
368 ec
.CurrentAnonymousMethod
= ae
;
371 protected virtual void EmitHoistedParameters (EmitContext ec
, ArrayList hoisted
)
373 foreach (HoistedParameter hp
in hoisted
) {
374 hp
.EmitHoistingAssignment (ec
);
378 public override void EmitType ()
380 SymbolWriter
.DefineAnonymousScope (ID
);
382 if (hoisted_this
!= null)
383 hoisted_this
.EmitSymbolInfo ();
385 if (hoisted_locals
!= null) {
386 foreach (HoistedVariable local
in hoisted_locals
)
387 local
.EmitSymbolInfo ();
390 if (hoisted_params
!= null) {
391 foreach (HoistedParameter param
in hoisted_params
)
392 param
.EmitSymbolInfo ();
395 if (used_parent_storeys
!= null) {
396 foreach (StoreyFieldPair sf
in used_parent_storeys
) {
397 SymbolWriter
.DefineCapturedScope (ID
, sf
.Storey
.ID
, sf
.Field
.Name
);
404 public AnonymousMethodStorey
GetGenericStorey ()
406 DeclSpace storey
= this;
407 while (storey
!= null && storey
.CurrentTypeParameters
== null)
408 storey
= storey
.Parent
;
410 return storey
as AnonymousMethodStorey
;
414 // Returns a field which holds referenced storey instance
416 Field
GetReferencedStoreyField (AnonymousMethodStorey storey
)
418 if (used_parent_storeys
== null)
421 foreach (StoreyFieldPair sf
in used_parent_storeys
) {
422 if (sf
.Storey
== storey
)
430 // Creates storey instance expression regardless of currect IP
432 public Expression
GetStoreyInstanceExpression (EmitContext ec
)
434 AnonymousExpression am
= ec
.CurrentAnonymousMethod
;
437 // Access from original block -> storey
443 // Access from anonymous method implemented as a static -> storey
445 if (am
.Storey
== null)
448 Field f
= am
.Storey
.GetReferencedStoreyField (this);
450 if (am
.Storey
== this) {
452 // Access inside of same storey (S -> S)
454 return new CompilerGeneratedThis (TypeBuilder
, Location
);
457 // External field access
463 // Storey was cached to local field
465 FieldExpr f_ind
= new FieldExpr (f
.FieldBuilder
, Location
);
466 f_ind
.InstanceExpression
= new CompilerGeneratedThis (TypeBuilder
, Location
);
470 protected virtual string GetVariableMangledName (LocalInfo local_info
)
473 // No need to mangle anonymous method hoisted variables cause they
474 // are hoisted in their own scopes
476 return local_info
.Name
;
479 public HoistedThis HoistedThis
{
480 get { return hoisted_this; }
484 // Mutate type dispatcher
486 public Type
MutateType (Type type
)
488 if (TypeManager
.IsGenericType (type
))
489 return MutateGenericType (type
);
491 if (TypeManager
.IsGenericParameter (type
))
492 return MutateGenericArgument (type
);
495 return MutateArrayType (type
);
500 // Changes method type arguments (MVAR) to storey (VAR) type arguments
502 public MethodInfo
MutateGenericMethod (MethodInfo method
)
504 Type
[] t_args
= TypeManager
.GetGenericArguments (method
);
505 if (TypeManager
.IsGenericType (method
.DeclaringType
)) {
506 Type t
= MutateGenericType (method
.DeclaringType
);
507 if (t
!= method
.DeclaringType
) {
508 method
= (MethodInfo
) TypeManager
.DropGenericMethodArguments (method
);
509 if (method
.Module
== Module
.Builder
)
510 method
= TypeBuilder
.GetMethod (t
, method
);
512 method
= (MethodInfo
) MethodInfo
.GetMethodFromHandle (method
.MethodHandle
, t
.TypeHandle
);
516 if (t_args
== null || t_args
.Length
== 0)
519 for (int i
= 0; i
< t_args
.Length
; ++i
)
520 t_args
[i
] = MutateType (t_args
[i
]);
522 return method
.GetGenericMethodDefinition ().MakeGenericMethod (t_args
);
525 public ConstructorInfo
MutateConstructor (ConstructorInfo ctor
)
527 if (TypeManager
.IsGenericType (ctor
.DeclaringType
)) {
528 Type t
= MutateGenericType (ctor
.DeclaringType
);
529 if (t
!= ctor
.DeclaringType
) {
530 ctor
= (ConstructorInfo
) TypeManager
.DropGenericMethodArguments (ctor
);
531 if (ctor
.Module
== Module
.Builder
)
532 return TypeBuilder
.GetConstructor (t
, ctor
);
534 return (ConstructorInfo
) ConstructorInfo
.GetMethodFromHandle (ctor
.MethodHandle
, t
.TypeHandle
);
541 public FieldInfo
MutateField (FieldInfo field
)
543 if (TypeManager
.IsGenericType (field
.DeclaringType
)) {
544 Type t
= MutateGenericType (field
.DeclaringType
);
545 if (t
!= field
.DeclaringType
) {
546 field
= TypeManager
.DropGenericTypeArguments (field
.DeclaringType
).GetField (field
.Name
, TypeManager
.AllMembers
);
547 if (field
.Module
== Module
.Builder
)
548 return TypeBuilder
.GetField (t
, field
);
550 return FieldInfo
.GetFieldFromHandle (field
.FieldHandle
, t
.TypeHandle
);
557 protected Type
MutateArrayType (Type array
)
559 Type element
= TypeManager
.GetElementType (array
);
560 if (element
.IsArray
) {
561 element
= MutateArrayType (element
);
562 } else if (TypeManager
.IsGenericParameter (element
)) {
563 element
= MutateGenericArgument (element
);
564 } else if (TypeManager
.IsGenericType (element
)) {
565 element
= MutateGenericType (element
);
570 int rank
= array
.GetArrayRank ();
572 return element
.MakeArrayType ();
574 return element
.MakeArrayType (rank
);
577 protected Type
MutateGenericType (Type type
)
579 Type
[] t_args
= TypeManager
.GetTypeArguments (type
);
580 if (t_args
== null || t_args
.Length
== 0)
583 for (int i
= 0; i
< t_args
.Length
; ++i
)
584 t_args
[i
] = MutateType (t_args
[i
]);
586 return TypeManager
.DropGenericTypeArguments (type
).MakeGenericType (t_args
);
590 // Changes method generic argument (MVAR) to type generic argument (VAR)
592 public Type
MutateGenericArgument (Type type
)
594 if (CurrentTypeParameters
!= null) {
595 TypeParameter tp
= TypeParameter
.FindTypeParameter (CurrentTypeParameters
, type
.Name
);
603 public ArrayList ReferencesFromChildrenBlock
{
604 get { return children_references; }
607 public static void Reset ()
613 public abstract class HoistedVariable
615 class ExpressionTreeProxy
: Expression
617 readonly HoistedVariable hv
;
619 public ExpressionTreeProxy (HoistedVariable hv
)
624 public override Expression
CreateExpressionTree (ResolveContext ec
)
626 throw new NotSupportedException ("ET");
629 public override Expression
DoResolve (ResolveContext ec
)
631 eclass
= ExprClass
.Value
;
632 type
= TypeManager
.expression_type_expr
.Type
;
636 public override void Emit (EmitContext ec
)
638 ResolveContext rc
= new ResolveContext (ec
.MemberContext
);
639 Expression e
= hv
.GetFieldExpression (ec
).CreateExpressionTree (rc
);
640 // This should never fail
647 protected readonly AnonymousMethodStorey storey
;
648 protected Field field
;
649 Hashtable cached_inner_access
; // TODO: Hashtable is too heavyweight
650 FieldExpr cached_outer_access
;
652 protected HoistedVariable (AnonymousMethodStorey storey
, string name
, Type type
)
653 : this (storey
, storey
.AddCapturedVariable (name
, type
))
657 protected HoistedVariable (AnonymousMethodStorey storey
, Field field
)
659 this.storey
= storey
;
663 public void AddressOf (EmitContext ec
, AddressOp mode
)
665 GetFieldExpression (ec
).AddressOf (ec
, mode
);
668 public Expression
CreateExpressionTree (ResolveContext ec
)
670 return new ExpressionTreeProxy (this);
673 public void Emit (EmitContext ec
)
675 GetFieldExpression (ec
).Emit (ec
);
679 // Creates field access expression for hoisted variable
681 protected FieldExpr
GetFieldExpression (EmitContext ec
)
683 if (ec
.CurrentAnonymousMethod
== null || ec
.CurrentAnonymousMethod
.Storey
== null) {
684 if (cached_outer_access
!= null)
685 return cached_outer_access
;
688 // When setting top-level hoisted variable in generic storey
689 // change storey generic types to method generic types (VAR -> MVAR)
691 cached_outer_access
= storey
.MemberName
.IsGeneric
?
692 new FieldExpr (field
.FieldBuilder
, storey
.Instance
.Type
, field
.Location
) :
693 new FieldExpr (field
.FieldBuilder
, field
.Location
);
695 cached_outer_access
.InstanceExpression
= storey
.GetStoreyInstanceExpression (ec
);
696 return cached_outer_access
;
699 FieldExpr inner_access
;
700 if (cached_inner_access
!= null) {
701 inner_access
= (FieldExpr
) cached_inner_access
[ec
.CurrentAnonymousMethod
];
704 cached_inner_access
= new Hashtable (4);
707 if (inner_access
== null) {
708 inner_access
= field
.Parent
.MemberName
.IsGeneric
?
709 new FieldExpr (field
.FieldBuilder
, field
.Parent
.CurrentType
, field
.Location
) :
710 new FieldExpr (field
.FieldBuilder
, field
.Location
);
712 inner_access
.InstanceExpression
= storey
.GetStoreyInstanceExpression (ec
);
713 cached_inner_access
.Add (ec
.CurrentAnonymousMethod
, inner_access
);
719 public abstract void EmitSymbolInfo ();
721 public void Emit (EmitContext ec
, bool leave_copy
)
723 GetFieldExpression (ec
).Emit (ec
, leave_copy
);
726 public void EmitAssign (EmitContext ec
, Expression source
, bool leave_copy
, bool prepare_for_load
)
728 GetFieldExpression (ec
).EmitAssign (ec
, source
, leave_copy
, false);
732 class HoistedParameter
: HoistedVariable
734 sealed class HoistedFieldAssign
: Assign
736 public HoistedFieldAssign (Expression target
, Expression source
)
737 : base (target
, source
, source
.Location
)
741 protected override Expression
ResolveConversions (ResolveContext ec
)
744 // Implicit conversion check fails for hoisted type arguments
745 // as they are of different types (!!0 x !0)
751 readonly ParameterReference parameter
;
753 public HoistedParameter (AnonymousMethodStorey scope
, ParameterReference par
)
754 : base (scope
, par
.Name
, par
.Type
)
756 this.parameter
= par
;
759 public HoistedParameter (HoistedParameter hp
, string name
)
760 : base (hp
.storey
, name
, hp
.parameter
.Type
)
762 this.parameter
= hp
.parameter
;
765 public void EmitHoistingAssignment (EmitContext ec
)
768 // Remove hoisted redirection to emit assignment from original parameter
770 HoistedVariable temp
= parameter
.Parameter
.HoistedVariableReference
;
771 parameter
.Parameter
.HoistedVariableReference
= null;
773 Assign a
= new HoistedFieldAssign (GetFieldExpression (ec
), parameter
);
774 if (a
.Resolve (new ResolveContext (ec
.MemberContext
)) != null)
775 a
.EmitStatement (ec
);
777 parameter
.Parameter
.HoistedVariableReference
= temp
;
780 public override void EmitSymbolInfo ()
782 SymbolWriter
.DefineCapturedParameter (storey
.ID
, field
.Name
, field
.Name
);
786 get { return field; }
790 class HoistedLocalVariable
: HoistedVariable
792 readonly string name
;
794 public HoistedLocalVariable (AnonymousMethodStorey scope
, LocalInfo local
, string name
)
795 : base (scope
, name
, local
.VariableType
)
797 this.name
= local
.Name
;
800 public override void EmitSymbolInfo ()
802 SymbolWriter
.DefineCapturedLocal (storey
.ID
, name
, field
.Name
);
806 public class HoistedThis
: HoistedVariable
808 public HoistedThis (AnonymousMethodStorey storey
, Field field
)
809 : base (storey
, field
)
813 public void EmitHoistingAssignment (EmitContext ec
)
815 SimpleAssign a
= new SimpleAssign (GetFieldExpression (ec
), new CompilerGeneratedThis (ec
.CurrentType
, field
.Location
));
816 if (a
.Resolve (new ResolveContext (ec
.MemberContext
)) != null)
817 a
.EmitStatement (ec
);
820 public override void EmitSymbolInfo ()
822 SymbolWriter
.DefineCapturedThis (storey
.ID
, field
.Name
);
826 get { return field; }
831 // Anonymous method expression as created by parser
833 public class AnonymousMethodExpression
: Expression
835 ListDictionary compatibles
;
836 public ToplevelBlock Block
;
838 public AnonymousMethodExpression (Location loc
)
841 this.compatibles
= new ListDictionary ();
844 public override string ExprClassName
{
846 return "anonymous method";
850 public virtual bool HasExplicitParameters
{
852 return Parameters
!= ParametersCompiled
.Undefined
;
856 public ParametersCompiled Parameters
{
857 get { return Block.Parameters; }
861 // Returns true if the body of lambda expression can be implicitly
862 // converted to the delegate of type `delegate_type'
864 public bool ImplicitStandardConversionExists (ResolveContext ec
, Type delegate_type
)
866 using (ec
.With (ResolveContext
.Options
.InferReturnType
, false)) {
867 using (ec
.Set (ResolveContext
.Options
.ProbingMode
)) {
868 return Compatible (ec
, delegate_type
) != null;
873 protected Type
CompatibleChecks (ResolveContext ec
, Type delegate_type
)
875 if (TypeManager
.IsDelegateType (delegate_type
))
876 return delegate_type
;
878 if (TypeManager
.DropGenericTypeArguments (delegate_type
) == TypeManager
.expression_type
) {
879 delegate_type
= TypeManager
.GetTypeArguments (delegate_type
) [0];
880 if (TypeManager
.IsDelegateType (delegate_type
))
881 return delegate_type
;
883 ec
.Report
.Error (835, loc
, "Cannot convert `{0}' to an expression tree of non-delegate type `{1}'",
884 GetSignatureForError (), TypeManager
.CSharpName (delegate_type
));
888 ec
.Report
.Error (1660, loc
, "Cannot convert `{0}' to non-delegate type `{1}'",
889 GetSignatureForError (), TypeManager
.CSharpName (delegate_type
));
893 protected bool VerifyExplicitParameters (ResolveContext ec
, Type delegate_type
, AParametersCollection parameters
)
895 if (VerifyParameterCompatibility (ec
, delegate_type
, parameters
, ec
.IsInProbingMode
))
898 if (!ec
.IsInProbingMode
)
899 ec
.Report
.Error (1661, loc
,
900 "Cannot convert `{0}' to delegate type `{1}' since there is a parameter mismatch",
901 GetSignatureForError (), TypeManager
.CSharpName (delegate_type
));
906 protected bool VerifyParameterCompatibility (ResolveContext ec
, Type delegate_type
, AParametersCollection invoke_pd
, bool ignore_errors
)
908 if (Parameters
.Count
!= invoke_pd
.Count
) {
912 ec
.Report
.Error (1593, loc
, "Delegate `{0}' does not take `{1}' arguments",
913 TypeManager
.CSharpName (delegate_type
), Parameters
.Count
.ToString ());
917 bool has_implicit_parameters
= !HasExplicitParameters
;
920 for (int i
= 0; i
< Parameters
.Count
; ++i
) {
921 Parameter
.Modifier p_mod
= invoke_pd
.FixedParameters
[i
].ModFlags
;
922 if (Parameters
.FixedParameters
[i
].ModFlags
!= p_mod
&& p_mod
!= Parameter
.Modifier
.PARAMS
) {
926 if (p_mod
== Parameter
.Modifier
.NONE
)
927 ec
.Report
.Error (1677, loc
, "Parameter `{0}' should not be declared with the `{1}' keyword",
928 (i
+ 1).ToString (), Parameter
.GetModifierSignature (Parameters
.FixedParameters
[i
].ModFlags
));
930 ec
.Report
.Error (1676, loc
, "Parameter `{0}' must be declared with the `{1}' keyword",
931 (i
+1).ToString (), Parameter
.GetModifierSignature (p_mod
));
935 if (has_implicit_parameters
)
938 Type type
= invoke_pd
.Types
[i
];
940 // We assume that generic parameters are always inflated
941 if (TypeManager
.IsGenericParameter (type
))
944 if (TypeManager
.HasElementType (type
) && TypeManager
.IsGenericParameter (TypeManager
.GetElementType (type
)))
947 if (invoke_pd
.Types
[i
] != Parameters
.Types
[i
]) {
951 ec
.Report
.Error (1678, loc
, "Parameter `{0}' is declared as type `{1}' but should be `{2}'",
953 TypeManager
.CSharpName (Parameters
.Types
[i
]),
954 TypeManager
.CSharpName (invoke_pd
.Types
[i
]));
963 // Infers type arguments based on explicit arguments
965 public bool ExplicitTypeInference (ResolveContext ec
, TypeInferenceContext type_inference
, Type delegate_type
)
967 if (!HasExplicitParameters
)
970 if (!TypeManager
.IsDelegateType (delegate_type
)) {
971 if (TypeManager
.DropGenericTypeArguments (delegate_type
) != TypeManager
.expression_type
)
974 delegate_type
= TypeManager
.GetTypeArguments (delegate_type
) [0];
975 if (!TypeManager
.IsDelegateType (delegate_type
))
979 AParametersCollection d_params
= TypeManager
.GetDelegateParameters (ec
, delegate_type
);
980 if (d_params
.Count
!= Parameters
.Count
)
983 for (int i
= 0; i
< Parameters
.Count
; ++i
) {
984 Type itype
= d_params
.Types
[i
];
985 if (!TypeManager
.IsGenericParameter (itype
)) {
986 if (!TypeManager
.HasElementType (itype
))
989 if (!TypeManager
.IsGenericParameter (TypeManager
.GetElementType (itype
)))
992 type_inference
.ExactInference (Parameters
.Types
[i
], itype
);
997 public Type
InferReturnType (ResolveContext ec
, TypeInferenceContext tic
, Type delegate_type
)
999 AnonymousMethodBody am
;
1000 using (ec
.Set (ResolveContext
.Options
.ProbingMode
| ResolveContext
.Options
.InferReturnType
)) {
1001 am
= CompatibleMethod (ec
, tic
, InternalType
.Arglist
, delegate_type
);
1007 return am
.ReturnType
;
1011 // Returns AnonymousMethod container if this anonymous method
1012 // expression can be implicitly converted to the delegate type `delegate_type'
1014 public Expression
Compatible (ResolveContext ec
, Type type
)
1016 Expression am
= (Expression
) compatibles
[type
];
1020 Type delegate_type
= CompatibleChecks (ec
, type
);
1021 if (delegate_type
== null)
1025 // At this point its the first time we know the return type that is
1026 // needed for the anonymous method. We create the method here.
1029 MethodInfo invoke_mb
= Delegate
.GetInvokeMethod (ec
.Compiler
,
1030 ec
.CurrentType
, delegate_type
);
1031 Type return_type
= TypeManager
.TypeToCoreType (invoke_mb
.ReturnType
);
1034 Type
[] g_args
= delegate_type
.GetGenericArguments ();
1035 if (return_type
.IsGenericParameter
)
1036 return_type
= g_args
[return_type
.GenericParameterPosition
];
1040 // Second: the return type of the delegate must be compatible with
1041 // the anonymous type. Instead of doing a pass to examine the block
1042 // we satisfy the rule by setting the return type on the EmitContext
1043 // to be the delegate type return type.
1047 int errors
= ec
.Report
.Errors
;
1048 am
= CompatibleMethod (ec
, null, return_type
, delegate_type
);
1049 if (am
!= null && delegate_type
!= type
&& errors
== ec
.Report
.Errors
)
1050 am
= CreateExpressionTree (ec
, delegate_type
);
1052 if (!ec
.IsInProbingMode
)
1053 compatibles
.Add (type
, am
== null ? EmptyExpression
.Null
: am
);
1056 } catch (CompletionResult
){
1058 } catch (Exception e
) {
1059 throw new InternalErrorException (e
, loc
);
1063 protected virtual Expression
CreateExpressionTree (ResolveContext ec
, Type delegate_type
)
1065 return CreateExpressionTree (ec
);
1068 public override Expression
CreateExpressionTree (ResolveContext ec
)
1070 ec
.Report
.Error (1946, loc
, "An anonymous method cannot be converted to an expression tree");
1074 protected virtual ParametersCompiled
ResolveParameters (ResolveContext ec
, TypeInferenceContext tic
, Type delegate_type
)
1076 AParametersCollection delegate_parameters
= TypeManager
.GetDelegateParameters (ec
, delegate_type
);
1078 if (Parameters
== ParametersCompiled
.Undefined
) {
1080 // We provide a set of inaccessible parameters
1082 Parameter
[] fixedpars
= new Parameter
[delegate_parameters
.Count
];
1084 for (int i
= 0; i
< delegate_parameters
.Count
; i
++) {
1085 Parameter
.Modifier i_mod
= delegate_parameters
.FixedParameters
[i
].ModFlags
;
1086 if (i_mod
== Parameter
.Modifier
.OUT
) {
1087 ec
.Report
.Error (1688, loc
, "Cannot convert anonymous " +
1088 "method block without a parameter list " +
1089 "to delegate type `{0}' because it has " +
1090 "one or more `out' parameters.",
1091 TypeManager
.CSharpName (delegate_type
));
1094 fixedpars
[i
] = new Parameter (
1096 delegate_parameters
.FixedParameters
[i
].ModFlags
, null, loc
);
1099 return ParametersCompiled
.CreateFullyResolved (fixedpars
, delegate_parameters
.Types
);
1102 if (!VerifyExplicitParameters (ec
, delegate_type
, delegate_parameters
)) {
1109 public override Expression
DoResolve (ResolveContext ec
)
1111 if (ec
.HasSet (ResolveContext
.Options
.ConstantScope
)) {
1112 ec
.Report
.Error (1706, loc
, "Anonymous methods and lambda expressions cannot be used in the current context");
1117 // Set class type, set type
1120 eclass
= ExprClass
.Value
;
1123 // This hack means `The type is not accessible
1124 // anywhere', we depend on special conversion
1127 type
= InternalType
.AnonymousMethod
;
1129 if ((Parameters
!= null) && !Parameters
.Resolve (ec
))
1132 // FIXME: The emitted code isn't very careful about reachability
1133 // so, ensure we have a 'ret' at the end
1134 BlockContext bc
= ec
as BlockContext
;
1135 if (bc
!= null && bc
.CurrentBranching
!= null && bc
.CurrentBranching
.CurrentUsageVector
.IsUnreachable
)
1136 bc
.NeedReturnLabel ();
1141 public override void Emit (EmitContext ec
)
1143 // nothing, as we only exist to not do anything.
1146 public static void Error_AddressOfCapturedVar (ResolveContext ec
, IVariableReference
var, Location loc
)
1148 ec
.Report
.Error (1686, loc
,
1149 "Local variable or parameter `{0}' cannot have their address taken and be used inside an anonymous method or lambda expression",
1153 public override string GetSignatureForError ()
1155 return ExprClassName
;
1158 protected AnonymousMethodBody
CompatibleMethod (ResolveContext ec
, TypeInferenceContext tic
, Type return_type
, Type delegate_type
)
1160 ParametersCompiled p
= ResolveParameters (ec
, tic
, delegate_type
);
1164 ToplevelBlock b
= ec
.IsInProbingMode
? (ToplevelBlock
) Block
.PerformClone () : Block
;
1166 AnonymousMethodBody anonymous
= CompatibleMethodFactory (return_type
, delegate_type
, p
, b
);
1167 if (!anonymous
.Compatible (ec
))
1173 protected virtual AnonymousMethodBody
CompatibleMethodFactory (Type return_type
, Type delegate_type
, ParametersCompiled p
, ToplevelBlock b
)
1175 return new AnonymousMethodBody (p
, b
, return_type
, delegate_type
, loc
);
1178 protected override void CloneTo (CloneContext clonectx
, Expression t
)
1180 AnonymousMethodExpression target
= (AnonymousMethodExpression
) t
;
1182 target
.Block
= (ToplevelBlock
) clonectx
.LookupBlock (Block
);
1187 // Abstract expression for any block which requires variables hoisting
1189 public abstract class AnonymousExpression
: Expression
1191 protected class AnonymousMethodMethod
: Method
1193 public readonly AnonymousExpression AnonymousMethod
;
1194 public readonly AnonymousMethodStorey Storey
;
1195 readonly string RealName
;
1197 public AnonymousMethodMethod (DeclSpace parent
, AnonymousExpression am
, AnonymousMethodStorey storey
,
1198 GenericMethod generic
, TypeExpr return_type
,
1199 int mod
, string real_name
, MemberName name
,
1200 ParametersCompiled parameters
)
1201 : base (parent
, generic
, return_type
, mod
| Modifiers
.COMPILER_GENERATED
,
1202 name
, parameters
, null)
1204 this.AnonymousMethod
= am
;
1205 this.Storey
= storey
;
1206 this.RealName
= real_name
;
1208 Parent
.PartialContainer
.AddMethod (this);
1212 public override EmitContext
CreateEmitContext (ILGenerator ig
)
1214 EmitContext ec
= new EmitContext (this, ig
, ReturnType
);
1215 ec
.CurrentAnonymousMethod
= AnonymousMethod
;
1216 if (AnonymousMethod
.return_label
!= null) {
1217 ec
.HasReturnLabel
= true;
1218 ec
.ReturnLabel
= (Label
) AnonymousMethod
.return_label
;
1224 protected override bool ResolveMemberType ()
1226 if (!base.ResolveMemberType ())
1229 if (Storey
!= null && Storey
.IsGeneric
) {
1230 AnonymousMethodStorey gstorey
= Storey
.GetGenericStorey ();
1231 if (gstorey
!= null) {
1232 if (!Parameters
.IsEmpty
) {
1233 Type
[] ptypes
= Parameters
.Types
;
1234 for (int i
= 0; i
< ptypes
.Length
; ++i
)
1235 ptypes
[i
] = gstorey
.MutateType (ptypes
[i
]);
1238 member_type
= gstorey
.MutateType (member_type
);
1245 public override void Emit ()
1248 // Before emitting any code we have to change all MVAR references to VAR
1249 // when the method is of generic type and has hoisted variables
1251 if (Storey
== Parent
&& Storey
.IsGeneric
) {
1252 AnonymousMethodStorey gstorey
= Storey
.GetGenericStorey ();
1253 if (gstorey
!= null) {
1254 block
.MutateHoistedGenericType (gstorey
);
1258 if (MethodBuilder
== null) {
1265 public override void EmitExtraSymbolInfo (SourceMethod source
)
1267 source
.SetRealMethodName (RealName
);
1272 // The block that makes up the body for the anonymous method
1274 protected readonly ToplevelBlock Block
;
1276 public Type ReturnType
;
1278 object return_label
;
1280 protected AnonymousExpression (ToplevelBlock block
, Type return_type
, Location loc
)
1282 this.ReturnType
= return_type
;
1287 public abstract string ContainerType { get; }
1288 public abstract bool IsIterator { get; }
1289 public abstract AnonymousMethodStorey Storey { get; }
1291 public bool Compatible (ResolveContext ec
)
1293 // TODO: Implement clone
1294 BlockContext aec
= new BlockContext (ec
.MemberContext
, Block
, ReturnType
);
1295 aec
.CurrentAnonymousMethod
= this;
1297 IDisposable aec_dispose
= null;
1298 ResolveContext
.Options flags
= 0;
1299 if (ec
.HasSet (ResolveContext
.Options
.InferReturnType
)) {
1300 flags
|= ResolveContext
.Options
.InferReturnType
;
1301 aec
.ReturnTypeInference
= new TypeInferenceContext ();
1304 if (ec
.IsInProbingMode
)
1305 flags
|= ResolveContext
.Options
.ProbingMode
;
1307 if (ec
.HasSet (ResolveContext
.Options
.FieldInitializerScope
))
1308 flags
|= ResolveContext
.Options
.FieldInitializerScope
;
1311 flags
|= ResolveContext
.Options
.UnsafeScope
;
1313 if (ec
.HasSet (ResolveContext
.Options
.CheckedScope
))
1314 flags
|= ResolveContext
.Options
.CheckedScope
;
1316 // HACK: Flag with 0 cannot be set
1318 aec_dispose
= aec
.Set (flags
);
1320 bool res
= Block
.Resolve (ec
.CurrentBranching
, aec
, Block
.Parameters
, null);
1322 if (aec
.HasReturnLabel
)
1323 return_label
= aec
.ReturnLabel
;
1325 if (ec
.HasSet (ResolveContext
.Options
.InferReturnType
)) {
1326 aec
.ReturnTypeInference
.FixAllTypes (ec
);
1327 ReturnType
= aec
.ReturnTypeInference
.InferredTypeArguments
[0];
1330 if (aec_dispose
!= null) {
1331 aec_dispose
.Dispose ();
1337 public void SetHasThisAccess ()
1339 Block
.HasCapturedThis
= true;
1340 ExplicitBlock b
= Block
.Parent
.Explicit
;
1343 if (b
.HasCapturedThis
)
1346 b
.HasCapturedThis
= true;
1347 b
= b
.Parent
== null ? null : b
.Parent
.Explicit
;
1352 public class AnonymousMethodBody
: AnonymousExpression
1354 protected readonly ParametersCompiled parameters
;
1355 AnonymousMethodStorey storey
;
1357 AnonymousMethodMethod method
;
1361 static int unique_id
;
1363 public AnonymousMethodBody (ParametersCompiled parameters
,
1364 ToplevelBlock block
, Type return_type
, Type delegate_type
,
1366 : base (block
, return_type
, loc
)
1368 this.type
= delegate_type
;
1369 this.parameters
= parameters
;
1372 public override string ContainerType
{
1373 get { return "anonymous method"; }
1376 public override AnonymousMethodStorey Storey
{
1377 get { return storey; }
1380 public override bool IsIterator
{
1381 get { return false; }
1384 public override Expression
CreateExpressionTree (ResolveContext ec
)
1386 ec
.Report
.Error (1945, loc
, "An expression tree cannot contain an anonymous method expression");
1390 bool Define (ResolveContext ec
)
1392 if (!Block
.Resolved
&& !Compatible (ec
))
1395 if (block_name
== null) {
1396 MemberCore mc
= (MemberCore
) ec
.MemberContext
;
1397 block_name
= mc
.MemberName
.Basename
;
1404 // Creates a host for the anonymous method
1406 AnonymousMethodMethod
DoCreateMethodHost (EmitContext ec
)
1409 // Anonymous method body can be converted to
1411 // 1, an instance method in current scope when only `this' is hoisted
1412 // 2, a static method in current scope when neither `this' nor any variable is hoisted
1413 // 3, an instance method in compiler generated storey when any hoisted variable exists
1417 if (Block
.HasCapturedVariable
|| Block
.HasCapturedThis
) {
1418 storey
= FindBestMethodStorey ();
1419 modifiers
= storey
!= null ? Modifiers
.INTERNAL
: Modifiers
.PRIVATE
;
1421 if (ec
.CurrentAnonymousMethod
!= null)
1422 storey
= ec
.CurrentAnonymousMethod
.Storey
;
1424 modifiers
= Modifiers
.STATIC
| Modifiers
.PRIVATE
;
1427 TypeContainer parent
= storey
!= null ? storey
: ec
.CurrentTypeDefinition
;
1429 MemberCore mc
= ec
.MemberContext
as MemberCore
;
1430 string name
= CompilerGeneratedClass
.MakeName (parent
!= storey
? block_name
: null,
1431 "m", null, unique_id
++);
1433 MemberName member_name
;
1434 GenericMethod generic_method
;
1435 if (storey
== null && mc
.MemberName
.IsGeneric
) {
1436 member_name
= new MemberName (name
, mc
.MemberName
.TypeArguments
.Clone (), Location
);
1438 generic_method
= new GenericMethod (parent
.NamespaceEntry
, parent
, member_name
,
1439 new TypeExpression (ReturnType
, Location
), parameters
);
1441 ArrayList list
= new ArrayList ();
1442 foreach (TypeParameter tparam
in ec
.CurrentTypeParameters
) {
1443 if (tparam
.Constraints
!= null)
1444 list
.Add (tparam
.Constraints
.Clone ());
1446 generic_method
.SetParameterInfo (list
);
1448 member_name
= new MemberName (name
, Location
);
1449 generic_method
= null;
1452 string real_name
= String
.Format (
1453 "{0}~{1}{2}", mc
.GetSignatureForError (), GetSignatureForError (),
1454 parameters
.GetSignatureForError ());
1456 return new AnonymousMethodMethod (parent
,
1457 this, storey
, generic_method
, new TypeExpression (ReturnType
, Location
), modifiers
,
1458 real_name
, member_name
, parameters
);
1461 public override Expression
DoResolve (ResolveContext ec
)
1463 if (eclass
== ExprClass
.Invalid
) {
1468 eclass
= ExprClass
.Value
;
1472 public override void Emit (EmitContext ec
)
1475 // Use same anonymous method implementation for scenarios where same
1476 // code is used from multiple blocks, e.g. field initializers
1478 if (method
== null) {
1480 // Delay an anonymous method definition to avoid emitting unused code
1481 // for unreachable blocks or expression trees
1483 method
= DoCreateMethodHost (ec
);
1487 bool is_static
= (method
.ModFlags
& Modifiers
.STATIC
) != 0;
1488 if (is_static
&& am_cache
== null) {
1490 // Creates a field cache to store delegate instance if it's not generic
1492 if (!method
.MemberName
.IsGeneric
) {
1493 TypeContainer parent
= method
.Parent
.PartialContainer
;
1494 int id
= parent
.Fields
== null ? 0 : parent
.Fields
.Count
;
1495 am_cache
= new Field (parent
, new TypeExpression (type
, loc
),
1496 Modifiers
.STATIC
| Modifiers
.PRIVATE
| Modifiers
.COMPILER_GENERATED
,
1497 new MemberName (CompilerGeneratedClass
.MakeName (null, "f", "am$cache", id
), loc
), null);
1499 parent
.AddField (am_cache
);
1501 // TODO: Implement caching of generated generic static methods
1505 // Some extra class is needed to capture variable generic type
1506 // arguments. Maybe we could re-use anonymous types, with a unique
1507 // anonymous method id, but they are quite heavy.
1509 // Consider : "() => typeof(T);"
1511 // We need something like
1512 // static class Wrap<Tn, Tm, DelegateType> {
1513 // public static DelegateType cache;
1516 // We then specialize local variable to capture all generic parameters
1517 // and delegate type, e.g. "Wrap<Ta, Tb, DelegateTypeInst> cache;"
1522 ILGenerator ig
= ec
.ig
;
1523 Label l_initialized
= ig
.DefineLabel ();
1525 if (am_cache
!= null) {
1526 ig
.Emit (OpCodes
.Ldsfld
, am_cache
.FieldBuilder
);
1527 ig
.Emit (OpCodes
.Brtrue_S
, l_initialized
);
1531 // Load method delegate implementation
1535 ig
.Emit (OpCodes
.Ldnull
);
1536 } else if (storey
!= null) {
1537 Expression e
= storey
.GetStoreyInstanceExpression (ec
).Resolve (new ResolveContext (ec
.MemberContext
));
1541 ig
.Emit (OpCodes
.Ldarg_0
);
1544 MethodInfo delegate_method
= method
.MethodBuilder
;
1545 if (storey
!= null && storey
.MemberName
.IsGeneric
) {
1546 Type t
= storey
.Instance
.Type
;
1549 // Mutate anonymous method instance type if we are in nested
1550 // hoisted generic anonymous method storey
1552 if (ec
.CurrentAnonymousMethod
!= null &&
1553 ec
.CurrentAnonymousMethod
.Storey
!= null &&
1554 ec
.CurrentAnonymousMethod
.Storey
.IsGeneric
) {
1555 t
= storey
.GetGenericStorey ().MutateType (t
);
1558 delegate_method
= TypeBuilder
.GetMethod (t
, delegate_method
);
1561 ig
.Emit (OpCodes
.Ldftn
, delegate_method
);
1563 ConstructorInfo constructor_method
= Delegate
.GetConstructor (RootContext
.ToplevelTypes
.Compiler
, ec
.CurrentType
, type
);
1565 if (type
.IsGenericType
&& type
is TypeBuilder
)
1566 constructor_method
= TypeBuilder
.GetConstructor (type
, constructor_method
);
1568 ig
.Emit (OpCodes
.Newobj
, constructor_method
);
1570 if (am_cache
!= null) {
1571 ig
.Emit (OpCodes
.Stsfld
, am_cache
.FieldBuilder
);
1572 ig
.MarkLabel (l_initialized
);
1573 ig
.Emit (OpCodes
.Ldsfld
, am_cache
.FieldBuilder
);
1578 // Look for the best storey for this anonymous method
1580 AnonymousMethodStorey
FindBestMethodStorey ()
1583 // Use the nearest parent block which has a storey
1585 for (Block b
= Block
.Parent
; b
!= null; b
= b
.Parent
) {
1586 AnonymousMethodStorey s
= b
.Explicit
.AnonymousMethodStorey
;
1594 public override string GetSignatureForError ()
1596 return TypeManager
.CSharpName (type
);
1599 public override void MutateHoistedGenericType (AnonymousMethodStorey storey
)
1601 type
= storey
.MutateType (type
);
1604 public static void Reset ()
1611 // Anonymous type container
1613 public class AnonymousTypeClass
: CompilerGeneratedClass
1615 sealed class AnonymousParameters
: ParametersCompiled
1617 public AnonymousParameters (params Parameter
[] parameters
)
1622 protected override void ErrorDuplicateName (Parameter p
, Report Report
)
1624 Report
.Error (833, p
.Location
, "`{0}': An anonymous type cannot have multiple properties with the same name",
1629 static int types_counter
;
1630 public const string ClassNamePrefix
= "<>__AnonType";
1631 public const string SignatureForError
= "anonymous type";
1633 readonly ArrayList parameters
;
1635 private AnonymousTypeClass (DeclSpace parent
, MemberName name
, ArrayList parameters
, Location loc
)
1636 : base (parent
, name
, (RootContext
.EvalMode
? Modifiers
.PUBLIC
: 0) | Modifiers
.SEALED
)
1638 this.parameters
= parameters
;
1641 public static AnonymousTypeClass
Create (CompilerContext ctx
, TypeContainer parent
, ArrayList parameters
, Location loc
)
1643 string name
= ClassNamePrefix
+ types_counter
++;
1645 SimpleName
[] t_args
= new SimpleName
[parameters
.Count
];
1646 TypeParameterName
[] t_params
= new TypeParameterName
[parameters
.Count
];
1647 Parameter
[] ctor_params
= new Parameter
[parameters
.Count
];
1648 for (int i
= 0; i
< parameters
.Count
; ++i
) {
1649 AnonymousTypeParameter p
= (AnonymousTypeParameter
) parameters
[i
];
1651 t_args
[i
] = new SimpleName ("<" + p
.Name
+ ">__T", p
.Location
);
1652 t_params
[i
] = new TypeParameterName (t_args
[i
].Name
, null, p
.Location
);
1653 ctor_params
[i
] = new Parameter (t_args
[i
], p
.Name
, 0, null, p
.Location
);
1657 // Create generic anonymous type host with generic arguments
1658 // named upon properties names
1660 AnonymousTypeClass a_type
= new AnonymousTypeClass (parent
.NamespaceEntry
.SlaveDeclSpace
,
1661 new MemberName (name
, new TypeArguments (t_params
), loc
), parameters
, loc
);
1663 if (parameters
.Count
> 0)
1664 a_type
.SetParameterInfo (null);
1666 Constructor c
= new Constructor (a_type
, name
, Modifiers
.PUBLIC
| Modifiers
.DEBUGGER_HIDDEN
,
1667 null, new AnonymousParameters (ctor_params
), null, loc
);
1668 c
.Block
= new ToplevelBlock (ctx
, c
.Parameters
, loc
);
1671 // Create fields and contructor body with field initialization
1674 for (int i
= 0; i
< parameters
.Count
; ++i
) {
1675 AnonymousTypeParameter p
= (AnonymousTypeParameter
) parameters
[i
];
1677 Field f
= new Field (a_type
, t_args
[i
], Modifiers
.PRIVATE
| Modifiers
.READONLY
,
1678 new MemberName ("<" + p
.Name
+ ">", p
.Location
), null);
1680 if (!a_type
.AddField (f
)) {
1685 c
.Block
.AddStatement (new StatementExpression (
1686 new SimpleAssign (new MemberAccess (new This (p
.Location
), f
.Name
),
1687 c
.Block
.GetParameterReference (p
.Name
, p
.Location
))));
1689 ToplevelBlock get_block
= new ToplevelBlock (ctx
, p
.Location
);
1690 get_block
.AddStatement (new Return (
1691 new MemberAccess (new This (p
.Location
), f
.Name
), p
.Location
));
1692 Accessor get_accessor
= new Accessor (get_block
, 0, null, null, p
.Location
);
1693 Property prop
= new Property (a_type
, t_args
[i
], Modifiers
.PUBLIC
,
1694 new MemberName (p
.Name
, p
.Location
), null, get_accessor
, null, false);
1695 a_type
.AddProperty (prop
);
1701 a_type
.AddConstructor (c
);
1705 public static void Reset ()
1710 protected override bool AddToContainer (MemberCore symbol
, string name
)
1712 MemberCore mc
= (MemberCore
) defined_names
[name
];
1715 defined_names
.Add (name
, symbol
);
1719 Report
.SymbolRelatedToPreviousError (mc
);
1723 void DefineOverrides ()
1725 Location loc
= Location
;
1727 Method equals
= new Method (this, null, TypeManager
.system_boolean_expr
,
1728 Modifiers
.PUBLIC
| Modifiers
.OVERRIDE
| Modifiers
.DEBUGGER_HIDDEN
, new MemberName ("Equals", loc
),
1729 Mono
.CSharp
.ParametersCompiled
.CreateFullyResolved (new Parameter (null, "obj", 0, null, loc
), TypeManager
.object_type
), null);
1731 Method tostring
= new Method (this, null, TypeManager
.system_string_expr
,
1732 Modifiers
.PUBLIC
| Modifiers
.OVERRIDE
| Modifiers
.DEBUGGER_HIDDEN
, new MemberName ("ToString", loc
),
1733 Mono
.CSharp
.ParametersCompiled
.EmptyReadOnlyParameters
, null);
1735 ToplevelBlock equals_block
= new ToplevelBlock (Compiler
, equals
.Parameters
, loc
);
1736 TypeExpr current_type
;
1738 current_type
= new GenericTypeExpr (this, loc
);
1740 current_type
= new TypeExpression (TypeBuilder
, loc
);
1742 equals_block
.AddVariable (current_type
, "other", loc
);
1743 LocalVariableReference other_variable
= new LocalVariableReference (equals_block
, "other", loc
);
1745 MemberAccess system_collections_generic
= new MemberAccess (new MemberAccess (
1746 new QualifiedAliasMember ("global", "System", loc
), "Collections", loc
), "Generic", loc
);
1748 Expression rs_equals
= null;
1749 Expression string_concat
= new StringConstant ("{", loc
);
1750 Expression rs_hashcode
= new IntConstant (-2128831035, loc
);
1751 for (int i
= 0; i
< parameters
.Count
; ++i
) {
1752 AnonymousTypeParameter p
= (AnonymousTypeParameter
) parameters
[i
];
1753 Field f
= (Field
) Fields
[i
];
1755 MemberAccess equality_comparer
= new MemberAccess (new MemberAccess (
1756 system_collections_generic
, "EqualityComparer",
1757 new TypeArguments (new SimpleName (TypeParameters
[i
].Name
, loc
)), loc
),
1760 Arguments arguments_equal
= new Arguments (2);
1761 arguments_equal
.Add (new Argument (new MemberAccess (new This (f
.Location
), f
.Name
)));
1762 arguments_equal
.Add (new Argument (new MemberAccess (other_variable
, f
.Name
)));
1764 Expression field_equal
= new Invocation (new MemberAccess (equality_comparer
,
1765 "Equals", loc
), arguments_equal
);
1767 Arguments arguments_hashcode
= new Arguments (1);
1768 arguments_hashcode
.Add (new Argument (new MemberAccess (new This (f
.Location
), f
.Name
)));
1769 Expression field_hashcode
= new Invocation (new MemberAccess (equality_comparer
,
1770 "GetHashCode", loc
), arguments_hashcode
);
1772 IntConstant FNV_prime
= new IntConstant (16777619, loc
);
1773 rs_hashcode
= new Binary (Binary
.Operator
.Multiply
,
1774 new Binary (Binary
.Operator
.ExclusiveOr
, rs_hashcode
, field_hashcode
),
1777 Expression field_to_string
= new Conditional (new BooleanExpression (new Binary (Binary
.Operator
.Inequality
,
1778 new MemberAccess (new This (f
.Location
), f
.Name
), new NullLiteral (loc
))),
1779 new Invocation (new MemberAccess (
1780 new MemberAccess (new This (f
.Location
), f
.Name
), "ToString"), null),
1781 new StringConstant (string.Empty
, loc
));
1783 if (rs_equals
== null) {
1784 rs_equals
= field_equal
;
1785 string_concat
= new Binary (Binary
.Operator
.Addition
,
1787 new Binary (Binary
.Operator
.Addition
,
1788 new StringConstant (" " + p
.Name
+ " = ", loc
),
1794 // Implementation of ToString () body using string concatenation
1796 string_concat
= new Binary (Binary
.Operator
.Addition
,
1797 new Binary (Binary
.Operator
.Addition
,
1799 new StringConstant (", " + p
.Name
+ " = ", loc
)),
1802 rs_equals
= new Binary (Binary
.Operator
.LogicalAnd
, rs_equals
, field_equal
);
1805 string_concat
= new Binary (Binary
.Operator
.Addition
,
1807 new StringConstant (" }", loc
));
1810 // Equals (object obj) override
1812 LocalVariableReference other_variable_assign
= new LocalVariableReference (equals_block
, "other", loc
);
1813 equals_block
.AddStatement (new StatementExpression (
1814 new SimpleAssign (other_variable_assign
,
1815 new As (equals_block
.GetParameterReference ("obj", loc
),
1816 current_type
, loc
), loc
)));
1818 Expression equals_test
= new Binary (Binary
.Operator
.Inequality
, other_variable
, new NullLiteral (loc
));
1819 if (rs_equals
!= null)
1820 equals_test
= new Binary (Binary
.Operator
.LogicalAnd
, equals_test
, rs_equals
);
1821 equals_block
.AddStatement (new Return (equals_test
, loc
));
1823 equals
.Block
= equals_block
;
1828 // GetHashCode () override
1830 Method hashcode
= new Method (this, null, TypeManager
.system_int32_expr
,
1831 Modifiers
.PUBLIC
| Modifiers
.OVERRIDE
| Modifiers
.DEBUGGER_HIDDEN
,
1832 new MemberName ("GetHashCode", loc
),
1833 Mono
.CSharp
.ParametersCompiled
.EmptyReadOnlyParameters
, null);
1836 // Modified FNV with good avalanche behavior and uniform
1837 // distribution with larger hash sizes.
1839 // const int FNV_prime = 16777619;
1840 // int hash = (int) 2166136261;
1841 // foreach (int d in data)
1842 // hash = (hash ^ d) * FNV_prime;
1843 // hash += hash << 13;
1844 // hash ^= hash >> 7;
1845 // hash += hash << 3;
1846 // hash ^= hash >> 17;
1847 // hash += hash << 5;
1849 ToplevelBlock hashcode_top
= new ToplevelBlock (Compiler
, loc
);
1850 Block hashcode_block
= new Block (hashcode_top
);
1851 hashcode_top
.AddStatement (new Unchecked (hashcode_block
));
1853 hashcode_block
.AddVariable (TypeManager
.system_int32_expr
, "hash", loc
);
1854 LocalVariableReference hash_variable
= new LocalVariableReference (hashcode_block
, "hash", loc
);
1855 LocalVariableReference hash_variable_assign
= new LocalVariableReference (hashcode_block
, "hash", loc
);
1856 hashcode_block
.AddStatement (new StatementExpression (
1857 new SimpleAssign (hash_variable_assign
, rs_hashcode
)));
1859 hashcode_block
.AddStatement (new StatementExpression (
1860 new CompoundAssign (Binary
.Operator
.Addition
, hash_variable
,
1861 new Binary (Binary
.Operator
.LeftShift
, hash_variable
, new IntConstant (13, loc
)))));
1862 hashcode_block
.AddStatement (new StatementExpression (
1863 new CompoundAssign (Binary
.Operator
.ExclusiveOr
, hash_variable
,
1864 new Binary (Binary
.Operator
.RightShift
, hash_variable
, new IntConstant (7, loc
)))));
1865 hashcode_block
.AddStatement (new StatementExpression (
1866 new CompoundAssign (Binary
.Operator
.Addition
, hash_variable
,
1867 new Binary (Binary
.Operator
.LeftShift
, hash_variable
, new IntConstant (3, loc
)))));
1868 hashcode_block
.AddStatement (new StatementExpression (
1869 new CompoundAssign (Binary
.Operator
.ExclusiveOr
, hash_variable
,
1870 new Binary (Binary
.Operator
.RightShift
, hash_variable
, new IntConstant (17, loc
)))));
1871 hashcode_block
.AddStatement (new StatementExpression (
1872 new CompoundAssign (Binary
.Operator
.Addition
, hash_variable
,
1873 new Binary (Binary
.Operator
.LeftShift
, hash_variable
, new IntConstant (5, loc
)))));
1875 hashcode_block
.AddStatement (new Return (hash_variable
, loc
));
1876 hashcode
.Block
= hashcode_top
;
1878 AddMethod (hashcode
);
1881 // ToString () override
1884 ToplevelBlock tostring_block
= new ToplevelBlock (Compiler
, loc
);
1885 tostring_block
.AddStatement (new Return (string_concat
, loc
));
1886 tostring
.Block
= tostring_block
;
1888 AddMethod (tostring
);
1891 public override bool Define ()
1893 if (!base.Define ())
1900 public override string GetSignatureForError ()
1902 return SignatureForError
;
1905 public ArrayList Parameters
{