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
.Generic
;
15 using System
.Reflection
;
16 using System
.Reflection
.Emit
;
18 namespace Mono
.CSharp
{
20 public abstract class CompilerGeneratedClass
: Class
22 public static string MakeName (string host
, string typePrefix
, string name
, int id
)
24 return "<" + host
+ ">" + typePrefix
+ "__" + name
+ id
.ToString ("X");
27 protected CompilerGeneratedClass (DeclSpace parent
, MemberName name
, Modifiers mod
)
28 : base (parent
.NamespaceEntry
, parent
, name
, mod
| Modifiers
.COMPILER_GENERATED
, null)
32 protected void CheckMembersDefined ()
34 if (HasMembersDefined
)
35 throw new InternalErrorException ("Helper class already defined!");
40 // Anonymous method storey is created when an anonymous method uses
41 // variable or parameter from outer scope. They are then hoisted to
42 // anonymous method storey (captured)
44 public class AnonymousMethodStorey
: CompilerGeneratedClass
46 struct StoreyFieldPair
48 public readonly AnonymousMethodStorey Storey
;
49 public readonly Field Field
;
51 public StoreyFieldPair (AnonymousMethodStorey storey
, Field field
)
58 sealed class HoistedGenericField
: Field
60 public HoistedGenericField (DeclSpace parent
, FullNamedExpression type
, Modifiers mod
, string name
,
61 Attributes attrs
, Location loc
)
62 : base (parent
, type
, mod
, new MemberName (name
, loc
), attrs
)
66 protected override bool ResolveMemberType ()
68 if (!base.ResolveMemberType ())
71 AnonymousMethodStorey parent
= ((AnonymousMethodStorey
) Parent
).GetGenericStorey ();
72 if (parent
!= null && parent
.Mutator
!= null)
73 member_type
= parent
.Mutator
.Mutate (MemberType
);
80 // Needed to delay hoisted _this_ initialization. When an anonymous
81 // method is used inside ctor and _this_ is hoisted, base ctor has to
82 // be called first, otherwise _this_ will be initialized with
83 // uninitialized value.
85 sealed class ThisInitializer
: Statement
87 readonly HoistedThis hoisted_this
;
89 public ThisInitializer (HoistedThis hoisted_this
)
91 this.hoisted_this
= hoisted_this
;
94 protected override void DoEmit (EmitContext ec
)
96 hoisted_this
.EmitHoistingAssignment (ec
);
99 protected override void CloneTo (CloneContext clonectx
, Statement target
)
106 public readonly int ID
;
107 static int unique_id
;
109 public readonly Block OriginalSourceBlock
;
111 // A list of StoreyFieldPair with local field keeping parent storey instance
112 List
<StoreyFieldPair
> used_parent_storeys
;
113 List
<ExplicitBlock
> children_references
;
115 // A list of hoisted parameters
116 protected List
<HoistedParameter
> hoisted_params
;
117 protected List
<HoistedVariable
> hoisted_locals
;
120 protected HoistedThis hoisted_this
;
122 // Local variable which holds this storey instance
123 public LocalTemporary Instance
;
125 TypeParameterMutator mutator
;
127 public AnonymousMethodStorey (Block block
, TypeContainer parent
, MemberBase host
, GenericMethod generic
, string name
)
128 : base (parent
, MakeMemberName (host
, name
, generic
, block
.StartLocation
), Modifiers
.PRIVATE
| Modifiers
.SEALED
)
131 OriginalSourceBlock
= block
;
134 if (generic
!= null) {
135 var hoisted_tparams
= generic
.CurrentTypeParameters
;
136 type_params
= new TypeParameter
[hoisted_tparams
.Length
];
137 for (int i
= 0; i
< type_params
.Length
; ++i
) {
138 type_params
[i
] = hoisted_tparams
[i
].CreateHoistedCopy (spec
);
143 static MemberName
MakeMemberName (MemberBase host
, string name
, GenericMethod generic
, Location loc
)
145 string host_name
= host
== null ? null : host
.Name
;
146 string tname
= MakeName (host_name
, "c", name
, unique_id
);
147 TypeArguments args
= null;
148 if (generic
!= null) {
149 args
= new TypeArguments ();
150 foreach (TypeParameter tparam
in generic
.CurrentTypeParameters
)
151 args
.Add (new TypeParameterName (tparam
.Name
, null, loc
));
154 return new MemberName (tname
, args
, loc
);
157 public void AddCapturedThisField (EmitContext ec
)
159 TypeExpr type_expr
= new TypeExpression (ec
.CurrentType
, Location
);
160 Field f
= AddCompilerGeneratedField ("<>f__this", type_expr
);
162 hoisted_this
= new HoistedThis (this, f
);
164 // Inflated type instance has to be updated manually
165 if (Instance
.Type
is InflatedTypeSpec
) {
166 var inflator
= new TypeParameterInflator (Instance
.Type
, TypeParameterSpec
.EmptyTypes
, TypeSpec
.EmptyTypes
);
167 Instance
.Type
.MemberCache
.AddMember (f
.Spec
.InflateMember (inflator
));
169 inflator
= new TypeParameterInflator (f
.Parent
.CurrentType
, TypeParameterSpec
.EmptyTypes
, TypeSpec
.EmptyTypes
);
170 f
.Parent
.CurrentType
.MemberCache
.AddMember (f
.Spec
.InflateMember (inflator
));
174 public Field
AddCapturedVariable (string name
, TypeSpec type
)
176 CheckMembersDefined ();
178 FullNamedExpression field_type
= new TypeExpression (type
, Location
);
180 return AddCompilerGeneratedField (name
, field_type
);
182 const Modifiers mod
= Modifiers
.INTERNAL
| Modifiers
.COMPILER_GENERATED
;
183 Field f
= new HoistedGenericField (this, field_type
, mod
, name
, null, Location
);
188 protected Field
AddCompilerGeneratedField (string name
, FullNamedExpression type
)
190 const Modifiers mod
= Modifiers
.INTERNAL
| Modifiers
.COMPILER_GENERATED
;
191 Field f
= new Field (this, type
, mod
, new MemberName (name
, Location
), null);
197 // Creates a link between block and the anonymous method storey
199 // An anonymous method can reference variables from any outer block, but they are
200 // hoisted in their own ExplicitBlock. When more than one block is referenced we
201 // need to create another link between those variable storeys
203 public void AddReferenceFromChildrenBlock (ExplicitBlock block
)
205 if (children_references
== null)
206 children_references
= new List
<ExplicitBlock
> ();
208 if (!children_references
.Contains (block
))
209 children_references
.Add (block
);
212 public void AddParentStoreyReference (EmitContext ec
, AnonymousMethodStorey storey
)
214 CheckMembersDefined ();
216 if (used_parent_storeys
== null)
217 used_parent_storeys
= new List
<StoreyFieldPair
> ();
218 else if (used_parent_storeys
.Exists (i
=> i
.Storey
== storey
))
221 TypeExpr type_expr
= storey
.CreateStoreyTypeExpression (ec
);
222 Field f
= AddCompilerGeneratedField ("<>f__ref$" + storey
.ID
, type_expr
);
223 used_parent_storeys
.Add (new StoreyFieldPair (storey
, f
));
226 public void CaptureLocalVariable (ResolveContext ec
, LocalInfo local_info
)
228 ec
.CurrentBlock
.Explicit
.HasCapturedVariable
= true;
229 if (ec
.CurrentBlock
.Explicit
!= local_info
.Block
.Explicit
)
230 AddReferenceFromChildrenBlock (ec
.CurrentBlock
.Explicit
);
232 if (local_info
.HoistedVariant
!= null)
235 HoistedVariable
var = new HoistedLocalVariable (this, local_info
, GetVariableMangledName (local_info
));
236 local_info
.HoistedVariant
= var;
238 if (hoisted_locals
== null)
239 hoisted_locals
= new List
<HoistedVariable
> ();
241 hoisted_locals
.Add (var);
244 public void CaptureParameter (ResolveContext ec
, ParameterReference param_ref
)
246 ec
.CurrentBlock
.Explicit
.HasCapturedVariable
= true;
247 AddReferenceFromChildrenBlock (ec
.CurrentBlock
.Explicit
);
249 if (param_ref
.GetHoistedVariable (ec
) != null)
252 if (hoisted_params
== null)
253 hoisted_params
= new List
<HoistedParameter
> (2);
255 var expr
= new HoistedParameter (this, param_ref
);
256 param_ref
.Parameter
.HoistedVariant
= expr
;
257 hoisted_params
.Add (expr
);
260 TypeExpr
CreateStoreyTypeExpression (EmitContext ec
)
263 // Create an instance of storey type
265 TypeExpr storey_type_expr
;
266 if (CurrentTypeParameters
!= null) {
268 // Use current method type parameter (MVAR) for top level storey only. All
269 // nested storeys use class type parameter (VAR)
271 TypeParameter
[] tparams
= ec
.CurrentAnonymousMethod
!= null && ec
.CurrentAnonymousMethod
.Storey
!= null ?
272 ec
.CurrentAnonymousMethod
.Storey
.TypeParameters
:
273 ec
.CurrentTypeParameters
;
275 TypeArguments targs
= new TypeArguments ();
278 // Use type parameter name instead of resolved type parameter
279 // specification to resolve to correctly nested type parameters
281 for (int i
= 0; i
< tparams
.Length
; ++i
)
282 targs
.Add (new SimpleName (tparams
[i
].Name
, Location
)); // new TypeParameterExpr (tparams[i], Location));
284 storey_type_expr
= new GenericTypeExpr (Definition
, targs
, Location
);
286 storey_type_expr
= new TypeExpression (CurrentType
, Location
);
289 return storey_type_expr
;
292 public void SetNestedStoryParent (AnonymousMethodStorey parentStorey
)
294 Parent
= parentStorey
;
296 spec
.IsGeneric
= false;
297 spec
.DeclaringType
= parentStorey
.CurrentType
;
298 MemberName
.TypeArguments
= null;
301 protected override bool DoResolveTypeParameters ()
303 // Although any storey can have type parameters they are all clones of method type
304 // parameters therefore have to mutate MVAR references in any of cloned constraints
305 if (type_params
!= null) {
306 for (int i
= 0; i
< type_params
.Length
; ++i
) {
307 var spec
= type_params
[i
].Type
;
308 spec
.BaseType
= mutator
.Mutate (spec
.BaseType
);
309 if (spec
.InterfacesDefined
!= null) {
310 var mutated
= new TypeSpec
[spec
.InterfacesDefined
.Length
];
311 for (int ii
= 0; ii
< mutated
.Length
; ++ii
) {
312 mutated
[ii
] = mutator
.Mutate (spec
.InterfacesDefined
[ii
]);
315 spec
.InterfacesDefined
= mutated
;
318 if (spec
.TypeArguments
!= null) {
319 spec
.TypeArguments
= mutator
.Mutate (spec
.TypeArguments
);
328 // Initializes all hoisted variables
330 public void EmitStoreyInstantiation (EmitContext ec
)
332 // There can be only one instance variable for each storey type
333 if (Instance
!= null)
334 throw new InternalErrorException ();
336 SymbolWriter
.OpenCompilerGeneratedBlock (ec
);
339 // Create an instance of a storey
341 var storey_type_expr
= CreateStoreyTypeExpression (ec
);
343 ResolveContext rc
= new ResolveContext (ec
.MemberContext
);
344 Expression e
= new New (storey_type_expr
, null, Location
).Resolve (rc
);
347 Instance
= new LocalTemporary (storey_type_expr
.Type
);
350 EmitHoistedFieldsInitialization (ec
);
352 SymbolWriter
.DefineScopeVariable (ID
, Instance
.Builder
);
353 SymbolWriter
.CloseCompilerGeneratedBlock (ec
);
356 void EmitHoistedFieldsInitialization (EmitContext ec
)
359 // Initialize all storey reference fields by using local or hoisted variables
361 if (used_parent_storeys
!= null) {
362 var rc
= new ResolveContext (ec
.MemberContext
);
364 foreach (StoreyFieldPair sf
in used_parent_storeys
) {
366 // Get instance expression of storey field
368 Expression instace_expr
= GetStoreyInstanceExpression (ec
);
369 var fs
= sf
.Field
.Spec
;
370 if (TypeManager
.IsGenericType (instace_expr
.Type
))
371 fs
= MemberCache
.GetMember (instace_expr
.Type
, fs
);
373 FieldExpr f_set_expr
= new FieldExpr (fs
, Location
);
374 f_set_expr
.InstanceExpression
= instace_expr
;
376 SimpleAssign a
= new SimpleAssign (f_set_expr
, sf
.Storey
.GetStoreyInstanceExpression (ec
));
377 if (a
.Resolve (rc
) != null)
378 a
.EmitStatement (ec
);
383 // Define hoisted `this' in top-level storey only
385 if (OriginalSourceBlock
.Explicit
.HasCapturedThis
&& !(Parent
is AnonymousMethodStorey
)) {
386 AddCapturedThisField (ec
);
387 OriginalSourceBlock
.AddScopeStatement (new ThisInitializer (hoisted_this
));
391 // Setting currect anonymous method to null blocks any further variable hoisting
393 AnonymousExpression ae
= ec
.CurrentAnonymousMethod
;
394 ec
.CurrentAnonymousMethod
= null;
396 if (hoisted_params
!= null) {
397 EmitHoistedParameters (ec
, hoisted_params
);
400 ec
.CurrentAnonymousMethod
= ae
;
403 protected virtual void EmitHoistedParameters (EmitContext ec
, IList
<HoistedParameter
> hoisted
)
405 foreach (HoistedParameter hp
in hoisted
) {
406 hp
.EmitHoistingAssignment (ec
);
410 public override void EmitType ()
412 SymbolWriter
.DefineAnonymousScope (ID
);
414 if (hoisted_this
!= null)
415 hoisted_this
.EmitSymbolInfo ();
417 if (hoisted_locals
!= null) {
418 foreach (HoistedVariable local
in hoisted_locals
)
419 local
.EmitSymbolInfo ();
422 if (hoisted_params
!= null) {
423 foreach (HoistedParameter param
in hoisted_params
)
424 param
.EmitSymbolInfo ();
427 if (used_parent_storeys
!= null) {
428 foreach (StoreyFieldPair sf
in used_parent_storeys
) {
429 SymbolWriter
.DefineCapturedScope (ID
, sf
.Storey
.ID
, sf
.Field
.Name
);
436 public AnonymousMethodStorey
GetGenericStorey ()
438 DeclSpace storey
= this;
439 while (storey
!= null && storey
.CurrentTypeParameters
== null)
440 storey
= storey
.Parent
;
442 return storey
as AnonymousMethodStorey
;
446 // Returns a field which holds referenced storey instance
448 Field
GetReferencedStoreyField (AnonymousMethodStorey storey
)
450 if (used_parent_storeys
== null)
453 foreach (StoreyFieldPair sf
in used_parent_storeys
) {
454 if (sf
.Storey
== storey
)
462 // Creates storey instance expression regardless of currect IP
464 public Expression
GetStoreyInstanceExpression (EmitContext ec
)
466 AnonymousExpression am
= ec
.CurrentAnonymousMethod
;
469 // Access from original block -> storey
475 // Access from anonymous method implemented as a static -> storey
477 if (am
.Storey
== null)
480 Field f
= am
.Storey
.GetReferencedStoreyField (this);
482 if (am
.Storey
== this) {
484 // Access inside of same storey (S -> S)
486 return new CompilerGeneratedThis (CurrentType
, Location
);
489 // External field access
495 // Storey was cached to local field
497 FieldExpr f_ind
= new FieldExpr (f
, Location
);
498 f_ind
.InstanceExpression
= new CompilerGeneratedThis (CurrentType
, Location
);
502 protected virtual string GetVariableMangledName (LocalInfo local_info
)
505 // No need to mangle anonymous method hoisted variables cause they
506 // are hoisted in their own scopes
508 return local_info
.Name
;
511 public HoistedThis HoistedThis
{
512 get { return hoisted_this; }
515 public TypeParameterMutator Mutator
{
524 public IList
<ExplicitBlock
> ReferencesFromChildrenBlock
{
525 get { return children_references; }
528 public static void Reset ()
534 public abstract class HoistedVariable
537 // Hoisted version of variable references used in expression
538 // tree has to be delayed until we know its location. The variable
539 // doesn't know its location until all stories are calculated
541 class ExpressionTreeVariableReference
: Expression
543 readonly HoistedVariable hv
;
545 public ExpressionTreeVariableReference (HoistedVariable hv
)
550 public override Expression
CreateExpressionTree (ResolveContext ec
)
552 throw new NotSupportedException ("ET");
555 protected override Expression
DoResolve (ResolveContext ec
)
557 eclass
= ExprClass
.Value
;
558 type
= TypeManager
.expression_type_expr
.Type
;
562 public override void Emit (EmitContext ec
)
564 ResolveContext rc
= new ResolveContext (ec
.MemberContext
);
565 Expression e
= hv
.GetFieldExpression (ec
).CreateExpressionTree (rc
);
566 // This should never fail
573 protected readonly AnonymousMethodStorey storey
;
574 protected Field field
;
575 Dictionary
<AnonymousExpression
, FieldExpr
> cached_inner_access
; // TODO: Hashtable is too heavyweight
576 FieldExpr cached_outer_access
;
578 protected HoistedVariable (AnonymousMethodStorey storey
, string name
, TypeSpec type
)
579 : this (storey
, storey
.AddCapturedVariable (name
, type
))
583 protected HoistedVariable (AnonymousMethodStorey storey
, Field field
)
585 this.storey
= storey
;
589 public void AddressOf (EmitContext ec
, AddressOp mode
)
591 GetFieldExpression (ec
).AddressOf (ec
, mode
);
594 public Expression
CreateExpressionTree ()
596 return new ExpressionTreeVariableReference (this);
599 public void Emit (EmitContext ec
)
601 GetFieldExpression (ec
).Emit (ec
);
605 // Creates field access expression for hoisted variable
607 protected FieldExpr
GetFieldExpression (EmitContext ec
)
609 if (ec
.CurrentAnonymousMethod
== null || ec
.CurrentAnonymousMethod
.Storey
== null) {
610 if (cached_outer_access
!= null)
611 return cached_outer_access
;
614 // When setting top-level hoisted variable in generic storey
615 // change storey generic types to method generic types (VAR -> MVAR)
617 if (storey
.Instance
.Type
.IsGenericOrParentIsGeneric
) {
618 var fs
= MemberCache
.GetMember (storey
.Instance
.Type
, field
.Spec
);
619 cached_outer_access
= new FieldExpr (fs
, field
.Location
);
621 cached_outer_access
= new FieldExpr (field
, field
.Location
);
624 cached_outer_access
.InstanceExpression
= storey
.GetStoreyInstanceExpression (ec
);
625 return cached_outer_access
;
628 FieldExpr inner_access
;
629 if (cached_inner_access
!= null) {
630 if (!cached_inner_access
.TryGetValue (ec
.CurrentAnonymousMethod
, out inner_access
))
634 cached_inner_access
= new Dictionary
<AnonymousExpression
, FieldExpr
> (4);
637 if (inner_access
== null) {
638 if (field
.Parent
.IsGeneric
) {
639 var fs
= MemberCache
.GetMember (field
.Parent
.CurrentType
, field
.Spec
);
640 inner_access
= new FieldExpr (fs
, field
.Location
);
642 inner_access
= new FieldExpr (field
, field
.Location
);
645 inner_access
.InstanceExpression
= storey
.GetStoreyInstanceExpression (ec
);
646 cached_inner_access
.Add (ec
.CurrentAnonymousMethod
, inner_access
);
652 public abstract void EmitSymbolInfo ();
654 public void Emit (EmitContext ec
, bool leave_copy
)
656 GetFieldExpression (ec
).Emit (ec
, leave_copy
);
659 public void EmitAssign (EmitContext ec
, Expression source
, bool leave_copy
, bool prepare_for_load
)
661 GetFieldExpression (ec
).EmitAssign (ec
, source
, leave_copy
, false);
665 public class HoistedParameter
: HoistedVariable
667 sealed class HoistedFieldAssign
: Assign
669 public HoistedFieldAssign (Expression target
, Expression source
)
670 : base (target
, source
, source
.Location
)
674 protected override Expression
ResolveConversions (ResolveContext ec
)
677 // Implicit conversion check fails for hoisted type arguments
678 // as they are of different types (!!0 x !0)
684 readonly ParameterReference parameter
;
686 public HoistedParameter (AnonymousMethodStorey scope
, ParameterReference par
)
687 : base (scope
, par
.Name
, par
.Type
)
689 this.parameter
= par
;
692 public HoistedParameter (HoistedParameter hp
, string name
)
693 : base (hp
.storey
, name
, hp
.parameter
.Type
)
695 this.parameter
= hp
.parameter
;
698 public void EmitHoistingAssignment (EmitContext ec
)
701 // Remove hoisted redirection to emit assignment from original parameter
703 HoistedVariable temp
= parameter
.Parameter
.HoistedVariant
;
704 parameter
.Parameter
.HoistedVariant
= null;
706 Assign a
= new HoistedFieldAssign (GetFieldExpression (ec
), parameter
);
707 if (a
.Resolve (new ResolveContext (ec
.MemberContext
)) != null)
708 a
.EmitStatement (ec
);
710 parameter
.Parameter
.HoistedVariant
= temp
;
713 public override void EmitSymbolInfo ()
715 SymbolWriter
.DefineCapturedParameter (storey
.ID
, field
.Name
, field
.Name
);
719 get { return field; }
723 class HoistedLocalVariable
: HoistedVariable
725 readonly string name
;
727 public HoistedLocalVariable (AnonymousMethodStorey scope
, LocalInfo local
, string name
)
728 : base (scope
, name
, local
.VariableType
)
730 this.name
= local
.Name
;
733 public override void EmitSymbolInfo ()
735 SymbolWriter
.DefineCapturedLocal (storey
.ID
, name
, field
.Name
);
739 public class HoistedThis
: HoistedVariable
741 public HoistedThis (AnonymousMethodStorey storey
, Field field
)
742 : base (storey
, field
)
746 public void EmitHoistingAssignment (EmitContext ec
)
748 SimpleAssign a
= new SimpleAssign (GetFieldExpression (ec
), new CompilerGeneratedThis (ec
.CurrentType
, field
.Location
));
749 if (a
.Resolve (new ResolveContext (ec
.MemberContext
)) != null)
750 a
.EmitStatement (ec
);
753 public override void EmitSymbolInfo ()
755 SymbolWriter
.DefineCapturedThis (storey
.ID
, field
.Name
);
759 get { return field; }
764 // Anonymous method expression as created by parser
766 public class AnonymousMethodExpression
: Expression
769 // Special conversion for nested expression tree lambdas
771 class Quote
: ShimExpression
773 public Quote (Expression expr
)
778 public override Expression
CreateExpressionTree (ResolveContext ec
)
780 var args
= new Arguments (1);
781 args
.Add (new Argument (expr
.CreateExpressionTree (ec
)));
782 return CreateExpressionFactoryCall (ec
, "Quote", args
);
785 protected override Expression
DoResolve (ResolveContext rc
)
787 expr
= expr
.Resolve (rc
);
791 eclass
= expr
.eclass
;
797 Dictionary
<TypeSpec
, Expression
> compatibles
;
798 public ToplevelBlock Block
;
800 public AnonymousMethodExpression (Location loc
)
803 this.compatibles
= new Dictionary
<TypeSpec
, Expression
> ();
806 public override string ExprClassName
{
808 return "anonymous method";
812 public virtual bool HasExplicitParameters
{
814 return Parameters
!= ParametersCompiled
.Undefined
;
818 public ParametersCompiled Parameters
{
819 get { return Block.Parameters; }
823 // Returns true if the body of lambda expression can be implicitly
824 // converted to the delegate of type `delegate_type'
826 public bool ImplicitStandardConversionExists (ResolveContext ec
, TypeSpec delegate_type
)
828 using (ec
.With (ResolveContext
.Options
.InferReturnType
, false)) {
829 using (ec
.Set (ResolveContext
.Options
.ProbingMode
)) {
830 return Compatible (ec
, delegate_type
) != null;
835 protected TypeSpec
CompatibleChecks (ResolveContext ec
, TypeSpec delegate_type
)
837 if (delegate_type
.IsDelegate
)
838 return delegate_type
;
840 if (delegate_type
.IsGeneric
&& delegate_type
.GetDefinition () == TypeManager
.expression_type
) {
841 delegate_type
= delegate_type
.TypeArguments
[0];
842 if (delegate_type
.IsDelegate
)
843 return delegate_type
;
845 ec
.Report
.Error (835, loc
, "Cannot convert `{0}' to an expression tree of non-delegate type `{1}'",
846 GetSignatureForError (), TypeManager
.CSharpName (delegate_type
));
850 ec
.Report
.Error (1660, loc
, "Cannot convert `{0}' to non-delegate type `{1}'",
851 GetSignatureForError (), TypeManager
.CSharpName (delegate_type
));
855 protected bool VerifyExplicitParameters (ResolveContext ec
, TypeSpec delegate_type
, AParametersCollection parameters
)
857 if (VerifyParameterCompatibility (ec
, delegate_type
, parameters
, ec
.IsInProbingMode
))
860 if (!ec
.IsInProbingMode
)
861 ec
.Report
.Error (1661, loc
,
862 "Cannot convert `{0}' to delegate type `{1}' since there is a parameter mismatch",
863 GetSignatureForError (), TypeManager
.CSharpName (delegate_type
));
868 protected bool VerifyParameterCompatibility (ResolveContext ec
, TypeSpec delegate_type
, AParametersCollection invoke_pd
, bool ignore_errors
)
870 if (Parameters
.Count
!= invoke_pd
.Count
) {
874 ec
.Report
.Error (1593, loc
, "Delegate `{0}' does not take `{1}' arguments",
875 TypeManager
.CSharpName (delegate_type
), Parameters
.Count
.ToString ());
879 bool has_implicit_parameters
= !HasExplicitParameters
;
882 for (int i
= 0; i
< Parameters
.Count
; ++i
) {
883 Parameter
.Modifier p_mod
= invoke_pd
.FixedParameters
[i
].ModFlags
;
884 if (Parameters
.FixedParameters
[i
].ModFlags
!= p_mod
&& p_mod
!= Parameter
.Modifier
.PARAMS
) {
888 if (p_mod
== Parameter
.Modifier
.NONE
)
889 ec
.Report
.Error (1677, loc
, "Parameter `{0}' should not be declared with the `{1}' keyword",
890 (i
+ 1).ToString (), Parameter
.GetModifierSignature (Parameters
.FixedParameters
[i
].ModFlags
));
892 ec
.Report
.Error (1676, loc
, "Parameter `{0}' must be declared with the `{1}' keyword",
893 (i
+1).ToString (), Parameter
.GetModifierSignature (p_mod
));
897 if (has_implicit_parameters
)
900 TypeSpec type
= invoke_pd
.Types
[i
];
902 // We assume that generic parameters are always inflated
903 if (TypeManager
.IsGenericParameter (type
))
906 if (TypeManager
.HasElementType (type
) && TypeManager
.IsGenericParameter (TypeManager
.GetElementType (type
)))
909 if (invoke_pd
.Types
[i
] != Parameters
.Types
[i
]) {
913 ec
.Report
.Error (1678, loc
, "Parameter `{0}' is declared as type `{1}' but should be `{2}'",
915 TypeManager
.CSharpName (Parameters
.Types
[i
]),
916 TypeManager
.CSharpName (invoke_pd
.Types
[i
]));
925 // Infers type arguments based on explicit arguments
927 public bool ExplicitTypeInference (ResolveContext ec
, TypeInferenceContext type_inference
, TypeSpec delegate_type
)
929 if (!HasExplicitParameters
)
932 if (!delegate_type
.IsDelegate
) {
933 if (delegate_type
.GetDefinition () != TypeManager
.expression_type
)
936 delegate_type
= TypeManager
.GetTypeArguments (delegate_type
) [0];
937 if (!delegate_type
.IsDelegate
)
941 AParametersCollection d_params
= Delegate
.GetParameters (ec
.Compiler
, delegate_type
);
942 if (d_params
.Count
!= Parameters
.Count
)
945 for (int i
= 0; i
< Parameters
.Count
; ++i
) {
946 TypeSpec itype
= d_params
.Types
[i
];
947 if (!TypeManager
.IsGenericParameter (itype
)) {
948 if (!TypeManager
.HasElementType (itype
))
951 if (!TypeManager
.IsGenericParameter (TypeManager
.GetElementType (itype
)))
954 type_inference
.ExactInference (Parameters
.Types
[i
], itype
);
959 public TypeSpec
InferReturnType (ResolveContext ec
, TypeInferenceContext tic
, TypeSpec delegate_type
)
961 AnonymousExpression am
;
962 using (ec
.Set (ResolveContext
.Options
.ProbingMode
| ResolveContext
.Options
.InferReturnType
)) {
963 am
= CompatibleMethodBody (ec
, tic
, InternalType
.Arglist
, delegate_type
);
965 am
= am
.Compatible (ec
);
971 return am
.ReturnType
;
975 // Returns AnonymousMethod container if this anonymous method
976 // expression can be implicitly converted to the delegate type `delegate_type'
978 public Expression
Compatible (ResolveContext ec
, TypeSpec type
)
981 if (compatibles
.TryGetValue (type
, out am
))
984 TypeSpec delegate_type
= CompatibleChecks (ec
, type
);
985 if (delegate_type
== null)
989 // At this point its the first time we know the return type that is
990 // needed for the anonymous method. We create the method here.
993 var invoke_mb
= Delegate
.GetInvokeMethod (ec
.Compiler
, delegate_type
);
994 TypeSpec return_type
= invoke_mb
.ReturnType
;
997 // Second: the return type of the delegate must be compatible with
998 // the anonymous type. Instead of doing a pass to examine the block
999 // we satisfy the rule by setting the return type on the EmitContext
1000 // to be the delegate type return type.
1003 var body
= CompatibleMethodBody (ec
, null, return_type
, delegate_type
);
1007 bool etree_conversion
= delegate_type
!= type
;
1010 if (etree_conversion
) {
1011 if (ec
.HasSet (ResolveContext
.Options
.ExpressionTreeConversion
)) {
1013 // Nested expression tree lambda use same scope as parent
1014 // lambda, this also means no variable capturing between this
1017 am
= body
.Compatible (ec
, ec
.CurrentAnonymousMethod
);
1020 // Quote nested expression tree
1023 am
= new Quote (am
);
1025 int errors
= ec
.Report
.Errors
;
1027 using (ec
.Set (ResolveContext
.Options
.ExpressionTreeConversion
)) {
1028 am
= body
.Compatible (ec
);
1032 // Rewrite expressions into expression tree when targeting Expression<T>
1034 if (am
!= null && errors
== ec
.Report
.Errors
)
1035 am
= CreateExpressionTree (ec
, delegate_type
);
1038 am
= body
.Compatible (ec
);
1040 } catch (CompletionResult
) {
1042 } catch (Exception e
) {
1043 throw new InternalErrorException (e
, loc
);
1046 if (!ec
.IsInProbingMode
)
1047 compatibles
.Add (type
, am
== null ? EmptyExpression
.Null
: am
);
1052 protected virtual Expression
CreateExpressionTree (ResolveContext ec
, TypeSpec delegate_type
)
1054 return CreateExpressionTree (ec
);
1057 public override Expression
CreateExpressionTree (ResolveContext ec
)
1059 ec
.Report
.Error (1946, loc
, "An anonymous method cannot be converted to an expression tree");
1063 protected virtual ParametersCompiled
ResolveParameters (ResolveContext ec
, TypeInferenceContext tic
, TypeSpec delegate_type
)
1065 var delegate_parameters
= Delegate
.GetParameters (ec
.Compiler
, delegate_type
);
1067 if (Parameters
== ParametersCompiled
.Undefined
) {
1069 // We provide a set of inaccessible parameters
1071 Parameter
[] fixedpars
= new Parameter
[delegate_parameters
.Count
];
1073 for (int i
= 0; i
< delegate_parameters
.Count
; i
++) {
1074 Parameter
.Modifier i_mod
= delegate_parameters
.FixedParameters
[i
].ModFlags
;
1075 if (i_mod
== Parameter
.Modifier
.OUT
) {
1076 ec
.Report
.Error (1688, loc
, "Cannot convert anonymous " +
1077 "method block without a parameter list " +
1078 "to delegate type `{0}' because it has " +
1079 "one or more `out' parameters.",
1080 TypeManager
.CSharpName (delegate_type
));
1083 fixedpars
[i
] = new Parameter (
1085 delegate_parameters
.FixedParameters
[i
].ModFlags
, null, loc
);
1088 return ParametersCompiled
.CreateFullyResolved (fixedpars
, delegate_parameters
.Types
);
1091 if (!VerifyExplicitParameters (ec
, delegate_type
, delegate_parameters
)) {
1098 protected override Expression
DoResolve (ResolveContext ec
)
1100 if (ec
.HasSet (ResolveContext
.Options
.ConstantScope
)) {
1101 ec
.Report
.Error (1706, loc
, "Anonymous methods and lambda expressions cannot be used in the current context");
1106 // Set class type, set type
1109 eclass
= ExprClass
.Value
;
1112 // This hack means `The type is not accessible
1113 // anywhere', we depend on special conversion
1116 type
= InternalType
.AnonymousMethod
;
1118 if ((Parameters
!= null) && !Parameters
.Resolve (ec
))
1121 // FIXME: The emitted code isn't very careful about reachability
1122 // so, ensure we have a 'ret' at the end
1123 BlockContext bc
= ec
as BlockContext
;
1124 if (bc
!= null && bc
.CurrentBranching
!= null && bc
.CurrentBranching
.CurrentUsageVector
.IsUnreachable
)
1125 bc
.NeedReturnLabel ();
1130 public override void Emit (EmitContext ec
)
1132 // nothing, as we only exist to not do anything.
1135 public static void Error_AddressOfCapturedVar (ResolveContext ec
, IVariableReference
var, Location loc
)
1137 ec
.Report
.Error (1686, loc
,
1138 "Local variable or parameter `{0}' cannot have their address taken and be used inside an anonymous method or lambda expression",
1142 public override string GetSignatureForError ()
1144 return ExprClassName
;
1147 AnonymousMethodBody
CompatibleMethodBody (ResolveContext ec
, TypeInferenceContext tic
, TypeSpec return_type
, TypeSpec delegate_type
)
1149 ParametersCompiled p
= ResolveParameters (ec
, tic
, delegate_type
);
1153 ToplevelBlock b
= ec
.IsInProbingMode
? (ToplevelBlock
) Block
.PerformClone () : Block
;
1155 return CompatibleMethodFactory (return_type
, delegate_type
, p
, b
);
1159 protected virtual AnonymousMethodBody
CompatibleMethodFactory (TypeSpec return_type
, TypeSpec delegate_type
, ParametersCompiled p
, ToplevelBlock b
)
1161 return new AnonymousMethodBody (p
, b
, return_type
, delegate_type
, loc
);
1164 protected override void CloneTo (CloneContext clonectx
, Expression t
)
1166 AnonymousMethodExpression target
= (AnonymousMethodExpression
) t
;
1168 target
.Block
= (ToplevelBlock
) clonectx
.LookupBlock (Block
);
1173 // Abstract expression for any block which requires variables hoisting
1175 public abstract class AnonymousExpression
: Expression
1177 protected class AnonymousMethodMethod
: Method
1179 public readonly AnonymousExpression AnonymousMethod
;
1180 public readonly AnonymousMethodStorey Storey
;
1181 readonly string RealName
;
1183 public AnonymousMethodMethod (DeclSpace parent
, AnonymousExpression am
, AnonymousMethodStorey storey
,
1184 GenericMethod generic
, TypeExpr return_type
,
1185 Modifiers mod
, string real_name
, MemberName name
,
1186 ParametersCompiled parameters
)
1187 : base (parent
, generic
, return_type
, mod
| Modifiers
.COMPILER_GENERATED
,
1188 name
, parameters
, null)
1190 this.AnonymousMethod
= am
;
1191 this.Storey
= storey
;
1192 this.RealName
= real_name
;
1194 Parent
.PartialContainer
.AddMethod (this);
1198 public override EmitContext
CreateEmitContext (ILGenerator ig
)
1200 EmitContext ec
= new EmitContext (this, ig
, ReturnType
);
1201 ec
.CurrentAnonymousMethod
= AnonymousMethod
;
1202 if (AnonymousMethod
.return_label
!= null) {
1203 ec
.HasReturnLabel
= true;
1204 ec
.ReturnLabel
= (Label
) AnonymousMethod
.return_label
;
1210 protected override void DefineTypeParameters ()
1212 // Type parameters were cloned
1215 protected override bool ResolveMemberType ()
1217 if (!base.ResolveMemberType ())
1220 if (Storey
!= null && Storey
.Mutator
!= null) {
1221 if (!parameters
.IsEmpty
) {
1222 var mutated
= Storey
.Mutator
.Mutate (parameters
.Types
);
1223 if (mutated
!= parameters
.Types
)
1224 parameters
= ParametersCompiled
.CreateFullyResolved ((Parameter
[]) parameters
.FixedParameters
, mutated
);
1227 member_type
= Storey
.Mutator
.Mutate (member_type
);
1233 public override void Emit ()
1235 if (MethodBuilder
== null) {
1242 public override void EmitExtraSymbolInfo (SourceMethod source
)
1244 source
.SetRealMethodName (RealName
);
1248 readonly ToplevelBlock block
;
1250 public TypeSpec ReturnType
;
1252 object return_label
;
1254 protected AnonymousExpression (ToplevelBlock block
, TypeSpec return_type
, Location loc
)
1256 this.ReturnType
= return_type
;
1261 public abstract string ContainerType { get; }
1262 public abstract bool IsIterator { get; }
1263 public abstract AnonymousMethodStorey Storey { get; }
1265 public AnonymousExpression
Compatible (ResolveContext ec
)
1267 return Compatible (ec
, this);
1270 public AnonymousExpression
Compatible (ResolveContext ec
, AnonymousExpression ae
)
1272 // TODO: Implement clone
1273 BlockContext aec
= new BlockContext (ec
.MemberContext
, Block
, ReturnType
);
1274 aec
.CurrentAnonymousMethod
= ae
;
1276 IDisposable aec_dispose
= null;
1277 ResolveContext
.Options flags
= 0;
1278 if (ec
.HasSet (ResolveContext
.Options
.InferReturnType
)) {
1279 flags
|= ResolveContext
.Options
.InferReturnType
;
1280 aec
.ReturnTypeInference
= new TypeInferenceContext ();
1283 if (ec
.IsInProbingMode
)
1284 flags
|= ResolveContext
.Options
.ProbingMode
;
1286 if (ec
.HasSet (ResolveContext
.Options
.FieldInitializerScope
))
1287 flags
|= ResolveContext
.Options
.FieldInitializerScope
;
1290 flags
|= ResolveContext
.Options
.UnsafeScope
;
1292 if (ec
.HasSet (ResolveContext
.Options
.CheckedScope
))
1293 flags
|= ResolveContext
.Options
.CheckedScope
;
1295 if (ec
.HasSet (ResolveContext
.Options
.ExpressionTreeConversion
))
1296 flags
|= ResolveContext
.Options
.ExpressionTreeConversion
;
1298 // HACK: Flag with 0 cannot be set
1300 aec_dispose
= aec
.Set (flags
);
1302 var errors
= ec
.Report
.Errors
;
1304 bool res
= Block
.Resolve (ec
.CurrentBranching
, aec
, Block
.Parameters
, null);
1306 if (aec
.HasReturnLabel
)
1307 return_label
= aec
.ReturnLabel
;
1309 if (ec
.HasSet (ResolveContext
.Options
.InferReturnType
)) {
1310 aec
.ReturnTypeInference
.FixAllTypes (ec
);
1311 ReturnType
= aec
.ReturnTypeInference
.InferredTypeArguments
[0];
1314 if (aec_dispose
!= null) {
1315 aec_dispose
.Dispose ();
1318 if (res
&& errors
!= ec
.Report
.Errors
)
1321 return res
? this : null;
1324 public void SetHasThisAccess ()
1326 Block
.HasCapturedThis
= true;
1327 ExplicitBlock b
= Block
.Parent
.Explicit
;
1330 if (b
.HasCapturedThis
)
1333 b
.HasCapturedThis
= true;
1334 b
= b
.Parent
== null ? null : b
.Parent
.Explicit
;
1339 // The block that makes up the body for the anonymous method
1341 public ToplevelBlock Block
{
1349 public class AnonymousMethodBody
: AnonymousExpression
1351 protected readonly ParametersCompiled parameters
;
1352 AnonymousMethodStorey storey
;
1354 AnonymousMethodMethod method
;
1358 static int unique_id
;
1360 public AnonymousMethodBody (ParametersCompiled parameters
,
1361 ToplevelBlock block
, TypeSpec return_type
, TypeSpec delegate_type
,
1363 : base (block
, return_type
, loc
)
1365 this.type
= delegate_type
;
1366 this.parameters
= parameters
;
1369 public override string ContainerType
{
1370 get { return "anonymous method"; }
1373 public override AnonymousMethodStorey Storey
{
1374 get { return storey; }
1377 public override bool IsIterator
{
1378 get { return false; }
1381 public override Expression
CreateExpressionTree (ResolveContext ec
)
1383 ec
.Report
.Error (1945, loc
, "An expression tree cannot contain an anonymous method expression");
1387 bool Define (ResolveContext ec
)
1389 if (!Block
.Resolved
&& Compatible (ec
) == null)
1392 if (block_name
== null) {
1393 MemberCore mc
= (MemberCore
) ec
.MemberContext
;
1394 block_name
= mc
.MemberName
.Basename
;
1401 // Creates a host for the anonymous method
1403 AnonymousMethodMethod
DoCreateMethodHost (EmitContext ec
)
1406 // Anonymous method body can be converted to
1408 // 1, an instance method in current scope when only `this' is hoisted
1409 // 2, a static method in current scope when neither `this' nor any variable is hoisted
1410 // 3, an instance method in compiler generated storey when any hoisted variable exists
1413 Modifiers modifiers
;
1414 if (Block
.HasCapturedVariable
|| Block
.HasCapturedThis
) {
1415 storey
= FindBestMethodStorey ();
1416 modifiers
= storey
!= null ? Modifiers
.INTERNAL
: Modifiers
.PRIVATE
;
1418 if (ec
.CurrentAnonymousMethod
!= null)
1419 storey
= ec
.CurrentAnonymousMethod
.Storey
;
1421 modifiers
= Modifiers
.STATIC
| Modifiers
.PRIVATE
;
1424 TypeContainer parent
= storey
!= null ? storey
: ec
.CurrentTypeDefinition
.Parent
.PartialContainer
;
1426 MemberCore mc
= ec
.MemberContext
as MemberCore
;
1427 string name
= CompilerGeneratedClass
.MakeName (parent
!= storey
? block_name
: null,
1428 "m", null, unique_id
++);
1430 MemberName member_name
;
1431 GenericMethod generic_method
;
1432 if (storey
== null && mc
.MemberName
.TypeArguments
!= null) {
1433 member_name
= new MemberName (name
, mc
.MemberName
.TypeArguments
.Clone (), Location
);
1435 var hoisted_tparams
= ec
.CurrentTypeParameters
;
1436 var type_params
= new TypeParameter
[hoisted_tparams
.Length
];
1437 for (int i
= 0; i
< type_params
.Length
; ++i
) {
1438 type_params
[i
] = hoisted_tparams
[i
].CreateHoistedCopy (null);
1441 generic_method
= new GenericMethod (parent
.NamespaceEntry
, parent
, member_name
, type_params
,
1442 new TypeExpression (ReturnType
, Location
), parameters
);
1444 member_name
= new MemberName (name
, Location
);
1445 generic_method
= null;
1448 string real_name
= String
.Format (
1449 "{0}~{1}{2}", mc
.GetSignatureForError (), GetSignatureForError (),
1450 parameters
.GetSignatureForError ());
1452 return new AnonymousMethodMethod (parent
,
1453 this, storey
, generic_method
, new TypeExpression (ReturnType
, Location
), modifiers
,
1454 real_name
, member_name
, parameters
);
1457 protected override Expression
DoResolve (ResolveContext ec
)
1462 eclass
= ExprClass
.Value
;
1466 public override void Emit (EmitContext ec
)
1469 // Use same anonymous method implementation for scenarios where same
1470 // code is used from multiple blocks, e.g. field initializers
1472 if (method
== null) {
1474 // Delay an anonymous method definition to avoid emitting unused code
1475 // for unreachable blocks or expression trees
1477 method
= DoCreateMethodHost (ec
);
1481 bool is_static
= (method
.ModFlags
& Modifiers
.STATIC
) != 0;
1482 if (is_static
&& am_cache
== null) {
1484 // Creates a field cache to store delegate instance if it's not generic
1486 if (!method
.MemberName
.IsGeneric
) {
1487 TypeContainer parent
= method
.Parent
.PartialContainer
;
1488 int id
= parent
.Fields
== null ? 0 : parent
.Fields
.Count
;
1489 var cache_type
= storey
!= null && storey
.Mutator
!= null ? storey
.Mutator
.Mutate (type
) : type
;
1491 am_cache
= new Field (parent
, new TypeExpression (cache_type
, loc
),
1492 Modifiers
.STATIC
| Modifiers
.PRIVATE
| Modifiers
.COMPILER_GENERATED
,
1493 new MemberName (CompilerGeneratedClass
.MakeName (null, "f", "am$cache", id
), loc
), null);
1495 parent
.AddField (am_cache
);
1497 // TODO: Implement caching of generated generic static methods
1501 // Some extra class is needed to capture variable generic type
1502 // arguments. Maybe we could re-use anonymous types, with a unique
1503 // anonymous method id, but they are quite heavy.
1505 // Consider : "() => typeof(T);"
1507 // We need something like
1508 // static class Wrap<Tn, Tm, DelegateType> {
1509 // public static DelegateType cache;
1512 // We then specialize local variable to capture all generic parameters
1513 // and delegate type, e.g. "Wrap<Ta, Tb, DelegateTypeInst> cache;"
1518 Label l_initialized
= ec
.DefineLabel ();
1520 if (am_cache
!= null) {
1521 ec
.Emit (OpCodes
.Ldsfld
, am_cache
.Spec
);
1522 ec
.Emit (OpCodes
.Brtrue_S
, l_initialized
);
1526 // Load method delegate implementation
1530 ec
.Emit (OpCodes
.Ldnull
);
1531 } else if (storey
!= null) {
1532 Expression e
= storey
.GetStoreyInstanceExpression (ec
).Resolve (new ResolveContext (ec
.MemberContext
));
1536 ec
.Emit (OpCodes
.Ldarg_0
);
1539 var delegate_method
= method
.Spec
;
1540 if (storey
!= null && storey
.MemberName
.IsGeneric
) {
1541 TypeSpec t
= storey
.Instance
.Type
;
1544 // Mutate anonymous method instance type if we are in nested
1545 // hoisted generic anonymous method storey
1547 if (ec
.CurrentAnonymousMethod
!= null &&
1548 ec
.CurrentAnonymousMethod
.Storey
!= null &&
1549 ec
.CurrentAnonymousMethod
.Storey
.Mutator
!= null) {
1550 t
= storey
.Mutator
.Mutate (t
);
1553 ec
.Emit (OpCodes
.Ldftn
, TypeBuilder
.GetMethod (t
.GetMetaInfo (), (MethodInfo
) delegate_method
.GetMetaInfo ()));
1555 ec
.Emit (OpCodes
.Ldftn
, delegate_method
);
1558 var constructor_method
= Delegate
.GetConstructor (ec
.MemberContext
.Compiler
, ec
.CurrentType
, type
);
1559 ec
.Emit (OpCodes
.Newobj
, constructor_method
);
1561 if (am_cache
!= null) {
1562 ec
.Emit (OpCodes
.Stsfld
, am_cache
.Spec
);
1563 ec
.MarkLabel (l_initialized
);
1564 ec
.Emit (OpCodes
.Ldsfld
, am_cache
.Spec
);
1569 // Look for the best storey for this anonymous method
1571 AnonymousMethodStorey
FindBestMethodStorey ()
1574 // Use the nearest parent block which has a storey
1576 for (Block b
= Block
.Parent
; b
!= null; b
= b
.Parent
) {
1577 AnonymousMethodStorey s
= b
.Explicit
.AnonymousMethodStorey
;
1585 public override string GetSignatureForError ()
1587 return TypeManager
.CSharpName (type
);
1590 public static void Reset ()
1597 // Anonymous type container
1599 public class AnonymousTypeClass
: CompilerGeneratedClass
1601 sealed class AnonymousParameters
: ParametersCompiled
1603 public AnonymousParameters (CompilerContext ctx
, params Parameter
[] parameters
)
1604 : base (ctx
, parameters
)
1608 protected override void ErrorDuplicateName (Parameter p
, Report Report
)
1610 Report
.Error (833, p
.Location
, "`{0}': An anonymous type cannot have multiple properties with the same name",
1615 static int types_counter
;
1616 public const string ClassNamePrefix
= "<>__AnonType";
1617 public const string SignatureForError
= "anonymous type";
1619 readonly IList
<AnonymousTypeParameter
> parameters
;
1621 private AnonymousTypeClass (DeclSpace parent
, MemberName name
, IList
<AnonymousTypeParameter
> parameters
, Location loc
)
1622 : base (parent
, name
, (RootContext
.EvalMode
? Modifiers
.PUBLIC
: 0) | Modifiers
.SEALED
)
1624 this.parameters
= parameters
;
1627 public static AnonymousTypeClass
Create (CompilerContext ctx
, TypeContainer parent
, IList
<AnonymousTypeParameter
> parameters
, Location loc
)
1629 string name
= ClassNamePrefix
+ types_counter
++;
1631 SimpleName
[] t_args
= new SimpleName
[parameters
.Count
];
1632 TypeParameterName
[] t_params
= new TypeParameterName
[parameters
.Count
];
1633 Parameter
[] ctor_params
= new Parameter
[parameters
.Count
];
1634 for (int i
= 0; i
< parameters
.Count
; ++i
) {
1635 AnonymousTypeParameter p
= (AnonymousTypeParameter
) parameters
[i
];
1637 t_args
[i
] = new SimpleName ("<" + p
.Name
+ ">__T", p
.Location
);
1638 t_params
[i
] = new TypeParameterName (t_args
[i
].Name
, null, p
.Location
);
1639 ctor_params
[i
] = new Parameter (t_args
[i
], p
.Name
, 0, null, p
.Location
);
1643 // Create generic anonymous type host with generic arguments
1644 // named upon properties names
1646 AnonymousTypeClass a_type
= new AnonymousTypeClass (parent
.NamespaceEntry
.SlaveDeclSpace
,
1647 new MemberName (name
, new TypeArguments (t_params
), loc
), parameters
, loc
);
1649 if (parameters
.Count
> 0)
1650 a_type
.SetParameterInfo (null);
1652 Constructor c
= new Constructor (a_type
, name
, Modifiers
.PUBLIC
| Modifiers
.DEBUGGER_HIDDEN
,
1653 null, new AnonymousParameters (ctx
, ctor_params
), null, loc
);
1654 c
.Block
= new ToplevelBlock (ctx
, c
.ParameterInfo
, loc
);
1657 // Create fields and contructor body with field initialization
1660 for (int i
= 0; i
< parameters
.Count
; ++i
) {
1661 AnonymousTypeParameter p
= (AnonymousTypeParameter
) parameters
[i
];
1663 Field f
= new Field (a_type
, t_args
[i
], Modifiers
.PRIVATE
| Modifiers
.READONLY
,
1664 new MemberName ("<" + p
.Name
+ ">", p
.Location
), null);
1666 if (!a_type
.AddField (f
)) {
1671 c
.Block
.AddStatement (new StatementExpression (
1672 new SimpleAssign (new MemberAccess (new This (p
.Location
), f
.Name
),
1673 c
.Block
.GetParameterReference (p
.Name
, p
.Location
))));
1675 ToplevelBlock get_block
= new ToplevelBlock (ctx
, p
.Location
);
1676 get_block
.AddStatement (new Return (
1677 new MemberAccess (new This (p
.Location
), f
.Name
), p
.Location
));
1679 Property prop
= new Property (a_type
, t_args
[i
], Modifiers
.PUBLIC
,
1680 new MemberName (p
.Name
, p
.Location
), null);
1681 prop
.Get
= new Property
.GetMethod (prop
, 0, null, p
.Location
);
1682 prop
.Get
.Block
= get_block
;
1683 a_type
.AddProperty (prop
);
1689 a_type
.AddConstructor (c
);
1693 public static void Reset ()
1698 protected override bool AddToContainer (MemberCore symbol
, string name
)
1700 MemberCore mc
= GetDefinition (name
);
1703 defined_names
.Add (name
, symbol
);
1707 Report
.SymbolRelatedToPreviousError (mc
);
1711 protected override bool DoDefineMembers ()
1713 if (!base.DoDefineMembers ())
1716 Location loc
= Location
;
1718 Method equals
= new Method (this, null, new TypeExpression (TypeManager
.bool_type
, loc
),
1719 Modifiers
.PUBLIC
| Modifiers
.OVERRIDE
| Modifiers
.DEBUGGER_HIDDEN
, new MemberName ("Equals", loc
),
1720 Mono
.CSharp
.ParametersCompiled
.CreateFullyResolved (new Parameter (null, "obj", 0, null, loc
), TypeManager
.object_type
), null);
1722 Method tostring
= new Method (this, null, new TypeExpression (TypeManager
.string_type
, loc
),
1723 Modifiers
.PUBLIC
| Modifiers
.OVERRIDE
| Modifiers
.DEBUGGER_HIDDEN
, new MemberName ("ToString", loc
),
1724 Mono
.CSharp
.ParametersCompiled
.EmptyReadOnlyParameters
, null);
1726 ToplevelBlock equals_block
= new ToplevelBlock (Compiler
, equals
.ParameterInfo
, loc
);
1727 TypeExpr current_type
;
1728 if (type_params
!= null) {
1729 var targs
= new TypeArguments ();
1730 foreach (var type_param
in type_params
)
1731 targs
.Add (new TypeParameterExpr (type_param
, type_param
.Location
));
1733 current_type
= new GenericTypeExpr (Definition
, targs
, loc
);
1735 current_type
= new TypeExpression (Definition
, loc
);
1738 equals_block
.AddVariable (current_type
, "other", loc
);
1739 LocalVariableReference other_variable
= new LocalVariableReference (equals_block
, "other", loc
);
1741 MemberAccess system_collections_generic
= new MemberAccess (new MemberAccess (
1742 new QualifiedAliasMember ("global", "System", loc
), "Collections", loc
), "Generic", loc
);
1744 Expression rs_equals
= null;
1745 Expression string_concat
= new StringConstant ("{", loc
);
1746 Expression rs_hashcode
= new IntConstant (-2128831035, loc
);
1747 for (int i
= 0; i
< parameters
.Count
; ++i
) {
1748 var p
= parameters
[i
];
1751 MemberAccess equality_comparer
= new MemberAccess (new MemberAccess (
1752 system_collections_generic
, "EqualityComparer",
1753 new TypeArguments (new SimpleName (CurrentTypeParameters
[i
].Name
, loc
)), loc
),
1756 Arguments arguments_equal
= new Arguments (2);
1757 arguments_equal
.Add (new Argument (new MemberAccess (new This (f
.Location
), f
.Name
)));
1758 arguments_equal
.Add (new Argument (new MemberAccess (other_variable
, f
.Name
)));
1760 Expression field_equal
= new Invocation (new MemberAccess (equality_comparer
,
1761 "Equals", loc
), arguments_equal
);
1763 Arguments arguments_hashcode
= new Arguments (1);
1764 arguments_hashcode
.Add (new Argument (new MemberAccess (new This (f
.Location
), f
.Name
)));
1765 Expression field_hashcode
= new Invocation (new MemberAccess (equality_comparer
,
1766 "GetHashCode", loc
), arguments_hashcode
);
1768 IntConstant FNV_prime
= new IntConstant (16777619, loc
);
1769 rs_hashcode
= new Binary (Binary
.Operator
.Multiply
,
1770 new Binary (Binary
.Operator
.ExclusiveOr
, rs_hashcode
, field_hashcode
, loc
),
1773 Expression field_to_string
= new Conditional (new BooleanExpression (new Binary (Binary
.Operator
.Inequality
,
1774 new MemberAccess (new This (f
.Location
), f
.Name
), new NullLiteral (loc
), loc
)),
1775 new Invocation (new MemberAccess (
1776 new MemberAccess (new This (f
.Location
), f
.Name
), "ToString"), null),
1777 new StringConstant (string.Empty
, loc
));
1779 if (rs_equals
== null) {
1780 rs_equals
= field_equal
;
1781 string_concat
= new Binary (Binary
.Operator
.Addition
,
1783 new Binary (Binary
.Operator
.Addition
,
1784 new StringConstant (" " + p
.Name
+ " = ", loc
),
1792 // Implementation of ToString () body using string concatenation
1794 string_concat
= new Binary (Binary
.Operator
.Addition
,
1795 new Binary (Binary
.Operator
.Addition
,
1797 new StringConstant (", " + p
.Name
+ " = ", loc
),
1802 rs_equals
= new Binary (Binary
.Operator
.LogicalAnd
, rs_equals
, field_equal
, loc
);
1805 string_concat
= new Binary (Binary
.Operator
.Addition
,
1807 new StringConstant (" }", loc
),
1811 // Equals (object obj) override
1813 LocalVariableReference other_variable_assign
= new LocalVariableReference (equals_block
, "other", loc
);
1814 equals_block
.AddStatement (new StatementExpression (
1815 new SimpleAssign (other_variable_assign
,
1816 new As (equals_block
.GetParameterReference ("obj", loc
),
1817 current_type
, loc
), loc
)));
1819 Expression equals_test
= new Binary (Binary
.Operator
.Inequality
, other_variable
, new NullLiteral (loc
), loc
);
1820 if (rs_equals
!= null)
1821 equals_test
= new Binary (Binary
.Operator
.LogicalAnd
, equals_test
, rs_equals
, loc
);
1822 equals_block
.AddStatement (new Return (equals_test
, loc
));
1824 equals
.Block
= equals_block
;
1829 // GetHashCode () override
1831 Method hashcode
= new Method (this, null, new TypeExpression (TypeManager
.int32_type
, loc
),
1832 Modifiers
.PUBLIC
| Modifiers
.OVERRIDE
| Modifiers
.DEBUGGER_HIDDEN
,
1833 new MemberName ("GetHashCode", loc
),
1834 Mono
.CSharp
.ParametersCompiled
.EmptyReadOnlyParameters
, null);
1837 // Modified FNV with good avalanche behavior and uniform
1838 // distribution with larger hash sizes.
1840 // const int FNV_prime = 16777619;
1841 // int hash = (int) 2166136261;
1842 // foreach (int d in data)
1843 // hash = (hash ^ d) * FNV_prime;
1844 // hash += hash << 13;
1845 // hash ^= hash >> 7;
1846 // hash += hash << 3;
1847 // hash ^= hash >> 17;
1848 // hash += hash << 5;
1850 ToplevelBlock hashcode_top
= new ToplevelBlock (Compiler
, loc
);
1851 Block hashcode_block
= new Block (hashcode_top
);
1852 hashcode_top
.AddStatement (new Unchecked (hashcode_block
, loc
));
1854 hashcode_block
.AddVariable (new TypeExpression (TypeManager
.int32_type
, loc
), "hash", loc
);
1855 LocalVariableReference hash_variable
= new LocalVariableReference (hashcode_block
, "hash", loc
);
1856 LocalVariableReference hash_variable_assign
= new LocalVariableReference (hashcode_block
, "hash", loc
);
1857 hashcode_block
.AddStatement (new StatementExpression (
1858 new SimpleAssign (hash_variable_assign
, rs_hashcode
)));
1860 hashcode_block
.AddStatement (new StatementExpression (
1861 new CompoundAssign (Binary
.Operator
.Addition
, hash_variable
,
1862 new Binary (Binary
.Operator
.LeftShift
, hash_variable
, new IntConstant (13, loc
), loc
), loc
)));
1863 hashcode_block
.AddStatement (new StatementExpression (
1864 new CompoundAssign (Binary
.Operator
.ExclusiveOr
, hash_variable
,
1865 new Binary (Binary
.Operator
.RightShift
, hash_variable
, new IntConstant (7, loc
), loc
), loc
)));
1866 hashcode_block
.AddStatement (new StatementExpression (
1867 new CompoundAssign (Binary
.Operator
.Addition
, hash_variable
,
1868 new Binary (Binary
.Operator
.LeftShift
, hash_variable
, new IntConstant (3, loc
), loc
), loc
)));
1869 hashcode_block
.AddStatement (new StatementExpression (
1870 new CompoundAssign (Binary
.Operator
.ExclusiveOr
, hash_variable
,
1871 new Binary (Binary
.Operator
.RightShift
, hash_variable
, new IntConstant (17, loc
), loc
), loc
)));
1872 hashcode_block
.AddStatement (new StatementExpression (
1873 new CompoundAssign (Binary
.Operator
.Addition
, hash_variable
,
1874 new Binary (Binary
.Operator
.LeftShift
, hash_variable
, new IntConstant (5, loc
), loc
), loc
)));
1876 hashcode_block
.AddStatement (new Return (hash_variable
, loc
));
1877 hashcode
.Block
= hashcode_top
;
1879 AddMethod (hashcode
);
1882 // ToString () override
1885 ToplevelBlock tostring_block
= new ToplevelBlock (Compiler
, loc
);
1886 tostring_block
.AddStatement (new Return (string_concat
, loc
));
1887 tostring
.Block
= tostring_block
;
1889 AddMethod (tostring
);
1894 public override string GetSignatureForError ()
1896 return SignatureForError
;
1899 public IList
<AnonymousTypeParameter
> Parameters
{