2009-11-24 Jb Evain <jbevain@novell.com>
[mcs.git] / mcs / anonymous.cs
blob2f410cff091feae476fd116f62d36b5bce2739a4
1 //
2 // anonymous.cs: Support for anonymous methods and types
3 //
4 // Author:
5 // Miguel de Icaza (miguel@ximain.com)
6 // Marek Safar (marek.safar@gmail.com)
7 //
8 // Dual licensed under the terms of the MIT X11 or GNU GPL
9 // Copyright 2003-2008 Novell, Inc.
12 using System;
13 using System.Text;
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 ()
48 if (members_defined)
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)
66 this.Storey = storey;
67 this.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 ())
92 return false;
94 AnonymousMethodStorey parent = ((AnonymousMethodStorey) Parent).GetGenericStorey ();
95 if (parent != null)
96 member_type = parent.MutateType (member_type);
98 return true;
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)
124 // Nothing to clone
127 public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
129 // Nothing to mutate
133 // Unique storey ID
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;
147 // Hoisted this
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)
156 Parent = parent;
157 OriginalSourceBlock = block;
158 ID = unique_id++;
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);
179 f.Define ();
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);
188 if (!IsGeneric)
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);
193 AddField (f);
194 return f;
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);
201 AddField (f);
202 return f;
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)
228 return;
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.HoistedVariant != null)
242 return;
244 HoistedVariable var = new HoistedLocalVariable (this, local_info, GetVariableMangledName (local_info));
245 local_info.HoistedVariant = 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)
259 return;
261 if (hoisted_params == null)
262 hoisted_params = new ArrayList (2);
264 HoistedVariable expr = new HoistedParameter (this, param_ref);
265 param_ref.Parameter.HoistedVariant = expr;
266 hoisted_params.Add (expr);
269 public void ChangeParentStorey (AnonymousMethodStorey parentStorey)
271 Parent = parentStorey;
272 type_params = null;
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;
290 if (is_generic) {
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);
311 } else {
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);
317 e.Emit (ec);
319 Instance = new LocalTemporary (storey_type_expr.Type);
320 Instance.Store (ec);
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);
401 base.EmitType ();
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)
419 return null;
421 foreach (StoreyFieldPair sf in used_parent_storeys) {
422 if (sf.Storey == storey)
423 return sf.Field;
426 return null;
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
439 if (am == null)
440 return Instance;
443 // Access from anonymous method implemented as a static -> storey
445 if (am.Storey == null)
446 return Instance;
448 Field f = am.Storey.GetReferencedStoreyField (this);
449 if (f == null) {
450 if (am.Storey == this) {
452 // Access inside of same storey (S -> S)
454 return new CompilerGeneratedThis (TypeBuilder, Location);
457 // External field access
459 return Instance;
463 // Storey was cached to local field
465 FieldExpr f_ind = new FieldExpr (f.FieldBuilder, Location);
466 f_ind.InstanceExpression = new CompilerGeneratedThis (TypeBuilder, Location);
467 return f_ind;
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);
494 if (type.IsArray)
495 return MutateArrayType (type);
496 return 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 (TypeManager.IsBeingCompiled (method))
510 method = TypeBuilder.GetMethod (t, method);
511 else
512 method = (MethodInfo) MethodInfo.GetMethodFromHandle (method.MethodHandle, t.TypeHandle);
516 if (t_args == null || t_args.Length == 0)
517 return method;
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 (TypeManager.IsBeingCompiled (ctor))
532 return TypeBuilder.GetConstructor (t, ctor);
534 return (ConstructorInfo) ConstructorInfo.GetMethodFromHandle (ctor.MethodHandle, t.TypeHandle);
538 return ctor;
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 (TypeManager.IsBeingCompiled (field))
548 return TypeBuilder.GetField (t, field);
550 return FieldInfo.GetFieldFromHandle (field.FieldHandle, t.TypeHandle);
554 return field;
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);
566 } else {
567 return array;
570 int rank = array.GetArrayRank ();
571 if (rank == 1)
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)
581 return type;
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);
596 if (tp != null)
597 return tp.Type;
600 return type;
603 public ArrayList ReferencesFromChildrenBlock {
604 get { return children_references; }
607 public static void Reset ()
609 unique_id = 0;
613 public abstract class HoistedVariable
616 // Hoisted version of variable references used in expression
617 // tree has to be delayed until we know its location. The variable
618 // doesn't know its location until all stories are calculated
620 class ExpressionTreeVariableReference : Expression
622 readonly HoistedVariable hv;
624 public ExpressionTreeVariableReference (HoistedVariable hv)
626 this.hv = hv;
629 public override Expression CreateExpressionTree (ResolveContext ec)
631 throw new NotSupportedException ("ET");
634 protected override Expression DoResolve (ResolveContext ec)
636 eclass = ExprClass.Value;
637 type = TypeManager.expression_type_expr.Type;
638 return this;
641 public override void Emit (EmitContext ec)
643 ResolveContext rc = new ResolveContext (ec.MemberContext);
644 Expression e = hv.GetFieldExpression (ec).CreateExpressionTree (rc);
645 // This should never fail
646 e = e.Resolve (rc);
647 if (e != null)
648 e.Emit (ec);
652 protected readonly AnonymousMethodStorey storey;
653 protected Field field;
654 Hashtable cached_inner_access; // TODO: Hashtable is too heavyweight
655 FieldExpr cached_outer_access;
657 protected HoistedVariable (AnonymousMethodStorey storey, string name, Type type)
658 : this (storey, storey.AddCapturedVariable (name, type))
662 protected HoistedVariable (AnonymousMethodStorey storey, Field field)
664 this.storey = storey;
665 this.field = field;
668 public void AddressOf (EmitContext ec, AddressOp mode)
670 GetFieldExpression (ec).AddressOf (ec, mode);
673 public Expression CreateExpressionTree ()
675 return new ExpressionTreeVariableReference (this);
678 public void Emit (EmitContext ec)
680 GetFieldExpression (ec).Emit (ec);
684 // Creates field access expression for hoisted variable
686 protected FieldExpr GetFieldExpression (EmitContext ec)
688 if (ec.CurrentAnonymousMethod == null || ec.CurrentAnonymousMethod.Storey == null) {
689 if (cached_outer_access != null)
690 return cached_outer_access;
693 // When setting top-level hoisted variable in generic storey
694 // change storey generic types to method generic types (VAR -> MVAR)
696 cached_outer_access = storey.MemberName.IsGeneric ?
697 new FieldExpr (field.FieldBuilder, storey.Instance.Type, field.Location) :
698 new FieldExpr (field.FieldBuilder, field.Location);
700 cached_outer_access.InstanceExpression = storey.GetStoreyInstanceExpression (ec);
701 return cached_outer_access;
704 FieldExpr inner_access;
705 if (cached_inner_access != null) {
706 inner_access = (FieldExpr) cached_inner_access [ec.CurrentAnonymousMethod];
707 } else {
708 inner_access = null;
709 cached_inner_access = new Hashtable (4);
712 if (inner_access == null) {
713 inner_access = field.Parent.MemberName.IsGeneric ?
714 new FieldExpr (field.FieldBuilder, field.Parent.CurrentType, field.Location) :
715 new FieldExpr (field.FieldBuilder, field.Location);
717 inner_access.InstanceExpression = storey.GetStoreyInstanceExpression (ec);
718 cached_inner_access.Add (ec.CurrentAnonymousMethod, inner_access);
721 return inner_access;
724 public abstract void EmitSymbolInfo ();
726 public void Emit (EmitContext ec, bool leave_copy)
728 GetFieldExpression (ec).Emit (ec, leave_copy);
731 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
733 GetFieldExpression (ec).EmitAssign (ec, source, leave_copy, false);
737 class HoistedParameter : HoistedVariable
739 sealed class HoistedFieldAssign : Assign
741 public HoistedFieldAssign (Expression target, Expression source)
742 : base (target, source, source.Location)
746 protected override Expression ResolveConversions (ResolveContext ec)
749 // Implicit conversion check fails for hoisted type arguments
750 // as they are of different types (!!0 x !0)
752 return this;
756 readonly ParameterReference parameter;
758 public HoistedParameter (AnonymousMethodStorey scope, ParameterReference par)
759 : base (scope, par.Name, par.Type)
761 this.parameter = par;
764 public HoistedParameter (HoistedParameter hp, string name)
765 : base (hp.storey, name, hp.parameter.Type)
767 this.parameter = hp.parameter;
770 public void EmitHoistingAssignment (EmitContext ec)
773 // Remove hoisted redirection to emit assignment from original parameter
775 HoistedVariable temp = parameter.Parameter.HoistedVariant;
776 parameter.Parameter.HoistedVariant = null;
778 Assign a = new HoistedFieldAssign (GetFieldExpression (ec), parameter);
779 if (a.Resolve (new ResolveContext (ec.MemberContext)) != null)
780 a.EmitStatement (ec);
782 parameter.Parameter.HoistedVariant = temp;
785 public override void EmitSymbolInfo ()
787 SymbolWriter.DefineCapturedParameter (storey.ID, field.Name, field.Name);
790 public Field Field {
791 get { return field; }
795 class HoistedLocalVariable : HoistedVariable
797 readonly string name;
799 public HoistedLocalVariable (AnonymousMethodStorey scope, LocalInfo local, string name)
800 : base (scope, name, local.VariableType)
802 this.name = local.Name;
805 public override void EmitSymbolInfo ()
807 SymbolWriter.DefineCapturedLocal (storey.ID, name, field.Name);
811 public class HoistedThis : HoistedVariable
813 public HoistedThis (AnonymousMethodStorey storey, Field field)
814 : base (storey, field)
818 public void EmitHoistingAssignment (EmitContext ec)
820 SimpleAssign a = new SimpleAssign (GetFieldExpression (ec), new CompilerGeneratedThis (ec.CurrentType, field.Location));
821 if (a.Resolve (new ResolveContext (ec.MemberContext)) != null)
822 a.EmitStatement (ec);
825 public override void EmitSymbolInfo ()
827 SymbolWriter.DefineCapturedThis (storey.ID, field.Name);
830 public Field Field {
831 get { return field; }
836 // Anonymous method expression as created by parser
838 public class AnonymousMethodExpression : Expression
841 // Special conversion for nested expression tree lambdas
843 class Quote : ShimExpression
845 public Quote (Expression expr)
846 : base (expr)
850 public override Expression CreateExpressionTree (ResolveContext ec)
852 var args = new Arguments (1);
853 args.Add (new Argument (expr.CreateExpressionTree (ec)));
854 return CreateExpressionFactoryCall (ec, "Quote", args);
857 protected override Expression DoResolve (ResolveContext rc)
859 expr = expr.Resolve (rc);
860 if (expr == null)
861 return null;
863 eclass = expr.eclass;
864 type = expr.Type;
865 return this;
869 ListDictionary compatibles;
870 public ToplevelBlock Block;
872 public AnonymousMethodExpression (Location loc)
874 this.loc = loc;
875 this.compatibles = new ListDictionary ();
878 public override string ExprClassName {
879 get {
880 return "anonymous method";
884 public virtual bool HasExplicitParameters {
885 get {
886 return Parameters != ParametersCompiled.Undefined;
890 public ParametersCompiled Parameters {
891 get { return Block.Parameters; }
895 // Returns true if the body of lambda expression can be implicitly
896 // converted to the delegate of type `delegate_type'
898 public bool ImplicitStandardConversionExists (ResolveContext ec, Type delegate_type)
900 using (ec.With (ResolveContext.Options.InferReturnType, false)) {
901 using (ec.Set (ResolveContext.Options.ProbingMode)) {
902 return Compatible (ec, delegate_type) != null;
907 protected Type CompatibleChecks (ResolveContext ec, Type delegate_type)
909 if (TypeManager.IsDelegateType (delegate_type))
910 return delegate_type;
912 if (TypeManager.DropGenericTypeArguments (delegate_type) == TypeManager.expression_type) {
913 delegate_type = TypeManager.GetTypeArguments (delegate_type) [0];
914 if (TypeManager.IsDelegateType (delegate_type))
915 return delegate_type;
917 ec.Report.Error (835, loc, "Cannot convert `{0}' to an expression tree of non-delegate type `{1}'",
918 GetSignatureForError (), TypeManager.CSharpName (delegate_type));
919 return null;
922 ec.Report.Error (1660, loc, "Cannot convert `{0}' to non-delegate type `{1}'",
923 GetSignatureForError (), TypeManager.CSharpName (delegate_type));
924 return null;
927 protected bool VerifyExplicitParameters (ResolveContext ec, Type delegate_type, AParametersCollection parameters)
929 if (VerifyParameterCompatibility (ec, delegate_type, parameters, ec.IsInProbingMode))
930 return true;
932 if (!ec.IsInProbingMode)
933 ec.Report.Error (1661, loc,
934 "Cannot convert `{0}' to delegate type `{1}' since there is a parameter mismatch",
935 GetSignatureForError (), TypeManager.CSharpName (delegate_type));
937 return false;
940 protected bool VerifyParameterCompatibility (ResolveContext ec, Type delegate_type, AParametersCollection invoke_pd, bool ignore_errors)
942 if (Parameters.Count != invoke_pd.Count) {
943 if (ignore_errors)
944 return false;
946 ec.Report.Error (1593, loc, "Delegate `{0}' does not take `{1}' arguments",
947 TypeManager.CSharpName (delegate_type), Parameters.Count.ToString ());
948 return false;
951 bool has_implicit_parameters = !HasExplicitParameters;
952 bool error = false;
954 for (int i = 0; i < Parameters.Count; ++i) {
955 Parameter.Modifier p_mod = invoke_pd.FixedParameters [i].ModFlags;
956 if (Parameters.FixedParameters [i].ModFlags != p_mod && p_mod != Parameter.Modifier.PARAMS) {
957 if (ignore_errors)
958 return false;
960 if (p_mod == Parameter.Modifier.NONE)
961 ec.Report.Error (1677, loc, "Parameter `{0}' should not be declared with the `{1}' keyword",
962 (i + 1).ToString (), Parameter.GetModifierSignature (Parameters.FixedParameters [i].ModFlags));
963 else
964 ec.Report.Error (1676, loc, "Parameter `{0}' must be declared with the `{1}' keyword",
965 (i+1).ToString (), Parameter.GetModifierSignature (p_mod));
966 error = true;
969 if (has_implicit_parameters)
970 continue;
972 Type type = invoke_pd.Types [i];
974 // We assume that generic parameters are always inflated
975 if (TypeManager.IsGenericParameter (type))
976 continue;
978 if (TypeManager.HasElementType (type) && TypeManager.IsGenericParameter (TypeManager.GetElementType (type)))
979 continue;
981 if (invoke_pd.Types [i] != Parameters.Types [i]) {
982 if (ignore_errors)
983 return false;
985 ec.Report.Error (1678, loc, "Parameter `{0}' is declared as type `{1}' but should be `{2}'",
986 (i+1).ToString (),
987 TypeManager.CSharpName (Parameters.Types [i]),
988 TypeManager.CSharpName (invoke_pd.Types [i]));
989 error = true;
993 return !error;
997 // Infers type arguments based on explicit arguments
999 public bool ExplicitTypeInference (ResolveContext ec, TypeInferenceContext type_inference, Type delegate_type)
1001 if (!HasExplicitParameters)
1002 return false;
1004 if (!TypeManager.IsDelegateType (delegate_type)) {
1005 if (TypeManager.DropGenericTypeArguments (delegate_type) != TypeManager.expression_type)
1006 return false;
1008 delegate_type = TypeManager.GetTypeArguments (delegate_type) [0];
1009 if (!TypeManager.IsDelegateType (delegate_type))
1010 return false;
1013 AParametersCollection d_params = TypeManager.GetDelegateParameters (ec, delegate_type);
1014 if (d_params.Count != Parameters.Count)
1015 return false;
1017 for (int i = 0; i < Parameters.Count; ++i) {
1018 Type itype = d_params.Types [i];
1019 if (!TypeManager.IsGenericParameter (itype)) {
1020 if (!TypeManager.HasElementType (itype))
1021 continue;
1023 if (!TypeManager.IsGenericParameter (TypeManager.GetElementType (itype)))
1024 continue;
1026 type_inference.ExactInference (Parameters.Types [i], itype);
1028 return true;
1031 public Type InferReturnType (ResolveContext ec, TypeInferenceContext tic, Type delegate_type)
1033 AnonymousExpression am;
1034 using (ec.Set (ResolveContext.Options.ProbingMode | ResolveContext.Options.InferReturnType)) {
1035 am = CompatibleMethodBody (ec, tic, InternalType.Arglist, delegate_type);
1036 if (am != null)
1037 am = am.Compatible (ec);
1040 if (am == null)
1041 return null;
1043 return am.ReturnType;
1047 // Returns AnonymousMethod container if this anonymous method
1048 // expression can be implicitly converted to the delegate type `delegate_type'
1050 public Expression Compatible (ResolveContext ec, Type type)
1052 Expression am = (Expression) compatibles [type];
1053 if (am != null)
1054 return am;
1056 Type delegate_type = CompatibleChecks (ec, type);
1057 if (delegate_type == null)
1058 return null;
1061 // At this point its the first time we know the return type that is
1062 // needed for the anonymous method. We create the method here.
1065 MethodInfo invoke_mb = Delegate.GetInvokeMethod (ec.Compiler,
1066 ec.CurrentType, delegate_type);
1067 Type return_type = TypeManager.TypeToCoreType (invoke_mb.ReturnType);
1069 #if MS_COMPATIBLE
1070 Type[] g_args = delegate_type.GetGenericArguments ();
1071 if (return_type.IsGenericParameter)
1072 return_type = g_args [return_type.GenericParameterPosition];
1073 #endif
1076 // Second: the return type of the delegate must be compatible with
1077 // the anonymous type. Instead of doing a pass to examine the block
1078 // we satisfy the rule by setting the return type on the EmitContext
1079 // to be the delegate type return type.
1082 var body = CompatibleMethodBody (ec, null, return_type, delegate_type);
1083 if (body == null)
1084 return null;
1086 bool etree_conversion = delegate_type != type;
1088 try {
1089 if (etree_conversion) {
1090 if (ec.HasSet (ResolveContext.Options.ExpressionTreeConversion)) {
1092 // Nested expression tree lambda use same scope as parent
1093 // lambda, this also means no variable capturing between this
1094 // and parent scope
1096 am = body.Compatible (ec, ec.CurrentAnonymousMethod);
1099 // Quote nested expression tree
1101 if (am != null)
1102 am = new Quote (am);
1103 } else {
1104 int errors = ec.Report.Errors;
1106 using (ec.Set (ResolveContext.Options.ExpressionTreeConversion)) {
1107 am = body.Compatible (ec);
1111 // Rewrite expressions into expression tree when targeting Expression<T>
1113 if (am != null && errors == ec.Report.Errors)
1114 am = CreateExpressionTree (ec, delegate_type);
1116 } else {
1117 am = body.Compatible (ec);
1119 } catch (CompletionResult) {
1120 throw;
1121 } catch (Exception e) {
1122 throw new InternalErrorException (e, loc);
1125 if (!ec.IsInProbingMode)
1126 compatibles.Add (type, am == null ? EmptyExpression.Null : am);
1128 return am;
1131 protected virtual Expression CreateExpressionTree (ResolveContext ec, Type delegate_type)
1133 return CreateExpressionTree (ec);
1136 public override Expression CreateExpressionTree (ResolveContext ec)
1138 ec.Report.Error (1946, loc, "An anonymous method cannot be converted to an expression tree");
1139 return null;
1142 protected virtual ParametersCompiled ResolveParameters (ResolveContext ec, TypeInferenceContext tic, Type delegate_type)
1144 AParametersCollection delegate_parameters = TypeManager.GetDelegateParameters (ec, delegate_type);
1146 if (Parameters == ParametersCompiled.Undefined) {
1148 // We provide a set of inaccessible parameters
1150 Parameter[] fixedpars = new Parameter[delegate_parameters.Count];
1152 for (int i = 0; i < delegate_parameters.Count; i++) {
1153 Parameter.Modifier i_mod = delegate_parameters.FixedParameters [i].ModFlags;
1154 if (i_mod == Parameter.Modifier.OUT) {
1155 ec.Report.Error (1688, loc, "Cannot convert anonymous " +
1156 "method block without a parameter list " +
1157 "to delegate type `{0}' because it has " +
1158 "one or more `out' parameters.",
1159 TypeManager.CSharpName (delegate_type));
1160 return null;
1162 fixedpars[i] = new Parameter (
1163 null, null,
1164 delegate_parameters.FixedParameters [i].ModFlags, null, loc);
1167 return ParametersCompiled.CreateFullyResolved (fixedpars, delegate_parameters.Types);
1170 if (!VerifyExplicitParameters (ec, delegate_type, delegate_parameters)) {
1171 return null;
1174 return Parameters;
1177 protected override Expression DoResolve (ResolveContext ec)
1179 if (ec.HasSet (ResolveContext.Options.ConstantScope)) {
1180 ec.Report.Error (1706, loc, "Anonymous methods and lambda expressions cannot be used in the current context");
1181 return null;
1185 // Set class type, set type
1188 eclass = ExprClass.Value;
1191 // This hack means `The type is not accessible
1192 // anywhere', we depend on special conversion
1193 // rules.
1195 type = InternalType.AnonymousMethod;
1197 if ((Parameters != null) && !Parameters.Resolve (ec))
1198 return null;
1200 // FIXME: The emitted code isn't very careful about reachability
1201 // so, ensure we have a 'ret' at the end
1202 BlockContext bc = ec as BlockContext;
1203 if (bc != null && bc.CurrentBranching != null && bc.CurrentBranching.CurrentUsageVector.IsUnreachable)
1204 bc.NeedReturnLabel ();
1206 return this;
1209 public override void Emit (EmitContext ec)
1211 // nothing, as we only exist to not do anything.
1214 public static void Error_AddressOfCapturedVar (ResolveContext ec, IVariableReference var, Location loc)
1216 ec.Report.Error (1686, loc,
1217 "Local variable or parameter `{0}' cannot have their address taken and be used inside an anonymous method or lambda expression",
1218 var.Name);
1221 public override string GetSignatureForError ()
1223 return ExprClassName;
1226 AnonymousMethodBody CompatibleMethodBody (ResolveContext ec, TypeInferenceContext tic, Type return_type, Type delegate_type)
1228 ParametersCompiled p = ResolveParameters (ec, tic, delegate_type);
1229 if (p == null)
1230 return null;
1232 ToplevelBlock b = ec.IsInProbingMode ? (ToplevelBlock) Block.PerformClone () : Block;
1234 return CompatibleMethodFactory (return_type, delegate_type, p, b);
1238 protected virtual AnonymousMethodBody CompatibleMethodFactory (Type return_type, Type delegate_type, ParametersCompiled p, ToplevelBlock b)
1240 return new AnonymousMethodBody (p, b, return_type, delegate_type, loc);
1243 protected override void CloneTo (CloneContext clonectx, Expression t)
1245 AnonymousMethodExpression target = (AnonymousMethodExpression) t;
1247 target.Block = (ToplevelBlock) clonectx.LookupBlock (Block);
1252 // Abstract expression for any block which requires variables hoisting
1254 public abstract class AnonymousExpression : Expression
1256 protected class AnonymousMethodMethod : Method
1258 public readonly AnonymousExpression AnonymousMethod;
1259 public readonly AnonymousMethodStorey Storey;
1260 readonly string RealName;
1262 public AnonymousMethodMethod (DeclSpace parent, AnonymousExpression am, AnonymousMethodStorey storey,
1263 GenericMethod generic, TypeExpr return_type,
1264 int mod, string real_name, MemberName name,
1265 ParametersCompiled parameters)
1266 : base (parent, generic, return_type, mod | Modifiers.COMPILER_GENERATED,
1267 name, parameters, null)
1269 this.AnonymousMethod = am;
1270 this.Storey = storey;
1271 this.RealName = real_name;
1273 Parent.PartialContainer.AddMethod (this);
1274 Block = am.Block;
1277 public override EmitContext CreateEmitContext (ILGenerator ig)
1279 EmitContext ec = new EmitContext (this, ig, ReturnType);
1280 ec.CurrentAnonymousMethod = AnonymousMethod;
1281 if (AnonymousMethod.return_label != null) {
1282 ec.HasReturnLabel = true;
1283 ec.ReturnLabel = (Label) AnonymousMethod.return_label;
1286 return ec;
1289 protected override bool ResolveMemberType ()
1291 if (!base.ResolveMemberType ())
1292 return false;
1294 if (Storey != null && Storey.IsGeneric) {
1295 AnonymousMethodStorey gstorey = Storey.GetGenericStorey ();
1296 if (gstorey != null) {
1297 if (!Parameters.IsEmpty) {
1298 Type [] ptypes = Parameters.Types;
1299 for (int i = 0; i < ptypes.Length; ++i)
1300 ptypes [i] = gstorey.MutateType (ptypes [i]);
1303 member_type = gstorey.MutateType (member_type);
1307 return true;
1310 public override void Emit ()
1313 // Before emitting any code we have to change all MVAR references to VAR
1314 // when the method is of generic type and has hoisted variables
1316 if (Storey == Parent && Storey.IsGeneric) {
1317 AnonymousMethodStorey gstorey = Storey.GetGenericStorey ();
1318 if (gstorey != null) {
1319 block.MutateHoistedGenericType (gstorey);
1323 if (MethodBuilder == null) {
1324 Define ();
1327 base.Emit ();
1330 public override void EmitExtraSymbolInfo (SourceMethod source)
1332 source.SetRealMethodName (RealName);
1336 readonly ToplevelBlock block;
1338 public Type ReturnType;
1340 object return_label;
1342 protected AnonymousExpression (ToplevelBlock block, Type return_type, Location loc)
1344 this.ReturnType = return_type;
1345 this.block = block;
1346 this.loc = loc;
1349 public abstract string ContainerType { get; }
1350 public abstract bool IsIterator { get; }
1351 public abstract AnonymousMethodStorey Storey { get; }
1353 public AnonymousExpression Compatible (ResolveContext ec)
1355 return Compatible (ec, this);
1358 public AnonymousExpression Compatible (ResolveContext ec, AnonymousExpression ae)
1360 // TODO: Implement clone
1361 BlockContext aec = new BlockContext (ec.MemberContext, Block, ReturnType);
1362 aec.CurrentAnonymousMethod = ae;
1364 IDisposable aec_dispose = null;
1365 ResolveContext.Options flags = 0;
1366 if (ec.HasSet (ResolveContext.Options.InferReturnType)) {
1367 flags |= ResolveContext.Options.InferReturnType;
1368 aec.ReturnTypeInference = new TypeInferenceContext ();
1371 if (ec.IsInProbingMode)
1372 flags |= ResolveContext.Options.ProbingMode;
1374 if (ec.HasSet (ResolveContext.Options.FieldInitializerScope))
1375 flags |= ResolveContext.Options.FieldInitializerScope;
1377 if (ec.IsUnsafe)
1378 flags |= ResolveContext.Options.UnsafeScope;
1380 if (ec.HasSet (ResolveContext.Options.CheckedScope))
1381 flags |= ResolveContext.Options.CheckedScope;
1383 if (ec.HasSet (ResolveContext.Options.ExpressionTreeConversion))
1384 flags |= ResolveContext.Options.ExpressionTreeConversion;
1386 // HACK: Flag with 0 cannot be set
1387 if (flags != 0)
1388 aec_dispose = aec.Set (flags);
1390 bool res = Block.Resolve (ec.CurrentBranching, aec, Block.Parameters, null);
1392 if (aec.HasReturnLabel)
1393 return_label = aec.ReturnLabel;
1395 if (ec.HasSet (ResolveContext.Options.InferReturnType)) {
1396 aec.ReturnTypeInference.FixAllTypes (ec);
1397 ReturnType = aec.ReturnTypeInference.InferredTypeArguments [0];
1400 if (aec_dispose != null) {
1401 aec_dispose.Dispose ();
1404 return res ? this : null;
1407 public void SetHasThisAccess ()
1409 Block.HasCapturedThis = true;
1410 ExplicitBlock b = Block.Parent.Explicit;
1412 while (b != null) {
1413 if (b.HasCapturedThis)
1414 return;
1416 b.HasCapturedThis = true;
1417 b = b.Parent == null ? null : b.Parent.Explicit;
1422 // The block that makes up the body for the anonymous method
1424 public ToplevelBlock Block {
1425 get {
1426 return block;
1432 public class AnonymousMethodBody : AnonymousExpression
1434 protected readonly ParametersCompiled parameters;
1435 AnonymousMethodStorey storey;
1437 AnonymousMethodMethod method;
1438 Field am_cache;
1439 string block_name;
1441 static int unique_id;
1443 public AnonymousMethodBody (ParametersCompiled parameters,
1444 ToplevelBlock block, Type return_type, Type delegate_type,
1445 Location loc)
1446 : base (block, return_type, loc)
1448 this.type = delegate_type;
1449 this.parameters = parameters;
1452 public override string ContainerType {
1453 get { return "anonymous method"; }
1456 public override AnonymousMethodStorey Storey {
1457 get { return storey; }
1460 public override bool IsIterator {
1461 get { return false; }
1464 public override Expression CreateExpressionTree (ResolveContext ec)
1466 ec.Report.Error (1945, loc, "An expression tree cannot contain an anonymous method expression");
1467 return null;
1470 bool Define (ResolveContext ec)
1472 if (!Block.Resolved && Compatible (ec) == null)
1473 return false;
1475 if (block_name == null) {
1476 MemberCore mc = (MemberCore) ec.MemberContext;
1477 block_name = mc.MemberName.Basename;
1480 return true;
1484 // Creates a host for the anonymous method
1486 AnonymousMethodMethod DoCreateMethodHost (EmitContext ec)
1489 // Anonymous method body can be converted to
1491 // 1, an instance method in current scope when only `this' is hoisted
1492 // 2, a static method in current scope when neither `this' nor any variable is hoisted
1493 // 3, an instance method in compiler generated storey when any hoisted variable exists
1496 int modifiers;
1497 if (Block.HasCapturedVariable || Block.HasCapturedThis) {
1498 storey = FindBestMethodStorey ();
1499 modifiers = storey != null ? Modifiers.INTERNAL : Modifiers.PRIVATE;
1500 } else {
1501 if (ec.CurrentAnonymousMethod != null)
1502 storey = ec.CurrentAnonymousMethod.Storey;
1504 modifiers = Modifiers.STATIC | Modifiers.PRIVATE;
1507 TypeContainer parent = storey != null ? storey : ec.CurrentTypeDefinition;
1509 MemberCore mc = ec.MemberContext as MemberCore;
1510 string name = CompilerGeneratedClass.MakeName (parent != storey ? block_name : null,
1511 "m", null, unique_id++);
1513 MemberName member_name;
1514 GenericMethod generic_method;
1515 if (storey == null && mc.MemberName.IsGeneric) {
1516 member_name = new MemberName (name, mc.MemberName.TypeArguments.Clone (), Location);
1518 generic_method = new GenericMethod (parent.NamespaceEntry, parent, member_name,
1519 new TypeExpression (ReturnType, Location), parameters);
1521 ArrayList list = new ArrayList ();
1522 foreach (TypeParameter tparam in ec.CurrentTypeParameters) {
1523 if (tparam.Constraints != null)
1524 list.Add (tparam.Constraints.Clone ());
1526 generic_method.SetParameterInfo (list);
1527 } else {
1528 member_name = new MemberName (name, Location);
1529 generic_method = null;
1532 string real_name = String.Format (
1533 "{0}~{1}{2}", mc.GetSignatureForError (), GetSignatureForError (),
1534 parameters.GetSignatureForError ());
1536 return new AnonymousMethodMethod (parent,
1537 this, storey, generic_method, new TypeExpression (ReturnType, Location), modifiers,
1538 real_name, member_name, parameters);
1541 protected override Expression DoResolve (ResolveContext ec)
1543 if (!Define (ec))
1544 return null;
1546 eclass = ExprClass.Value;
1547 return this;
1550 public override void Emit (EmitContext ec)
1553 // Use same anonymous method implementation for scenarios where same
1554 // code is used from multiple blocks, e.g. field initializers
1556 if (method == null) {
1558 // Delay an anonymous method definition to avoid emitting unused code
1559 // for unreachable blocks or expression trees
1561 method = DoCreateMethodHost (ec);
1562 method.Define ();
1565 bool is_static = (method.ModFlags & Modifiers.STATIC) != 0;
1566 if (is_static && am_cache == null) {
1568 // Creates a field cache to store delegate instance if it's not generic
1570 if (!method.MemberName.IsGeneric) {
1571 TypeContainer parent = method.Parent.PartialContainer;
1572 int id = parent.Fields == null ? 0 : parent.Fields.Count;
1573 am_cache = new Field (parent, new TypeExpression (type, loc),
1574 Modifiers.STATIC | Modifiers.PRIVATE | Modifiers.COMPILER_GENERATED,
1575 new MemberName (CompilerGeneratedClass.MakeName (null, "f", "am$cache", id), loc), null);
1576 am_cache.Define ();
1577 parent.AddField (am_cache);
1578 } else {
1579 // TODO: Implement caching of generated generic static methods
1581 // Idea:
1583 // Some extra class is needed to capture variable generic type
1584 // arguments. Maybe we could re-use anonymous types, with a unique
1585 // anonymous method id, but they are quite heavy.
1587 // Consider : "() => typeof(T);"
1589 // We need something like
1590 // static class Wrap<Tn, Tm, DelegateType> {
1591 // public static DelegateType cache;
1592 // }
1594 // We then specialize local variable to capture all generic parameters
1595 // and delegate type, e.g. "Wrap<Ta, Tb, DelegateTypeInst> cache;"
1600 ILGenerator ig = ec.ig;
1601 Label l_initialized = ig.DefineLabel ();
1603 if (am_cache != null) {
1604 ig.Emit (OpCodes.Ldsfld, am_cache.FieldBuilder);
1605 ig.Emit (OpCodes.Brtrue_S, l_initialized);
1609 // Load method delegate implementation
1612 if (is_static) {
1613 ig.Emit (OpCodes.Ldnull);
1614 } else if (storey != null) {
1615 Expression e = storey.GetStoreyInstanceExpression (ec).Resolve (new ResolveContext (ec.MemberContext));
1616 if (e != null)
1617 e.Emit (ec);
1618 } else {
1619 ig.Emit (OpCodes.Ldarg_0);
1622 MethodInfo delegate_method = method.MethodBuilder;
1623 if (storey != null && storey.MemberName.IsGeneric) {
1624 Type t = storey.Instance.Type;
1627 // Mutate anonymous method instance type if we are in nested
1628 // hoisted generic anonymous method storey
1630 if (ec.CurrentAnonymousMethod != null &&
1631 ec.CurrentAnonymousMethod.Storey != null &&
1632 ec.CurrentAnonymousMethod.Storey.IsGeneric) {
1633 t = storey.GetGenericStorey ().MutateType (t);
1636 delegate_method = TypeBuilder.GetMethod (t, delegate_method);
1639 ig.Emit (OpCodes.Ldftn, delegate_method);
1641 ConstructorInfo constructor_method = Delegate.GetConstructor (ec.MemberContext.Compiler, ec.CurrentType, type);
1642 #if MS_COMPATIBLE
1643 if (type.IsGenericType && type is TypeBuilder)
1644 constructor_method = TypeBuilder.GetConstructor (type, constructor_method);
1645 #endif
1646 ig.Emit (OpCodes.Newobj, constructor_method);
1648 if (am_cache != null) {
1649 ig.Emit (OpCodes.Stsfld, am_cache.FieldBuilder);
1650 ig.MarkLabel (l_initialized);
1651 ig.Emit (OpCodes.Ldsfld, am_cache.FieldBuilder);
1656 // Look for the best storey for this anonymous method
1658 AnonymousMethodStorey FindBestMethodStorey ()
1661 // Use the nearest parent block which has a storey
1663 for (Block b = Block.Parent; b != null; b = b.Parent) {
1664 AnonymousMethodStorey s = b.Explicit.AnonymousMethodStorey;
1665 if (s != null)
1666 return s;
1669 return null;
1672 public override string GetSignatureForError ()
1674 return TypeManager.CSharpName (type);
1677 public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
1679 type = storey.MutateType (type);
1682 public static void Reset ()
1684 unique_id = 0;
1689 // Anonymous type container
1691 public class AnonymousTypeClass : CompilerGeneratedClass
1693 sealed class AnonymousParameters : ParametersCompiled
1695 public AnonymousParameters (CompilerContext ctx, params Parameter[] parameters)
1696 : base (ctx, parameters)
1700 protected override void ErrorDuplicateName (Parameter p, Report Report)
1702 Report.Error (833, p.Location, "`{0}': An anonymous type cannot have multiple properties with the same name",
1703 p.Name);
1707 static int types_counter;
1708 public const string ClassNamePrefix = "<>__AnonType";
1709 public const string SignatureForError = "anonymous type";
1711 readonly ArrayList parameters;
1713 private AnonymousTypeClass (DeclSpace parent, MemberName name, ArrayList parameters, Location loc)
1714 : base (parent, name, (RootContext.EvalMode ? Modifiers.PUBLIC : 0) | Modifiers.SEALED)
1716 this.parameters = parameters;
1719 public static AnonymousTypeClass Create (CompilerContext ctx, TypeContainer parent, ArrayList parameters, Location loc)
1721 string name = ClassNamePrefix + types_counter++;
1723 SimpleName [] t_args = new SimpleName [parameters.Count];
1724 TypeParameterName [] t_params = new TypeParameterName [parameters.Count];
1725 Parameter [] ctor_params = new Parameter [parameters.Count];
1726 for (int i = 0; i < parameters.Count; ++i) {
1727 AnonymousTypeParameter p = (AnonymousTypeParameter) parameters [i];
1729 t_args [i] = new SimpleName ("<" + p.Name + ">__T", p.Location);
1730 t_params [i] = new TypeParameterName (t_args [i].Name, null, p.Location);
1731 ctor_params [i] = new Parameter (t_args [i], p.Name, 0, null, p.Location);
1735 // Create generic anonymous type host with generic arguments
1736 // named upon properties names
1738 AnonymousTypeClass a_type = new AnonymousTypeClass (parent.NamespaceEntry.SlaveDeclSpace,
1739 new MemberName (name, new TypeArguments (t_params), loc), parameters, loc);
1741 if (parameters.Count > 0)
1742 a_type.SetParameterInfo (null);
1744 Constructor c = new Constructor (a_type, name, Modifiers.PUBLIC | Modifiers.DEBUGGER_HIDDEN,
1745 null, new AnonymousParameters (ctx, ctor_params), null, loc);
1746 c.Block = new ToplevelBlock (ctx, c.Parameters, loc);
1749 // Create fields and contructor body with field initialization
1751 bool error = false;
1752 for (int i = 0; i < parameters.Count; ++i) {
1753 AnonymousTypeParameter p = (AnonymousTypeParameter) parameters [i];
1755 Field f = new Field (a_type, t_args [i], Modifiers.PRIVATE | Modifiers.READONLY,
1756 new MemberName ("<" + p.Name + ">", p.Location), null);
1758 if (!a_type.AddField (f)) {
1759 error = true;
1760 continue;
1763 c.Block.AddStatement (new StatementExpression (
1764 new SimpleAssign (new MemberAccess (new This (p.Location), f.Name),
1765 c.Block.GetParameterReference (p.Name, p.Location))));
1767 ToplevelBlock get_block = new ToplevelBlock (ctx, p.Location);
1768 get_block.AddStatement (new Return (
1769 new MemberAccess (new This (p.Location), f.Name), p.Location));
1770 Accessor get_accessor = new Accessor (get_block, 0, null, null, p.Location);
1771 Property prop = new Property (a_type, t_args [i], Modifiers.PUBLIC,
1772 new MemberName (p.Name, p.Location), null, get_accessor, null, false);
1773 a_type.AddProperty (prop);
1776 if (error)
1777 return null;
1779 a_type.AddConstructor (c);
1780 return a_type;
1783 public static void Reset ()
1785 types_counter = 0;
1788 protected override bool AddToContainer (MemberCore symbol, string name)
1790 MemberCore mc = (MemberCore) defined_names [name];
1792 if (mc == null) {
1793 defined_names.Add (name, symbol);
1794 return true;
1797 Report.SymbolRelatedToPreviousError (mc);
1798 return false;
1801 void DefineOverrides ()
1803 Location loc = Location;
1805 Method equals = new Method (this, null, TypeManager.system_boolean_expr,
1806 Modifiers.PUBLIC | Modifiers.OVERRIDE | Modifiers.DEBUGGER_HIDDEN, new MemberName ("Equals", loc),
1807 Mono.CSharp.ParametersCompiled.CreateFullyResolved (new Parameter (null, "obj", 0, null, loc), TypeManager.object_type), null);
1809 Method tostring = new Method (this, null, TypeManager.system_string_expr,
1810 Modifiers.PUBLIC | Modifiers.OVERRIDE | Modifiers.DEBUGGER_HIDDEN, new MemberName ("ToString", loc),
1811 Mono.CSharp.ParametersCompiled.EmptyReadOnlyParameters, null);
1813 ToplevelBlock equals_block = new ToplevelBlock (Compiler, equals.Parameters, loc);
1814 TypeExpr current_type;
1815 if (IsGeneric)
1816 current_type = new GenericTypeExpr (this, loc);
1817 else
1818 current_type = new TypeExpression (TypeBuilder, loc);
1820 equals_block.AddVariable (current_type, "other", loc);
1821 LocalVariableReference other_variable = new LocalVariableReference (equals_block, "other", loc);
1823 MemberAccess system_collections_generic = new MemberAccess (new MemberAccess (
1824 new QualifiedAliasMember ("global", "System", loc), "Collections", loc), "Generic", loc);
1826 Expression rs_equals = null;
1827 Expression string_concat = new StringConstant ("{", loc);
1828 Expression rs_hashcode = new IntConstant (-2128831035, loc);
1829 for (int i = 0; i < parameters.Count; ++i) {
1830 AnonymousTypeParameter p = (AnonymousTypeParameter) parameters [i];
1831 Field f = (Field) Fields [i];
1833 MemberAccess equality_comparer = new MemberAccess (new MemberAccess (
1834 system_collections_generic, "EqualityComparer",
1835 new TypeArguments (new SimpleName (TypeParameters [i].Name, loc)), loc),
1836 "Default", loc);
1838 Arguments arguments_equal = new Arguments (2);
1839 arguments_equal.Add (new Argument (new MemberAccess (new This (f.Location), f.Name)));
1840 arguments_equal.Add (new Argument (new MemberAccess (other_variable, f.Name)));
1842 Expression field_equal = new Invocation (new MemberAccess (equality_comparer,
1843 "Equals", loc), arguments_equal);
1845 Arguments arguments_hashcode = new Arguments (1);
1846 arguments_hashcode.Add (new Argument (new MemberAccess (new This (f.Location), f.Name)));
1847 Expression field_hashcode = new Invocation (new MemberAccess (equality_comparer,
1848 "GetHashCode", loc), arguments_hashcode);
1850 IntConstant FNV_prime = new IntConstant (16777619, loc);
1851 rs_hashcode = new Binary (Binary.Operator.Multiply,
1852 new Binary (Binary.Operator.ExclusiveOr, rs_hashcode, field_hashcode),
1853 FNV_prime);
1855 Expression field_to_string = new Conditional (new BooleanExpression (new Binary (Binary.Operator.Inequality,
1856 new MemberAccess (new This (f.Location), f.Name), new NullLiteral (loc))),
1857 new Invocation (new MemberAccess (
1858 new MemberAccess (new This (f.Location), f.Name), "ToString"), null),
1859 new StringConstant (string.Empty, loc));
1861 if (rs_equals == null) {
1862 rs_equals = field_equal;
1863 string_concat = new Binary (Binary.Operator.Addition,
1864 string_concat,
1865 new Binary (Binary.Operator.Addition,
1866 new StringConstant (" " + p.Name + " = ", loc),
1867 field_to_string));
1868 continue;
1872 // Implementation of ToString () body using string concatenation
1874 string_concat = new Binary (Binary.Operator.Addition,
1875 new Binary (Binary.Operator.Addition,
1876 string_concat,
1877 new StringConstant (", " + p.Name + " = ", loc)),
1878 field_to_string);
1880 rs_equals = new Binary (Binary.Operator.LogicalAnd, rs_equals, field_equal);
1883 string_concat = new Binary (Binary.Operator.Addition,
1884 string_concat,
1885 new StringConstant (" }", loc));
1888 // Equals (object obj) override
1890 LocalVariableReference other_variable_assign = new LocalVariableReference (equals_block, "other", loc);
1891 equals_block.AddStatement (new StatementExpression (
1892 new SimpleAssign (other_variable_assign,
1893 new As (equals_block.GetParameterReference ("obj", loc),
1894 current_type, loc), loc)));
1896 Expression equals_test = new Binary (Binary.Operator.Inequality, other_variable, new NullLiteral (loc));
1897 if (rs_equals != null)
1898 equals_test = new Binary (Binary.Operator.LogicalAnd, equals_test, rs_equals);
1899 equals_block.AddStatement (new Return (equals_test, loc));
1901 equals.Block = equals_block;
1902 equals.Define ();
1903 AddMethod (equals);
1906 // GetHashCode () override
1908 Method hashcode = new Method (this, null, TypeManager.system_int32_expr,
1909 Modifiers.PUBLIC | Modifiers.OVERRIDE | Modifiers.DEBUGGER_HIDDEN,
1910 new MemberName ("GetHashCode", loc),
1911 Mono.CSharp.ParametersCompiled.EmptyReadOnlyParameters, null);
1914 // Modified FNV with good avalanche behavior and uniform
1915 // distribution with larger hash sizes.
1917 // const int FNV_prime = 16777619;
1918 // int hash = (int) 2166136261;
1919 // foreach (int d in data)
1920 // hash = (hash ^ d) * FNV_prime;
1921 // hash += hash << 13;
1922 // hash ^= hash >> 7;
1923 // hash += hash << 3;
1924 // hash ^= hash >> 17;
1925 // hash += hash << 5;
1927 ToplevelBlock hashcode_top = new ToplevelBlock (Compiler, loc);
1928 Block hashcode_block = new Block (hashcode_top);
1929 hashcode_top.AddStatement (new Unchecked (hashcode_block));
1931 hashcode_block.AddVariable (TypeManager.system_int32_expr, "hash", loc);
1932 LocalVariableReference hash_variable = new LocalVariableReference (hashcode_block, "hash", loc);
1933 LocalVariableReference hash_variable_assign = new LocalVariableReference (hashcode_block, "hash", loc);
1934 hashcode_block.AddStatement (new StatementExpression (
1935 new SimpleAssign (hash_variable_assign, rs_hashcode)));
1937 hashcode_block.AddStatement (new StatementExpression (
1938 new CompoundAssign (Binary.Operator.Addition, hash_variable,
1939 new Binary (Binary.Operator.LeftShift, hash_variable, new IntConstant (13, loc)))));
1940 hashcode_block.AddStatement (new StatementExpression (
1941 new CompoundAssign (Binary.Operator.ExclusiveOr, hash_variable,
1942 new Binary (Binary.Operator.RightShift, hash_variable, new IntConstant (7, loc)))));
1943 hashcode_block.AddStatement (new StatementExpression (
1944 new CompoundAssign (Binary.Operator.Addition, hash_variable,
1945 new Binary (Binary.Operator.LeftShift, hash_variable, new IntConstant (3, loc)))));
1946 hashcode_block.AddStatement (new StatementExpression (
1947 new CompoundAssign (Binary.Operator.ExclusiveOr, hash_variable,
1948 new Binary (Binary.Operator.RightShift, hash_variable, new IntConstant (17, loc)))));
1949 hashcode_block.AddStatement (new StatementExpression (
1950 new CompoundAssign (Binary.Operator.Addition, hash_variable,
1951 new Binary (Binary.Operator.LeftShift, hash_variable, new IntConstant (5, loc)))));
1953 hashcode_block.AddStatement (new Return (hash_variable, loc));
1954 hashcode.Block = hashcode_top;
1955 hashcode.Define ();
1956 AddMethod (hashcode);
1959 // ToString () override
1962 ToplevelBlock tostring_block = new ToplevelBlock (Compiler, loc);
1963 tostring_block.AddStatement (new Return (string_concat, loc));
1964 tostring.Block = tostring_block;
1965 tostring.Define ();
1966 AddMethod (tostring);
1969 public override bool Define ()
1971 if (!base.Define ())
1972 return false;
1974 DefineOverrides ();
1975 return true;
1978 public override string GetSignatureForError ()
1980 return SignatureForError;
1983 public ArrayList Parameters {
1984 get {
1985 return parameters;