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-2011 Novell, Inc.
10 // Copyright 2011 Xamarin Inc
14 using System.Collections.Generic;
15 using Mono.CompilerServices.SymbolWriter;
16 using System.Diagnostics;
19 using IKVM.Reflection;
20 using IKVM.Reflection.Emit;
22 using System.Reflection;
23 using System.Reflection.Emit;
26 namespace Mono.CSharp {
28 public abstract class CompilerGeneratedContainer : ClassOrStruct
30 protected CompilerGeneratedContainer (TypeContainer parent, MemberName name, Modifiers mod)
31 : this (parent, name, mod, MemberKind.Class)
35 protected CompilerGeneratedContainer (TypeContainer parent, MemberName name, Modifiers mod, MemberKind kind)
36 : base (parent, name, null, kind)
38 Debug.Assert ((mod & Modifiers.AccessibilityMask) != 0);
40 ModFlags = mod | Modifiers.COMPILER_GENERATED | Modifiers.SEALED;
41 spec = new TypeSpec (Kind, null, this, null, ModFlags);
44 protected void CheckMembersDefined ()
46 if (HasMembersDefined)
47 throw new InternalErrorException ("Helper class already defined!");
50 protected override bool DoDefineMembers ()
52 if (Kind == MemberKind.Class && !IsStatic && !PartialContainer.HasInstanceConstructor) {
53 DefineDefaultConstructor (false);
56 return base.DoDefineMembers ();
59 protected static MemberName MakeMemberName (MemberBase host, string name, int unique_id, TypeParameters tparams, Location loc)
61 string host_name = host == null ? null : host is InterfaceMemberBase ? ((InterfaceMemberBase)host).GetFullName (host.MemberName) : host.MemberName.Name;
62 string tname = MakeName (host_name, "c", name, unique_id);
63 TypeParameters args = null;
64 if (tparams != null) {
65 args = new TypeParameters (tparams.Count);
67 // Type parameters will be filled later when we have TypeContainer
68 // instance, for now we need only correct arity to create valid name
69 for (int i = 0; i < tparams.Count; ++i)
70 args.Add ((TypeParameter) null);
73 return new MemberName (tname, args, loc);
76 public static string MakeName (string host, string typePrefix, string name, int id)
78 return "<" + host + ">" + typePrefix + "__" + name + id.ToString ("X");
81 protected override TypeSpec[] ResolveBaseTypes (out FullNamedExpression base_class)
83 base_type = Compiler.BuiltinTypes.Object;
90 public class HoistedStoreyClass : CompilerGeneratedContainer
92 public sealed class HoistedField : Field
94 public HoistedField (HoistedStoreyClass parent, FullNamedExpression type, Modifiers mod, string name,
95 Attributes attrs, Location loc)
96 : base (parent, type, mod, new MemberName (name, loc), attrs)
100 protected override bool ResolveMemberType ()
102 if (!base.ResolveMemberType ())
105 HoistedStoreyClass parent = ((HoistedStoreyClass) Parent).GetGenericStorey ();
106 if (parent != null && parent.Mutator != null)
107 member_type = parent.Mutator.Mutate (MemberType);
113 protected TypeParameterMutator mutator;
115 public HoistedStoreyClass (TypeDefinition parent, MemberName name, TypeParameters tparams, Modifiers mods, MemberKind kind)
116 : base (parent, name, mods | Modifiers.PRIVATE, kind)
119 if (tparams != null) {
120 var type_params = name.TypeParameters;
121 var src = new TypeParameterSpec[tparams.Count];
122 var dst = new TypeParameterSpec[tparams.Count];
124 for (int i = 0; i < tparams.Count; ++i) {
125 type_params[i] = tparams[i].CreateHoistedCopy (spec);
127 src[i] = tparams[i].Type;
128 dst[i] = type_params[i].Type;
131 // A copy is not enough, inflate any type parameter constraints
132 // using a new type parameters
133 var inflator = new TypeParameterInflator (this, null, src, dst);
134 for (int i = 0; i < tparams.Count; ++i) {
135 src[i].InflateConstraints (inflator, dst[i]);
138 mutator = new TypeParameterMutator (tparams, type_params);
144 public TypeParameterMutator Mutator {
155 public HoistedStoreyClass GetGenericStorey ()
157 TypeContainer storey = this;
158 while (storey != null && storey.CurrentTypeParameters == null)
159 storey = storey.Parent;
161 return storey as HoistedStoreyClass;
167 // Anonymous method storey is created when an anonymous method uses
168 // variable or parameter from outer scope. They are then hoisted to
169 // anonymous method storey (captured)
171 public class AnonymousMethodStorey : HoistedStoreyClass
173 struct StoreyFieldPair
175 public readonly AnonymousMethodStorey Storey;
176 public readonly Field Field;
178 public StoreyFieldPair (AnonymousMethodStorey storey, Field field)
180 this.Storey = storey;
186 // Needed to delay hoisted _this_ initialization. When an anonymous
187 // method is used inside ctor and _this_ is hoisted, base ctor has to
188 // be called first, otherwise _this_ will be initialized with
189 // uninitialized value.
191 sealed class ThisInitializer : Statement
193 readonly HoistedThis hoisted_this;
195 public ThisInitializer (HoistedThis hoisted_this)
197 this.hoisted_this = hoisted_this;
200 protected override void DoEmit (EmitContext ec)
202 hoisted_this.EmitAssign (ec, new CompilerGeneratedThis (ec.CurrentType, loc), false, false);
205 protected override void CloneTo (CloneContext clonectx, Statement target)
212 public readonly int ID;
214 public readonly ExplicitBlock OriginalSourceBlock;
216 // A list of StoreyFieldPair with local field keeping parent storey instance
217 List<StoreyFieldPair> used_parent_storeys;
218 List<ExplicitBlock> children_references;
220 // A list of hoisted parameters
221 protected List<HoistedParameter> hoisted_params;
222 List<HoistedParameter> hoisted_local_params;
223 protected List<HoistedVariable> hoisted_locals;
226 protected HoistedThis hoisted_this;
228 // Local variable which holds this storey instance
229 public Expression Instance;
231 bool initialize_hoisted_this;
233 public AnonymousMethodStorey (ExplicitBlock block, TypeDefinition parent, MemberBase host, TypeParameters tparams, string name, MemberKind kind)
234 : base (parent, MakeMemberName (host, name, parent.Module.CounterAnonymousContainers, tparams, block.StartLocation),
237 OriginalSourceBlock = block;
238 ID = parent.Module.CounterAnonymousContainers++;
241 public void AddCapturedThisField (EmitContext ec)
243 TypeExpr type_expr = new TypeExpression (ec.CurrentType, Location);
244 Field f = AddCompilerGeneratedField ("$this", type_expr);
245 hoisted_this = new HoistedThis (this, f);
247 initialize_hoisted_this = true;
250 public Field AddCapturedVariable (string name, TypeSpec type)
252 CheckMembersDefined ();
254 FullNamedExpression field_type = new TypeExpression (type, Location);
255 if (!spec.IsGenericOrParentIsGeneric)
256 return AddCompilerGeneratedField (name, field_type);
258 const Modifiers mod = Modifiers.INTERNAL | Modifiers.COMPILER_GENERATED;
259 Field f = new HoistedField (this, field_type, mod, name, null, Location);
264 protected Field AddCompilerGeneratedField (string name, FullNamedExpression type)
266 return AddCompilerGeneratedField (name, type, false);
269 protected Field AddCompilerGeneratedField (string name, FullNamedExpression type, bool privateAccess)
271 Modifiers mod = Modifiers.COMPILER_GENERATED | (privateAccess ? Modifiers.PRIVATE : Modifiers.INTERNAL);
272 Field f = new Field (this, type, mod, new MemberName (name, Location), null);
278 // Creates a link between hoisted variable block and the anonymous method storey
280 // An anonymous method can reference variables from any outer block, but they are
281 // hoisted in their own ExplicitBlock. When more than one block is referenced we
282 // need to create another link between those variable storeys
284 public void AddReferenceFromChildrenBlock (ExplicitBlock block)
286 if (children_references == null)
287 children_references = new List<ExplicitBlock> ();
289 if (!children_references.Contains (block))
290 children_references.Add (block);
293 public void AddParentStoreyReference (EmitContext ec, AnonymousMethodStorey storey)
295 CheckMembersDefined ();
297 if (used_parent_storeys == null)
298 used_parent_storeys = new List<StoreyFieldPair> ();
299 else if (used_parent_storeys.Exists (i => i.Storey == storey))
302 TypeExpr type_expr = storey.CreateStoreyTypeExpression (ec);
303 Field f = AddCompilerGeneratedField ("<>f__ref$" + storey.ID, type_expr);
304 used_parent_storeys.Add (new StoreyFieldPair (storey, f));
307 public void CaptureLocalVariable (ResolveContext ec, LocalVariable localVariable)
309 if (this is StateMachine) {
310 if (ec.CurrentBlock.ParametersBlock != localVariable.Block.ParametersBlock)
311 ec.CurrentBlock.Explicit.HasCapturedVariable = true;
313 ec.CurrentBlock.Explicit.HasCapturedVariable = true;
316 var hoisted = localVariable.HoistedVariant;
317 if (hoisted != null && hoisted.Storey != this && hoisted.Storey is StateMachine) {
319 // Variable is already hoisted but we need it in storey which can be shared
321 hoisted.Storey.hoisted_locals.Remove (hoisted);
322 hoisted.Storey.Members.Remove (hoisted.Field);
326 if (hoisted == null) {
327 hoisted = new HoistedLocalVariable (this, localVariable, GetVariableMangledName (localVariable));
328 localVariable.HoistedVariant = hoisted;
330 if (hoisted_locals == null)
331 hoisted_locals = new List<HoistedVariable> ();
333 hoisted_locals.Add (hoisted);
336 if (ec.CurrentBlock.Explicit != localVariable.Block.Explicit && !(hoisted.Storey is StateMachine))
337 hoisted.Storey.AddReferenceFromChildrenBlock (ec.CurrentBlock.Explicit);
340 public void CaptureParameter (ResolveContext ec, ParametersBlock.ParameterInfo parameterInfo, ParameterReference parameterReference)
342 if (!(this is StateMachine)) {
343 ec.CurrentBlock.Explicit.HasCapturedVariable = true;
346 var hoisted = parameterInfo.Parameter.HoistedVariant;
348 if (parameterInfo.Block.StateMachine != null) {
350 // Another storey in same block exists but state machine does not
351 // have parameter captured. We need to add it there as well to
352 // proxy parameter value correctly.
354 if (hoisted == null && parameterInfo.Block.StateMachine != this) {
355 var storey = parameterInfo.Block.StateMachine;
357 hoisted = new HoistedParameter (storey, parameterReference);
358 parameterInfo.Parameter.HoistedVariant = hoisted;
360 if (storey.hoisted_params == null)
361 storey.hoisted_params = new List<HoistedParameter> ();
363 storey.hoisted_params.Add (hoisted);
367 // Lift captured parameter from value type storey to reference type one. Otherwise
368 // any side effects would be done on a copy
370 if (hoisted != null && hoisted.Storey != this && hoisted.Storey is StateMachine) {
371 if (hoisted_local_params == null)
372 hoisted_local_params = new List<HoistedParameter> ();
374 hoisted_local_params.Add (hoisted);
379 if (hoisted == null) {
380 hoisted = new HoistedParameter (this, parameterReference);
381 parameterInfo.Parameter.HoistedVariant = hoisted;
383 if (hoisted_params == null)
384 hoisted_params = new List<HoistedParameter> ();
386 hoisted_params.Add (hoisted);
390 // Register link between current block and parameter storey. It will
391 // be used when setting up storey definition to deploy storey reference
392 // when parameters are used from multiple blocks
394 if (ec.CurrentBlock.Explicit != parameterInfo.Block) {
395 hoisted.Storey.AddReferenceFromChildrenBlock (ec.CurrentBlock.Explicit);
399 TypeExpr CreateStoreyTypeExpression (EmitContext ec)
402 // Create an instance of storey type
404 TypeExpr storey_type_expr;
405 if (CurrentTypeParameters != null) {
407 // Use current method type parameter (MVAR) for top level storey only. All
408 // nested storeys use class type parameter (VAR)
410 var tparams = ec.CurrentAnonymousMethod != null && ec.CurrentAnonymousMethod.Storey != null ?
411 ec.CurrentAnonymousMethod.Storey.CurrentTypeParameters :
412 ec.CurrentTypeParameters;
414 TypeArguments targs = new TypeArguments ();
417 // Use type parameter name instead of resolved type parameter
418 // specification to resolve to correctly nested type parameters
420 for (int i = 0; i < tparams.Count; ++i)
421 targs.Add (new SimpleName (tparams [i].Name, Location)); // new TypeParameterExpr (tparams[i], Location));
423 storey_type_expr = new GenericTypeExpr (Definition, targs, Location);
425 storey_type_expr = new TypeExpression (CurrentType, Location);
428 return storey_type_expr;
431 public void SetNestedStoryParent (AnonymousMethodStorey parentStorey)
433 Parent = parentStorey;
434 spec.IsGeneric = false;
435 spec.DeclaringType = parentStorey.CurrentType;
436 MemberName.TypeParameters = null;
439 protected override bool DoResolveTypeParameters ()
441 // Although any storey can have type parameters they are all clones of method type
442 // parameters therefore have to mutate MVAR references in any of cloned constraints
443 if (CurrentTypeParameters != null) {
444 for (int i = 0; i < CurrentTypeParameters.Count; ++i) {
445 var spec = CurrentTypeParameters[i].Type;
446 spec.BaseType = mutator.Mutate (spec.BaseType);
447 if (spec.InterfacesDefined != null) {
448 var mutated = new TypeSpec[spec.InterfacesDefined.Length];
449 for (int ii = 0; ii < mutated.Length; ++ii) {
450 mutated[ii] = mutator.Mutate (spec.InterfacesDefined[ii]);
453 spec.InterfacesDefined = mutated;
456 if (spec.TypeArguments != null) {
457 spec.TypeArguments = mutator.Mutate (spec.TypeArguments);
463 // Update parent cache as we most likely passed the point
464 // where the cache was constructed
466 Parent.CurrentType.MemberCache.AddMember (this.spec);
472 // Initializes all hoisted variables
474 public void EmitStoreyInstantiation (EmitContext ec, ExplicitBlock block)
476 // There can be only one instance variable for each storey type
477 if (Instance != null)
478 throw new InternalErrorException ();
481 // Create an instance of this storey
483 ResolveContext rc = new ResolveContext (ec.MemberContext);
484 rc.CurrentBlock = block;
486 var storey_type_expr = CreateStoreyTypeExpression (ec);
487 var source = new New (storey_type_expr, null, Location).Resolve (rc);
490 // When the current context is async (or iterator) lift local storey
491 // instantiation to the currect storey
493 if (ec.CurrentAnonymousMethod is StateMachineInitializer && (block.HasYield || block.HasAwait)) {
495 // Unfortunately, normal capture mechanism could not be used because we are
496 // too late in the pipeline and standart assign cannot be used either due to
497 // recursive nature of GetStoreyInstanceExpression
499 var field = ec.CurrentAnonymousMethod.Storey.AddCompilerGeneratedField (
500 LocalVariable.GetCompilerGeneratedName (block), storey_type_expr, true);
505 var fexpr = new FieldExpr (field, Location);
506 fexpr.InstanceExpression = new CompilerGeneratedThis (ec.CurrentType, Location);
507 fexpr.EmitAssign (ec, source, false, false);
510 var local = TemporaryVariableReference.Create (source.Type, block, Location);
511 if (source.Type.IsStruct) {
512 local.LocalInfo.CreateBuilder (ec);
514 local.EmitAssign (ec, source);
520 EmitHoistedFieldsInitialization (rc, ec);
522 // TODO: Implement properly
523 //SymbolWriter.DefineScopeVariable (ID, Instance.Builder);
526 void EmitHoistedFieldsInitialization (ResolveContext rc, EmitContext ec)
529 // Initialize all storey reference fields by using local or hoisted variables
531 if (used_parent_storeys != null) {
532 foreach (StoreyFieldPair sf in used_parent_storeys) {
534 // Get instance expression of storey field
536 Expression instace_expr = GetStoreyInstanceExpression (ec);
537 var fs = sf.Field.Spec;
538 if (TypeManager.IsGenericType (instace_expr.Type))
539 fs = MemberCache.GetMember (instace_expr.Type, fs);
541 FieldExpr f_set_expr = new FieldExpr (fs, Location);
542 f_set_expr.InstanceExpression = instace_expr;
544 // TODO: CompilerAssign expression
545 SimpleAssign a = new SimpleAssign (f_set_expr, sf.Storey.GetStoreyInstanceExpression (ec));
546 if (a.Resolve (rc) != null)
547 a.EmitStatement (ec);
552 // Initialize hoisted `this' only once, everywhere else will be
553 // referenced indirectly
555 if (initialize_hoisted_this) {
556 rc.CurrentBlock.AddScopeStatement (new ThisInitializer (hoisted_this));
560 // Setting currect anonymous method to null blocks any further variable hoisting
562 AnonymousExpression ae = ec.CurrentAnonymousMethod;
563 ec.CurrentAnonymousMethod = null;
565 if (hoisted_params != null) {
566 EmitHoistedParameters (ec, hoisted_params);
569 ec.CurrentAnonymousMethod = ae;
572 protected virtual void EmitHoistedParameters (EmitContext ec, List<HoistedParameter> hoisted)
574 foreach (HoistedParameter hp in hoisted) {
579 // Parameters could be proxied via local fields for value type storey
581 if (hoisted_local_params != null) {
582 var local_param = hoisted_local_params.Find (l => l.Parameter.Parameter == hp.Parameter.Parameter);
583 var source = new FieldExpr (local_param.Field, Location);
584 source.InstanceExpression = new CompilerGeneratedThis (CurrentType, Location);
585 hp.EmitAssign (ec, source, false, false);
589 hp.EmitHoistingAssignment (ec);
594 // Returns a field which holds referenced storey instance
596 Field GetReferencedStoreyField (AnonymousMethodStorey storey)
598 if (used_parent_storeys == null)
601 foreach (StoreyFieldPair sf in used_parent_storeys) {
602 if (sf.Storey == storey)
610 // Creates storey instance expression regardless of currect IP
612 public Expression GetStoreyInstanceExpression (EmitContext ec)
614 AnonymousExpression am = ec.CurrentAnonymousMethod;
617 // Access from original block -> storey
623 // Access from anonymous method implemented as a static -> storey
625 if (am.Storey == null)
628 Field f = am.Storey.GetReferencedStoreyField (this);
630 if (am.Storey == this) {
632 // Access from inside of same storey (S -> S)
634 return new CompilerGeneratedThis (CurrentType, Location);
638 // External field access
644 // Storey was cached to local field
646 FieldExpr f_ind = new FieldExpr (f, Location);
647 f_ind.InstanceExpression = new CompilerGeneratedThis (CurrentType, Location);
651 protected virtual string GetVariableMangledName (LocalVariable local_info)
654 // No need to mangle anonymous method hoisted variables cause they
655 // are hoisted in their own scopes
657 return local_info.Name;
660 public HoistedThis HoistedThis {
665 hoisted_this = value;
669 public IList<ExplicitBlock> ReferencesFromChildrenBlock {
670 get { return children_references; }
674 public abstract class HoistedVariable
677 // Hoisted version of variable references used in expression
678 // tree has to be delayed until we know its location. The variable
679 // doesn't know its location until all stories are calculated
681 class ExpressionTreeVariableReference : Expression
683 readonly HoistedVariable hv;
685 public ExpressionTreeVariableReference (HoistedVariable hv)
690 public override bool ContainsEmitWithAwait ()
695 public override Expression CreateExpressionTree (ResolveContext ec)
697 return hv.CreateExpressionTree ();
700 protected override Expression DoResolve (ResolveContext ec)
702 eclass = ExprClass.Value;
703 type = ec.Module.PredefinedTypes.Expression.Resolve ();
707 public override void Emit (EmitContext ec)
709 ResolveContext rc = new ResolveContext (ec.MemberContext);
710 Expression e = hv.GetFieldExpression (ec).CreateExpressionTree (rc, false);
711 // This should never fail
718 protected readonly AnonymousMethodStorey storey;
719 protected Field field;
720 Dictionary<AnonymousExpression, FieldExpr> cached_inner_access; // TODO: Hashtable is too heavyweight
721 FieldExpr cached_outer_access;
723 protected HoistedVariable (AnonymousMethodStorey storey, string name, TypeSpec type)
724 : this (storey, storey.AddCapturedVariable (name, type))
728 protected HoistedVariable (AnonymousMethodStorey storey, Field field)
730 this.storey = storey;
740 public AnonymousMethodStorey Storey {
746 public void AddressOf (EmitContext ec, AddressOp mode)
748 GetFieldExpression (ec).AddressOf (ec, mode);
751 public Expression CreateExpressionTree ()
753 return new ExpressionTreeVariableReference (this);
756 public void Emit (EmitContext ec)
758 GetFieldExpression (ec).Emit (ec);
761 public Expression EmitToField (EmitContext ec)
763 return GetFieldExpression (ec);
767 // Creates field access expression for hoisted variable
769 protected virtual FieldExpr GetFieldExpression (EmitContext ec)
771 if (ec.CurrentAnonymousMethod == null || ec.CurrentAnonymousMethod.Storey == null) {
772 if (cached_outer_access != null)
773 return cached_outer_access;
776 // When setting top-level hoisted variable in generic storey
777 // change storey generic types to method generic types (VAR -> MVAR)
779 if (storey.Instance.Type.IsGenericOrParentIsGeneric) {
780 var fs = MemberCache.GetMember (storey.Instance.Type, field.Spec);
781 cached_outer_access = new FieldExpr (fs, field.Location);
783 cached_outer_access = new FieldExpr (field, field.Location);
786 cached_outer_access.InstanceExpression = storey.GetStoreyInstanceExpression (ec);
787 return cached_outer_access;
790 FieldExpr inner_access;
791 if (cached_inner_access != null) {
792 if (!cached_inner_access.TryGetValue (ec.CurrentAnonymousMethod, out inner_access))
796 cached_inner_access = new Dictionary<AnonymousExpression, FieldExpr> (4);
799 if (inner_access == null) {
800 if (field.Parent.IsGenericOrParentIsGeneric) {
801 var fs = MemberCache.GetMember (field.Parent.CurrentType, field.Spec);
802 inner_access = new FieldExpr (fs, field.Location);
804 inner_access = new FieldExpr (field, field.Location);
807 inner_access.InstanceExpression = storey.GetStoreyInstanceExpression (ec);
808 cached_inner_access.Add (ec.CurrentAnonymousMethod, inner_access);
814 public void Emit (EmitContext ec, bool leave_copy)
816 GetFieldExpression (ec).Emit (ec, leave_copy);
819 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool isCompound)
821 GetFieldExpression (ec).EmitAssign (ec, source, leave_copy, false);
825 public class HoistedParameter : HoistedVariable
827 sealed class HoistedFieldAssign : CompilerAssign
829 public HoistedFieldAssign (Expression target, Expression source)
830 : base (target, source, target.Location)
834 protected override Expression ResolveConversions (ResolveContext ec)
837 // Implicit conversion check fails for hoisted type arguments
838 // as they are of different types (!!0 x !0)
844 readonly ParameterReference parameter;
846 public HoistedParameter (AnonymousMethodStorey scope, ParameterReference par)
847 : base (scope, par.Name, par.Type)
849 this.parameter = par;
852 public HoistedParameter (HoistedParameter hp, string name)
853 : base (hp.storey, name, hp.parameter.Type)
855 this.parameter = hp.parameter;
860 public bool IsAssigned { get; set; }
862 public ParameterReference Parameter {
870 public void EmitHoistingAssignment (EmitContext ec)
873 // Remove hoisted redirection to emit assignment from original parameter
875 var temp = parameter.Parameter.HoistedVariant;
876 parameter.Parameter.HoistedVariant = null;
878 var a = new HoistedFieldAssign (GetFieldExpression (ec), parameter);
879 a.EmitStatement (ec);
881 parameter.Parameter.HoistedVariant = temp;
885 class HoistedLocalVariable : HoistedVariable
887 public HoistedLocalVariable (AnonymousMethodStorey storey, LocalVariable local, string name)
888 : base (storey, name, local.Type)
893 public class HoistedThis : HoistedVariable
895 public HoistedThis (AnonymousMethodStorey storey, Field field)
896 : base (storey, field)
902 // Anonymous method expression as created by parser
904 public class AnonymousMethodExpression : Expression
907 // Special conversion for nested expression tree lambdas
909 class Quote : ShimExpression
911 public Quote (Expression expr)
916 public override Expression CreateExpressionTree (ResolveContext ec)
918 var args = new Arguments (1);
919 args.Add (new Argument (expr.CreateExpressionTree (ec)));
920 return CreateExpressionFactoryCall (ec, "Quote", args);
923 protected override Expression DoResolve (ResolveContext rc)
925 expr = expr.Resolve (rc);
929 eclass = expr.eclass;
935 readonly Dictionary<TypeSpec, Expression> compatibles;
937 public ParametersBlock Block;
939 public AnonymousMethodExpression (Location loc)
942 this.compatibles = new Dictionary<TypeSpec, Expression> ();
947 public override string ExprClassName {
949 return "anonymous method";
953 public virtual bool HasExplicitParameters {
955 return Parameters != ParametersCompiled.Undefined;
959 public ParametersCompiled Parameters {
961 return Block.Parameters;
965 public ReportPrinter TypeInferenceReportPrinter {
972 // Returns true if the body of lambda expression can be implicitly
973 // converted to the delegate of type `delegate_type'
975 public bool ImplicitStandardConversionExists (ResolveContext ec, TypeSpec delegate_type)
977 using (ec.With (ResolveContext.Options.InferReturnType, false)) {
978 using (ec.Set (ResolveContext.Options.ProbingMode)) {
979 var prev = ec.Report.SetPrinter (TypeInferenceReportPrinter ?? new NullReportPrinter ());
981 var res = Compatible (ec, delegate_type) != null;
983 ec.Report.SetPrinter (prev);
990 TypeSpec CompatibleChecks (ResolveContext ec, TypeSpec delegate_type)
992 if (delegate_type.IsDelegate)
993 return delegate_type;
995 if (delegate_type.IsExpressionTreeType) {
996 delegate_type = delegate_type.TypeArguments [0];
997 if (delegate_type.IsDelegate)
998 return delegate_type;
1000 ec.Report.Error (835, loc, "Cannot convert `{0}' to an expression tree of non-delegate type `{1}'",
1001 GetSignatureForError (), delegate_type.GetSignatureForError ());
1005 ec.Report.Error (1660, loc, "Cannot convert `{0}' to non-delegate type `{1}'",
1006 GetSignatureForError (), delegate_type.GetSignatureForError ());
1010 protected bool VerifyExplicitParameters (ResolveContext ec, TypeSpec delegate_type, AParametersCollection parameters)
1012 if (VerifyParameterCompatibility (ec, delegate_type, parameters, ec.IsInProbingMode))
1015 if (!ec.IsInProbingMode)
1016 ec.Report.Error (1661, loc,
1017 "Cannot convert `{0}' to delegate type `{1}' since there is a parameter mismatch",
1018 GetSignatureForError (), delegate_type.GetSignatureForError ());
1023 protected bool VerifyParameterCompatibility (ResolveContext ec, TypeSpec delegate_type, AParametersCollection invoke_pd, bool ignore_errors)
1025 if (Parameters.Count != invoke_pd.Count) {
1029 ec.Report.Error (1593, loc, "Delegate `{0}' does not take `{1}' arguments",
1030 delegate_type.GetSignatureForError (), Parameters.Count.ToString ());
1034 bool has_implicit_parameters = !HasExplicitParameters;
1037 for (int i = 0; i < Parameters.Count; ++i) {
1038 Parameter.Modifier p_mod = invoke_pd.FixedParameters [i].ModFlags;
1039 if (Parameters.FixedParameters [i].ModFlags != p_mod && p_mod != Parameter.Modifier.PARAMS) {
1043 if (p_mod == Parameter.Modifier.NONE)
1044 ec.Report.Error (1677, Parameters[i].Location, "Parameter `{0}' should not be declared with the `{1}' keyword",
1045 (i + 1).ToString (), Parameter.GetModifierSignature (Parameters [i].ModFlags));
1047 ec.Report.Error (1676, Parameters[i].Location, "Parameter `{0}' must be declared with the `{1}' keyword",
1048 (i+1).ToString (), Parameter.GetModifierSignature (p_mod));
1052 if (has_implicit_parameters)
1055 TypeSpec type = invoke_pd.Types [i];
1058 // Assumes that generic mvar parameters are always inflated
1060 if (ImplicitDelegateCreation.ContainsMethodTypeParameter (type))
1063 if (!TypeSpecComparer.IsEqual (invoke_pd.Types [i], Parameters.Types [i])) {
1067 ec.Report.Error (1678, Parameters [i].Location, "Parameter `{0}' is declared as type `{1}' but should be `{2}'",
1069 Parameters.Types [i].GetSignatureForError (),
1070 invoke_pd.Types [i].GetSignatureForError ());
1079 // Infers type arguments based on explicit arguments
1081 public bool ExplicitTypeInference (ResolveContext ec, TypeInferenceContext type_inference, TypeSpec delegate_type)
1083 if (!HasExplicitParameters)
1086 if (!delegate_type.IsDelegate) {
1087 if (!delegate_type.IsExpressionTreeType)
1090 delegate_type = TypeManager.GetTypeArguments (delegate_type) [0];
1091 if (!delegate_type.IsDelegate)
1095 AParametersCollection d_params = Delegate.GetParameters (delegate_type);
1096 if (d_params.Count != Parameters.Count)
1099 var ptypes = Parameters.Types;
1100 var dtypes = d_params.Types;
1101 for (int i = 0; i < Parameters.Count; ++i) {
1102 if (type_inference.ExactInference (ptypes[i], dtypes[i]) == 0) {
1104 // Continue when 0 (quick path) does not mean inference failure. Checking for
1105 // same type handles cases like int -> int
1107 if (ptypes[i] == dtypes[i])
1117 public TypeSpec InferReturnType (ResolveContext ec, TypeInferenceContext tic, TypeSpec delegate_type)
1120 AnonymousExpression am;
1122 if (compatibles.TryGetValue (delegate_type, out expr)) {
1123 am = expr as AnonymousExpression;
1124 return am == null ? null : am.ReturnType;
1127 using (ec.Set (ResolveContext.Options.ProbingMode | ResolveContext.Options.InferReturnType)) {
1129 if (TypeInferenceReportPrinter != null) {
1130 prev = ec.Report.SetPrinter (TypeInferenceReportPrinter);
1135 var body = CompatibleMethodBody (ec, tic, null, delegate_type);
1137 am = body.Compatible (ec, body);
1142 if (TypeInferenceReportPrinter != null) {
1143 ec.Report.SetPrinter (prev);
1150 // compatibles.Add (delegate_type, am);
1151 return am.ReturnType;
1154 public override bool ContainsEmitWithAwait ()
1160 // Returns AnonymousMethod container if this anonymous method
1161 // expression can be implicitly converted to the delegate type `delegate_type'
1163 public Expression Compatible (ResolveContext ec, TypeSpec type)
1166 if (compatibles.TryGetValue (type, out am))
1169 TypeSpec delegate_type = CompatibleChecks (ec, type);
1170 if (delegate_type == null)
1174 // At this point its the first time we know the return type that is
1175 // needed for the anonymous method. We create the method here.
1178 var invoke_mb = Delegate.GetInvokeMethod (delegate_type);
1179 TypeSpec return_type = invoke_mb.ReturnType;
1182 // Second: the return type of the delegate must be compatible with
1183 // the anonymous type. Instead of doing a pass to examine the block
1184 // we satisfy the rule by setting the return type on the EmitContext
1185 // to be the delegate type return type.
1188 var body = CompatibleMethodBody (ec, null, return_type, delegate_type);
1192 bool etree_conversion = delegate_type != type;
1195 if (etree_conversion) {
1196 if (ec.HasSet (ResolveContext.Options.ExpressionTreeConversion)) {
1198 // Nested expression tree lambda use same scope as parent
1199 // lambda, this also means no variable capturing between this
1202 am = body.Compatible (ec, ec.CurrentAnonymousMethod);
1205 // Quote nested expression tree
1208 am = new Quote (am);
1210 int errors = ec.Report.Errors;
1212 if (Block.IsAsync) {
1213 ec.Report.Error (1989, loc, "Async lambda expressions cannot be converted to expression trees");
1216 using (ec.Set (ResolveContext.Options.ExpressionTreeConversion)) {
1217 am = body.Compatible (ec);
1221 // Rewrite expressions into expression tree when targeting Expression<T>
1223 if (am != null && errors == ec.Report.Errors)
1224 am = CreateExpressionTree (ec, delegate_type);
1227 am = body.Compatible (ec);
1229 if (body.DirectMethodGroupConversion != null) {
1230 var errors_printer = new SessionReportPrinter ();
1231 var old = ec.Report.SetPrinter (errors_printer);
1232 var expr = new ImplicitDelegateCreation (delegate_type, body.DirectMethodGroupConversion, loc) {
1233 AllowSpecialMethodsInvocation = true
1235 ec.Report.SetPrinter (old);
1236 if (expr != null && errors_printer.ErrorsCount == 0)
1240 } catch (CompletionResult) {
1242 } catch (FatalException) {
1244 } catch (Exception e) {
1245 throw new InternalErrorException (e, loc);
1248 if (!ec.IsInProbingMode) {
1249 compatibles.Add (type, am ?? EmptyExpression.Null);
1255 protected virtual Expression CreateExpressionTree (ResolveContext ec, TypeSpec delegate_type)
1257 return CreateExpressionTree (ec);
1260 public override Expression CreateExpressionTree (ResolveContext ec)
1262 ec.Report.Error (1946, loc, "An anonymous method cannot be converted to an expression tree");
1266 protected virtual ParametersCompiled ResolveParameters (ResolveContext ec, TypeInferenceContext tic, TypeSpec delegate_type)
1268 var delegate_parameters = Delegate.GetParameters (delegate_type);
1270 if (Parameters == ParametersCompiled.Undefined) {
1272 // We provide a set of inaccessible parameters
1274 Parameter[] fixedpars = new Parameter[delegate_parameters.Count];
1276 for (int i = 0; i < delegate_parameters.Count; i++) {
1277 Parameter.Modifier i_mod = delegate_parameters.FixedParameters [i].ModFlags;
1278 if ((i_mod & Parameter.Modifier.OUT) != 0) {
1279 if (!ec.IsInProbingMode) {
1280 ec.Report.Error (1688, loc,
1281 "Cannot convert anonymous method block without a parameter list to delegate type `{0}' because it has one or more `out' parameters",
1282 delegate_type.GetSignatureForError ());
1287 fixedpars[i] = new Parameter (
1288 new TypeExpression (delegate_parameters.Types [i], loc), null,
1289 delegate_parameters.FixedParameters [i].ModFlags, null, loc);
1292 return ParametersCompiled.CreateFullyResolved (fixedpars, delegate_parameters.Types);
1295 if (!VerifyExplicitParameters (ec, delegate_type, delegate_parameters)) {
1302 protected override Expression DoResolve (ResolveContext ec)
1304 if (ec.HasSet (ResolveContext.Options.ConstantScope)) {
1305 ec.Report.Error (1706, loc, "Anonymous methods and lambda expressions cannot be used in the current context");
1310 // Set class type, set type
1313 eclass = ExprClass.Value;
1316 // This hack means `The type is not accessible
1317 // anywhere', we depend on special conversion
1320 type = InternalType.AnonymousMethod;
1322 if (!DoResolveParameters (ec))
1326 // FIXME: The emitted code isn't very careful about reachability
1327 // so, ensure we have a 'ret' at the end
1328 BlockContext bc = ec as BlockContext;
1329 if (bc != null && bc.CurrentBranching != null && bc.CurrentBranching.CurrentUsageVector.IsUnreachable)
1330 bc.NeedReturnLabel ();
1335 protected virtual bool DoResolveParameters (ResolveContext rc)
1337 return Parameters.Resolve (rc);
1340 public override void Emit (EmitContext ec)
1342 // nothing, as we only exist to not do anything.
1345 public static void Error_AddressOfCapturedVar (ResolveContext ec, IVariableReference var, Location loc)
1347 ec.Report.Error (1686, loc,
1348 "Local variable or parameter `{0}' cannot have their address taken and be used inside an anonymous method, lambda expression or query expression",
1352 public override string GetSignatureForError ()
1354 return ExprClassName;
1357 AnonymousMethodBody CompatibleMethodBody (ResolveContext ec, TypeInferenceContext tic, TypeSpec return_type, TypeSpec delegate_type)
1359 ParametersCompiled p = ResolveParameters (ec, tic, delegate_type);
1363 ParametersBlock b = ec.IsInProbingMode ? (ParametersBlock) Block.PerformClone () : Block;
1366 var rt = return_type;
1367 if (rt != null && rt.Kind != MemberKind.Void && rt != ec.Module.PredefinedTypes.Task.TypeSpec && !rt.IsGenericTask) {
1368 ec.Report.Error (4010, loc, "Cannot convert async {0} to delegate type `{1}'",
1369 GetSignatureForError (), delegate_type.GetSignatureForError ());
1374 b = b.ConvertToAsyncTask (ec, ec.CurrentMemberDefinition.Parent.PartialContainer, p, return_type, delegate_type, loc);
1377 return CompatibleMethodFactory (return_type ?? InternalType.ErrorType, delegate_type, p, b);
1380 protected virtual AnonymousMethodBody CompatibleMethodFactory (TypeSpec return_type, TypeSpec delegate_type, ParametersCompiled p, ParametersBlock b)
1382 return new AnonymousMethodBody (p, b, return_type, delegate_type, loc);
1385 protected override void CloneTo (CloneContext clonectx, Expression t)
1387 AnonymousMethodExpression target = (AnonymousMethodExpression) t;
1389 target.Block = (ParametersBlock) clonectx.LookupBlock (Block);
1392 public override object Accept (StructuralVisitor visitor)
1394 return visitor.Visit (this);
1399 // Abstract expression for any block which requires variables hoisting
1401 public abstract class AnonymousExpression : ExpressionStatement
1403 protected class AnonymousMethodMethod : Method
1405 public readonly AnonymousExpression AnonymousMethod;
1406 public readonly AnonymousMethodStorey Storey;
1408 public AnonymousMethodMethod (TypeDefinition parent, AnonymousExpression am, AnonymousMethodStorey storey,
1409 TypeExpr return_type,
1410 Modifiers mod, MemberName name,
1411 ParametersCompiled parameters)
1412 : base (parent, return_type, mod | Modifiers.COMPILER_GENERATED,
1413 name, parameters, null)
1415 this.AnonymousMethod = am;
1416 this.Storey = storey;
1418 Parent.PartialContainer.Members.Add (this);
1419 Block = new ToplevelBlock (am.block, parameters);
1422 public override EmitContext CreateEmitContext (ILGenerator ig, SourceMethodBuilder sourceMethod)
1424 EmitContext ec = new EmitContext (this, ig, ReturnType, sourceMethod);
1425 ec.CurrentAnonymousMethod = AnonymousMethod;
1429 protected override void DefineTypeParameters ()
1431 // Type parameters were cloned
1434 protected override bool ResolveMemberType ()
1436 if (!base.ResolveMemberType ())
1439 if (Storey != null && Storey.Mutator != null) {
1440 if (!parameters.IsEmpty) {
1441 var mutated = Storey.Mutator.Mutate (parameters.Types);
1442 if (mutated != parameters.Types)
1443 parameters = ParametersCompiled.CreateFullyResolved ((Parameter[]) parameters.FixedParameters, mutated);
1446 member_type = Storey.Mutator.Mutate (member_type);
1452 public override void Emit ()
1454 if (MethodBuilder == null) {
1462 protected readonly ParametersBlock block;
1464 public TypeSpec ReturnType;
1466 protected AnonymousExpression (ParametersBlock block, TypeSpec return_type, Location loc)
1468 this.ReturnType = return_type;
1473 public abstract string ContainerType { get; }
1474 public abstract bool IsIterator { get; }
1475 public abstract AnonymousMethodStorey Storey { get; }
1478 // The block that makes up the body for the anonymous method
1480 public ParametersBlock Block {
1486 public AnonymousExpression Compatible (ResolveContext ec)
1488 return Compatible (ec, this);
1491 public AnonymousExpression Compatible (ResolveContext ec, AnonymousExpression ae)
1496 // TODO: Implement clone
1497 BlockContext aec = new BlockContext (ec, block, ReturnType);
1498 aec.CurrentAnonymousMethod = ae;
1500 var am = this as AnonymousMethodBody;
1502 if (ec.HasSet (ResolveContext.Options.InferReturnType) && am != null) {
1503 am.ReturnTypeInference = new TypeInferenceContext ();
1506 var bc = ec as BlockContext;
1508 aec.FlowOffset = bc.FlowOffset;
1510 var errors = ec.Report.Errors;
1512 bool res = Block.Resolve (ec.CurrentBranching, aec, null);
1514 if (am != null && am.ReturnTypeInference != null) {
1515 am.ReturnTypeInference.FixAllTypes (ec);
1516 ReturnType = am.ReturnTypeInference.InferredTypeArguments [0];
1517 am.ReturnTypeInference = null;
1520 // If e is synchronous the inferred return type is T
1521 // If e is asynchronous the inferred return type is Task<T>
1523 if (block.IsAsync && ReturnType != null) {
1524 ReturnType = ec.Module.PredefinedTypes.TaskGeneric.TypeSpec.MakeGenericType (ec, new [] { ReturnType });
1528 if (res && errors != ec.Report.Errors)
1531 return res ? this : null;
1534 public override bool ContainsEmitWithAwait ()
1539 public void SetHasThisAccess ()
1541 ExplicitBlock b = block;
1543 if (b.HasCapturedThis)
1546 b.HasCapturedThis = true;
1547 b = b.Parent == null ? null : b.Parent.Explicit;
1548 } while (b != null);
1552 public class AnonymousMethodBody : AnonymousExpression
1554 protected readonly ParametersCompiled parameters;
1555 AnonymousMethodStorey storey;
1557 AnonymousMethodMethod method;
1560 TypeInferenceContext return_inference;
1562 public AnonymousMethodBody (ParametersCompiled parameters,
1563 ParametersBlock block, TypeSpec return_type, TypeSpec delegate_type,
1565 : base (block, return_type, loc)
1567 this.type = delegate_type;
1568 this.parameters = parameters;
1573 public override string ContainerType {
1574 get { return "anonymous method"; }
1578 // Method-group instance for lambdas which can be replaced with
1579 // simple method group call
1581 public MethodGroupExpr DirectMethodGroupConversion {
1585 public override bool IsIterator {
1591 public ParametersCompiled Parameters {
1597 public TypeInferenceContext ReturnTypeInference {
1599 return return_inference;
1602 return_inference = value;
1606 public override AnonymousMethodStorey Storey {
1614 public override Expression CreateExpressionTree (ResolveContext ec)
1616 ec.Report.Error (1945, loc, "An expression tree cannot contain an anonymous method expression");
1620 bool Define (ResolveContext ec)
1622 if (!Block.Resolved && Compatible (ec) == null)
1625 if (block_name == null) {
1626 MemberCore mc = (MemberCore) ec.MemberContext;
1627 block_name = mc.MemberName.Basename;
1634 // Creates a host for the anonymous method
1636 AnonymousMethodMethod DoCreateMethodHost (EmitContext ec)
1639 // Anonymous method body can be converted to
1641 // 1, an instance method in current scope when only `this' is hoisted
1642 // 2, a static method in current scope when neither `this' nor any variable is hoisted
1643 // 3, an instance method in compiler generated storey when any hoisted variable exists
1646 Modifiers modifiers;
1647 TypeDefinition parent = null;
1649 var src_block = Block.Original.Explicit;
1650 if (src_block.HasCapturedVariable || src_block.HasCapturedThis) {
1651 parent = storey = FindBestMethodStorey ();
1653 if (storey == null) {
1654 var top_block = src_block.ParametersBlock.TopBlock;
1655 var sm = top_block.StateMachine;
1657 if (src_block.HasCapturedThis) {
1659 // Remove hoisted 'this' request when simple instance method is
1660 // enough. No hoisted variables only 'this' and don't need to
1661 // propagate this to value type state machine.
1663 StateMachine sm_parent = null;
1664 var pb = src_block.ParametersBlock;
1666 sm_parent = pb.StateMachine;
1667 pb = pb.Parent == null ? null : pb.Parent.ParametersBlock;
1668 } while (sm_parent == null && pb != null);
1670 if (sm_parent == null) {
1671 top_block.RemoveThisReferenceFromChildrenBlock (src_block);
1672 } else if (sm_parent.Kind == MemberKind.Struct) {
1674 // Special case where parent class is used to emit instance method
1675 // because currect storey is of value type (async host). We cannot
1676 // use ldftn on non-boxed instances either to share mutated state
1678 parent = sm_parent.Parent.PartialContainer;
1683 // For iterators we can host everything in one class
1685 if (sm is IteratorStorey)
1686 parent = storey = sm;
1689 modifiers = storey != null ? Modifiers.INTERNAL : Modifiers.PRIVATE;
1691 if (ec.CurrentAnonymousMethod != null)
1692 parent = storey = ec.CurrentAnonymousMethod.Storey;
1694 modifiers = Modifiers.STATIC | Modifiers.PRIVATE;
1698 parent = ec.CurrentTypeDefinition.Parent.PartialContainer;
1700 string name = CompilerGeneratedContainer.MakeName (parent != storey ? block_name : null,
1701 "m", null, ec.Module.CounterAnonymousMethods++);
1703 MemberName member_name;
1704 if (storey == null && ec.CurrentTypeParameters != null) {
1706 var hoisted_tparams = ec.CurrentTypeParameters;
1707 var type_params = new TypeParameters (hoisted_tparams.Count);
1708 for (int i = 0; i < hoisted_tparams.Count; ++i) {
1709 type_params.Add (hoisted_tparams[i].CreateHoistedCopy (null));
1712 member_name = new MemberName (name, type_params, Location);
1714 member_name = new MemberName (name, Location);
1717 return new AnonymousMethodMethod (parent,
1718 this, storey, new TypeExpression (ReturnType, Location), modifiers,
1719 member_name, parameters);
1722 protected override Expression DoResolve (ResolveContext ec)
1727 eclass = ExprClass.Value;
1731 public override void Emit (EmitContext ec)
1734 // Use same anonymous method implementation for scenarios where same
1735 // code is used from multiple blocks, e.g. field initializers
1737 if (method == null) {
1739 // Delay an anonymous method definition to avoid emitting unused code
1740 // for unreachable blocks or expression trees
1742 method = DoCreateMethodHost (ec);
1744 method.PrepareEmit ();
1747 bool is_static = (method.ModFlags & Modifiers.STATIC) != 0;
1748 if (is_static && am_cache == null) {
1750 // Creates a field cache to store delegate instance if it's not generic
1752 if (!method.MemberName.IsGeneric) {
1753 var parent = method.Parent.PartialContainer;
1754 int id = parent.AnonymousMethodsCounter++;
1755 var cache_type = storey != null && storey.Mutator != null ? storey.Mutator.Mutate (type) : type;
1757 am_cache = new Field (parent, new TypeExpression (cache_type, loc),
1758 Modifiers.STATIC | Modifiers.PRIVATE | Modifiers.COMPILER_GENERATED,
1759 new MemberName (CompilerGeneratedContainer.MakeName (null, "f", "am$cache", id), loc), null);
1761 parent.AddField (am_cache);
1763 // TODO: Implement caching of generated generic static methods
1767 // Some extra class is needed to capture variable generic type
1768 // arguments. Maybe we could re-use anonymous types, with a unique
1769 // anonymous method id, but they are quite heavy.
1771 // Consider : "() => typeof(T);"
1773 // We need something like
1774 // static class Wrap<Tn, Tm, DelegateType> {
1775 // public static DelegateType cache;
1778 // We then specialize local variable to capture all generic parameters
1779 // and delegate type, e.g. "Wrap<Ta, Tb, DelegateTypeInst> cache;"
1784 Label l_initialized = ec.DefineLabel ();
1786 if (am_cache != null) {
1787 ec.Emit (OpCodes.Ldsfld, am_cache.Spec);
1788 ec.Emit (OpCodes.Brtrue_S, l_initialized);
1792 // Load method delegate implementation
1797 } else if (storey != null) {
1798 Expression e = storey.GetStoreyInstanceExpression (ec).Resolve (new ResolveContext (ec.MemberContext));
1806 // Special case for value type storey where this is not lifted but
1807 // droped off to parent class
1809 for (var b = Block.Parent; b != null; b = b.Parent) {
1810 if (b.ParametersBlock.StateMachine != null) {
1811 ec.Emit (OpCodes.Ldfld, b.ParametersBlock.StateMachine.HoistedThis.Field.Spec);
1817 var delegate_method = method.Spec;
1818 if (storey != null && storey.MemberName.IsGeneric) {
1819 TypeSpec t = storey.Instance.Type;
1822 // Mutate anonymous method instance type if we are in nested
1823 // hoisted generic anonymous method storey
1825 if (ec.IsAnonymousStoreyMutateRequired) {
1826 t = storey.Mutator.Mutate (t);
1829 ec.Emit (OpCodes.Ldftn, TypeBuilder.GetMethod (t.GetMetaInfo (), (MethodInfo) delegate_method.GetMetaInfo ()));
1831 if (delegate_method.IsGeneric)
1832 delegate_method = delegate_method.MakeGenericMethod (ec.MemberContext, method.TypeParameters);
1834 ec.Emit (OpCodes.Ldftn, delegate_method);
1837 var constructor_method = Delegate.GetConstructor (type);
1838 ec.Emit (OpCodes.Newobj, constructor_method);
1840 if (am_cache != null) {
1841 ec.Emit (OpCodes.Stsfld, am_cache.Spec);
1842 ec.MarkLabel (l_initialized);
1843 ec.Emit (OpCodes.Ldsfld, am_cache.Spec);
1847 public override void EmitStatement (EmitContext ec)
1849 throw new NotImplementedException ();
1853 // Look for the best storey for this anonymous method
1855 AnonymousMethodStorey FindBestMethodStorey ()
1858 // Use the nearest parent block which has a storey
1860 for (Block b = Block.Parent; b != null; b = b.Parent) {
1861 AnonymousMethodStorey s = b.Explicit.AnonymousMethodStorey;
1869 public override string GetSignatureForError ()
1871 return type.GetSignatureForError ();
1876 // Anonymous type container
1878 public class AnonymousTypeClass : CompilerGeneratedContainer
1880 public const string ClassNamePrefix = "<>__AnonType";
1881 public const string SignatureForError = "anonymous type";
1883 readonly IList<AnonymousTypeParameter> parameters;
1885 private AnonymousTypeClass (ModuleContainer parent, MemberName name, IList<AnonymousTypeParameter> parameters, Location loc)
1886 : base (parent, name, parent.Evaluator != null ? Modifiers.PUBLIC : Modifiers.INTERNAL)
1888 this.parameters = parameters;
1891 public static AnonymousTypeClass Create (TypeContainer parent, IList<AnonymousTypeParameter> parameters, Location loc)
1893 string name = ClassNamePrefix + parent.Module.CounterAnonymousTypes++;
1895 ParametersCompiled all_parameters;
1896 TypeParameters tparams = null;
1897 SimpleName[] t_args;
1899 if (parameters.Count == 0) {
1900 all_parameters = ParametersCompiled.EmptyReadOnlyParameters;
1903 t_args = new SimpleName[parameters.Count];
1904 tparams = new TypeParameters ();
1905 Parameter[] ctor_params = new Parameter[parameters.Count];
1906 for (int i = 0; i < parameters.Count; ++i) {
1907 AnonymousTypeParameter p = parameters[i];
1908 for (int ii = 0; ii < i; ++ii) {
1909 if (parameters[ii].Name == p.Name) {
1910 parent.Compiler.Report.Error (833, parameters[ii].Location,
1911 "`{0}': An anonymous type cannot have multiple properties with the same name",
1914 p = new AnonymousTypeParameter (null, "$" + i.ToString (), p.Location);
1920 t_args[i] = new SimpleName ("<" + p.Name + ">__T", p.Location);
1921 tparams.Add (new TypeParameter (i, new MemberName (t_args[i].Name, p.Location), null, null, Variance.None));
1922 ctor_params[i] = new Parameter (t_args[i], p.Name, Parameter.Modifier.NONE, null, p.Location);
1925 all_parameters = new ParametersCompiled (ctor_params);
1929 // Create generic anonymous type host with generic arguments
1930 // named upon properties names
1932 AnonymousTypeClass a_type = new AnonymousTypeClass (parent.Module, new MemberName (name, tparams, loc), parameters, loc);
1934 Constructor c = new Constructor (a_type, name, Modifiers.PUBLIC | Modifiers.DEBUGGER_HIDDEN,
1935 null, all_parameters, loc);
1936 c.Block = new ToplevelBlock (parent.Module.Compiler, c.ParameterInfo, loc);
1939 // Create fields and constructor body with field initialization
1942 for (int i = 0; i < parameters.Count; ++i) {
1943 AnonymousTypeParameter p = parameters [i];
1945 Field f = new Field (a_type, t_args [i], Modifiers.PRIVATE | Modifiers.READONLY | Modifiers.DEBUGGER_HIDDEN,
1946 new MemberName ("<" + p.Name + ">", p.Location), null);
1948 if (!a_type.AddField (f)) {
1953 c.Block.AddStatement (new StatementExpression (
1954 new SimpleAssign (new MemberAccess (new This (p.Location), f.Name),
1955 c.Block.GetParameterReference (i, p.Location))));
1957 ToplevelBlock get_block = new ToplevelBlock (parent.Module.Compiler, p.Location);
1958 get_block.AddStatement (new Return (
1959 new MemberAccess (new This (p.Location), f.Name), p.Location));
1961 Property prop = new Property (a_type, t_args [i], Modifiers.PUBLIC,
1962 new MemberName (p.Name, p.Location), null);
1963 prop.Get = new Property.GetMethod (prop, 0, null, p.Location);
1964 prop.Get.Block = get_block;
1965 a_type.AddMember (prop);
1971 a_type.AddConstructor (c);
1975 protected override bool DoDefineMembers ()
1977 if (!base.DoDefineMembers ())
1980 Location loc = Location;
1982 var equals_parameters = ParametersCompiled.CreateFullyResolved (
1983 new Parameter (new TypeExpression (Compiler.BuiltinTypes.Object, loc), "obj", 0, null, loc), Compiler.BuiltinTypes.Object);
1985 Method equals = new Method (this, new TypeExpression (Compiler.BuiltinTypes.Bool, loc),
1986 Modifiers.PUBLIC | Modifiers.OVERRIDE | Modifiers.DEBUGGER_HIDDEN, new MemberName ("Equals", loc),
1987 equals_parameters, null);
1989 equals_parameters[0].Resolve (equals, 0);
1991 Method tostring = new Method (this, new TypeExpression (Compiler.BuiltinTypes.String, loc),
1992 Modifiers.PUBLIC | Modifiers.OVERRIDE | Modifiers.DEBUGGER_HIDDEN, new MemberName ("ToString", loc),
1993 Mono.CSharp.ParametersCompiled.EmptyReadOnlyParameters, null);
1995 ToplevelBlock equals_block = new ToplevelBlock (Compiler, equals.ParameterInfo, loc);
1997 TypeExpr current_type;
1998 if (CurrentTypeParameters != null) {
1999 var targs = new TypeArguments ();
2000 for (int i = 0; i < CurrentTypeParameters.Count; ++i) {
2001 targs.Add (new TypeParameterExpr (CurrentTypeParameters[i], Location));
2004 current_type = new GenericTypeExpr (Definition, targs, loc);
2006 current_type = new TypeExpression (Definition, loc);
2009 var li_other = LocalVariable.CreateCompilerGenerated (CurrentType, equals_block, loc);
2010 equals_block.AddStatement (new BlockVariable (new TypeExpression (li_other.Type, loc), li_other));
2011 var other_variable = new LocalVariableReference (li_other, loc);
2013 MemberAccess system_collections_generic = new MemberAccess (new MemberAccess (
2014 new QualifiedAliasMember ("global", "System", loc), "Collections", loc), "Generic", loc);
2016 Expression rs_equals = null;
2017 Expression string_concat = new StringConstant (Compiler.BuiltinTypes, "{", loc);
2018 Expression rs_hashcode = new IntConstant (Compiler.BuiltinTypes, -2128831035, loc);
2019 for (int i = 0; i < parameters.Count; ++i) {
2020 var p = parameters [i];
2021 var f = (Field) Members [i * 2];
2023 MemberAccess equality_comparer = new MemberAccess (new MemberAccess (
2024 system_collections_generic, "EqualityComparer",
2025 new TypeArguments (new SimpleName (CurrentTypeParameters [i].Name, loc)), loc),
2028 Arguments arguments_equal = new Arguments (2);
2029 arguments_equal.Add (new Argument (new MemberAccess (new This (f.Location), f.Name)));
2030 arguments_equal.Add (new Argument (new MemberAccess (other_variable, f.Name)));
2032 Expression field_equal = new Invocation (new MemberAccess (equality_comparer,
2033 "Equals", loc), arguments_equal);
2035 Arguments arguments_hashcode = new Arguments (1);
2036 arguments_hashcode.Add (new Argument (new MemberAccess (new This (f.Location), f.Name)));
2037 Expression field_hashcode = new Invocation (new MemberAccess (equality_comparer,
2038 "GetHashCode", loc), arguments_hashcode);
2040 IntConstant FNV_prime = new IntConstant (Compiler.BuiltinTypes, 16777619, loc);
2041 rs_hashcode = new Binary (Binary.Operator.Multiply,
2042 new Binary (Binary.Operator.ExclusiveOr, rs_hashcode, field_hashcode),
2045 Expression field_to_string = new Conditional (new BooleanExpression (new Binary (Binary.Operator.Inequality,
2046 new MemberAccess (new This (f.Location), f.Name), new NullLiteral (loc))),
2047 new Invocation (new MemberAccess (
2048 new MemberAccess (new This (f.Location), f.Name), "ToString"), null),
2049 new StringConstant (Compiler.BuiltinTypes, string.Empty, loc), loc);
2051 if (rs_equals == null) {
2052 rs_equals = field_equal;
2053 string_concat = new Binary (Binary.Operator.Addition,
2055 new Binary (Binary.Operator.Addition,
2056 new StringConstant (Compiler.BuiltinTypes, " " + p.Name + " = ", loc),
2062 // Implementation of ToString () body using string concatenation
2064 string_concat = new Binary (Binary.Operator.Addition,
2065 new Binary (Binary.Operator.Addition,
2067 new StringConstant (Compiler.BuiltinTypes, ", " + p.Name + " = ", loc)),
2070 rs_equals = new Binary (Binary.Operator.LogicalAnd, rs_equals, field_equal);
2073 string_concat = new Binary (Binary.Operator.Addition,
2075 new StringConstant (Compiler.BuiltinTypes, " }", loc));
2078 // Equals (object obj) override
2080 var other_variable_assign = new TemporaryVariableReference (li_other, loc);
2081 equals_block.AddStatement (new StatementExpression (
2082 new SimpleAssign (other_variable_assign,
2083 new As (equals_block.GetParameterReference (0, loc),
2084 current_type, loc), loc)));
2086 Expression equals_test = new Binary (Binary.Operator.Inequality, other_variable, new NullLiteral (loc));
2087 if (rs_equals != null)
2088 equals_test = new Binary (Binary.Operator.LogicalAnd, equals_test, rs_equals);
2089 equals_block.AddStatement (new Return (equals_test, loc));
2091 equals.Block = equals_block;
2093 equals.PrepareEmit ();
2094 Members.Add (equals);
2097 // GetHashCode () override
2099 Method hashcode = new Method (this, new TypeExpression (Compiler.BuiltinTypes.Int, loc),
2100 Modifiers.PUBLIC | Modifiers.OVERRIDE | Modifiers.DEBUGGER_HIDDEN,
2101 new MemberName ("GetHashCode", loc),
2102 Mono.CSharp.ParametersCompiled.EmptyReadOnlyParameters, null);
2105 // Modified FNV with good avalanche behavior and uniform
2106 // distribution with larger hash sizes.
2108 // const int FNV_prime = 16777619;
2109 // int hash = (int) 2166136261;
2110 // foreach (int d in data)
2111 // hash = (hash ^ d) * FNV_prime;
2112 // hash += hash << 13;
2113 // hash ^= hash >> 7;
2114 // hash += hash << 3;
2115 // hash ^= hash >> 17;
2116 // hash += hash << 5;
2118 ToplevelBlock hashcode_top = new ToplevelBlock (Compiler, loc);
2119 Block hashcode_block = new Block (hashcode_top, loc, loc);
2120 hashcode_top.AddStatement (new Unchecked (hashcode_block, loc));
2122 var li_hash = LocalVariable.CreateCompilerGenerated (Compiler.BuiltinTypes.Int, hashcode_top, loc);
2123 hashcode_block.AddStatement (new BlockVariable (new TypeExpression (li_hash.Type, loc), li_hash));
2124 LocalVariableReference hash_variable_assign = new LocalVariableReference (li_hash, loc);
2125 hashcode_block.AddStatement (new StatementExpression (
2126 new SimpleAssign (hash_variable_assign, rs_hashcode)));
2128 var hash_variable = new LocalVariableReference (li_hash, loc);
2129 hashcode_block.AddStatement (new StatementExpression (
2130 new CompoundAssign (Binary.Operator.Addition, hash_variable,
2131 new Binary (Binary.Operator.LeftShift, hash_variable, new IntConstant (Compiler.BuiltinTypes, 13, loc)))));
2132 hashcode_block.AddStatement (new StatementExpression (
2133 new CompoundAssign (Binary.Operator.ExclusiveOr, hash_variable,
2134 new Binary (Binary.Operator.RightShift, hash_variable, new IntConstant (Compiler.BuiltinTypes, 7, loc)))));
2135 hashcode_block.AddStatement (new StatementExpression (
2136 new CompoundAssign (Binary.Operator.Addition, hash_variable,
2137 new Binary (Binary.Operator.LeftShift, hash_variable, new IntConstant (Compiler.BuiltinTypes, 3, loc)))));
2138 hashcode_block.AddStatement (new StatementExpression (
2139 new CompoundAssign (Binary.Operator.ExclusiveOr, hash_variable,
2140 new Binary (Binary.Operator.RightShift, hash_variable, new IntConstant (Compiler.BuiltinTypes, 17, loc)))));
2141 hashcode_block.AddStatement (new StatementExpression (
2142 new CompoundAssign (Binary.Operator.Addition, hash_variable,
2143 new Binary (Binary.Operator.LeftShift, hash_variable, new IntConstant (Compiler.BuiltinTypes, 5, loc)))));
2145 hashcode_block.AddStatement (new Return (hash_variable, loc));
2146 hashcode.Block = hashcode_top;
2148 hashcode.PrepareEmit ();
2149 Members.Add (hashcode);
2152 // ToString () override
2155 ToplevelBlock tostring_block = new ToplevelBlock (Compiler, loc);
2156 tostring_block.AddStatement (new Return (string_concat, loc));
2157 tostring.Block = tostring_block;
2159 tostring.PrepareEmit ();
2160 Members.Add (tostring);
2165 public override string GetSignatureForError ()
2167 return SignatureForError;
2170 public override CompilationSourceFile GetCompilationSourceFile ()
2175 public IList<AnonymousTypeParameter> Parameters {